Removes standalone classes, we can replace these with what we've got in the LinqPad provider

This commit is contained in:
Shannon
2015-07-29 15:07:55 +02:00
parent 3f19878c18
commit 0e992f897f
9 changed files with 0 additions and 1004 deletions

View File

@@ -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();
}
}
}

View File

@@ -1,122 +0,0 @@
using System;
using System.Collections.Generic;
namespace Umbraco.Core.Standalone
{
internal class StandaloneCoreApplication : UmbracoApplicationBase
{
/// <summary>
/// Initializes a new instance of the <see cref="StandaloneCoreApplication"/> class.
/// </summary>
protected StandaloneCoreApplication(string baseDirectory)
{
_baseDirectory = baseDirectory;
}
/// <summary>
/// Provides the application boot manager.
/// </summary>
/// <returns>An application boot manager.</returns>
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();
/// <summary>
/// Gets the instance of the standalone Umbraco application.
/// </summary>
public static StandaloneCoreApplication GetApplication(string baseDirectory)
{
lock (AppLock)
{
return _application ?? (_application = new StandaloneCoreApplication(baseDirectory));
}
}
/// <summary>
/// Starts the application.
/// </summary>
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<Type> _handlersToAdd = new List<Type>();
private readonly List<Type> _handlersToRemove = new List<Type>();
/// <summary>
/// Associates an <see cref="IApplicationEventHandler"/> type with the application.
/// </summary>
/// <typeparam name="T">The type to associate.</typeparam>
/// <returns>The application.</returns>
/// <remarks>Types implementing <see cref="IApplicationEventHandler"/> from within
/// an executable are not automatically discovered by Umbraco and have to be
/// explicitely associated with the application using this method.</remarks>
public StandaloneCoreApplication WithApplicationEventHandler<T>()
where T : IApplicationEventHandler
{
_handlersToAdd.Add(typeof(T));
return this;
}
/// <summary>
/// Dissociates an <see cref="IApplicationEventHandler"/> type from the application.
/// </summary>
/// <typeparam name="T">The type to dissociate.</typeparam>
/// <returns>The application.</returns>
public StandaloneCoreApplication WithoutApplicationEventHandler<T>()
where T : IApplicationEventHandler
{
_handlersToRemove.Add(typeof(T));
return this;
}
/// <summary>
/// Associates an <see cref="IApplicationEventHandler"/> type with the application.
/// </summary>
/// <param name="type">The type to associate.</param>
/// <returns>The application.</returns>
/// <remarks>Types implementing <see cref="IApplicationEventHandler"/> from within
/// an executable are not automatically discovered by Umbraco and have to be
/// explicitely associated with the application using this method.</remarks>
public StandaloneCoreApplication WithApplicationEventHandler(Type type)
{
if (type.Implements<IApplicationEventHandler>() == false)
throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type");
_handlersToAdd.Add(type);
return this;
}
/// <summary>
/// Dissociates an <see cref="IApplicationEventHandler"/> type from the application.
/// </summary>
/// <param name="type">The type to dissociate.</param>
/// <returns>The application.</returns>
public StandaloneCoreApplication WithoutApplicationEventHandler(Type type)
{
if (type.Implements<IApplicationEventHandler>() == false)
throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type");
_handlersToRemove.Add(type);
return this;
}
#endregion
}
}

View File

@@ -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<Type> _handlersToAdd;
private readonly IEnumerable<Type> _handlersToRemove;
private readonly string _baseDirectory;
public StandaloneCoreBootManager(UmbracoApplicationBase umbracoApplication, IEnumerable<Type> handlersToAdd, IEnumerable<Type> 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<Type>
{
typeof (ContentMapper),
typeof (ContentTypeMapper),
typeof (MediaMapper),
typeof (MediaTypeMapper),
typeof (DataTypeDefinitionMapper),
typeof (UmbracoEntityMapper)
});*/
}
}
}

View File

@@ -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<string, string> Assemblies;
private static readonly object Locko = new object();
static PowershellAssemblyResolver()
{
var comparer = StringComparer.CurrentCultureIgnoreCase;
Assemblies = new Dictionary<string,string>(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;
}
}
}

View File

@@ -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();
}
}
}

View File

@@ -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
{
/// <summary>
/// An application standalone applications.
/// </summary>
internal class StandaloneApplication : UmbracoApplicationBase
{
/// <summary>
/// Initializes a new instance of the <see cref="StandaloneApplication"/> class.
/// </summary>
protected StandaloneApplication(string baseDirectory)
{
_baseDirectory = baseDirectory;
}
/// <summary>
/// Provides the application boot manager.
/// </summary>
/// <returns>An application boot manager.</returns>
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();
/// <summary>
/// Gets the instance of the standalone Umbraco application.
/// </summary>
public static StandaloneApplication GetApplication(string baseDirectory)
{
lock (AppLock)
{
return _application ?? (_application = new StandaloneApplication(baseDirectory));
}
}
/// <summary>
/// Starts the application.
/// </summary>
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<Type> _handlersToAdd = new List<Type>();
private readonly List<Type> _handlersToRemove = new List<Type>();
/// <summary>
/// Associates an <see cref="IApplicationEventHandler"/> type with the application.
/// </summary>
/// <typeparam name="T">The type to associate.</typeparam>
/// <returns>The application.</returns>
/// <remarks>Types implementing <see cref="IApplicationEventHandler"/> from within
/// an executable are not automatically discovered by Umbraco and have to be
/// explicitely associated with the application using this method.</remarks>
public StandaloneApplication WithApplicationEventHandler<T>()
where T : IApplicationEventHandler
{
_handlersToAdd.Add(typeof(T));
return this;
}
/// <summary>
/// Dissociates an <see cref="IApplicationEventHandler"/> type from the application.
/// </summary>
/// <typeparam name="T">The type to dissociate.</typeparam>
/// <returns>The application.</returns>
public StandaloneApplication WithoutApplicationEventHandler<T>()
where T : IApplicationEventHandler
{
_handlersToRemove.Add(typeof(T));
return this;
}
/// <summary>
/// Associates an <see cref="IApplicationEventHandler"/> type with the application.
/// </summary>
/// <param name="type">The type to associate.</param>
/// <returns>The application.</returns>
/// <remarks>Types implementing <see cref="IApplicationEventHandler"/> from within
/// an executable are not automatically discovered by Umbraco and have to be
/// explicitely associated with the application using this method.</remarks>
public StandaloneApplication WithApplicationEventHandler(Type type)
{
if (type.Implements<IApplicationEventHandler>() == false)
throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type");
_handlersToAdd.Add(type);
return this;
}
/// <summary>
/// Dissociates an <see cref="IApplicationEventHandler"/> type from the application.
/// </summary>
/// <param name="type">The type to dissociate.</param>
/// <returns>The application.</returns>
public StandaloneApplication WithoutApplicationEventHandler(Type type)
{
if (type.Implements<IApplicationEventHandler>() == false)
throw new ArgumentException("Type does not implement IApplicationEventHandler.", "type");
_handlersToRemove.Add(type);
return this;
}
#endregion
#region Shortcuts to contexts
/// <summary>
/// Gets the current <see cref="ApplicationContext"/>.
/// </summary>
/// <remarks>This is a shortcut for scripts to be able to do <c>$app.ApplicationContext</c>.</remarks>
public ApplicationContext ApplicationContext { get { return ApplicationContext.Current; } }
/// <summary>
/// Gets the current <see cref="UmbracoContext"/>.
/// </summary>
/// <remarks>This is a shortcut for scripts to be able to do <c>$app.UmbracoContext</c>.</remarks>
public UmbracoContext UmbracoContext { get { return UmbracoContext.Current; } }
#endregion
}
}

View File

@@ -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
{
/// <summary>
/// A boot manager for use in standalone applications.
/// </summary>
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<Type> _handlersToAdd;
private readonly IEnumerable<Type> _handlersToRemove;
private readonly string _baseDirectory;
public StandaloneBootManager(UmbracoApplicationBase umbracoApplication, IEnumerable<Type> handlersToAdd, IEnumerable<Type> 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);
}
}
}

View File

@@ -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
{
/// <summary>
/// An Http context for use in standalone applications.
/// </summary>
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<string, object>();
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"); }
}
}
}

View File

@@ -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();
}
}
}
/// <summary>
/// Re-initializes the ConfigurationManager, allowing us to merge in the settings from Core.Config
/// </summary>
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<string, string> 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
}
}