diff --git a/src/Umbraco.Core/Standalone/ServiceContextManager.cs b/src/Umbraco.Core/Standalone/ServiceContextManager.cs deleted file mode 100644 index e86a904439..0000000000 --- a/src/Umbraco.Core/Standalone/ServiceContextManager.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Diagnostics; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.Events; -using Umbraco.Core.Logging; -using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.Mappers; -using Umbraco.Core.Persistence.SqlSyntax; -using Umbraco.Core.Persistence.UnitOfWork; -using Umbraco.Core.Publishing; -using Umbraco.Core.Services; - -namespace Umbraco.Core.Standalone -{ - internal class ServiceContextManager : IDisposable - { - private readonly string _connectionString; - private readonly string _providerName; - private readonly ILogger _logger; - private readonly ISqlSyntaxProvider _syntaxProvider; - private ServiceContext _serviceContext; - private readonly StandaloneCoreApplication _application; - - public ServiceContextManager(string connectionString, string providerName, string baseDirectory, ILogger logger, ISqlSyntaxProvider syntaxProvider) - { - _connectionString = connectionString; - _providerName = providerName; - _logger = logger; - _syntaxProvider = syntaxProvider; - - Trace.WriteLine("ServiceContextManager-Current AppDomain: " + AppDomain.CurrentDomain.FriendlyName); - Trace.WriteLine("ServiceContextManager-Current AppDomain: " + AppDomain.CurrentDomain.BaseDirectory); - - //var webAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("umbraco")); - //if (webAssembly != null && examineEventHandlerToRemove == null) - //{ - // var examineEventType = webAssembly.GetType("Umbraco.Web.Search.ExamineEvents"); - // examineEventHandlerToRemove = examineEventType; - //} - - _application = StandaloneCoreApplication.GetApplication(baseDirectory); - - var examineEventHandlerToRemove = Type.GetType("Umbraco.Web.Search.ExamineEvents, umbraco"); - if (examineEventHandlerToRemove != null) - _application.WithoutApplicationEventHandler(examineEventHandlerToRemove); - - _application.Start(); - } - - public ServiceContext Services - { - get - { - if (_serviceContext == null) - { - var cacheHelper = new CacheHelper( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - //we have no request based cache when running standalone - new NullCacheProvider()); - - var dbFactory = new DefaultDatabaseFactory(_connectionString, _providerName, _logger); - var dbContext = new DatabaseContext(dbFactory, _logger, _syntaxProvider, _providerName); - Database.Mapper = new PetaPocoMapper(); - _serviceContext = new ServiceContext( - new RepositoryFactory(cacheHelper, _logger, dbContext.SqlSyntax, UmbracoConfig.For.UmbracoSettings()), - new PetaPocoUnitOfWorkProvider(dbFactory), - new FileUnitOfWorkProvider(), - new PublishingStrategy(), - cacheHelper, - new DebugDiagnosticsLogger(), - new TransientMessagesFactory()); - - //initialize the DatabaseContext - dbContext.Initialize(_providerName); - } - - return _serviceContext; - } - } - - public void Dispose() - { - ((IDisposable)ApplicationContext.Current).Dispose(); - _application.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Standalone/StandaloneCoreApplication.cs b/src/Umbraco.Core/Standalone/StandaloneCoreApplication.cs deleted file mode 100644 index c22a648478..0000000000 --- a/src/Umbraco.Core/Standalone/StandaloneCoreApplication.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Umbraco.Core.Standalone -{ - internal class StandaloneCoreApplication : UmbracoApplicationBase - { - /// - /// Initializes a new instance of the class. - /// - protected StandaloneCoreApplication(string baseDirectory) - { - _baseDirectory = baseDirectory; - } - - /// - /// Provides the application boot manager. - /// - /// An application boot manager. - protected override IBootManager GetBootManager() - { - return new StandaloneCoreBootManager(this, _handlersToAdd, _handlersToRemove, _baseDirectory); - } - - #region Application - - private readonly string _baseDirectory; - private static StandaloneCoreApplication _application; - private static bool _started; - private static readonly object AppLock = new object(); - - /// - /// Gets the instance of the standalone Umbraco application. - /// - public static StandaloneCoreApplication GetApplication(string baseDirectory) - { - lock (AppLock) - { - return _application ?? (_application = new StandaloneCoreApplication(baseDirectory)); - } - } - - /// - /// Starts the application. - /// - public void Start() - { - lock (AppLock) - { - if (_started) - throw new InvalidOperationException("Application has already started."); - Application_Start(this, EventArgs.Empty); - _started = true; - } - } - - #endregion - - #region IApplicationEventHandler management - - private readonly List _handlersToAdd = new List(); - private readonly List _handlersToRemove = new List(); - - /// - /// Associates an type with the application. - /// - /// The type to associate. - /// The application. - /// Types implementing from within - /// an executable are not automatically discovered by Umbraco and have to be - /// explicitely associated with the application using this method. - public StandaloneCoreApplication WithApplicationEventHandler() - where T : IApplicationEventHandler - { - _handlersToAdd.Add(typeof(T)); - return this; - } - - /// - /// Dissociates an type from the application. - /// - /// The type to dissociate. - /// The application. - public StandaloneCoreApplication WithoutApplicationEventHandler() - where T : IApplicationEventHandler - { - _handlersToRemove.Add(typeof(T)); - return this; - } - - /// - /// Associates an type with the application. - /// - /// The type to associate. - /// The application. - /// Types implementing from within - /// an executable are not automatically discovered by Umbraco and have to be - /// explicitely associated with the application using this method. - public StandaloneCoreApplication WithApplicationEventHandler(Type type) - { - if (type.Implements() == false) - throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type"); - _handlersToAdd.Add(type); - return this; - } - - /// - /// Dissociates an type from the application. - /// - /// The type to dissociate. - /// The application. - public StandaloneCoreApplication WithoutApplicationEventHandler(Type type) - { - if (type.Implements() == false) - throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type"); - _handlersToRemove.Add(type); - return this; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Standalone/StandaloneCoreBootManager.cs b/src/Umbraco.Core/Standalone/StandaloneCoreBootManager.cs deleted file mode 100644 index 84c73f95b7..0000000000 --- a/src/Umbraco.Core/Standalone/StandaloneCoreBootManager.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using Umbraco.Core.ObjectResolution; -using Umbraco.Core.Persistence.Mappers; -using umbraco.interfaces; - -namespace Umbraco.Core.Standalone -{ - internal class StandaloneCoreBootManager : CoreBootManager - { - private readonly IEnumerable _handlersToAdd; - private readonly IEnumerable _handlersToRemove; - private readonly string _baseDirectory; - - public StandaloneCoreBootManager(UmbracoApplicationBase umbracoApplication, IEnumerable handlersToAdd, IEnumerable handlersToRemove, string baseDirectory) - : base(umbracoApplication) - { - _handlersToAdd = handlersToAdd; - _handlersToRemove = handlersToRemove; - _baseDirectory = baseDirectory; - - base.InitializeApplicationRootPath(_baseDirectory); - - // this is only here to ensure references to the assemblies needed for - // the DataTypesResolver otherwise they won't be loaded into the AppDomain. - var interfacesAssemblyName = typeof(IDataType).Assembly.FullName; - } - - protected override void InitializeApplicationEventsResolver() - { - base.InitializeApplicationEventsResolver(); - - foreach (var type in _handlersToAdd) - ApplicationEventsResolver.Current.AddType(type); - - foreach (var type in _handlersToRemove) - ApplicationEventsResolver.Current.RemoveType(type); - } - - protected override void InitializeResolvers() - { - base.InitializeResolvers(); - - //Mappers are not resolved, which could be because of a known TypeMapper issue - /*MappingResolver.Reset(); - MappingResolver.Current = new MappingResolver( - () => - new List - { - typeof (ContentMapper), - typeof (ContentTypeMapper), - typeof (MediaMapper), - typeof (MediaTypeMapper), - typeof (DataTypeDefinitionMapper), - typeof (UmbracoEntityMapper) - });*/ - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Web/Standalone/PowershellAssemblyResolver.cs b/src/Umbraco.Web/Standalone/PowershellAssemblyResolver.cs deleted file mode 100644 index 63dd2ff252..0000000000 --- a/src/Umbraco.Web/Standalone/PowershellAssemblyResolver.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - -namespace Umbraco.Web.Standalone -{ - internal static class PowershellAssemblyResolver - { - private static readonly Dictionary Assemblies; - private static readonly object Locko = new object(); - - static PowershellAssemblyResolver() - { - var comparer = StringComparer.CurrentCultureIgnoreCase; - Assemblies = new Dictionary(comparer); - AppDomain.CurrentDomain.AssemblyResolve += ResolveHandler; - } - - public static void AddAssemblyLocation(string path) - { - if (string.IsNullOrWhiteSpace(path)) - throw new ArgumentException("Arg is null or empty.", "path"); - - lock (Locko) - { - var name = Path.GetFileNameWithoutExtension(path); - Assemblies.Add(name, path); - } - } - - private static Assembly ResolveHandler(object sender, ResolveEventArgs args) - { - var assemblyName = new AssemblyName(args.Name); - string assemblyFile; - return Assemblies.TryGetValue(assemblyName.Name, out assemblyFile) - ? Assembly.LoadFrom(assemblyFile) - : null; - } - } -} diff --git a/src/Umbraco.Web/Standalone/ServiceContextManager.cs b/src/Umbraco.Web/Standalone/ServiceContextManager.cs deleted file mode 100644 index 2795f3b486..0000000000 --- a/src/Umbraco.Web/Standalone/ServiceContextManager.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Diagnostics; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.Events; -using Umbraco.Core.Logging; -using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.Mappers; -using Umbraco.Core.Persistence.SqlSyntax; -using Umbraco.Core.Persistence.UnitOfWork; -using Umbraco.Core.Publishing; -using Umbraco.Core.Services; - -namespace Umbraco.Web.Standalone -{ - //TODO: Why does this exist? there's the same thing in the Core proj - - internal class ServiceContextManager : IDisposable - { - private readonly string _connectionString; - private readonly string _providerName; - private readonly ILogger _logger; - private readonly ISqlSyntaxProvider _syntaxProvider; - private ServiceContext _serviceContext; - private readonly StandaloneApplication _application; - - public ServiceContextManager(string connectionString, string providerName, string baseDirectory, ILogger logger, ISqlSyntaxProvider syntaxProvider) - { - _connectionString = connectionString; - _providerName = providerName; - _logger = logger; - _syntaxProvider = syntaxProvider; - - Trace.WriteLine("Current AppDomain: " + AppDomain.CurrentDomain.FriendlyName); - Trace.WriteLine("Current AppDomain: " + AppDomain.CurrentDomain.BaseDirectory); - - _application = StandaloneApplication.GetApplication(baseDirectory); - _application.Start(); - } - - public ServiceContext Services - { - get - { - if (_serviceContext == null) - { - var cacheHelper = new CacheHelper( - //SD: Not sure if this is correct? Should we be using HttpRuntime.Cache here since this is for 'Web' ? - // just not quite sure what this standalone stuff is. - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - //SD: Not sure if this is correct? Should we be using request cache here since this is for 'Web' ? - // just not quite sure what this standalone stuff is. - new NullCacheProvider()); - - var dbFactory = new DefaultDatabaseFactory(_connectionString, _providerName, _logger); - var dbContext = new DatabaseContext(dbFactory, _logger, _syntaxProvider, _providerName); - Database.Mapper = new PetaPocoMapper(); - _serviceContext = new ServiceContext( - new RepositoryFactory(cacheHelper, _logger, dbContext.SqlSyntax, UmbracoConfig.For.UmbracoSettings()), - new PetaPocoUnitOfWorkProvider(dbFactory), - new FileUnitOfWorkProvider(), - new PublishingStrategy(), - cacheHelper, - new DebugDiagnosticsLogger(), - new TransientMessagesFactory()); - - //initialize the DatabaseContext - dbContext.Initialize(_providerName); - } - - return _serviceContext; - } - } - - public void Dispose() - { - ((IDisposable)ApplicationContext.Current).Dispose(); - _application.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Web/Standalone/StandaloneApplication.cs b/src/Umbraco.Web/Standalone/StandaloneApplication.cs deleted file mode 100644 index e490684dc7..0000000000 --- a/src/Umbraco.Web/Standalone/StandaloneApplication.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Umbraco.Core; -using Umbraco.Core.ObjectResolution; - -namespace Umbraco.Web.Standalone -{ - /// - /// An application standalone applications. - /// - internal class StandaloneApplication : UmbracoApplicationBase - { - /// - /// Initializes a new instance of the class. - /// - protected StandaloneApplication(string baseDirectory) - { - _baseDirectory = baseDirectory; - } - - /// - /// Provides the application boot manager. - /// - /// An application boot manager. - protected override IBootManager GetBootManager() - { - return new StandaloneBootManager(this, _handlersToAdd, _handlersToRemove, _baseDirectory); - } - - #region Application - - private static StandaloneApplication _application; - private readonly string _baseDirectory; - private static bool _started; - private static readonly object AppLock = new object(); - - /// - /// Gets the instance of the standalone Umbraco application. - /// - public static StandaloneApplication GetApplication(string baseDirectory) - { - lock (AppLock) - { - return _application ?? (_application = new StandaloneApplication(baseDirectory)); - } - } - - /// - /// Starts the application. - /// - public void Start(bool noerr = false) - { - lock (AppLock) - { - if (_started) - { - if (noerr) return; - throw new InvalidOperationException("Application has already started."); - } - try - { - Application_Start(this, EventArgs.Empty); - } - catch - { - TerminateInternal(); - throw; - } - _started = true; - } - } - - public void Terminate(bool noerr = false) - { - lock (AppLock) - { - if (_started == false) - { - if (noerr) return; - throw new InvalidOperationException("Application has already been terminated."); - } - - TerminateInternal(); - } - } - - private void TerminateInternal() - { - if (ApplicationContext.Current != null) - { - ApplicationContext.Current.DisposeIfDisposable(); // should reset resolution, clear caches & resolvers... - ApplicationContext.Current = null; - } - if (UmbracoContext.Current != null) - { - UmbracoContext.Current.DisposeIfDisposable(); // dunno - UmbracoContext.Current = null; - } - _started = false; - _application = null; - } - - #endregion - - #region IApplicationEventHandler management - - private readonly List _handlersToAdd = new List(); - private readonly List _handlersToRemove = new List(); - - /// - /// Associates an type with the application. - /// - /// The type to associate. - /// The application. - /// Types implementing from within - /// an executable are not automatically discovered by Umbraco and have to be - /// explicitely associated with the application using this method. - public StandaloneApplication WithApplicationEventHandler() - where T : IApplicationEventHandler - { - _handlersToAdd.Add(typeof(T)); - return this; - } - - /// - /// Dissociates an type from the application. - /// - /// The type to dissociate. - /// The application. - public StandaloneApplication WithoutApplicationEventHandler() - where T : IApplicationEventHandler - { - _handlersToRemove.Add(typeof(T)); - return this; - } - - /// - /// Associates an type with the application. - /// - /// The type to associate. - /// The application. - /// Types implementing from within - /// an executable are not automatically discovered by Umbraco and have to be - /// explicitely associated with the application using this method. - public StandaloneApplication WithApplicationEventHandler(Type type) - { - if (type.Implements() == false) - throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type"); - _handlersToAdd.Add(type); - return this; - } - - /// - /// Dissociates an type from the application. - /// - /// The type to dissociate. - /// The application. - public StandaloneApplication WithoutApplicationEventHandler(Type type) - { - if (type.Implements() == false) - throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type"); - _handlersToRemove.Add(type); - return this; - } - - #endregion - - #region Shortcuts to contexts - - /// - /// Gets the current . - /// - /// This is a shortcut for scripts to be able to do $app.ApplicationContext. - public ApplicationContext ApplicationContext { get { return ApplicationContext.Current; } } - - /// - /// Gets the current . - /// - /// This is a shortcut for scripts to be able to do $app.UmbracoContext. - public UmbracoContext UmbracoContext { get { return UmbracoContext.Current; } } - - #endregion - } -} diff --git a/src/Umbraco.Web/Standalone/StandaloneBootManager.cs b/src/Umbraco.Web/Standalone/StandaloneBootManager.cs deleted file mode 100644 index b06135d522..0000000000 --- a/src/Umbraco.Web/Standalone/StandaloneBootManager.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Umbraco.Core; -using Umbraco.Core.Logging; -using Umbraco.Core.ObjectResolution; -using Umbraco.Web.PublishedCache; -using Umbraco.Web.Routing; -using Umbraco.Web.Security; -using umbraco.interfaces; - -namespace Umbraco.Web.Standalone -{ - /// - /// A boot manager for use in standalone applications. - /// - internal class StandaloneBootManager : CoreBootManager - { - // TODO - // this is highly experimental and probably not complete - not for production usage! - // also, could we inherit from WebBootManager? - - private readonly IEnumerable _handlersToAdd; - private readonly IEnumerable _handlersToRemove; - private readonly string _baseDirectory; - - public StandaloneBootManager(UmbracoApplicationBase umbracoApplication, IEnumerable handlersToAdd, IEnumerable handlersToRemove, string baseDirectory) - : base(umbracoApplication) - { - _handlersToAdd = handlersToAdd; - _handlersToRemove = handlersToRemove; - _baseDirectory = baseDirectory; - - base.InitializeApplicationRootPath(_baseDirectory); - - // this is only here to ensure references to the assemblies needed for - // the DataTypesResolver otherwise they won't be loaded into the AppDomain. - var interfacesAssemblyName = typeof(IDataType).Assembly.FullName; - - // TODO there's also that one... but we don't use it in standalone? - //using umbraco.editorControls; - //var editorControlsAssemblyName = typeof(uploadField).Assembly.FullName; - } - - protected override void InitializeApplicationEventsResolver() - { - base.InitializeApplicationEventsResolver(); - foreach (var type in _handlersToAdd) - ApplicationEventsResolver.Current.AddType(type); - foreach (var type in _handlersToRemove) - ApplicationEventsResolver.Current.RemoveType(type); - } - - protected override void InitializeResolvers() - { - base.InitializeResolvers(); - - var caches = new PublishedCaches( - new PublishedCache.XmlPublishedCache.PublishedContentCache(), - new PublishedCache.XmlPublishedCache.PublishedMediaCache(ApplicationContext.Current)); - - PublishedCachesResolver.Current = new PublishedCachesResolver(caches); - - UrlProviderResolver.Current = new UrlProviderResolver(ServiceProvider, LoggerResolver.Current.Logger, typeof(DefaultUrlProvider)); - SiteDomainHelperResolver.Current = new SiteDomainHelperResolver(new SiteDomainHelper()); - - ContentLastChanceFinderResolver.Current = new ContentLastChanceFinderResolver(); - ContentFinderResolver.Current = new ContentFinderResolver( - ServiceProvider, LoggerResolver.Current.Logger, - typeof (ContentFinderByPageIdQuery), - typeof (ContentFinderByNiceUrl), - typeof (ContentFinderByIdPath), - typeof (ContentFinderByNotFoundHandlers) - ); - - // TODO what else? - } - - // can't create context before resolution is frozen! - protected override void FreezeResolution() - { - base.FreezeResolution(); - - var httpContext = new StandaloneHttpContext(); - UmbracoContext.EnsureContext(httpContext, ApplicationContext.Current, new WebSecurity(httpContext, ApplicationContext.Current), false, false); - } - } -} diff --git a/src/Umbraco.Web/Standalone/StandaloneHttpContext.cs b/src/Umbraco.Web/Standalone/StandaloneHttpContext.cs deleted file mode 100644 index dec95dd372..0000000000 --- a/src/Umbraco.Web/Standalone/StandaloneHttpContext.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Web; - -namespace Umbraco.Web.Standalone -{ - /// - /// An Http context for use in standalone applications. - /// - internal class StandaloneHttpContext : HttpContextBase - { - private readonly string _url; - private readonly HttpSessionStateBase _session = new StandaloneHttpSessionState(); - private readonly HttpResponseBase _response; - private readonly HttpRequestBase _request = new StandaloneHttpRequest(); - private readonly TextWriter _writer = new StringWriter(); - private readonly IDictionary _items = new Dictionary(); - - public StandaloneHttpContext() - { - _response = new HttpResponseWrapper(new HttpResponse(_writer)); - } - - public StandaloneHttpContext(string url) - : this() - { - if (url == null) throw new ArgumentNullException("url"); - _url = url; - _request = new HttpRequestWrapper(new HttpRequest("", _url, "")); - } - - - // what else should we implement here? - - public override IDictionary Items - { - get { return _items; } - } - - public override HttpSessionStateBase Session - { - get { return _session; } - } - - public override HttpRequestBase Request - { - get { return _request; } - } - - public override HttpResponseBase Response - { - get { return _response; } - } - - } - - internal class StandaloneHttpSessionState : HttpSessionStateBase - { - - } - - internal class StandaloneHttpRequest : HttpRequestBase - { - public override Uri Url - { - get { return new Uri("http://localhost"); } - } - } -} diff --git a/src/Umbraco.Web/Standalone/WriteableConfigSystem.cs b/src/Umbraco.Web/Standalone/WriteableConfigSystem.cs deleted file mode 100644 index 2438256cce..0000000000 --- a/src/Umbraco.Web/Standalone/WriteableConfigSystem.cs +++ /dev/null @@ -1,262 +0,0 @@ -using System; -using System.Collections.Specialized; -using System.Configuration; -using System.Configuration.Internal; -using System.Reflection; -using System.Threading; - -namespace Umbraco.Web.Standalone -{ - // see http://stackoverflow.com/questions/15653621/how-to-update-add-modify-delete-keys-in-appsettings-section-of-web-config-at-r - // see http://www.codeproject.com/Articles/69364/Override-Configuration-Manager - - internal sealed class WriteableConfigSystem : IInternalConfigSystem - { - private static readonly ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(); - private static WriteableConfigSystem _installed; - private static IInternalConfigSystem _clientConfigSystem; - private object _appsettings; - private object _connectionStrings; - private static object _sInitStateOrig; - private static object _sConfigSystemOrig; - - public static bool Installed - { - get - { - try - { - RwLock.EnterReadLock(); - return _installed != null; - } - finally - { - RwLock.ExitReadLock(); - } - } - } - - /// - /// Re-initializes the ConfigurationManager, allowing us to merge in the settings from Core.Config - /// - public static void Install() - { - try - { - RwLock.EnterWriteLock(); - - if (_installed != null) - throw new InvalidOperationException("ConfigSystem is already installed."); - - FieldInfo[] fiStateValues = null; - var tInitState = typeof(ConfigurationManager).GetNestedType("InitState", BindingFlags.NonPublic); - - if (tInitState != null) - fiStateValues = tInitState.GetFields(); - // 0: NotStarted - // 1: Started - // 2: Usable - // 3: Completed - - var fiInit = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static); - var fiSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static); - - if (fiInit != null && fiSystem != null && fiStateValues != null) - { - _sInitStateOrig = fiInit.GetValue(null); - _sConfigSystemOrig = fiSystem.GetValue(null); - fiInit.SetValue(null, fiStateValues[1].GetValue(null)); // set to Started - fiSystem.SetValue(null, null); // clear current config system - } - - _installed = new WriteableConfigSystem(); - - var configFactoryType = Type.GetType("System.Configuration.Internal.InternalConfigSettingsFactory, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true); - var configSettingsFactory = (IInternalConfigSettingsFactory)Activator.CreateInstance(configFactoryType, true); - // just does ConfigurationManager.SetConfigurationSystem(_installed, false); - // 'false' turns initState to 2 ie usable (vs 3 ie completed) - configSettingsFactory.SetConfigurationSystem(_installed, false); - - // note: prob. don't need the factory... see how we uninstall... - - var clientConfigSystemType = Type.GetType("System.Configuration.ClientConfigurationSystem, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true); - _clientConfigSystem = (IInternalConfigSystem)Activator.CreateInstance(clientConfigSystemType, true); - } - finally - { - RwLock.ExitWriteLock(); - } - } - - public static void Uninstall() - { - try - { - RwLock.EnterWriteLock(); - - if (_installed == null) - throw new InvalidOperationException("ConfigSystem is not installed."); - - FieldInfo[] fiStateValues = null; - var tInitState = typeof(ConfigurationManager).GetNestedType("InitState", BindingFlags.NonPublic); - - if (tInitState != null) - fiStateValues = tInitState.GetFields(); - - var fiInit = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static); - var fiSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static); - - if (fiInit != null && fiSystem != null && fiStateValues != null) - { - // reset - the hard way - fiInit.SetValue(null, _sInitStateOrig); - fiSystem.SetValue(null, _sConfigSystemOrig); - } - - _installed = null; - _clientConfigSystem = null; - } - finally - { - RwLock.ExitWriteLock(); - } - } - - public static void Reset() - { - try - { - RwLock.EnterWriteLock(); - - if (_installed == null) - throw new InvalidOperationException("ConfigSystem is not installed."); - - _installed._appsettings = null; - _installed._connectionStrings = null; - } - finally - { - RwLock.ExitWriteLock(); - } - } - - #region IInternalConfigSystem Members - - public object GetSection(string configKey) - { - // get the section from the default location (web.config or app.config) - var section = _clientConfigSystem.GetSection(configKey); - - try - { - RwLock.EnterReadLock(); - - switch (configKey) - { - case "appSettings": - // Return cached version if exists - if (_appsettings != null) - return _appsettings; - - // create a new collection because the underlying collection is read-only - var cfg = new NameValueCollection(); - - // If an AppSettings section exists in Web.config, read and add values from it - var nvSection = section as NameValueCollection; - if (nvSection != null) - { - var localSettings = nvSection; - foreach (string key in localSettings) - cfg.Add(key, localSettings[key]); - } - - //// -------------------------------------------------------------------- - //// Here I read and decrypt keys and add them to secureConfig dictionary - //// To test assume the following line is a key stored in secure sotrage. - ////secureConfig = SecureConfig.LoadConfig(); - //secureConfig.Add("ACriticalKey", "VeryCriticalValue"); - //// -------------------------------------------------------------------- - //foreach (KeyValuePair item in secureConfig) - //{ - // if (cfg.AllKeys.Contains(item.Key)) - // { - // cfg[item.Key] = item.Value; - // } - // else - // { - // cfg.Add(item.Key, item.Value); - // } - //} - //// -------------------------------------------------------------------- - - - // Cach the settings for future use - - _appsettings = cfg; - // return the merged version of the items from secure storage and appsettings - section = _appsettings; - break; - - case "connectionStrings": - // Return cached version if exists - if (_connectionStrings != null) - return _connectionStrings; - - // create a new collection because the underlying collection is read-only - var connectionStringsSection = new ConnectionStringsSection(); - - // copy the existing connection strings into the new collection - foreach ( - ConnectionStringSettings connectionStringSetting in - ((ConnectionStringsSection)section).ConnectionStrings) - connectionStringsSection.ConnectionStrings.Add(connectionStringSetting); - - // -------------------------------------------------------------------- - // Again Load connection strings from secure storage and merge like below - // connectionStringsSection.ConnectionStrings.Add(connectionStringSetting); - // -------------------------------------------------------------------- - - // Cach the settings for future use - _connectionStrings = connectionStringsSection; - // return the merged version of the items from secure storage and appsettings - section = _connectionStrings; - break; - } - } - finally - { - RwLock.ExitReadLock(); - } - - return section; - } - - public void RefreshConfig(string sectionName) - { - try - { - RwLock.EnterWriteLock(); - - if (sectionName == "appSettings") - { - _appsettings = null; - } - - if (sectionName == "connectionStrings") - { - _connectionStrings = null; - } - } - finally - { - RwLock.ExitWriteLock(); - } - - _clientConfigSystem.RefreshConfig(sectionName); - } - - public bool SupportsUserConfig { get { return _clientConfigSystem.SupportsUserConfig; } } - - #endregion - } -} \ No newline at end of file