Files
Umbraco-CMS/src/Umbraco.Web.Common/DependencyInjection/UmbracoBuilderExtensions.cs

426 lines
20 KiB
C#
Raw Normal View History

using System;
2020-11-20 12:24:16 +00:00
using System.Data.Common;
using System.Linq;
using System.Net.Http;
2020-11-19 09:06:04 +00:00
using System.Reflection;
using Dazinator.Extensions.FileProviders.GlobPatternFilter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection.Infrastructure;
using Microsoft.AspNetCore.Hosting;
2020-11-19 09:06:04 +00:00
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
2020-11-19 09:06:04 +00:00
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Hosting;
using Serilog.Extensions.Logging;
2020-11-19 09:06:04 +00:00
using Smidge;
using Smidge.Cache;
using Smidge.FileProcessors;
using Smidge.InMemory;
2020-11-19 09:06:04 +00:00
using Smidge.Nuglify;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Diagnostics;
using Umbraco.Cms.Core.Extensions;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Macros;
using Umbraco.Cms.Core.Net;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
2021-12-15 11:38:17 +01:00
using Umbraco.Cms.Core.Telemetry;
using Umbraco.Cms.Core.Templates;
using Umbraco.Cms.Core.Web;
using Umbraco.Cms.Core.WebAssets;
using Umbraco.Cms.Infrastructure.DependencyInjection;
using Umbraco.Cms.Infrastructure.HostedServices;
using Umbraco.Cms.Infrastructure.HostedServices.ServerRegistration;
using Umbraco.Cms.Infrastructure.Migrations.Install;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax;
2021-02-10 11:42:04 +01:00
using Umbraco.Cms.Web.Common;
using Umbraco.Cms.Web.Common.ApplicationModels;
using Umbraco.Cms.Web.Common.AspNetCore;
using Umbraco.Cms.Web.Common.Controllers;
2021-02-17 15:41:54 +01:00
using Umbraco.Cms.Web.Common.DependencyInjection;
2021-02-10 11:42:04 +01:00
using Umbraco.Cms.Web.Common.Localization;
using Umbraco.Cms.Web.Common.Macros;
using Umbraco.Cms.Web.Common.Middleware;
using Umbraco.Cms.Web.Common.ModelBinders;
using Umbraco.Cms.Web.Common.Mvc;
using Umbraco.Cms.Web.Common.Profiler;
using Umbraco.Cms.Web.Common.RuntimeMinification;
2021-02-10 11:42:04 +01:00
using Umbraco.Cms.Web.Common.Security;
using Umbraco.Cms.Web.Common.Templates;
using Umbraco.Cms.Web.Common.UmbracoContext;
using IHostingEnvironment = Umbraco.Cms.Core.Hosting.IHostingEnvironment;
2021-02-10 11:42:04 +01:00
namespace Umbraco.Extensions
{
// TODO: We could add parameters to configure each of these for flexibility
/// <summary>
/// Extension methods for <see cref="IUmbracoBuilder"/> for the common Umbraco functionality
/// </summary>
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
public static partial class UmbracoBuilderExtensions
{
/// <summary>
/// Creates an <see cref="IUmbracoBuilder"/> and registers basic Umbraco services
/// </summary>
public static IUmbracoBuilder AddUmbraco(
this IServiceCollection services,
IWebHostEnvironment webHostEnvironment,
2020-11-20 12:24:16 +00:00
IConfiguration config)
{
if (services is null)
2020-12-08 11:08:14 +11:00
{
throw new ArgumentNullException(nameof(services));
2020-12-08 11:08:14 +11:00
}
if (config is null)
2020-12-08 11:08:14 +11:00
{
throw new ArgumentNullException(nameof(config));
2020-12-08 11:08:14 +11:00
}
// Setup static application logging ASAP (e.g. during configure services).
// Will log to SilentLogger until Serilog.Log.Logger is setup.
StaticApplicationLogging.Initialize(new SerilogLoggerFactory());
// The DataDirectory is used to resolve database file paths (directly supported by SQL CE and manually replaced for LocalDB)
AppDomain.CurrentDomain.SetData("DataDirectory", webHostEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data));
// Manually create and register the HttpContextAccessor. In theory this should not be registered
// again by the user but if that is the case it's not the end of the world since HttpContextAccessor
// is just based on AsyncLocal, see https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http/src/HttpContextAccessor.cs
IHttpContextAccessor httpContextAccessor = new HttpContextAccessor();
2020-11-20 12:24:16 +00:00
services.AddSingleton(httpContextAccessor);
var requestCache = new HttpContextRequestAppCache(httpContextAccessor);
2021-08-05 21:42:36 +02:00
var appCaches = AppCaches.Create(requestCache);
services.ConfigureOptions<ConfigureKestrelServerOptions>();
services.ConfigureOptions<ConfigureFormOptions>();
2020-12-08 11:08:14 +11:00
IProfiler profiler = GetWebProfiler(config);
2021-08-05 21:42:36 +02:00
services.AddLogger(webHostEnvironment, config);
ILoggerFactory loggerFactory = new SerilogLoggerFactory();
TypeLoader typeLoader = services.AddTypeLoader(Assembly.GetEntryAssembly(), loggerFactory, config);
IHostingEnvironment tempHostingEnvironment = GetTemporaryHostingEnvironment(webHostEnvironment, config);
return new UmbracoBuilder(services, config, typeLoader, loggerFactory, profiler, appCaches, tempHostingEnvironment);
}
/// <summary>
/// Adds core Umbraco services
/// </summary>
/// <remarks>
/// This will not add any composers/components
/// </remarks>
2020-11-20 12:24:16 +00:00
public static IUmbracoBuilder AddUmbracoCore(this IUmbracoBuilder builder)
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
2020-11-20 12:24:16 +00:00
// Add ASP.NET specific services
builder.Services.AddUnique<IBackOfficeInfo, AspNetCoreBackOfficeInfo>();
builder.Services.AddUnique<IHostingEnvironment>(sp => ActivatorUtilities.CreateInstance<AspNetCoreHostingEnvironment>(sp, sp.GetRequiredService<IApplicationDiscriminator>()));
builder.Services.AddHostedService(factory => factory.GetRequiredService<IRuntime>());
2020-11-20 12:24:16 +00:00
builder.Services.AddSingleton<DatabaseSchemaCreatorFactory>();
v10 SQLite support + distributed locking abstractions (#11922) * Created Persistence.SQLite project skeleton. * SQLite database initialization * Various changes and hacks to make things work. * WIP integration tests * Fix thread safety tests * Fix tests that relied on tie breaker sorting. Spent a fair amount of time looking for a less lazy fix but gave up. * Convert right join to left join ContentTypeRepository.PerformGetByQuery SQLite doesn't support right join * Fix test Can_Generate_Delete_SubQuery_Statement Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override EscapeSqlIdentifier so NPoco will escape with []. SQLite docs say > "A keyword enclosed in square brackets is an identifier. This is not standard SQL. This quoting mechanism is used by MS Access and SQL Server and is included in SQLite for compatibility." Also could have updated SqliteSyntaxProvider to match npoco but decided against it. * Fixes for paginated custom order by * Fix tests broken by lack of unique indexes. * Fix SqlServerTableByTableTest tests. These tests didn't actually do anything as the tables already exist so schema creator just returned. Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation. * Fix ValidateLoginSession - SelectTop must come later * dry up database cleanup * Fix up db migration tests. We can't drop pk in sqlite without recreating table. Test looks to be testing that add column works as intended which we can test. * Prevent schema creation errors. * SQLite ignore lock tests, WAL back on. * Fix package schema tests * Fix NPocoFetchTests - case sensitivity not under test * Fix AdvancedMigrationTests (where possible) Migrations probably need a good look later. Maybe nuke old migrations and only support moving to v10 from v9. If we do that can do some cleanup. * Cleanup test database configuration * Run integration tests against SQLite on build agent. * Drop MS.Data.SQLite System.Data.SQLite was quicker to roll out due to more CLR type mapping * YAML * Skip Umbraco.Tests.Integration.SqlCe * Drop SqlServerTableByTable tests. Until this week they did nothing anyway as they with NewSchemaPerTest so the tests all passed as CreateTable was no op (already exists). Also all of the tables are created in an empty database by SchemaValidationTest.cs DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors * Might aswell run against macOS also. * Copy azure pipelines task header layout * Delete SQLCe projects * Remove SQL CE specific code. * Remove SQL CE NuSpec, template params, build script setup * Delete umbraco-netcore-only.sln * Add SkipTests solution configuration and use for codeql * Remove reference to deleted nuspec file. * Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName. At this point you can try out SQLite support by setting the following in appsettings.json and then completing the install process. "ConnectionStrings": { "umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite", "umbracoDbDSN_ProviderName": "System.Data.SQLite" }, Not currently possible via installer UI without provider name pre-set in configuration. * Switch to Microsoft.Data.Sqlite Some gross hacks but will be good to find out if this works with apple silicon. * Enable selection of SQLite via installer UI (also quick install) * Remove SqlServerDbProviderFactoryCreator to cleanup a TODO * Move SQL Server support to its own class library * Add persistence dependencies to Umbraco.CMS metapackage * Bugfix packages delete query Created invalid query for SQLite. * Try out cypress tests Linux + SQLite * Prevent cypress test artifact upload failure on attempt 2+ * LocalDb bugfixes * Drop redundant enum * Move SqlClient constant * Misc whitespace * Remove IsSqlCe extension (TODO: drop non 9->10 migrations later). * Umbraco.Persistence.* -> Umbraco.Cms.Persistence.* * Display quick install defaults and per provider default database name. * Misc remove old comment * little re-arrange * Remove almost all usages of IsSqlite extension. * visual adjustments * Custom Database Configuration is last step and should then say Install. * use text instead of disabled inputs * move legend, rename to Install * Update SqlMainDomLock to work without distributed locks. * Added IDistributedLockingMechanism interface and in memory impl. * Drop locking from ISqlSyntaxProvider & wire up scope to abstraction. * Added SqlServerDistributedLockingMechanism * Move distributed locking interfaces and exceptions to Core + xmldocs. * Fix tests, Misc cleanup, Add SQL distributed locking integration tests * Provide mechanism to specify DistributedLockingMechanism in config (even if added by composer) * Nomplementation -> NoImplementation * Fix misleading comment * Integration tests use SqlServerDistributedLockingMechanism when possible * Handle up-gradable locks SqlServerDistributedLockingMechanism. TODO: InMemoryDistributedLockingMechanism. Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep at night. Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests * Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky. * Tweak constraints on WithCollectionBuilder so i can drop bad constructor * Added SqliteDistributedLockingMechanism * Dropped InMemoryDistributedMechanism + magic InMemoryDistributedMechanism was pretty rubbish and now we have a decent implementation for SQLite as we no longer block readers see 8d1f42b. Also drop the CollectionBuilder setup, instead do the same as we do for syntax providers etc, it's more automagical so we never require an explicit selection although we are allowing for it. However keeping the optional IUmbracoBuilder constructor param for CollectionBuilders as it's extremely useful. * Fix quick install "" database name. * Hide Database Configuration section when a connection string is pre-set. Doesn't seem worth it to extract db name from connection string. * Ensure wal test 2+ * Fix logging inconsistencies. * Ensure in transaction when obtaining locks + no-op the SQLite read lock. There's no point in running the query just to make a single test pass. * Fix installer database display names * Allow SQLite shared cache without losing deferred transactions * Opt into shared cache for new SQLite databases + fix filename * Fix misc inconsistency in .gitignore * Prefer our interceptor interface * Restore DEBUG_DATABASES code OnConnectionOpened in case it's used. * Back to private cache. * Added retry strategy for SQLite + refactor out SQL server specific stuff * Fix SQL server tests. * Misc - Orphaned comment, incorrect casing. * InMemory SQLite test database & turn shared cache back on everywhere. Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IDatabaseProviderMetadata, CustomConnectionStringDatabaseProviderMetadata>());
2020-11-20 12:24:16 +00:00
// Must be added here because DbProviderFactories is netstandard 2.1 so cannot exist in Infra for now
builder.Services.AddSingleton<IDbProviderFactoryCreator>(factory => new DbProviderFactoryCreator(
2020-11-20 12:24:16 +00:00
DbProviderFactories.GetFactory,
factory.GetServices<ISqlSyntaxProvider>(),
factory.GetServices<IBulkSqlInsertProvider>(),
factory.GetServices<IDatabaseCreator>(),
v10 SQLite support + distributed locking abstractions (#11922) * Created Persistence.SQLite project skeleton. * SQLite database initialization * Various changes and hacks to make things work. * WIP integration tests * Fix thread safety tests * Fix tests that relied on tie breaker sorting. Spent a fair amount of time looking for a less lazy fix but gave up. * Convert right join to left join ContentTypeRepository.PerformGetByQuery SQLite doesn't support right join * Fix test Can_Generate_Delete_SubQuery_Statement Worth noting that NPoco.DatabaseTypes.SQLiteDatabaseType doesn't override EscapeSqlIdentifier so NPoco will escape with []. SQLite docs say > "A keyword enclosed in square brackets is an identifier. This is not standard SQL. This quoting mechanism is used by MS Access and SQL Server and is included in SQLite for compatibility." Also could have updated SqliteSyntaxProvider to match npoco but decided against it. * Fixes for paginated custom order by * Fix tests broken by lack of unique indexes. * Fix SqlServerTableByTableTest tests. These tests didn't actually do anything as the tables already exist so schema creator just returned. Did however point out that the default implementation for DoesTableExist just returns false so added a default naive implementation. * Fix ValidateLoginSession - SelectTop must come later * dry up database cleanup * Fix up db migration tests. We can't drop pk in sqlite without recreating table. Test looks to be testing that add column works as intended which we can test. * Prevent schema creation errors. * SQLite ignore lock tests, WAL back on. * Fix package schema tests * Fix NPocoFetchTests - case sensitivity not under test * Fix AdvancedMigrationTests (where possible) Migrations probably need a good look later. Maybe nuke old migrations and only support moving to v10 from v9. If we do that can do some cleanup. * Cleanup test database configuration * Run integration tests against SQLite on build agent. * Drop MS.Data.SQLite System.Data.SQLite was quicker to roll out due to more CLR type mapping * YAML * Skip Umbraco.Tests.Integration.SqlCe * Drop SqlServerTableByTable tests. Until this week they did nothing anyway as they with NewSchemaPerTest so the tests all passed as CreateTable was no op (already exists). Also all of the tables are created in an empty database by SchemaValidationTest.cs DatabaseSchemaCreation_Produces_DatabaseSchemaResult_With_Zero_Errors * Might aswell run against macOS also. * Copy azure pipelines task header layout * Delete SQLCe projects * Remove SQL CE specific code. * Remove SQL CE NuSpec, template params, build script setup * Delete umbraco-netcore-only.sln * Add SkipTests solution configuration and use for codeql * Remove reference to deleted nuspec file. * Refactor ConnectionStrings WRT DataDirectory placeholder & ProviderName. At this point you can try out SQLite support by setting the following in appsettings.json and then completing the install process. "ConnectionStrings": { "umbracoDbDSN": "Data Source=|DataDirectory|/umbraco.sqlite", "umbracoDbDSN_ProviderName": "System.Data.SQLite" }, Not currently possible via installer UI without provider name pre-set in configuration. * Switch to Microsoft.Data.Sqlite Some gross hacks but will be good to find out if this works with apple silicon. * Enable selection of SQLite via installer UI (also quick install) * Remove SqlServerDbProviderFactoryCreator to cleanup a TODO * Move SQL Server support to its own class library * Add persistence dependencies to Umbraco.CMS metapackage * Bugfix packages delete query Created invalid query for SQLite. * Try out cypress tests Linux + SQLite * Prevent cypress test artifact upload failure on attempt 2+ * LocalDb bugfixes * Drop redundant enum * Move SqlClient constant * Misc whitespace * Remove IsSqlCe extension (TODO: drop non 9->10 migrations later). * Umbraco.Persistence.* -> Umbraco.Cms.Persistence.* * Display quick install defaults and per provider default database name. * Misc remove old comment * little re-arrange * Remove almost all usages of IsSqlite extension. * visual adjustments * Custom Database Configuration is last step and should then say Install. * use text instead of disabled inputs * move legend, rename to Install * Update SqlMainDomLock to work without distributed locks. * Added IDistributedLockingMechanism interface and in memory impl. * Drop locking from ISqlSyntaxProvider & wire up scope to abstraction. * Added SqlServerDistributedLockingMechanism * Move distributed locking interfaces and exceptions to Core + xmldocs. * Fix tests, Misc cleanup, Add SQL distributed locking integration tests * Provide mechanism to specify DistributedLockingMechanism in config (even if added by composer) * Nomplementation -> NoImplementation * Fix misleading comment * Integration tests use SqlServerDistributedLockingMechanism when possible * Handle up-gradable locks SqlServerDistributedLockingMechanism. TODO: InMemoryDistributedLockingMechanism. Note: Nuked SqlServerDistributedLockingMechanismTests, will still sleep at night. Is covered by Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.LockTests * Make tests pass for InMemoryDistributedLockingMechanism, pretty hacky. * Tweak constraints on WithCollectionBuilder so i can drop bad constructor * Added SqliteDistributedLockingMechanism * Dropped InMemoryDistributedMechanism + magic InMemoryDistributedMechanism was pretty rubbish and now we have a decent implementation for SQLite as we no longer block readers see 8d1f42b. Also drop the CollectionBuilder setup, instead do the same as we do for syntax providers etc, it's more automagical so we never require an explicit selection although we are allowing for it. However keeping the optional IUmbracoBuilder constructor param for CollectionBuilders as it's extremely useful. * Fix quick install "" database name. * Hide Database Configuration section when a connection string is pre-set. Doesn't seem worth it to extract db name from connection string. * Ensure wal test 2+ * Fix logging inconsistencies. * Ensure in transaction when obtaining locks + no-op the SQLite read lock. There's no point in running the query just to make a single test pass. * Fix installer database display names * Allow SQLite shared cache without losing deferred transactions * Opt into shared cache for new SQLite databases + fix filename * Fix misc inconsistency in .gitignore * Prefer our interceptor interface * Restore DEBUG_DATABASES code OnConnectionOpened in case it's used. * Back to private cache. * Added retry strategy for SQLite + refactor out SQL server specific stuff * Fix SQL server tests. * Misc - Orphaned comment, incorrect casing. * InMemory SQLite test database & turn shared cache back on everywhere. Co-authored-by: Niels Lyngsø <niels.lyngso@gmail.com>
2022-03-11 16:14:20 +00:00
factory.GetServices<IProviderSpecificMapperFactory>(),
factory.GetServices<IProviderSpecificInterceptor>()
));
2020-11-20 12:24:16 +00:00
builder.AddCoreInitialServices();
v9: Implement telemetry levels (#12267) * Add initial classes * Add TelemetryProviders * Add new NodeCountService.cs and NodeTelemetryProvider * Add data contract attribute to UsageInformation Otherwise it wont serialize correctly * Implement more providers * Fix builders and propertyEditorTelemetry * Add MediaTelemetryProvider * Add MediaTelemetryProvider * Fix doubling of media telemetry * Move contentCount from NodeCountTelemetryProvider and move to ContentTelemetryProvider * Revert ContentTelemetryProvider changes * Add detailed information to TelemetryService * Add integration tests * Add more tests and todos for tests * Fix stylecop warnings * Use yield return instead of instantiating local list * Implement Macro test * Inject interface instead of implementation in TelemetryService * Fix TelemetryServiceTests.cs * Implement media tests * Implement propertyTypeTests * Implement constants instead of hardcoded strings * Add SystemInformationTelemetryProvider * Use SystemInformationTableDataProvider in UserDataService * Implement more properties * Add UsageInformation * Replace UserDataService with SystemInformationTelemetryProvider * Undo changes to UserDataService and obsolete it * Remove ISystemInformationTableDataProvider * Register SystemInformationTelemetryProvider as telemetry provider * Use constants for telemetry names * Make UserDataServiceTests test SystemInformationTelemetryProvider instead * Update UserDataServiceTests to cover new data * Add unit tests * Add integration test testing expected data is returned * Implement Analytics dashboard * Improve assertion message * Add text and styling to analyticspage * Rename consent to analytic * implement save button for consent level * Implement save button * Fix system information test * Add TelemetryResource * Move telemetry providers to infrastructure * Add database provider to system information * Set startvalue for slider * Fix unit tests * Implement MetricsConsentService using KeyValueService * Return void hen setting the telemetry level * fix startposition when not reloading * Add a couple tests * Update src/Umbraco.Core/Services/MetricsConsentService.cs * Rename ConsentLevel.cs * Use direct Enum instead of parsing * rename consent resource * add lazy database * refactor slider * Implement ng-if and propers pips * Make classes internal * Fix slider not loading when navigating to tab * Add telemetry level check to TelemetryService.cs * Add Consent for analytics text * Fix build errors for unit tests * Fix TelemetryServiceTests * revert package-lock.json * Fix integration test * Update slider * Update TelemetryService.cs * Apply suggestions from code review Co-authored-by: Mole <nikolajlauridsen@protonmail.ch> Co-authored-by: Nikolaj Geisle <niko737@edu.ucl.dk> Co-authored-by: nikolajlauridsen <nikolajlauridsen@protonmail.ch>
2022-04-19 15:06:10 +02:00
builder.AddTelemetryProviders();
2020-11-20 12:24:16 +00:00
// aspnet app lifetime mgmt
builder.Services.AddUnique<IUmbracoApplicationLifetime, AspNetCoreUmbracoApplicationLifetime>();
builder.Services.AddUnique<IApplicationShutdownRegistry, AspNetCoreApplicationShutdownRegistry>();
builder.Services.AddTransient<IIpAddressUtilities, IpAddressUtilities>();
2020-11-19 09:06:04 +00:00
return builder;
}
/// <summary>
/// Add Umbraco hosted services
/// </summary>
2020-11-19 09:06:04 +00:00
public static IUmbracoBuilder AddHostedServices(this IUmbracoBuilder builder)
{
builder.Services.AddHostedService<QueuedHostedService>();
2020-11-20 12:24:16 +00:00
builder.Services.AddHostedService<HealthCheckNotifier>();
builder.Services.AddHostedService<KeepAlive>();
builder.Services.AddHostedService<LogScrubber>();
Merge remote-tracking branch 'origin/v8/feature/version-history-cleanup-ui' into v9/dev # Conflicts: # src/Umbraco.Core/Composing/CompositionExtensions/Repositories.cs # src/Umbraco.Core/Composing/CompositionExtensions/Services.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentElement.cs # src/Umbraco.Core/Configuration/UmbracoSettings/IContentSection.cs # src/Umbraco.Core/ContentEditing/HistoryCleanup.cs # src/Umbraco.Core/Models/ContentEditing/DocumentTypeDisplay.cs # src/Umbraco.Core/Models/ContentType.cs # src/Umbraco.Core/Models/Mapping/ContentTypeMapDefinition.cs # src/Umbraco.Core/Persistence/Repositories/DocumentVersionRepository.cs # src/Umbraco.Core/Scheduling/ContentVersionCleanup.cs # src/Umbraco.Core/Services/DefaultContentVersionCleanupPolicy.cs # src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs # src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs # src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ContentTypeCommonRepository.cs # src/Umbraco.Infrastructure/Services/Implement/ContentService.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config # src/Umbraco.Tests/TestHelpers/Entities/MockedContent.cs # src/Umbraco.Tests/TestHelpers/Entities/MockedContentTypes.cs # src/Umbraco.Tests/Umbraco.Tests.csproj # src/Umbraco.Web.UI.Client/package-lock.json # src/Umbraco.Web.UI/config/umbracoSettings.Release.config # src/Umbraco.Web.UI/umbraco/config/lang/en.xml # src/Umbraco.Web.UI/umbraco/config/lang/en_us.xml # src/Umbraco.Web/Scheduling/SchedulerComponent.cs # src/Umbraco.Web/Umbraco.Web.csproj # tests/Umbraco.Tests.Common/Extensions/AutoMoqDataAttribute.cs # tests/Umbraco.Tests.UnitTests/Umbraco.Core/Persistence/Repositories/DocumentVersionRepository_Tests_Integration.cs # tests/Umbraco.Tests.UnitTests/Umbraco.Core/Scheduling/ContentVersionCleanup_Tests_UnitTests.cs # tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/ContentVersionCleanupService_Tests_Integration.cs # tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/ContentVersionCleanupService_Tests_UnitTests.cs # tests/Umbraco.Tests.UnitTests/Umbraco.Core/Services/DefaultContentVersionCleanupPolicy_Tests_UnitTests.cs
2021-10-29 15:00:27 +02:00
builder.Services.AddHostedService<ContentVersionCleanup>();
2020-11-20 12:24:16 +00:00
builder.Services.AddHostedService<ScheduledPublishing>();
builder.Services.AddHostedService<TempFileCleanup>();
builder.Services.AddHostedService<InstructionProcessTask>();
builder.Services.AddHostedService<TouchServerTask>();
2021-12-15 11:38:17 +01:00
builder.Services.AddHostedService(provider =>
new ReportSiteTask(
provider.GetRequiredService<ILogger<ReportSiteTask>>(),
provider.GetRequiredService<ITelemetryService>()));
2020-11-19 09:06:04 +00:00
return builder;
}
private static IUmbracoBuilder AddHttpClients(this IUmbracoBuilder builder)
2020-11-19 09:06:04 +00:00
{
2020-11-20 12:24:16 +00:00
builder.Services.AddHttpClient();
builder.Services.AddHttpClient(Constants.HttpClients.IgnoreCertificateErrors)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
});
2020-11-19 09:06:04 +00:00
return builder;
}
/// <summary>
/// Adds the Umbraco request profiler
/// </summary>
public static IUmbracoBuilder AddUmbracoProfiler(this IUmbracoBuilder builder)
2020-11-19 09:06:04 +00:00
{
builder.Services.AddSingleton<WebProfilerHtml>();
builder.Services.AddMiniProfiler(options =>
Merge remote-tracking branch 'origin/v8/dev' into netcore/dev # Conflicts: # build/NuSpecs/UmbracoCms.Core.nuspec # build/NuSpecs/UmbracoCms.Web.nuspec # src/SolutionInfo.cs # src/Umbraco.Core/Cache/CacheKeys.cs # src/Umbraco.Core/Composing/TypeFinder.cs # src/Umbraco.Core/Configuration/GlobalSettings.cs # src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs # src/Umbraco.Core/Configuration/IGlobalSettings.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentElement.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs # src/Umbraco.Core/Constants-AppSettings.cs # src/Umbraco.Core/Editors/UserEditorAuthorizationHelper.cs # src/Umbraco.Core/Extensions/StringExtensions.cs # src/Umbraco.Core/Extensions/UriExtensions.cs # src/Umbraco.Core/IO/IOHelper.cs # src/Umbraco.Core/IO/PhysicalFileSystem.cs # src/Umbraco.Core/Media/Exif/MathEx.cs # src/Umbraco.Core/Media/UploadAutoFillProperties.cs # src/Umbraco.Core/Models/Mapping/UserMapDefinition.cs # src/Umbraco.Core/Models/Membership/User.cs # src/Umbraco.Core/Models/UserExtensions.cs # src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs # src/Umbraco.Core/PropertyEditors/ListViewConfiguration.cs # src/Umbraco.Core/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs # src/Umbraco.Core/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs # src/Umbraco.Core/Routing/AliasUrlProvider.cs # src/Umbraco.Core/Routing/DefaultUrlProvider.cs # src/Umbraco.Core/Routing/UriUtility.cs # src/Umbraco.Core/Routing/UrlProviderExtensions.cs # src/Umbraco.Core/Runtime/CoreRuntime.cs # src/Umbraco.Core/RuntimeOptions.cs # src/Umbraco.Core/RuntimeState.cs # src/Umbraco.Core/Security/BackOfficeUserStore.cs # src/Umbraco.Core/Security/ContentPermissions.cs # src/Umbraco.Core/Sync/ApplicationUrlHelper.cs # src/Umbraco.Core/Trees/TreeNode.cs # src/Umbraco.Core/Udi.cs # src/Umbraco.Examine.Lucene/BackOfficeExamineSearcher.cs # src/Umbraco.Examine/Umbraco.Examine.csproj # src/Umbraco.Infrastructure/Examine/ContentValueSetValidator.cs # src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs # src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs # src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs # src/Umbraco.Infrastructure/Scoping/Scope.cs # src/Umbraco.Infrastructure/Search/ExamineComponent.cs # src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs # src/Umbraco.Infrastructure/Services/Implement/ContentService.cs # src/Umbraco.Infrastructure/Services/Implement/MediaService.cs # src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs # src/Umbraco.Persistence.SqlCe/SqlCeSyntaxProvider.cs # src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/LocksTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/ContentElementTests.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config # src/Umbraco.Tests/TestHelpers/SettingsForTests.cs # src/Umbraco.Tests/Testing/TestDatabase.cs # src/Umbraco.Tests/Web/Controllers/ContentControllerUnitTests.cs # src/Umbraco.Tests/Web/Controllers/FilterAllowedOutgoingContentAttributeTests.cs # src/Umbraco.Tests/Web/Controllers/MediaControllerUnitTests.cs # src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs # src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs # src/Umbraco.Web.BackOffice/Controllers/ContentController.cs # src/Umbraco.Web.BackOffice/Controllers/EntityController.cs # src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs # src/Umbraco.Web.BackOffice/Controllers/MediaController.cs # src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs # src/Umbraco.Web.BackOffice/Controllers/TourController.cs # src/Umbraco.Web.BackOffice/Controllers/UserGroupEditorAuthorizationHelper.cs # src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs # src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs # src/Umbraco.Web.BackOffice/Mapping/ContentMapDefinition.cs # src/Umbraco.Web.BackOffice/Services/IconService.cs # src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs # src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs # src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs # src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs # src/Umbraco.Web.Common/Extensions/FormCollectionExtensions.cs # src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js # src/Umbraco.Web.UI.Client/src/views/content/overlays/publish.html # src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml # src/Umbraco.Web.UI/config/umbracoSettings.Release.config # src/Umbraco.Web/Cache/MemberCacheRefresher.cs # src/Umbraco.Web/Composing/ModuleInjector.cs # src/Umbraco.Web/Editors/BackOfficeController.cs # src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs # src/Umbraco.Web/Editors/ContentTypeController.cs # src/Umbraco.Web/Editors/Filters/ContentSaveValidationAttribute.cs # src/Umbraco.Web/Editors/Filters/MediaItemSaveValidationAttribute.cs # src/Umbraco.Web/Editors/Filters/UserGroupAuthorizationAttribute.cs # src/Umbraco.Web/Editors/TinyMceController.cs # src/Umbraco.Web/Editors/UserGroupsController.cs # src/Umbraco.Web/Editors/UsersController.cs # src/Umbraco.Web/ImageCropperTemplateExtensions.cs # src/Umbraco.Web/Logging/WebProfiler.cs # src/Umbraco.Web/Logging/WebProfilerProvider.cs # src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs # src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs # src/Umbraco.Web/Mvc/JsonNetResult.cs # src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs # src/Umbraco.Web/Mvc/RenderRouteHandler.cs # src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs # src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs # src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs # src/Umbraco.Web/RoutableDocumentFilter.cs # src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs # src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs # src/Umbraco.Web/Routing/PublishedRouter.cs # src/Umbraco.Web/Runtime/WebInitialComposer.cs # src/Umbraco.Web/Scheduling/KeepAlive.cs # src/Umbraco.Web/Security/AppBuilderExtensions.cs # src/Umbraco.Web/Security/BackOfficeClaimsIdentityFactory.cs # src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs # src/Umbraco.Web/Trees/DictionaryTreeController.cs # src/Umbraco.Web/Trees/LanguageTreeController.cs # src/Umbraco.Web/Trees/LogViewerTreeController.cs # src/Umbraco.Web/Trees/PackagesTreeController.cs # src/Umbraco.Web/UmbracoApplication.cs # src/Umbraco.Web/UmbracoApplicationBase.cs # src/Umbraco.Web/UmbracoInjectedModule.cs # src/Umbraco.Web/WebApi/Filters/AdminUsersAuthorizeAttribute.cs # src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs # src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs # src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs # src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs
2021-03-05 15:36:27 +01:00
{
// WebProfiler determine and start profiling. We should not use the MiniProfilerMiddleware to also profile
Merge remote-tracking branch 'origin/v8/dev' into netcore/dev # Conflicts: # build/NuSpecs/UmbracoCms.Core.nuspec # build/NuSpecs/UmbracoCms.Web.nuspec # src/SolutionInfo.cs # src/Umbraco.Core/Cache/CacheKeys.cs # src/Umbraco.Core/Composing/TypeFinder.cs # src/Umbraco.Core/Configuration/GlobalSettings.cs # src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs # src/Umbraco.Core/Configuration/IGlobalSettings.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentElement.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs # src/Umbraco.Core/Constants-AppSettings.cs # src/Umbraco.Core/Editors/UserEditorAuthorizationHelper.cs # src/Umbraco.Core/Extensions/StringExtensions.cs # src/Umbraco.Core/Extensions/UriExtensions.cs # src/Umbraco.Core/IO/IOHelper.cs # src/Umbraco.Core/IO/PhysicalFileSystem.cs # src/Umbraco.Core/Media/Exif/MathEx.cs # src/Umbraco.Core/Media/UploadAutoFillProperties.cs # src/Umbraco.Core/Models/Mapping/UserMapDefinition.cs # src/Umbraco.Core/Models/Membership/User.cs # src/Umbraco.Core/Models/UserExtensions.cs # src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs # src/Umbraco.Core/PropertyEditors/ListViewConfiguration.cs # src/Umbraco.Core/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs # src/Umbraco.Core/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs # src/Umbraco.Core/Routing/AliasUrlProvider.cs # src/Umbraco.Core/Routing/DefaultUrlProvider.cs # src/Umbraco.Core/Routing/UriUtility.cs # src/Umbraco.Core/Routing/UrlProviderExtensions.cs # src/Umbraco.Core/Runtime/CoreRuntime.cs # src/Umbraco.Core/RuntimeOptions.cs # src/Umbraco.Core/RuntimeState.cs # src/Umbraco.Core/Security/BackOfficeUserStore.cs # src/Umbraco.Core/Security/ContentPermissions.cs # src/Umbraco.Core/Sync/ApplicationUrlHelper.cs # src/Umbraco.Core/Trees/TreeNode.cs # src/Umbraco.Core/Udi.cs # src/Umbraco.Examine.Lucene/BackOfficeExamineSearcher.cs # src/Umbraco.Examine/Umbraco.Examine.csproj # src/Umbraco.Infrastructure/Examine/ContentValueSetValidator.cs # src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs # src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs # src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs # src/Umbraco.Infrastructure/Scoping/Scope.cs # src/Umbraco.Infrastructure/Search/ExamineComponent.cs # src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs # src/Umbraco.Infrastructure/Services/Implement/ContentService.cs # src/Umbraco.Infrastructure/Services/Implement/MediaService.cs # src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs # src/Umbraco.Persistence.SqlCe/SqlCeSyntaxProvider.cs # src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/LocksTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/ContentElementTests.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config # src/Umbraco.Tests/TestHelpers/SettingsForTests.cs # src/Umbraco.Tests/Testing/TestDatabase.cs # src/Umbraco.Tests/Web/Controllers/ContentControllerUnitTests.cs # src/Umbraco.Tests/Web/Controllers/FilterAllowedOutgoingContentAttributeTests.cs # src/Umbraco.Tests/Web/Controllers/MediaControllerUnitTests.cs # src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs # src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs # src/Umbraco.Web.BackOffice/Controllers/ContentController.cs # src/Umbraco.Web.BackOffice/Controllers/EntityController.cs # src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs # src/Umbraco.Web.BackOffice/Controllers/MediaController.cs # src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs # src/Umbraco.Web.BackOffice/Controllers/TourController.cs # src/Umbraco.Web.BackOffice/Controllers/UserGroupEditorAuthorizationHelper.cs # src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs # src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs # src/Umbraco.Web.BackOffice/Mapping/ContentMapDefinition.cs # src/Umbraco.Web.BackOffice/Services/IconService.cs # src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs # src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs # src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs # src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs # src/Umbraco.Web.Common/Extensions/FormCollectionExtensions.cs # src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js # src/Umbraco.Web.UI.Client/src/views/content/overlays/publish.html # src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml # src/Umbraco.Web.UI/config/umbracoSettings.Release.config # src/Umbraco.Web/Cache/MemberCacheRefresher.cs # src/Umbraco.Web/Composing/ModuleInjector.cs # src/Umbraco.Web/Editors/BackOfficeController.cs # src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs # src/Umbraco.Web/Editors/ContentTypeController.cs # src/Umbraco.Web/Editors/Filters/ContentSaveValidationAttribute.cs # src/Umbraco.Web/Editors/Filters/MediaItemSaveValidationAttribute.cs # src/Umbraco.Web/Editors/Filters/UserGroupAuthorizationAttribute.cs # src/Umbraco.Web/Editors/TinyMceController.cs # src/Umbraco.Web/Editors/UserGroupsController.cs # src/Umbraco.Web/Editors/UsersController.cs # src/Umbraco.Web/ImageCropperTemplateExtensions.cs # src/Umbraco.Web/Logging/WebProfiler.cs # src/Umbraco.Web/Logging/WebProfilerProvider.cs # src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs # src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs # src/Umbraco.Web/Mvc/JsonNetResult.cs # src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs # src/Umbraco.Web/Mvc/RenderRouteHandler.cs # src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs # src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs # src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs # src/Umbraco.Web/RoutableDocumentFilter.cs # src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs # src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs # src/Umbraco.Web/Routing/PublishedRouter.cs # src/Umbraco.Web/Runtime/WebInitialComposer.cs # src/Umbraco.Web/Scheduling/KeepAlive.cs # src/Umbraco.Web/Security/AppBuilderExtensions.cs # src/Umbraco.Web/Security/BackOfficeClaimsIdentityFactory.cs # src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs # src/Umbraco.Web/Trees/DictionaryTreeController.cs # src/Umbraco.Web/Trees/LanguageTreeController.cs # src/Umbraco.Web/Trees/LogViewerTreeController.cs # src/Umbraco.Web/Trees/PackagesTreeController.cs # src/Umbraco.Web/UmbracoApplication.cs # src/Umbraco.Web/UmbracoApplicationBase.cs # src/Umbraco.Web/UmbracoInjectedModule.cs # src/Umbraco.Web/WebApi/Filters/AdminUsersAuthorizeAttribute.cs # src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs # src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs # src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs # src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs
2021-03-05 15:36:27 +01:00
options.ShouldProfile = request => false;
// this is a default path and by default it performs a 'contains' check which will match our content controller
// (and probably other requests) and ignore them.
options.IgnoredPaths.Remove("/content/");
});
2020-11-19 09:06:04 +00:00
builder.AddNotificationHandler<UmbracoApplicationStartingNotification, InitializeWebProfiling>();
2020-11-19 09:06:04 +00:00
return builder;
}
2022-03-29 13:44:21 +02:00
public static IUmbracoBuilder AddMvcAndRazor(this IUmbracoBuilder builder, Action<IMvcBuilder>? mvcBuilding = null)
2020-11-19 09:06:04 +00:00
{
// TODO: We need to figure out if we can work around this because calling AddControllersWithViews modifies the global app and order is very important
// this will directly affect developers who need to call that themselves.
// We need to have runtime compilation of views when using umbraco. We could consider having only this when a specific config is set.
// But as far as I can see, there are still precompiled views, even when this is activated, so maybe it is okay.
IMvcBuilder mvcBuilder = builder.Services
.AddControllersWithViews();
FixForDotnet6Preview1(builder.Services);
mvcBuilder.AddRazorRuntimeCompilation();
2020-11-19 09:06:04 +00:00
mvcBuilding?.Invoke(mvcBuilder);
2020-11-19 09:06:04 +00:00
return builder;
}
/// <summary>
/// This fixes an issue for .NET6 Preview1, that in AddRazorRuntimeCompilation cannot remove the existing IViewCompilerProvider.
/// </summary>
/// <remarks>
/// When running .NET6 Preview1 there is an issue with looks to be fixed when running ASP.NET Core 6.
/// This issue is because the default implementation of IViewCompilerProvider has changed, so the
/// AddRazorRuntimeCompilation extension can't remove the default and replace with the runtimeviewcompiler.
///
/// This method basically does the same as the ASP.NET Core 6 version of AddRazorRuntimeCompilation
/// https://github.com/dotnet/aspnetcore/blob/f7dc5e24af7f9692a1db66741954b90b42d84c3a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcCoreBuilderExtensions.cs#L71-L80
///
/// While running .NET5 this does nothing as the ImplementationType has another FullName, and this is handled by the .NET5 version of AddRazorRuntimeCompilation
/// </remarks>
private static void FixForDotnet6Preview1(IServiceCollection services)
{
var compilerProvider = services.FirstOrDefault(f =>
f.ServiceType == typeof(IViewCompilerProvider) &&
f.ImplementationType?.Assembly == typeof(IViewCompilerProvider).Assembly &&
f.ImplementationType.FullName == "Microsoft.AspNetCore.Mvc.Razor.Compilation.DefaultViewCompiler");
if (compilerProvider != null)
{
services.Remove(compilerProvider);
}
}
/// <summary>
/// Add runtime minifier support for Umbraco
/// </summary>
public static IUmbracoBuilder AddRuntimeMinifier(this IUmbracoBuilder builder)
2020-11-19 09:06:04 +00:00
{
// Add custom ISmidgeFileProvider to include the additional App_Plugins location
// to load assets from.
builder.Services.AddSingleton<ISmidgeFileProvider>(f =>
{
IWebHostEnvironment hostEnv = f.GetRequiredService<IWebHostEnvironment>();
return new SmidgeFileProvider(
hostEnv.WebRootFileProvider,
new GlobPatternFilterFileProvider(
hostEnv.ContentRootFileProvider,
// only include js or css files within App_Plugins
new[] { "/App_Plugins/**/*.js", "/App_Plugins/**/*.css" }));
});
builder.Services.AddUnique<ICacheBuster, UmbracoSmidgeConfigCacheBuster>();
builder.Services.AddSmidge(builder.Config.GetSection(Constants.Configuration.ConfigRuntimeMinification));
// Replace the Smidge request helper, in order to discourage the use of brotli since it's super slow
builder.Services.AddUnique<IRequestHelper, SmidgeRequestHelper>();
2020-11-19 09:06:04 +00:00
builder.Services.AddSmidgeNuglify();
builder.Services.AddSmidgeInMemory(false); // it will be enabled based on config/cachebuster
builder.Services.AddUnique<IRuntimeMinifier, SmidgeRuntimeMinifier>();
builder.Services.AddSingleton<SmidgeHelperAccessor>();
builder.Services.AddTransient<IPreProcessor, SmidgeNuglifyJs>();
builder.Services.ConfigureOptions<SmidgeOptionsSetup>();
2020-11-19 09:06:04 +00:00
return builder;
}
/// <summary>
/// Adds all web based services required for Umbraco to run
/// </summary>
2020-11-19 09:06:04 +00:00
public static IUmbracoBuilder AddWebComponents(this IUmbracoBuilder builder)
{
2020-11-24 09:22:38 +00:00
// Add service session
// This can be overwritten by the user by adding their own call to AddSession
// since the last call of AddSession take precedence
builder.Services.AddSession(options =>
{
options.Cookie.Name = "UMB_SESSION";
options.Cookie.HttpOnly = true;
});
builder.Services.ConfigureOptions<UmbracoMvcConfigureOptions>();
builder.Services.ConfigureOptions<UmbracoRequestLocalizationOptions>();
2020-11-19 09:06:04 +00:00
builder.Services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, UmbracoApiBehaviorApplicationModelProvider>());
builder.Services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, BackOfficeApplicationModelProvider>());
builder.Services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, VirtualPageApplicationModelProvider>());
Implements Public Access in netcore (#10137) * Getting new netcore PublicAccessChecker in place * Adds full test coverage for PublicAccessChecker * remove PublicAccessComposer * adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller * Implements the required methods on IMemberManager, removes old migrated code * Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops * adds note * adds note * Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling. * Changes name to IUmbracoEndpointBuilder * adds note * Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect * fixing build * Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware. * adds note * removes unused filter, fixes build * fixes WebPath and tests * Looks up entities in one query * remove usings * Fix test, remove stylesheet * Set status code before we write to response to avoid error * Ensures that users and members are validated when logging in. Shares more code between users and members. * Fixes RepositoryCacheKeys to ensure the keys are normalized * oops didn't mean to commit this * Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy * bah, far out this keeps getting recommitted. sorry Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-20 15:11:45 +10:00
builder.AddUmbracoImageSharp();
// AspNetCore specific services
builder.Services.AddUnique<IRequestAccessor, AspNetCoreRequestAccessor>();
builder.AddNotificationHandler<UmbracoRequestBeginNotification, AspNetCoreRequestAccessor>();
// Password hasher
builder.Services.AddUnique<IPasswordHasher, AspNetCorePasswordHasher>();
builder.Services.AddUnique<Cms.Core.Web.ICookieManager, AspNetCoreCookieManager>();
builder.Services.AddTransient<IIpResolver, AspNetCoreIpResolver>();
builder.Services.AddUnique<IUserAgentProvider, AspNetCoreUserAgentProvider>();
builder.Services.AddMultipleUnique<ISessionIdResolver, ISessionManager, AspNetCoreSessionManager>();
builder.Services.AddUnique<IMarchal, AspNetCoreMarchal>();
builder.Services.AddUnique<IProfilerHtml, WebProfilerHtml>();
builder.Services.AddUnique<IMacroRenderer, MacroRenderer>();
builder.Services.AddSingleton<PartialViewMacroEngine>();
// register the umbraco context factory
builder.Services.AddUnique<IUmbracoContextFactory, UmbracoContextFactory>();
builder.Services.AddUnique<IBackOfficeSecurityAccessor, BackOfficeSecurityAccessor>();
var umbracoApiControllerTypes = builder.TypeLoader.GetUmbracoApiControllers().ToList();
2022-03-29 13:44:21 +02:00
builder.WithCollectionBuilder<UmbracoApiControllerTypeCollectionBuilder>()?
.Add(umbracoApiControllerTypes);
builder.Services.AddSingleton<UmbracoRequestLoggingMiddleware>();
builder.Services.AddSingleton<PreviewAuthenticationMiddleware>();
builder.Services.AddSingleton<UmbracoRequestMiddleware>();
builder.Services.AddSingleton<BootFailedMiddleware>();
builder.Services.AddSingleton<UmbracoJsonModelBinder>();
builder.Services.AddUnique<ITemplateRenderer, TemplateRenderer>();
builder.Services.AddUnique<IPublicAccessChecker, PublicAccessChecker>();
builder.Services.AddSingleton<ContentModelBinder>();
builder.Services.AddSingleton<IUmbracoHelperAccessor, UmbracoHelperAccessor>();
builder.Services.AddSingleton<IScopedServiceProvider, ScopedServiceProvider>();
builder.Services.AddScoped<UmbracoHelper>();
builder.Services.AddScoped<IBackOfficeSecurity, BackOfficeSecurity>();
builder.AddHttpClients();
2020-11-19 09:06:04 +00:00
return builder;
}
// TODO: Does this need to exist and/or be public?
2020-11-19 09:06:04 +00:00
public static IUmbracoBuilder AddWebServer(this IUmbracoBuilder builder)
{
// TODO: We need to figure out why this is needed and fix those endpoints to not need them, we don't want to change global things
2020-11-19 09:06:04 +00:00
// If using Kestrel: https://stackoverflow.com/a/55196057
builder.Services.Configure<KestrelServerOptions>(options =>
{
2020-11-19 09:06:04 +00:00
options.AllowSynchronousIO = true;
});
2020-11-19 09:06:04 +00:00
builder.Services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
return builder;
}
2020-11-20 12:24:16 +00:00
2020-11-24 09:22:38 +00:00
private static IProfiler GetWebProfiler(IConfiguration config)
{
var isDebug = config.GetValue<bool>($"{Cms.Core.Constants.Configuration.ConfigHosting}:Debug");
2020-11-24 09:22:38 +00:00
// create and start asap to profile boot
if (!isDebug)
{
// should let it be null, that's how MiniProfiler is meant to work,
// but our own IProfiler expects an instance so let's get one
return new NoopProfiler();
2020-11-24 09:22:38 +00:00
}
var webProfiler = new WebProfiler();
webProfiler.StartBoot();
return webProfiler;
}
/// <summary>
/// HACK: returns an AspNetCoreHostingEnvironment that doesn't monitor changes to configuration.<br/>
/// We require this to create a TypeLoader during ConfigureServices.<br/>
/// Instances returned from this method shouldn't be registered in the service collection.
/// </summary>
private static IHostingEnvironment GetTemporaryHostingEnvironment(IWebHostEnvironment webHostEnvironment, IConfiguration config)
{
var hostingSettings = config.GetSection(Cms.Core.Constants.Configuration.ConfigHosting).Get<HostingSettings>() ?? new HostingSettings();
2020-11-24 09:22:38 +00:00
var wrappedHostingSettings = new OptionsMonitorAdapter<HostingSettings>(hostingSettings);
var webRoutingSettings = config.GetSection(Cms.Core.Constants.Configuration.ConfigWebRouting).Get<WebRoutingSettings>() ?? new WebRoutingSettings();
var wrappedWebRoutingSettings = new OptionsMonitorAdapter<WebRoutingSettings>(webRoutingSettings);
Examine 2.0 integration (#10241) * Init commit for examine 2.0 work, most old umb examine tests working, probably a lot that doesn't * Gets Umbraco Examine tests passing and makes some sense out of them, fixes some underlying issues. * Large refactor, remove TaskHelper, rename Notifications to be consistent, Gets all examine/lucene indexes building and startup ordered in the correct way, removes old files, creates new IUmbracoIndexingHandler for abstracting out all index operations for umbraco data, abstracts out IIndexRebuilder, Fixes Stack overflow with LiveModelsProvider and loading assemblies, ports some changes from v8 for startup handling with cold boots, refactors out LastSyncedFileManager * fix up issues with rebuilding and management dashboard. * removes old files, removes NetworkHelper, fixes LastSyncedFileManager implementation to ensure the machine name is used, fix up logging with cold boot state. * Makes MainDom safer to use and makes PublishedSnapshotService lazily register with MainDom * lazily acquire application id (fix unit tests) * Fixes resource casing and missing test file * Ensures caches when requiring internal services for PublishedSnapshotService, UseNuCache is a separate call, shouldn't be buried in AddWebComponents, was also causing issues in integration tests since nucache was being used for the Id2Key service. * For UmbracoTestServerTestBase enable nucache services * Fixing tests * Fix another test * Fixes tests, use TestHostingEnvironment, make Tests.Common use net5, remove old Lucene.Net.Contrib ref. * Fixes up some review notes * Fixes issue with doubly registering PublishedSnapshotService meanig there could be 2x instances of it * Checks for parseexception when executing the query * Use application root instead of duplicating functionality. * Added Examine project to netcore only solution file * Fixed casing issue with LazyLoad, that is not lowercase. * uses cancellationToken instead of bool flag, fixes always reading lastId from the LastSyncedFileManager, fixes RecurringHostedServiceBase so that there isn't an overlapping thread for the same task type * Fix tests * remove legacy test project from solution file * Fix test Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-05-18 18:31:38 +10:00
return new AspNetCoreHostingEnvironment(
wrappedHostingSettings,
wrappedWebRoutingSettings,
webHostEnvironment);
2020-11-24 09:22:38 +00:00
}
}
}