Moved discovery of loggers and weather providers to MEF. Also added support for third-party image processors, also discovered through MEF.

This commit is contained in:
LukePulverenti Luke Pulverenti luke pulverenti
2012-09-18 15:33:57 -04:00
parent 01a25c48a0
commit 8b7effd6ff
23 changed files with 370 additions and 334 deletions

View File

@@ -1,81 +0,0 @@
using System;
using System.Drawing;
namespace MediaBrowser.Common.Drawing
{
public static class DrawingUtils
{
/// <summary>
/// Resizes a set of dimensions
/// </summary>
public static Size Resize(int currentWidth, int currentHeight, int? width, int? height, int? maxWidth, int? maxHeight)
{
return Resize(new Size(currentWidth, currentHeight), width, height, maxWidth, maxHeight);
}
/// <summary>
/// Resizes a set of dimensions
/// </summary>
/// <param name="size">The original size object</param>
/// <param name="width">A new fixed width, if desired</param>
/// <param name="height">A new fixed neight, if desired</param>
/// <param name="maxWidth">A max fixed width, if desired</param>
/// <param name="maxHeight">A max fixed height, if desired</param>
/// <returns>A new size object</returns>
public static Size Resize(Size size, int? width, int? height, int? maxWidth, int? maxHeight)
{
decimal newWidth = size.Width;
decimal newHeight = size.Height;
if (width.HasValue && height.HasValue)
{
newWidth = width.Value;
newHeight = height.Value;
}
else if (height.HasValue)
{
newWidth = GetNewWidth(newHeight, newWidth, height.Value);
newHeight = height.Value;
}
else if (width.HasValue)
{
newHeight = GetNewHeight(newHeight, newWidth, width.Value);
newWidth = width.Value;
}
if (maxHeight.HasValue && maxHeight < newHeight)
{
newWidth = GetNewWidth(newHeight, newWidth, maxHeight.Value);
newHeight = maxHeight.Value;
}
if (maxWidth.HasValue && maxWidth < newWidth)
{
newHeight = GetNewHeight(newHeight, newWidth, maxWidth.Value);
newWidth = maxWidth.Value;
}
return new Size(Convert.ToInt32(newWidth), Convert.ToInt32(newHeight));
}
private static decimal GetNewWidth(decimal currentHeight, decimal currentWidth, int newHeight)
{
decimal scaleFactor = newHeight;
scaleFactor /= currentHeight;
scaleFactor *= currentWidth;
return scaleFactor;
}
private static decimal GetNewHeight(decimal currentHeight, decimal currentWidth, int newWidth)
{
decimal scaleFactor = newWidth;
scaleFactor /= currentWidth;
scaleFactor *= currentHeight;
return scaleFactor;
}
}
}

View File

@@ -10,7 +10,6 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -72,6 +71,12 @@ namespace MediaBrowser.Common.Kernel
[ImportMany(typeof(BaseHandler))]
private IEnumerable<BaseHandler> HttpHandlers { get; set; }
/// <summary>
/// Gets the list of currently registered Loggers
/// </summary>
[ImportMany(typeof(BaseLogger))]
public IEnumerable<BaseLogger> Loggers { get; set; }
/// <summary>
/// Both the Ui and server will have a built-in HttpServer.
/// People will inevitably want remote control apps so it's needed in the Ui too.
@@ -83,6 +88,8 @@ namespace MediaBrowser.Common.Kernel
/// </summary>
private IDisposable HttpListener { get; set; }
private CompositionContainer CompositionContainer { get; set; }
protected virtual string HttpServerUrlPrefix
{
get
@@ -101,13 +108,13 @@ namespace MediaBrowser.Common.Kernel
/// </summary>
public async Task Init(IProgress<TaskProgress> progress)
{
Logger.Kernel = this;
// Performs initializations that only occur once
InitializeInternal(progress);
// Performs initializations that can be reloaded at anytime
await Reload(progress).ConfigureAwait(false);
ReportProgress(progress, "Loading Complete");
}
/// <summary>
@@ -117,8 +124,6 @@ namespace MediaBrowser.Common.Kernel
{
ApplicationPaths = new TApplicationPathsType();
ReloadLogger();
ReportProgress(progress, "Loading Configuration");
ReloadConfiguration();
@@ -136,6 +141,8 @@ namespace MediaBrowser.Common.Kernel
await ReloadInternal(progress).ConfigureAwait(false);
OnReloadCompleted(progress);
ReportProgress(progress, "Kernel.Reload Complete");
}
/// <summary>
@@ -151,23 +158,6 @@ namespace MediaBrowser.Common.Kernel
}).ConfigureAwait(false);
}
/// <summary>
/// Disposes the current logger and creates a new one
/// </summary>
private void ReloadLogger()
{
DisposeLogger();
DateTime now = DateTime.Now;
string logFilePath = Path.Combine(ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
Trace.Listeners.Add(new TextWriterTraceListener(logFilePath));
Trace.AutoFlush = true;
Logger.LoggerInstance = new TraceLogger();
}
/// <summary>
/// Uses MEF to locate plugins
/// Subclasses can use this to locate types within plugins
@@ -176,14 +166,13 @@ namespace MediaBrowser.Common.Kernel
{
DisposeComposableParts();
var container = GetCompositionContainer(includeCurrentAssembly: true);
CompositionContainer = GetCompositionContainer(includeCurrentAssembly: true);
container.ComposeParts(this);
CompositionContainer.ComposeParts(this);
OnComposablePartsLoaded();
container.Catalog.Dispose();
container.Dispose();
CompositionContainer.Catalog.Dispose();
}
/// <summary>
@@ -198,8 +187,7 @@ namespace MediaBrowser.Common.Kernel
var catalog = new AggregateCatalog(pluginAssemblies.Select(a => new AssemblyCatalog(a)));
// Include composable parts in the Common assembly
// Uncomment this if it's ever needed
//catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
if (includeCurrentAssembly)
{
@@ -215,8 +203,13 @@ namespace MediaBrowser.Common.Kernel
/// </summary>
protected virtual void OnComposablePartsLoaded()
{
foreach (var logger in Loggers)
{
logger.Initialize(this);
}
// Start-up each plugin
foreach (BasePlugin plugin in Plugins)
foreach (var plugin in Plugins)
{
plugin.Initialize(this);
}
@@ -230,17 +223,16 @@ namespace MediaBrowser.Common.Kernel
//Configuration information for anything other than server-specific configuration will have to come via the API... -ebr
// Deserialize config
if (!File.Exists(ApplicationPaths.SystemConfigurationFilePath))
// Use try/catch to avoid the extra file system lookup using File.Exists
try
{
Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
}
catch (FileNotFoundException)
{
Configuration = new TConfigurationType();
XmlSerializer.SerializeToFile(Configuration, ApplicationPaths.SystemConfigurationFilePath);
}
else
{
Configuration = XmlSerializer.DeserializeFromFile<TConfigurationType>(ApplicationPaths.SystemConfigurationFilePath);
}
Logger.LoggerInstance.LogSeverity = Configuration.EnableDebugLevelLogging ? LogSeverity.Debug : LogSeverity.Info;
}
/// <summary>
@@ -275,11 +267,9 @@ namespace MediaBrowser.Common.Kernel
{
Logger.LogInfo("Beginning Kernel.Dispose");
DisposeComposableParts();
DisposeHttpServer();
DisposeLogger();
DisposeComposableParts();
}
/// <summary>
@@ -287,22 +277,9 @@ namespace MediaBrowser.Common.Kernel
/// </summary>
protected virtual void DisposeComposableParts()
{
DisposePlugins();
}
/// <summary>
/// Disposes all plugins
/// </summary>
private void DisposePlugins()
{
if (Plugins != null)
if (CompositionContainer != null)
{
Logger.LogInfo("Disposing Plugins");
foreach (BasePlugin plugin in Plugins)
{
plugin.Dispose();
}
CompositionContainer.Dispose();
}
}
@@ -324,21 +301,6 @@ namespace MediaBrowser.Common.Kernel
}
}
/// <summary>
/// Disposes the current Logger instance
/// </summary>
private void DisposeLogger()
{
Trace.Listeners.Clear();
if (Logger.LoggerInstance != null)
{
Logger.LogInfo("Disposing Logger");
Logger.LoggerInstance.Dispose();
}
}
/// <summary>
/// Gets the current application version
/// </summary>
@@ -354,10 +316,7 @@ namespace MediaBrowser.Common.Kernel
{
progress.Report(new TaskProgress { Description = message });
if (Logger.LoggerInstance != null)
{
Logger.LogInfo(message);
}
Logger.LogInfo(message);
}
BaseApplicationPaths IKernel.ApplicationPaths
@@ -373,6 +332,7 @@ namespace MediaBrowser.Common.Kernel
Task Init(IProgress<TaskProgress> progress);
Task Reload(IProgress<TaskProgress> progress);
IEnumerable<BaseLogger> Loggers { get; }
void Dispose();
}
}

View File

@@ -1,92 +1,16 @@
using System;
using System.Text;
using System.Threading;
using MediaBrowser.Common.Kernel;
using System;
namespace MediaBrowser.Common.Logging
{
public abstract class BaseLogger : IDisposable
{
public LogSeverity LogSeverity { get; set; }
public void LogInfo(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Info, paramList);
}
public void LogDebugInfo(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Debug, paramList);
}
public void LogError(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Error, paramList);
}
public void LogException(string message, Exception exception, params object[] paramList)
{
var builder = new StringBuilder();
if (exception != null)
{
builder.AppendFormat("Exception. Type={0} Msg={1} StackTrace={3}{2}",
exception.GetType().FullName,
exception.Message,
exception.StackTrace,
Environment.NewLine);
}
message = FormatMessage(message, paramList);
LogError(string.Format("{0} ( {1} )", message, builder));
}
public void LogWarning(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Warning, paramList);
}
private string FormatMessage(string message, params object[] paramList)
{
if (paramList != null)
{
for (int i = 0; i < paramList.Length; i++)
{
message = message.Replace("{" + i + "}", paramList[i].ToString());
}
}
return message;
}
private void LogEntry(string message, LogSeverity severity, params object[] paramList)
{
if (severity < LogSeverity) return;
message = FormatMessage(message, paramList);
Thread currentThread = Thread.CurrentThread;
var row = new LogRow
{
Severity = severity,
Message = message,
ThreadId = currentThread.ManagedThreadId,
ThreadName = currentThread.Name,
Time = DateTime.Now
};
LogEntry(row);
}
protected virtual void Flush()
{
}
public abstract void Initialize(IKernel kernel);
public abstract void LogEntry(LogRow row);
public virtual void Dispose()
{
Logger.LogInfo("Disposing " + GetType().Name);
}
protected abstract void LogEntry(LogRow row);
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
namespace MediaBrowser.Common.Logging
{
@@ -11,4 +11,4 @@ namespace MediaBrowser.Common.Logging
Warning = 4,
Error = 8
}
}
}

View File

@@ -1,24 +1,28 @@
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using MediaBrowser.Common.Kernel;
namespace MediaBrowser.Common.Logging
{
public static class Logger
{
public static BaseLogger LoggerInstance { get; set; }
internal static IKernel Kernel { get; set; }
public static void LogInfo(string message, params object[] paramList)
{
LoggerInstance.LogInfo(message, paramList);
LogEntry(message, LogSeverity.Info, paramList);
}
public static void LogDebugInfo(string message, params object[] paramList)
{
LoggerInstance.LogDebugInfo(message, paramList);
LogEntry(message, LogSeverity.Debug, paramList);
}
public static void LogError(string message, params object[] paramList)
{
LoggerInstance.LogError(message, paramList);
LogEntry(message, LogSeverity.Error, paramList);
}
public static void LogException(Exception ex, params object[] paramList)
@@ -28,12 +32,62 @@ namespace MediaBrowser.Common.Logging
public static void LogException(string message, Exception ex, params object[] paramList)
{
LoggerInstance.LogException(message, ex, paramList);
var builder = new StringBuilder();
if (ex != null)
{
builder.AppendFormat("Exception. Type={0} Msg={1} StackTrace={3}{2}",
ex.GetType().FullName,
ex.Message,
ex.StackTrace,
Environment.NewLine);
}
message = FormatMessage(message, paramList);
LogError(string.Format("{0} ( {1} )", message, builder));
}
public static void LogWarning(string message, params object[] paramList)
{
LoggerInstance.LogWarning(message, paramList);
LogEntry(message, LogSeverity.Warning, paramList);
}
private static void LogEntry(string message, LogSeverity severity, params object[] paramList)
{
message = FormatMessage(message, paramList);
Thread currentThread = Thread.CurrentThread;
var row = new LogRow
{
Severity = severity,
Message = message,
ThreadId = currentThread.ManagedThreadId,
ThreadName = currentThread.Name,
Time = DateTime.Now
};
if (Kernel.Loggers != null)
{
foreach (var logger in Kernel.Loggers)
{
logger.LogEntry(row);
}
}
}
private static string FormatMessage(string message, params object[] paramList)
{
if (paramList != null)
{
for (int i = 0; i < paramList.Length; i++)
{
message = message.Replace("{" + i + "}", paramList[i].ToString());
}
}
return message;
}
}
}

View File

@@ -1,37 +0,0 @@
using System;
using System.IO;
using System.Text;
namespace MediaBrowser.Common.Logging
{
/// <summary>
/// Provides a Logger that can write to any Stream
/// </summary>
public class StreamLogger : BaseLogger
{
private Stream Stream { get; set; }
public StreamLogger(Stream stream)
: base()
{
Stream = stream;
}
protected override void LogEntry(LogRow row)
{
byte[] bytes = new UTF8Encoding().GetBytes(row.ToString() + Environment.NewLine);
lock (Stream)
{
Stream.Write(bytes, 0, bytes.Length);
Stream.Flush();
}
}
public override void Dispose()
{
base.Dispose();
Stream.Dispose();
}
}
}

View File

@@ -0,0 +1,38 @@
using MediaBrowser.Common.Kernel;
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
namespace MediaBrowser.Common.Logging
{
[Export(typeof(BaseLogger))]
public class TraceFileLogger : BaseLogger
{
private TraceListener Listener { get; set; }
public override void Initialize(IKernel kernel)
{
DateTime now = DateTime.Now;
string logFilePath = Path.Combine(kernel.ApplicationPaths.LogDirectoryPath, "log-" + now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
Listener = new TextWriterTraceListener(logFilePath);
Trace.Listeners.Add(Listener);
Trace.AutoFlush = true;
}
public override void Dispose()
{
base.Dispose();
Trace.Listeners.Remove(Listener);
Listener.Dispose();
}
public override void LogEntry(LogRow row)
{
Trace.WriteLine(row.ToString());
}
}
}

View File

@@ -1,12 +0,0 @@
using System.Diagnostics;
namespace MediaBrowser.Common.Logging
{
public class TraceLogger : BaseLogger
{
protected override void LogEntry(LogRow row)
{
Trace.WriteLine(row.ToString());
}
}
}

View File

@@ -83,8 +83,9 @@
<ItemGroup>
<Compile Include="Events\GenericEventArgs.cs" />
<Compile Include="Kernel\BaseApplicationPaths.cs" />
<Compile Include="Drawing\DrawingUtils.cs" />
<Compile Include="Logging\TraceLogger.cs" />
<Compile Include="Logging\BaseLogger.cs" />
<Compile Include="Logging\LogSeverity.cs" />
<Compile Include="Logging\TraceFileLogger.cs" />
<Compile Include="Net\Handlers\StaticFileHandler.cs" />
<Compile Include="Net\MimeTypes.cs" />
<Compile Include="Plugins\BaseTheme.cs" />
@@ -96,11 +97,8 @@
<Compile Include="Serialization\JsonSerializer.cs" />
<Compile Include="Kernel\BaseKernel.cs" />
<Compile Include="Kernel\KernelContext.cs" />
<Compile Include="Logging\BaseLogger.cs" />
<Compile Include="Logging\Logger.cs" />
<Compile Include="Logging\LogRow.cs" />
<Compile Include="Logging\LogSeverity.cs" />
<Compile Include="Logging\StreamLogger.cs" />
<Compile Include="Net\Handlers\BaseEmbeddedResourceHandler.cs" />
<Compile Include="Net\Handlers\BaseHandler.cs" />
<Compile Include="Net\Handlers\BaseSerializationHandler.cs" />

View File

@@ -1,4 +1,5 @@
using MediaBrowser.Common.Kernel;
using MediaBrowser.Common.Logging;
using MediaBrowser.Common.Serialization;
using MediaBrowser.Model.Plugins;
using System;
@@ -200,6 +201,8 @@ namespace MediaBrowser.Common.Plugins
/// </summary>
public void Dispose()
{
Logger.LogInfo("Disposing {0} Plugin", Name);
if (Context == KernelContext.Server)
{
DisposeOnServer();

View File

@@ -64,10 +64,7 @@ namespace MediaBrowser.Common.UI
}
catch (Exception ex)
{
if (Logger.LoggerInstance != null)
{
Logger.LogException(ex);
}
Logger.LogException(ex);
MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
splash.Close();