GIT: perform LF normalization
This commit is contained in:
+16
-16
@@ -1,17 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<configSections>
|
||||
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
|
||||
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
|
||||
</configSections>
|
||||
<entityFramework>
|
||||
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
|
||||
<parameters>
|
||||
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
|
||||
</parameters>
|
||||
</defaultConnectionFactory>
|
||||
</entityFramework>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<configSections>
|
||||
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
|
||||
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
|
||||
</configSections>
|
||||
<entityFramework>
|
||||
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
|
||||
<parameters>
|
||||
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
|
||||
</parameters>
|
||||
</defaultConnectionFactory>
|
||||
</entityFramework>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
||||
@@ -1,43 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public abstract class LogBase
|
||||
{
|
||||
private Dictionary<int, Models.LogEventType> _EventTypes;
|
||||
|
||||
public LogBase()
|
||||
{
|
||||
// Cache Event Types
|
||||
_EventTypes = this.LoadEventTypes().ToDictionary(et => et.Id);
|
||||
}
|
||||
|
||||
public abstract int ModuleId { get; }
|
||||
public abstract string ModuleName { get; }
|
||||
public abstract string ModuleDescription { get; }
|
||||
protected abstract List<Models.LogEventType> LoadEventTypes();
|
||||
|
||||
public Dictionary<int, Models.LogEventType> EventTypes
|
||||
{
|
||||
get
|
||||
{
|
||||
return _EventTypes;
|
||||
}
|
||||
}
|
||||
protected void Log(int EventTypeId, params object[] Args)
|
||||
{
|
||||
LogContext.Current.Log(this.ModuleId, EventTypeId, Args);
|
||||
}
|
||||
public string LiveLogGroupName
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.ModuleName;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public abstract class LogBase
|
||||
{
|
||||
private Dictionary<int, Models.LogEventType> _EventTypes;
|
||||
|
||||
public LogBase()
|
||||
{
|
||||
// Cache Event Types
|
||||
_EventTypes = this.LoadEventTypes().ToDictionary(et => et.Id);
|
||||
}
|
||||
|
||||
public abstract int ModuleId { get; }
|
||||
public abstract string ModuleName { get; }
|
||||
public abstract string ModuleDescription { get; }
|
||||
protected abstract List<Models.LogEventType> LoadEventTypes();
|
||||
|
||||
public Dictionary<int, Models.LogEventType> EventTypes
|
||||
{
|
||||
get
|
||||
{
|
||||
return _EventTypes;
|
||||
}
|
||||
}
|
||||
protected void Log(int EventTypeId, params object[] Args)
|
||||
{
|
||||
LogContext.Current.Log(this.ModuleId, EventTypeId, Args);
|
||||
}
|
||||
public string LiveLogGroupName
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.ModuleName;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,314 +1,314 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Data.Repository;
|
||||
using System.IO;
|
||||
using System.Management;
|
||||
using System.Diagnostics;
|
||||
using System.Data.SqlServerCe;
|
||||
using System.Data.EntityClient;
|
||||
using System.Data.Entity;
|
||||
using Quartz;
|
||||
using Quartz.Impl;
|
||||
using Quartz.Impl.Triggers;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public class LogContext
|
||||
{
|
||||
public static Dictionary<int, LogBase> LogModules { get; private set; }
|
||||
private static object _LogModulesLock = new object();
|
||||
|
||||
private static LogContext _Current;
|
||||
private static object _CurrentLock = new Object();
|
||||
public static LogContext Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_CurrentLock)
|
||||
{
|
||||
if (_Current == null)
|
||||
throw new InvalidOperationException("Logging Context has not been Initialized");
|
||||
return _Current;
|
||||
}
|
||||
}
|
||||
private set
|
||||
{
|
||||
lock (_CurrentLock)
|
||||
{
|
||||
_Current = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitalizeModules()
|
||||
{
|
||||
if (LogModules == null)
|
||||
{
|
||||
lock (_LogModulesLock)
|
||||
{
|
||||
if (LogModules == null)
|
||||
{
|
||||
LogModules = new Dictionary<int, LogBase>();
|
||||
// Load all LogModules (Only from Disco Assemblies)
|
||||
var appDomain = AppDomain.CurrentDomain;
|
||||
|
||||
var logModuleTypes = (from a in appDomain.GetAssemblies()
|
||||
where !a.GlobalAssemblyCache && !a.IsDynamic && a.FullName.StartsWith("Disco.", StringComparison.InvariantCultureIgnoreCase)
|
||||
from type in a.GetTypes()
|
||||
where typeof(LogBase).IsAssignableFrom(type) && !type.IsAbstract
|
||||
select type);
|
||||
foreach (var logModuleType in logModuleTypes)
|
||||
{
|
||||
var instance = (LogBase)Activator.CreateInstance(logModuleType);
|
||||
LogModules[instance.ModuleId] = instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitalizeDatabase(Targets.LogPersistContext logDbContext)
|
||||
{
|
||||
// Add Modules
|
||||
var existingModules = logDbContext.Modules.Include("EventTypes").ToDictionary(m => m.Id);
|
||||
foreach (var module in LogModules)
|
||||
{
|
||||
// Update/Insert Module
|
||||
Models.LogModule dbModule;
|
||||
if (existingModules.TryGetValue(module.Key, out dbModule))
|
||||
{
|
||||
// Update
|
||||
if (dbModule.Name != module.Value.ModuleName)
|
||||
dbModule.Name = module.Value.ModuleName;
|
||||
if (dbModule.Description != module.Value.ModuleDescription)
|
||||
dbModule.Description = module.Value.ModuleDescription;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Insert
|
||||
dbModule = new Models.LogModule()
|
||||
{
|
||||
Id = module.Key,
|
||||
Name = module.Value.ModuleName,
|
||||
Description = module.Value.ModuleDescription
|
||||
};
|
||||
logDbContext.Modules.Add(dbModule);
|
||||
}
|
||||
// Update/Insert Event Types
|
||||
Dictionary<int, Models.LogEventType> existingEventTypes = (dbModule.EventTypes == null) ? new Dictionary<int, Models.LogEventType>() : dbModule.EventTypes.ToDictionary(et => et.Id);
|
||||
foreach (var eventType in module.Value.EventTypes)
|
||||
{
|
||||
Models.LogEventType dbEventType;
|
||||
if (existingEventTypes.TryGetValue(eventType.Key, out dbEventType))
|
||||
{
|
||||
// Update
|
||||
if (dbEventType.Name != eventType.Value.Name)
|
||||
dbEventType.Name = eventType.Value.Name;
|
||||
if (dbEventType.Severity != eventType.Value.Severity)
|
||||
dbEventType.Severity = eventType.Value.Severity;
|
||||
if (dbEventType.Format != eventType.Value.Format)
|
||||
dbEventType.Format = eventType.Value.Format;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Insert
|
||||
dbEventType = new Models.LogEventType()
|
||||
{
|
||||
Id = eventType.Key,
|
||||
ModuleId = module.Key,
|
||||
Name = eventType.Value.Name,
|
||||
Severity = eventType.Value.Severity,
|
||||
Format = eventType.Value.Format
|
||||
};
|
||||
logDbContext.EventTypes.Add(dbEventType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logDbContext.SaveChanges();
|
||||
}
|
||||
|
||||
public static string LogFileBasePath(DiscoDataContext DiscoContext)
|
||||
{
|
||||
var logDirectoryBase = Path.Combine(DiscoContext.DiscoConfiguration.DataStoreLocation, "Logs");
|
||||
// Create Directory Structure
|
||||
if (!Directory.Exists(logDirectoryBase))
|
||||
{
|
||||
Directory.CreateDirectory(logDirectoryBase);
|
||||
}
|
||||
// Ensure Logs are NTFS Compressed - TODO...
|
||||
//Utilities.CompressDirectory(logDirectory);
|
||||
// WMI - Doesn't Work for Network Folders...
|
||||
//var logDirectoryBaseInfo = new DirectoryInfo(logDirectoryBase);
|
||||
//if ((logDirectoryBaseInfo.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed)
|
||||
//{
|
||||
// var logDirectoryWmiPath = string.Format("Win32_Directory.Name=\"{0}\"", logDirectoryBase);
|
||||
// using (ManagementObject logDirectoryBaseMO = new ManagementObject(logDirectoryWmiPath))
|
||||
// {
|
||||
// ManagementBaseObject outParams = logDirectoryBaseMO.InvokeMethod("Compress", null, null);
|
||||
// Debug.WriteLine("LoggingContext.InitalizeCurrent: Compressing Log Folder; Result: " + outParams.Properties["ReturnValue"].Value.ToString());
|
||||
// }
|
||||
//}
|
||||
return logDirectoryBase;
|
||||
}
|
||||
|
||||
public static string LogFilePath(DiscoDataContext DiscoContext, DateTime Date, bool CreateDirectory = true)
|
||||
{
|
||||
var logDirectoryBase = LogFileBasePath(DiscoContext);
|
||||
var logDirectory = Path.Combine(logDirectoryBase, Date.Year.ToString());
|
||||
if (CreateDirectory && !Directory.Exists(logDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(logDirectory);
|
||||
}
|
||||
var logFileName = string.Format("DiscoLog_{0:yyy-MM-dd}.sdf", Date);
|
||||
return Path.Combine(logDirectory, logFileName);
|
||||
}
|
||||
|
||||
internal static void ReInitalize(DiscoDataContext DiscoContext)
|
||||
{
|
||||
lock (_CurrentLock)
|
||||
{
|
||||
var logPath = LogFilePath(DiscoContext, DateTime.Today);
|
||||
|
||||
//var connectionString = string.Format("Data Source=\"{0}\"", logPath);
|
||||
|
||||
SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder();
|
||||
sqlCeCSB.DataSource = logPath;
|
||||
var connectionString = sqlCeCSB.ToString();
|
||||
|
||||
// Ensure Database Exists
|
||||
if (!File.Exists(logPath))
|
||||
{
|
||||
// Create Database
|
||||
using (var context = new Targets.LogPersistContext(connectionString))
|
||||
{
|
||||
context.Database.CreateIfNotExists();
|
||||
}
|
||||
}
|
||||
|
||||
// Add Modules/Event Types
|
||||
InitalizeModules();
|
||||
using (var context = new Targets.LogPersistContext(connectionString))
|
||||
{
|
||||
InitalizeDatabase(context);
|
||||
}
|
||||
|
||||
// Create Current LogContext
|
||||
var currentLogContext = new LogContext(logPath, connectionString);
|
||||
_Current = currentLogContext;
|
||||
}
|
||||
SystemLog.LogLogInitialized(_Current.PersistantStorePath);
|
||||
try
|
||||
{
|
||||
// Get Yesterdays Log
|
||||
var yesterdaysLogPath = LogFilePath(DiscoContext, DateTime.Today.AddDays(-1), false);
|
||||
if (File.Exists(yesterdaysLogPath))
|
||||
{
|
||||
SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder();
|
||||
sqlCeCSB.DataSource = yesterdaysLogPath;
|
||||
var connectionString = sqlCeCSB.ToString();
|
||||
int logCount;
|
||||
using (var context = new Targets.LogPersistContext(connectionString))
|
||||
{
|
||||
logCount = context.Events.Where(e => !(e.ModuleId == 0 && e.EventTypeId == 100)).Count();
|
||||
if (logCount == 0)
|
||||
{
|
||||
// Delete (empty) Database
|
||||
context.Database.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SystemLog.LogError("Error occurred while investigating yesterdays log for deletion", ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
private static IScheduler _ReInitializeScheduler;
|
||||
public static void Initalize(DiscoDataContext DiscoContext, ISchedulerFactory SchedulerFactory)
|
||||
{
|
||||
ReInitalize(DiscoContext);
|
||||
|
||||
_ReInitializeScheduler = SchedulerFactory.GetScheduler();
|
||||
|
||||
var reInitalizeJobDetail = new JobDetailImpl("DiscoLogContextReinialize", typeof(LogReInitalizeJob));
|
||||
|
||||
// Simple Trigger - Issue with Day light savings
|
||||
//var reInitalizeTrigger = TriggerBuilder.Create()
|
||||
// .WithIdentity("DiscoLogContextReinializeTrigger")
|
||||
// .StartAt(DateBuilder.TomorrowAt(0,0,0))
|
||||
// .WithSchedule(SimpleScheduleBuilder.Create().WithIntervalInHours(24).RepeatForever())
|
||||
// .Build();
|
||||
// Use Cron Schedule instead
|
||||
var reInitalizeTrigger = TriggerBuilder.Create()
|
||||
.WithIdentity("DiscoLogContextReinializeTrigger")
|
||||
.StartNow()
|
||||
.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 0)) // Midnight
|
||||
.Build();
|
||||
|
||||
_ReInitializeScheduler.ScheduleJob(reInitalizeJobDetail, reInitalizeTrigger);
|
||||
}
|
||||
public static string LiveLogAllEventsGroupName
|
||||
{
|
||||
get
|
||||
{
|
||||
return Targets.LogLiveContext.LiveLogNameAll;
|
||||
}
|
||||
}
|
||||
|
||||
private LogContext(string PersistantStorePath, string PersistantStoreConnectionString)
|
||||
{
|
||||
this.PersistantStorePath = PersistantStorePath;
|
||||
this.PersistantStoreConnectionString = PersistantStoreConnectionString;
|
||||
}
|
||||
|
||||
public string PersistantStorePath { get; private set; }
|
||||
public string PersistantStoreConnectionString { get; private set; }
|
||||
|
||||
public void Log(int ModuleId, int EventTypeId, params object[] Args)
|
||||
{
|
||||
LogBase logModule;
|
||||
if (LogModules.TryGetValue(ModuleId, out logModule))
|
||||
{
|
||||
Models.LogEventType eventType;
|
||||
if (logModule.EventTypes.TryGetValue(EventTypeId, out eventType))
|
||||
{
|
||||
var eventTimestamp = DateTime.Now;
|
||||
if (eventType.UseLive)
|
||||
{
|
||||
Targets.LogLiveContext.Broadcast(logModule, eventType, eventTimestamp, Args);
|
||||
}
|
||||
if (eventType.UsePersist)
|
||||
{
|
||||
string args = null;
|
||||
if (Args != null && Args.Length > 0)
|
||||
{ //args = fastJSON.JSON.Instance.ToJSON(Args, false); // Old fastJSON Implementation
|
||||
args = JsonConvert.SerializeObject(Args);
|
||||
}
|
||||
using (var context = new Targets.LogPersistContext(PersistantStoreConnectionString))
|
||||
{
|
||||
var e = new Models.LogEvent()
|
||||
{
|
||||
Timestamp = eventTimestamp,
|
||||
ModuleId = logModule.ModuleId,
|
||||
EventTypeId = eventType.Id,
|
||||
Arguments = args
|
||||
};
|
||||
context.Events.Add(e);
|
||||
context.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException(string.Format("Unknown Log Event Type Called: {0} (for Module: {1})", EventTypeId, ModuleId));
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException(string.Format("Unknown Log Module Called: {0}", ModuleId));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Data.Repository;
|
||||
using System.IO;
|
||||
using System.Management;
|
||||
using System.Diagnostics;
|
||||
using System.Data.SqlServerCe;
|
||||
using System.Data.EntityClient;
|
||||
using System.Data.Entity;
|
||||
using Quartz;
|
||||
using Quartz.Impl;
|
||||
using Quartz.Impl.Triggers;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public class LogContext
|
||||
{
|
||||
public static Dictionary<int, LogBase> LogModules { get; private set; }
|
||||
private static object _LogModulesLock = new object();
|
||||
|
||||
private static LogContext _Current;
|
||||
private static object _CurrentLock = new Object();
|
||||
public static LogContext Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_CurrentLock)
|
||||
{
|
||||
if (_Current == null)
|
||||
throw new InvalidOperationException("Logging Context has not been Initialized");
|
||||
return _Current;
|
||||
}
|
||||
}
|
||||
private set
|
||||
{
|
||||
lock (_CurrentLock)
|
||||
{
|
||||
_Current = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitalizeModules()
|
||||
{
|
||||
if (LogModules == null)
|
||||
{
|
||||
lock (_LogModulesLock)
|
||||
{
|
||||
if (LogModules == null)
|
||||
{
|
||||
LogModules = new Dictionary<int, LogBase>();
|
||||
// Load all LogModules (Only from Disco Assemblies)
|
||||
var appDomain = AppDomain.CurrentDomain;
|
||||
|
||||
var logModuleTypes = (from a in appDomain.GetAssemblies()
|
||||
where !a.GlobalAssemblyCache && !a.IsDynamic && a.FullName.StartsWith("Disco.", StringComparison.InvariantCultureIgnoreCase)
|
||||
from type in a.GetTypes()
|
||||
where typeof(LogBase).IsAssignableFrom(type) && !type.IsAbstract
|
||||
select type);
|
||||
foreach (var logModuleType in logModuleTypes)
|
||||
{
|
||||
var instance = (LogBase)Activator.CreateInstance(logModuleType);
|
||||
LogModules[instance.ModuleId] = instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitalizeDatabase(Targets.LogPersistContext logDbContext)
|
||||
{
|
||||
// Add Modules
|
||||
var existingModules = logDbContext.Modules.Include("EventTypes").ToDictionary(m => m.Id);
|
||||
foreach (var module in LogModules)
|
||||
{
|
||||
// Update/Insert Module
|
||||
Models.LogModule dbModule;
|
||||
if (existingModules.TryGetValue(module.Key, out dbModule))
|
||||
{
|
||||
// Update
|
||||
if (dbModule.Name != module.Value.ModuleName)
|
||||
dbModule.Name = module.Value.ModuleName;
|
||||
if (dbModule.Description != module.Value.ModuleDescription)
|
||||
dbModule.Description = module.Value.ModuleDescription;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Insert
|
||||
dbModule = new Models.LogModule()
|
||||
{
|
||||
Id = module.Key,
|
||||
Name = module.Value.ModuleName,
|
||||
Description = module.Value.ModuleDescription
|
||||
};
|
||||
logDbContext.Modules.Add(dbModule);
|
||||
}
|
||||
// Update/Insert Event Types
|
||||
Dictionary<int, Models.LogEventType> existingEventTypes = (dbModule.EventTypes == null) ? new Dictionary<int, Models.LogEventType>() : dbModule.EventTypes.ToDictionary(et => et.Id);
|
||||
foreach (var eventType in module.Value.EventTypes)
|
||||
{
|
||||
Models.LogEventType dbEventType;
|
||||
if (existingEventTypes.TryGetValue(eventType.Key, out dbEventType))
|
||||
{
|
||||
// Update
|
||||
if (dbEventType.Name != eventType.Value.Name)
|
||||
dbEventType.Name = eventType.Value.Name;
|
||||
if (dbEventType.Severity != eventType.Value.Severity)
|
||||
dbEventType.Severity = eventType.Value.Severity;
|
||||
if (dbEventType.Format != eventType.Value.Format)
|
||||
dbEventType.Format = eventType.Value.Format;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Insert
|
||||
dbEventType = new Models.LogEventType()
|
||||
{
|
||||
Id = eventType.Key,
|
||||
ModuleId = module.Key,
|
||||
Name = eventType.Value.Name,
|
||||
Severity = eventType.Value.Severity,
|
||||
Format = eventType.Value.Format
|
||||
};
|
||||
logDbContext.EventTypes.Add(dbEventType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logDbContext.SaveChanges();
|
||||
}
|
||||
|
||||
public static string LogFileBasePath(DiscoDataContext DiscoContext)
|
||||
{
|
||||
var logDirectoryBase = Path.Combine(DiscoContext.DiscoConfiguration.DataStoreLocation, "Logs");
|
||||
// Create Directory Structure
|
||||
if (!Directory.Exists(logDirectoryBase))
|
||||
{
|
||||
Directory.CreateDirectory(logDirectoryBase);
|
||||
}
|
||||
// Ensure Logs are NTFS Compressed - TODO...
|
||||
//Utilities.CompressDirectory(logDirectory);
|
||||
// WMI - Doesn't Work for Network Folders...
|
||||
//var logDirectoryBaseInfo = new DirectoryInfo(logDirectoryBase);
|
||||
//if ((logDirectoryBaseInfo.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed)
|
||||
//{
|
||||
// var logDirectoryWmiPath = string.Format("Win32_Directory.Name=\"{0}\"", logDirectoryBase);
|
||||
// using (ManagementObject logDirectoryBaseMO = new ManagementObject(logDirectoryWmiPath))
|
||||
// {
|
||||
// ManagementBaseObject outParams = logDirectoryBaseMO.InvokeMethod("Compress", null, null);
|
||||
// Debug.WriteLine("LoggingContext.InitalizeCurrent: Compressing Log Folder; Result: " + outParams.Properties["ReturnValue"].Value.ToString());
|
||||
// }
|
||||
//}
|
||||
return logDirectoryBase;
|
||||
}
|
||||
|
||||
public static string LogFilePath(DiscoDataContext DiscoContext, DateTime Date, bool CreateDirectory = true)
|
||||
{
|
||||
var logDirectoryBase = LogFileBasePath(DiscoContext);
|
||||
var logDirectory = Path.Combine(logDirectoryBase, Date.Year.ToString());
|
||||
if (CreateDirectory && !Directory.Exists(logDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(logDirectory);
|
||||
}
|
||||
var logFileName = string.Format("DiscoLog_{0:yyy-MM-dd}.sdf", Date);
|
||||
return Path.Combine(logDirectory, logFileName);
|
||||
}
|
||||
|
||||
internal static void ReInitalize(DiscoDataContext DiscoContext)
|
||||
{
|
||||
lock (_CurrentLock)
|
||||
{
|
||||
var logPath = LogFilePath(DiscoContext, DateTime.Today);
|
||||
|
||||
//var connectionString = string.Format("Data Source=\"{0}\"", logPath);
|
||||
|
||||
SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder();
|
||||
sqlCeCSB.DataSource = logPath;
|
||||
var connectionString = sqlCeCSB.ToString();
|
||||
|
||||
// Ensure Database Exists
|
||||
if (!File.Exists(logPath))
|
||||
{
|
||||
// Create Database
|
||||
using (var context = new Targets.LogPersistContext(connectionString))
|
||||
{
|
||||
context.Database.CreateIfNotExists();
|
||||
}
|
||||
}
|
||||
|
||||
// Add Modules/Event Types
|
||||
InitalizeModules();
|
||||
using (var context = new Targets.LogPersistContext(connectionString))
|
||||
{
|
||||
InitalizeDatabase(context);
|
||||
}
|
||||
|
||||
// Create Current LogContext
|
||||
var currentLogContext = new LogContext(logPath, connectionString);
|
||||
_Current = currentLogContext;
|
||||
}
|
||||
SystemLog.LogLogInitialized(_Current.PersistantStorePath);
|
||||
try
|
||||
{
|
||||
// Get Yesterdays Log
|
||||
var yesterdaysLogPath = LogFilePath(DiscoContext, DateTime.Today.AddDays(-1), false);
|
||||
if (File.Exists(yesterdaysLogPath))
|
||||
{
|
||||
SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder();
|
||||
sqlCeCSB.DataSource = yesterdaysLogPath;
|
||||
var connectionString = sqlCeCSB.ToString();
|
||||
int logCount;
|
||||
using (var context = new Targets.LogPersistContext(connectionString))
|
||||
{
|
||||
logCount = context.Events.Where(e => !(e.ModuleId == 0 && e.EventTypeId == 100)).Count();
|
||||
if (logCount == 0)
|
||||
{
|
||||
// Delete (empty) Database
|
||||
context.Database.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SystemLog.LogError("Error occurred while investigating yesterdays log for deletion", ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
private static IScheduler _ReInitializeScheduler;
|
||||
public static void Initalize(DiscoDataContext DiscoContext, ISchedulerFactory SchedulerFactory)
|
||||
{
|
||||
ReInitalize(DiscoContext);
|
||||
|
||||
_ReInitializeScheduler = SchedulerFactory.GetScheduler();
|
||||
|
||||
var reInitalizeJobDetail = new JobDetailImpl("DiscoLogContextReinialize", typeof(LogReInitalizeJob));
|
||||
|
||||
// Simple Trigger - Issue with Day light savings
|
||||
//var reInitalizeTrigger = TriggerBuilder.Create()
|
||||
// .WithIdentity("DiscoLogContextReinializeTrigger")
|
||||
// .StartAt(DateBuilder.TomorrowAt(0,0,0))
|
||||
// .WithSchedule(SimpleScheduleBuilder.Create().WithIntervalInHours(24).RepeatForever())
|
||||
// .Build();
|
||||
// Use Cron Schedule instead
|
||||
var reInitalizeTrigger = TriggerBuilder.Create()
|
||||
.WithIdentity("DiscoLogContextReinializeTrigger")
|
||||
.StartNow()
|
||||
.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 0)) // Midnight
|
||||
.Build();
|
||||
|
||||
_ReInitializeScheduler.ScheduleJob(reInitalizeJobDetail, reInitalizeTrigger);
|
||||
}
|
||||
public static string LiveLogAllEventsGroupName
|
||||
{
|
||||
get
|
||||
{
|
||||
return Targets.LogLiveContext.LiveLogNameAll;
|
||||
}
|
||||
}
|
||||
|
||||
private LogContext(string PersistantStorePath, string PersistantStoreConnectionString)
|
||||
{
|
||||
this.PersistantStorePath = PersistantStorePath;
|
||||
this.PersistantStoreConnectionString = PersistantStoreConnectionString;
|
||||
}
|
||||
|
||||
public string PersistantStorePath { get; private set; }
|
||||
public string PersistantStoreConnectionString { get; private set; }
|
||||
|
||||
public void Log(int ModuleId, int EventTypeId, params object[] Args)
|
||||
{
|
||||
LogBase logModule;
|
||||
if (LogModules.TryGetValue(ModuleId, out logModule))
|
||||
{
|
||||
Models.LogEventType eventType;
|
||||
if (logModule.EventTypes.TryGetValue(EventTypeId, out eventType))
|
||||
{
|
||||
var eventTimestamp = DateTime.Now;
|
||||
if (eventType.UseLive)
|
||||
{
|
||||
Targets.LogLiveContext.Broadcast(logModule, eventType, eventTimestamp, Args);
|
||||
}
|
||||
if (eventType.UsePersist)
|
||||
{
|
||||
string args = null;
|
||||
if (Args != null && Args.Length > 0)
|
||||
{ //args = fastJSON.JSON.Instance.ToJSON(Args, false); // Old fastJSON Implementation
|
||||
args = JsonConvert.SerializeObject(Args);
|
||||
}
|
||||
using (var context = new Targets.LogPersistContext(PersistantStoreConnectionString))
|
||||
{
|
||||
var e = new Models.LogEvent()
|
||||
{
|
||||
Timestamp = eventTimestamp,
|
||||
ModuleId = logModule.ModuleId,
|
||||
EventTypeId = eventType.Id,
|
||||
Arguments = args
|
||||
};
|
||||
context.Events.Add(e);
|
||||
context.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException(string.Format("Unknown Log Event Type Called: {0} (for Module: {1})", EventTypeId, ModuleId));
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException(string.Format("Unknown Log Module Called: {0}", ModuleId));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Quartz;
|
||||
using Disco.Data.Repository;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
class LogReInitalizeJob : IJob
|
||||
{
|
||||
public void Execute(IJobExecutionContext context)
|
||||
{
|
||||
using (DiscoDataContext DiscoContext = new DiscoDataContext())
|
||||
{
|
||||
LogContext.ReInitalize(DiscoContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Quartz;
|
||||
using Disco.Data.Repository;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
class LogReInitalizeJob : IJob
|
||||
{
|
||||
public void Execute(IJobExecutionContext context)
|
||||
{
|
||||
using (DiscoDataContext DiscoContext = new DiscoDataContext())
|
||||
{
|
||||
LogContext.ReInitalize(DiscoContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
[Table("Events")]
|
||||
public class LogEvent
|
||||
{
|
||||
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
[Required]
|
||||
public int ModuleId { get; set; }
|
||||
[Required]
|
||||
public int EventTypeId { get; set; }
|
||||
[Required]
|
||||
public DateTime Timestamp { get; set; }
|
||||
public string Arguments { get; set; }
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
[Table("Events")]
|
||||
public class LogEvent
|
||||
{
|
||||
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
[Required]
|
||||
public int ModuleId { get; set; }
|
||||
[Required]
|
||||
public int EventTypeId { get; set; }
|
||||
[Required]
|
||||
public DateTime Timestamp { get; set; }
|
||||
public string Arguments { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
[Table("EventTypes")]
|
||||
public class LogEventType
|
||||
{
|
||||
[Required, Key, Column(Order=0), DatabaseGenerated(DatabaseGeneratedOption.None)]
|
||||
public int ModuleId { get; set; }
|
||||
[Required, Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.None)]
|
||||
public int Id { get; set; }
|
||||
[Required, MaxLength(200)]
|
||||
public string Name { get; set; }
|
||||
[Required]
|
||||
public int Severity { get; set; }
|
||||
[MaxLength(1024)]
|
||||
public string Format { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public bool UsePersist { get; set; }
|
||||
[NotMapped]
|
||||
public bool UseLive { get; set; }
|
||||
[NotMapped]
|
||||
public bool UseDisplay { get; set; }
|
||||
|
||||
[ForeignKey("ModuleId")]
|
||||
public LogModule Module { get; set; }
|
||||
|
||||
public enum Severities
|
||||
{
|
||||
Information = 0,
|
||||
Warning = 1,
|
||||
Error = 2
|
||||
}
|
||||
|
||||
public string FormatMessage(object[] Arguments)
|
||||
{
|
||||
|
||||
if (Arguments != null && Arguments.Length > 0)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Format))
|
||||
{
|
||||
return string.Format(Format, Arguments);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Arguments
|
||||
.Select(v => v == null ? string.Empty : v.ToString())
|
||||
.Aggregate((a, b) => a + ", " + (b == null ? string.Empty : b));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Format))
|
||||
{
|
||||
return Format;
|
||||
}
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
[Table("EventTypes")]
|
||||
public class LogEventType
|
||||
{
|
||||
[Required, Key, Column(Order=0), DatabaseGenerated(DatabaseGeneratedOption.None)]
|
||||
public int ModuleId { get; set; }
|
||||
[Required, Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.None)]
|
||||
public int Id { get; set; }
|
||||
[Required, MaxLength(200)]
|
||||
public string Name { get; set; }
|
||||
[Required]
|
||||
public int Severity { get; set; }
|
||||
[MaxLength(1024)]
|
||||
public string Format { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public bool UsePersist { get; set; }
|
||||
[NotMapped]
|
||||
public bool UseLive { get; set; }
|
||||
[NotMapped]
|
||||
public bool UseDisplay { get; set; }
|
||||
|
||||
[ForeignKey("ModuleId")]
|
||||
public LogModule Module { get; set; }
|
||||
|
||||
public enum Severities
|
||||
{
|
||||
Information = 0,
|
||||
Warning = 1,
|
||||
Error = 2
|
||||
}
|
||||
|
||||
public string FormatMessage(object[] Arguments)
|
||||
{
|
||||
|
||||
if (Arguments != null && Arguments.Length > 0)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Format))
|
||||
{
|
||||
return string.Format(Format, Arguments);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Arguments
|
||||
.Select(v => v == null ? string.Empty : v.ToString())
|
||||
.Aggregate((a, b) => a + ", " + (b == null ? string.Empty : b));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Format))
|
||||
{
|
||||
return Format;
|
||||
}
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
public class LogLiveEvent
|
||||
{
|
||||
public int ModuleId { get; set; }
|
||||
public string ModuleName { get; set; }
|
||||
public string ModuleDescription { get; set; }
|
||||
public int EventTypeId { get; set; }
|
||||
public string EventTypeName { get; set; }
|
||||
public int EventTypeSeverity { get; set; }
|
||||
|
||||
public DateTime Timestamp { get; set; }
|
||||
public object[] Arguments { get; set; }
|
||||
public string FormattedMessage { get; set; }
|
||||
public string FormattedTimestamp { get; set; }
|
||||
public bool UseDisplay { get; set; }
|
||||
|
||||
public static LogLiveEvent Create(LogBase logModule, Models.LogEventType eventType, DateTime Timestamp, string jsonArguments)
|
||||
{
|
||||
object[] Arguments = null;
|
||||
if (jsonArguments != null)
|
||||
{
|
||||
//var alArguments = fastJSON.JSON.Instance.Parse(jsonArguments) as ArrayList; // Old fastJSON Implementation
|
||||
Arguments = JsonConvert.DeserializeObject<object[]>(jsonArguments);
|
||||
//if (alArguments != null)
|
||||
//{
|
||||
// Arguments = alArguments.ToArray();
|
||||
//}
|
||||
}
|
||||
return Create(logModule, eventType, Timestamp, Arguments);
|
||||
}
|
||||
|
||||
public static LogLiveEvent Create(LogBase logModule, Models.LogEventType eventType, DateTime Timestamp, params object[] Arguments)
|
||||
{
|
||||
return new Models.LogLiveEvent()
|
||||
{
|
||||
ModuleId = logModule.ModuleId,
|
||||
ModuleName = logModule.ModuleName,
|
||||
ModuleDescription = logModule.ModuleDescription,
|
||||
EventTypeId = eventType.Id,
|
||||
EventTypeName = eventType.Name,
|
||||
EventTypeSeverity = eventType.Severity,
|
||||
Timestamp = Timestamp,
|
||||
Arguments = Arguments,
|
||||
FormattedMessage = eventType.FormatMessage(Arguments),
|
||||
FormattedTimestamp = Timestamp.ToString("dd/MM/yyy hh:mm:ss tt"),
|
||||
UseDisplay = eventType.UseDisplay
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Collections;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
public class LogLiveEvent
|
||||
{
|
||||
public int ModuleId { get; set; }
|
||||
public string ModuleName { get; set; }
|
||||
public string ModuleDescription { get; set; }
|
||||
public int EventTypeId { get; set; }
|
||||
public string EventTypeName { get; set; }
|
||||
public int EventTypeSeverity { get; set; }
|
||||
|
||||
public DateTime Timestamp { get; set; }
|
||||
public object[] Arguments { get; set; }
|
||||
public string FormattedMessage { get; set; }
|
||||
public string FormattedTimestamp { get; set; }
|
||||
public bool UseDisplay { get; set; }
|
||||
|
||||
public static LogLiveEvent Create(LogBase logModule, Models.LogEventType eventType, DateTime Timestamp, string jsonArguments)
|
||||
{
|
||||
object[] Arguments = null;
|
||||
if (jsonArguments != null)
|
||||
{
|
||||
//var alArguments = fastJSON.JSON.Instance.Parse(jsonArguments) as ArrayList; // Old fastJSON Implementation
|
||||
Arguments = JsonConvert.DeserializeObject<object[]>(jsonArguments);
|
||||
//if (alArguments != null)
|
||||
//{
|
||||
// Arguments = alArguments.ToArray();
|
||||
//}
|
||||
}
|
||||
return Create(logModule, eventType, Timestamp, Arguments);
|
||||
}
|
||||
|
||||
public static LogLiveEvent Create(LogBase logModule, Models.LogEventType eventType, DateTime Timestamp, params object[] Arguments)
|
||||
{
|
||||
return new Models.LogLiveEvent()
|
||||
{
|
||||
ModuleId = logModule.ModuleId,
|
||||
ModuleName = logModule.ModuleName,
|
||||
ModuleDescription = logModule.ModuleDescription,
|
||||
EventTypeId = eventType.Id,
|
||||
EventTypeName = eventType.Name,
|
||||
EventTypeSeverity = eventType.Severity,
|
||||
Timestamp = Timestamp,
|
||||
Arguments = Arguments,
|
||||
FormattedMessage = eventType.FormatMessage(Arguments),
|
||||
FormattedTimestamp = Timestamp.ToString("dd/MM/yyy hh:mm:ss tt"),
|
||||
UseDisplay = eventType.UseDisplay
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
[Table("Modules")]
|
||||
public class LogModule
|
||||
{
|
||||
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
|
||||
public int Id { get; set; }
|
||||
[Required, MaxLength(200)]
|
||||
public string Name { get; set; }
|
||||
[Required, MaxLength(500)]
|
||||
public string Description { get; set; }
|
||||
|
||||
public virtual IList<LogEventType> EventTypes { get; set; }
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Disco.Services.Logging.Models
|
||||
{
|
||||
[Table("Modules")]
|
||||
public class LogModule
|
||||
{
|
||||
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
|
||||
public int Id { get; set; }
|
||||
[Required, MaxLength(200)]
|
||||
public string Name { get; set; }
|
||||
[Required, MaxLength(500)]
|
||||
public string Description { get; set; }
|
||||
|
||||
public virtual IList<LogEventType> EventTypes { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,179 +1,179 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Services.Logging.Targets;
|
||||
using Disco.Data.Repository;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Data.SqlServerCe;
|
||||
using Disco.Services.Logging.Models;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public class ReadLogContext
|
||||
{
|
||||
public DateTime? Start { get; set; }
|
||||
public DateTime? End { get; set; }
|
||||
public int? Take { get; set; }
|
||||
public int? Module { get; set; }
|
||||
public List<int> EventTypes { get; set; }
|
||||
|
||||
public bool Validate()
|
||||
{
|
||||
if (this.Start.HasValue && this.End.HasValue && this.End.Value < this.Start.Value)
|
||||
throw new ArgumentOutOfRangeException("End", "End must be greater than Start");
|
||||
if (this.Start.HasValue && !this.End.HasValue && this.Start > DateTime.Now)
|
||||
throw new ArgumentOutOfRangeException("Start", "Start must be less than current time");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public List<Models.LogLiveEvent> Query(DiscoDataContext DiscoContext)
|
||||
{
|
||||
List<Models.LogLiveEvent> results = new List<LogLiveEvent>();
|
||||
|
||||
// Validate Options
|
||||
this.Validate();
|
||||
|
||||
var relevantLogFiles = RelevantLogFiles(DiscoContext);
|
||||
relevantLogFiles.Reverse();
|
||||
foreach (var logFile in relevantLogFiles)
|
||||
{
|
||||
SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder();
|
||||
sqlCeCSB.DataSource = logFile.Item1;
|
||||
|
||||
var logModules = LogContext.LogModules;
|
||||
|
||||
using (var context = new Targets.LogPersistContext(sqlCeCSB.ToString()))
|
||||
{
|
||||
var query = this.BuildQuery(context, logFile.Item2, results.Count);
|
||||
IEnumerable<LogEvent> queryResults = query; // Run the Query
|
||||
results.AddRange(queryResults.Select(le => Models.LogLiveEvent.Create(logModules[le.ModuleId], logModules[le.ModuleId].EventTypes[le.EventTypeId], le.Timestamp, le.Arguments)));
|
||||
}
|
||||
if (this.Take.HasValue && this.Take.Value < results.Count)
|
||||
break;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static Regex LogFileDateRegex = new Regex("DiscoLog_([0-9]{4})-([0-9]{2})-([0-9]{2}).sdf", RegexOptions.IgnoreCase);
|
||||
private static DateTime? LogFileDate(string LogFilePath)
|
||||
{
|
||||
var fileNameMatch = LogFileDateRegex.Match(LogFilePath);
|
||||
if (fileNameMatch.Success)
|
||||
{
|
||||
return new DateTime(int.Parse(fileNameMatch.Groups[1].Value),
|
||||
int.Parse(fileNameMatch.Groups[2].Value),
|
||||
int.Parse(fileNameMatch.Groups[3].Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private List<Tuple<string, DateTime>> RelevantLogFiles(DiscoDataContext DiscoContext)
|
||||
{
|
||||
List<Tuple<string, DateTime>> relevantFiles = new List<Tuple<string, DateTime>>();
|
||||
var logDirectoryBase = LogContext.LogFileBasePath(DiscoContext);
|
||||
var logDirectoryBaseInfo = new DirectoryInfo(logDirectoryBase);
|
||||
var endDate = this.End.HasValue ? this.End.Value : DateTime.Now;
|
||||
var endDateYear = endDate.Year.ToString();
|
||||
|
||||
// Try Shortcut ( < 31 Days in Query)
|
||||
if (this.Start.HasValue)
|
||||
{
|
||||
if ((this.End.HasValue && this.End.Value.Subtract(this.Start.Value).Days < 31) ||
|
||||
(!this.End.HasValue && DateTime.Now.Subtract(this.Start.Value).Days < 31))
|
||||
{
|
||||
// Less than 31 Days in Query - Just evaluate each Path
|
||||
var queryDate = this.Start.Value.Date;
|
||||
while (queryDate <= endDate)
|
||||
{
|
||||
var fileName = LogContext.LogFilePath(DiscoContext, queryDate, false);
|
||||
if (File.Exists(fileName))
|
||||
relevantFiles.Add(new Tuple<string, DateTime>(fileName, LogFileDate(fileName).Value));
|
||||
|
||||
queryDate = queryDate.AddDays(1);
|
||||
}
|
||||
return relevantFiles;
|
||||
}
|
||||
}
|
||||
|
||||
List<string> logYears = new List<string>();
|
||||
foreach (var directoryName in logDirectoryBaseInfo.GetDirectories())
|
||||
{
|
||||
int directoryYear;
|
||||
if (int.TryParse(directoryName.Name, out directoryYear))
|
||||
{
|
||||
logYears.Add(directoryName.Name);
|
||||
}
|
||||
}
|
||||
logYears.Sort();
|
||||
|
||||
foreach (var logYear in logYears)
|
||||
{
|
||||
List<string> logFiles = Directory.EnumerateFiles(Path.Combine(logDirectoryBase, logYear), "DiscoLog_*.sdf").ToList();
|
||||
logFiles.Sort();
|
||||
if (logYear != endDateYear)
|
||||
{
|
||||
foreach (var logFile in logFiles)
|
||||
{
|
||||
relevantFiles.Add(new Tuple<string, DateTime>(logFile, LogFileDate(logFile).Value));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var logFile in logFiles)
|
||||
{
|
||||
var fileNameDate = LogFileDate(logFile);
|
||||
if (fileNameDate != null)
|
||||
{
|
||||
if (fileNameDate.Value < endDate)
|
||||
{
|
||||
relevantFiles.Add(new Tuple<string, DateTime>(logFile, fileNameDate.Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
break; // Files are sorted, must be no more...
|
||||
}
|
||||
}
|
||||
}
|
||||
break; // Years are sorted, must be no more...
|
||||
}
|
||||
}
|
||||
return relevantFiles;
|
||||
}
|
||||
|
||||
private IQueryable<LogEvent> BuildQuery(LogPersistContext LogContext, DateTime LogDate, int Taken)
|
||||
{
|
||||
IQueryable<LogEvent> query = LogContext.Events.OrderByDescending(le => le.Timestamp);
|
||||
if (this.Module.HasValue)
|
||||
{
|
||||
query = query.Where(le => le.ModuleId == this.Module.Value);
|
||||
}
|
||||
if (this.EventTypes != null && this.EventTypes.Count > 0)
|
||||
{
|
||||
query = query.Where(le => this.EventTypes.Contains(le.EventTypeId));
|
||||
}
|
||||
if (this.Start.HasValue && this.Start.Value > LogDate)
|
||||
{
|
||||
var startValue = DateTime.SpecifyKind(this.Start.Value, DateTimeKind.Local);
|
||||
query = query.Where(le => le.Timestamp > startValue);
|
||||
}
|
||||
if (this.End.HasValue && this.End.Value <= LogDate.AddDays(1))
|
||||
{
|
||||
var endValue = DateTime.SpecifyKind(this.End.Value, DateTimeKind.Local);
|
||||
query = query.Where(le => le.Timestamp < endValue);
|
||||
}
|
||||
if (this.Take.HasValue && this.Take.Value > 0)
|
||||
{
|
||||
var take = this.Take.Value - Taken;
|
||||
query = query.Take(take);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Services.Logging.Targets;
|
||||
using Disco.Data.Repository;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Data.SqlServerCe;
|
||||
using Disco.Services.Logging.Models;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public class ReadLogContext
|
||||
{
|
||||
public DateTime? Start { get; set; }
|
||||
public DateTime? End { get; set; }
|
||||
public int? Take { get; set; }
|
||||
public int? Module { get; set; }
|
||||
public List<int> EventTypes { get; set; }
|
||||
|
||||
public bool Validate()
|
||||
{
|
||||
if (this.Start.HasValue && this.End.HasValue && this.End.Value < this.Start.Value)
|
||||
throw new ArgumentOutOfRangeException("End", "End must be greater than Start");
|
||||
if (this.Start.HasValue && !this.End.HasValue && this.Start > DateTime.Now)
|
||||
throw new ArgumentOutOfRangeException("Start", "Start must be less than current time");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public List<Models.LogLiveEvent> Query(DiscoDataContext DiscoContext)
|
||||
{
|
||||
List<Models.LogLiveEvent> results = new List<LogLiveEvent>();
|
||||
|
||||
// Validate Options
|
||||
this.Validate();
|
||||
|
||||
var relevantLogFiles = RelevantLogFiles(DiscoContext);
|
||||
relevantLogFiles.Reverse();
|
||||
foreach (var logFile in relevantLogFiles)
|
||||
{
|
||||
SqlCeConnectionStringBuilder sqlCeCSB = new SqlCeConnectionStringBuilder();
|
||||
sqlCeCSB.DataSource = logFile.Item1;
|
||||
|
||||
var logModules = LogContext.LogModules;
|
||||
|
||||
using (var context = new Targets.LogPersistContext(sqlCeCSB.ToString()))
|
||||
{
|
||||
var query = this.BuildQuery(context, logFile.Item2, results.Count);
|
||||
IEnumerable<LogEvent> queryResults = query; // Run the Query
|
||||
results.AddRange(queryResults.Select(le => Models.LogLiveEvent.Create(logModules[le.ModuleId], logModules[le.ModuleId].EventTypes[le.EventTypeId], le.Timestamp, le.Arguments)));
|
||||
}
|
||||
if (this.Take.HasValue && this.Take.Value < results.Count)
|
||||
break;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static Regex LogFileDateRegex = new Regex("DiscoLog_([0-9]{4})-([0-9]{2})-([0-9]{2}).sdf", RegexOptions.IgnoreCase);
|
||||
private static DateTime? LogFileDate(string LogFilePath)
|
||||
{
|
||||
var fileNameMatch = LogFileDateRegex.Match(LogFilePath);
|
||||
if (fileNameMatch.Success)
|
||||
{
|
||||
return new DateTime(int.Parse(fileNameMatch.Groups[1].Value),
|
||||
int.Parse(fileNameMatch.Groups[2].Value),
|
||||
int.Parse(fileNameMatch.Groups[3].Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private List<Tuple<string, DateTime>> RelevantLogFiles(DiscoDataContext DiscoContext)
|
||||
{
|
||||
List<Tuple<string, DateTime>> relevantFiles = new List<Tuple<string, DateTime>>();
|
||||
var logDirectoryBase = LogContext.LogFileBasePath(DiscoContext);
|
||||
var logDirectoryBaseInfo = new DirectoryInfo(logDirectoryBase);
|
||||
var endDate = this.End.HasValue ? this.End.Value : DateTime.Now;
|
||||
var endDateYear = endDate.Year.ToString();
|
||||
|
||||
// Try Shortcut ( < 31 Days in Query)
|
||||
if (this.Start.HasValue)
|
||||
{
|
||||
if ((this.End.HasValue && this.End.Value.Subtract(this.Start.Value).Days < 31) ||
|
||||
(!this.End.HasValue && DateTime.Now.Subtract(this.Start.Value).Days < 31))
|
||||
{
|
||||
// Less than 31 Days in Query - Just evaluate each Path
|
||||
var queryDate = this.Start.Value.Date;
|
||||
while (queryDate <= endDate)
|
||||
{
|
||||
var fileName = LogContext.LogFilePath(DiscoContext, queryDate, false);
|
||||
if (File.Exists(fileName))
|
||||
relevantFiles.Add(new Tuple<string, DateTime>(fileName, LogFileDate(fileName).Value));
|
||||
|
||||
queryDate = queryDate.AddDays(1);
|
||||
}
|
||||
return relevantFiles;
|
||||
}
|
||||
}
|
||||
|
||||
List<string> logYears = new List<string>();
|
||||
foreach (var directoryName in logDirectoryBaseInfo.GetDirectories())
|
||||
{
|
||||
int directoryYear;
|
||||
if (int.TryParse(directoryName.Name, out directoryYear))
|
||||
{
|
||||
logYears.Add(directoryName.Name);
|
||||
}
|
||||
}
|
||||
logYears.Sort();
|
||||
|
||||
foreach (var logYear in logYears)
|
||||
{
|
||||
List<string> logFiles = Directory.EnumerateFiles(Path.Combine(logDirectoryBase, logYear), "DiscoLog_*.sdf").ToList();
|
||||
logFiles.Sort();
|
||||
if (logYear != endDateYear)
|
||||
{
|
||||
foreach (var logFile in logFiles)
|
||||
{
|
||||
relevantFiles.Add(new Tuple<string, DateTime>(logFile, LogFileDate(logFile).Value));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var logFile in logFiles)
|
||||
{
|
||||
var fileNameDate = LogFileDate(logFile);
|
||||
if (fileNameDate != null)
|
||||
{
|
||||
if (fileNameDate.Value < endDate)
|
||||
{
|
||||
relevantFiles.Add(new Tuple<string, DateTime>(logFile, fileNameDate.Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
break; // Files are sorted, must be no more...
|
||||
}
|
||||
}
|
||||
}
|
||||
break; // Years are sorted, must be no more...
|
||||
}
|
||||
}
|
||||
return relevantFiles;
|
||||
}
|
||||
|
||||
private IQueryable<LogEvent> BuildQuery(LogPersistContext LogContext, DateTime LogDate, int Taken)
|
||||
{
|
||||
IQueryable<LogEvent> query = LogContext.Events.OrderByDescending(le => le.Timestamp);
|
||||
if (this.Module.HasValue)
|
||||
{
|
||||
query = query.Where(le => le.ModuleId == this.Module.Value);
|
||||
}
|
||||
if (this.EventTypes != null && this.EventTypes.Count > 0)
|
||||
{
|
||||
query = query.Where(le => this.EventTypes.Contains(le.EventTypeId));
|
||||
}
|
||||
if (this.Start.HasValue && this.Start.Value > LogDate)
|
||||
{
|
||||
var startValue = DateTime.SpecifyKind(this.Start.Value, DateTimeKind.Local);
|
||||
query = query.Where(le => le.Timestamp > startValue);
|
||||
}
|
||||
if (this.End.HasValue && this.End.Value <= LogDate.AddDays(1))
|
||||
{
|
||||
var endValue = DateTime.SpecifyKind(this.End.Value, DateTimeKind.Local);
|
||||
query = query.Where(le => le.Timestamp < endValue);
|
||||
}
|
||||
if (this.Take.HasValue && this.Take.Value > 0)
|
||||
{
|
||||
var take = this.Take.Value - Taken;
|
||||
query = query.Take(take);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+140
-140
@@ -1,140 +1,140 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Services.Logging.Models;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public class SystemLog : LogBase
|
||||
{
|
||||
private const int _ModuleId = 0;
|
||||
public enum EventTypeIds : int
|
||||
{
|
||||
Information = 0,
|
||||
Warning = 1,
|
||||
Error = 2,
|
||||
Exception = 10,
|
||||
ExceptionWithInner = 11,
|
||||
LogInitialized = 100,
|
||||
Uninitialized = 200
|
||||
}
|
||||
public static SystemLog Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return (SystemLog)LogContext.LogModules[_ModuleId];
|
||||
}
|
||||
}
|
||||
private static void Log(EventTypeIds EventTypeId, params object[] Args)
|
||||
{
|
||||
Current.Log((int)EventTypeId, Args);
|
||||
}
|
||||
public static void LogInformation(params object[] Messages)
|
||||
{
|
||||
Log(EventTypeIds.Information, Messages);
|
||||
}
|
||||
public static void LogWarning(params object[] Messages)
|
||||
{
|
||||
Log(EventTypeIds.Warning, Messages);
|
||||
}
|
||||
public static void LogError(params object[] Messages)
|
||||
{
|
||||
Log(EventTypeIds.Error, Messages);
|
||||
}
|
||||
public static void LogException(string Component, Exception ex)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.ExceptionWithInner, Component, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.Exception, Component, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
public static void LogLogInitialized(string PersistantStorePath)
|
||||
{
|
||||
Log(EventTypeIds.LogInitialized, PersistantStorePath);
|
||||
}
|
||||
|
||||
public static void LogUninitialized()
|
||||
{
|
||||
if (Current != null)
|
||||
Log(EventTypeIds.Uninitialized);
|
||||
}
|
||||
|
||||
public override int ModuleId
|
||||
{
|
||||
get { return _ModuleId; }
|
||||
}
|
||||
|
||||
public override string ModuleName
|
||||
{
|
||||
get { return "System"; }
|
||||
}
|
||||
|
||||
public override string ModuleDescription
|
||||
{
|
||||
get { return "Core System Log"; }
|
||||
}
|
||||
|
||||
protected override List<LogEventType> LoadEventTypes()
|
||||
{
|
||||
List<LogEventType> eventTypes = new List<LogEventType>() {
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Information,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Information",
|
||||
Format = null,
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Warning,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Warning",
|
||||
Format = null,
|
||||
Severity = (int)LogEventType.Severities.Warning,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Error,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Error",
|
||||
Format = null,
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Exception,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Exception",
|
||||
Format = "{0}; {1}: {2}; {3}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.ExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Exception with Inner Exception",
|
||||
Format = "{0}; {1}: {2}; {3}; {4}: {5}; {6}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.LogInitialized,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Log Initialized",
|
||||
Format = "Log Initialized to '{0}'",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = false, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Uninitialized,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Disco Uninitialized",
|
||||
Format = "Disco Uninitialized",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = false, UsePersist = true, UseDisplay = false }
|
||||
};
|
||||
|
||||
return eventTypes;
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Services.Logging.Models;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public class SystemLog : LogBase
|
||||
{
|
||||
private const int _ModuleId = 0;
|
||||
public enum EventTypeIds : int
|
||||
{
|
||||
Information = 0,
|
||||
Warning = 1,
|
||||
Error = 2,
|
||||
Exception = 10,
|
||||
ExceptionWithInner = 11,
|
||||
LogInitialized = 100,
|
||||
Uninitialized = 200
|
||||
}
|
||||
public static SystemLog Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return (SystemLog)LogContext.LogModules[_ModuleId];
|
||||
}
|
||||
}
|
||||
private static void Log(EventTypeIds EventTypeId, params object[] Args)
|
||||
{
|
||||
Current.Log((int)EventTypeId, Args);
|
||||
}
|
||||
public static void LogInformation(params object[] Messages)
|
||||
{
|
||||
Log(EventTypeIds.Information, Messages);
|
||||
}
|
||||
public static void LogWarning(params object[] Messages)
|
||||
{
|
||||
Log(EventTypeIds.Warning, Messages);
|
||||
}
|
||||
public static void LogError(params object[] Messages)
|
||||
{
|
||||
Log(EventTypeIds.Error, Messages);
|
||||
}
|
||||
public static void LogException(string Component, Exception ex)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.ExceptionWithInner, Component, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.Exception, Component, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
public static void LogLogInitialized(string PersistantStorePath)
|
||||
{
|
||||
Log(EventTypeIds.LogInitialized, PersistantStorePath);
|
||||
}
|
||||
|
||||
public static void LogUninitialized()
|
||||
{
|
||||
if (Current != null)
|
||||
Log(EventTypeIds.Uninitialized);
|
||||
}
|
||||
|
||||
public override int ModuleId
|
||||
{
|
||||
get { return _ModuleId; }
|
||||
}
|
||||
|
||||
public override string ModuleName
|
||||
{
|
||||
get { return "System"; }
|
||||
}
|
||||
|
||||
public override string ModuleDescription
|
||||
{
|
||||
get { return "Core System Log"; }
|
||||
}
|
||||
|
||||
protected override List<LogEventType> LoadEventTypes()
|
||||
{
|
||||
List<LogEventType> eventTypes = new List<LogEventType>() {
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Information,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Information",
|
||||
Format = null,
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Warning,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Warning",
|
||||
Format = null,
|
||||
Severity = (int)LogEventType.Severities.Warning,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Error,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Error",
|
||||
Format = null,
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Exception,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Exception",
|
||||
Format = "{0}; {1}: {2}; {3}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.ExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Exception with Inner Exception",
|
||||
Format = "{0}; {1}: {2}; {3}; {4}: {5}; {6}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.LogInitialized,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Log Initialized",
|
||||
Format = "Log Initialized to '{0}'",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = false, UsePersist = true, UseDisplay = true },
|
||||
new LogEventType() {
|
||||
Id = (int)EventTypeIds.Uninitialized,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Disco Uninitialized",
|
||||
Format = "Disco Uninitialized",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = false, UsePersist = true, UseDisplay = false }
|
||||
};
|
||||
|
||||
return eventTypes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using SignalR;
|
||||
using SignalR.Hosting.AspNet;
|
||||
using SignalR.Infrastructure;
|
||||
|
||||
namespace Disco.Services.Logging.Targets
|
||||
{
|
||||
public class LogLiveContext : PersistentConnection
|
||||
{
|
||||
|
||||
protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest request, string connectionId, string data)
|
||||
{
|
||||
// Add to Group
|
||||
if (!string.IsNullOrWhiteSpace(data) && data.StartsWith("/addToGroups:") && data.Length > 13)
|
||||
{
|
||||
var groups = data.Substring(13).Split(',');
|
||||
foreach (var g in groups)
|
||||
{
|
||||
this.Groups.Add(connectionId, g);
|
||||
}
|
||||
}
|
||||
|
||||
return base.OnReceivedAsync(request, connectionId, data);
|
||||
}
|
||||
|
||||
internal static void Broadcast(LogBase logModule, Models.LogEventType eventType, DateTime Timestamp, params object[] Arguments)
|
||||
{
|
||||
var message = Models.LogLiveEvent.Create(logModule, eventType, Timestamp, Arguments);
|
||||
|
||||
var connectionManager = GlobalHost.ConnectionManager;
|
||||
var connectionContext = connectionManager.GetConnectionContext<LogLiveContext>();
|
||||
connectionContext.Groups.Send(_GroupNameAll, message);
|
||||
connectionContext.Groups.Send(logModule.ModuleName, message);
|
||||
}
|
||||
|
||||
private const string _GroupNameAll = "__All";
|
||||
//private static string _QualifiedTypeName = typeof(LogLiveContext).FullName + ".";
|
||||
//private static string _QualifiedTypeNameAll = _QualifiedTypeName + "__All";
|
||||
//private static string LiveLogNameGroup(string LogName)
|
||||
//{
|
||||
// return string.Concat(_QualifiedTypeName, LogName);
|
||||
//}
|
||||
public static string LiveLogNameAll
|
||||
{
|
||||
get
|
||||
{
|
||||
//return _QualifiedTypeNameAll;
|
||||
return _GroupNameAll;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using SignalR;
|
||||
using SignalR.Hosting.AspNet;
|
||||
using SignalR.Infrastructure;
|
||||
|
||||
namespace Disco.Services.Logging.Targets
|
||||
{
|
||||
public class LogLiveContext : PersistentConnection
|
||||
{
|
||||
|
||||
protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest request, string connectionId, string data)
|
||||
{
|
||||
// Add to Group
|
||||
if (!string.IsNullOrWhiteSpace(data) && data.StartsWith("/addToGroups:") && data.Length > 13)
|
||||
{
|
||||
var groups = data.Substring(13).Split(',');
|
||||
foreach (var g in groups)
|
||||
{
|
||||
this.Groups.Add(connectionId, g);
|
||||
}
|
||||
}
|
||||
|
||||
return base.OnReceivedAsync(request, connectionId, data);
|
||||
}
|
||||
|
||||
internal static void Broadcast(LogBase logModule, Models.LogEventType eventType, DateTime Timestamp, params object[] Arguments)
|
||||
{
|
||||
var message = Models.LogLiveEvent.Create(logModule, eventType, Timestamp, Arguments);
|
||||
|
||||
var connectionManager = GlobalHost.ConnectionManager;
|
||||
var connectionContext = connectionManager.GetConnectionContext<LogLiveContext>();
|
||||
connectionContext.Groups.Send(_GroupNameAll, message);
|
||||
connectionContext.Groups.Send(logModule.ModuleName, message);
|
||||
}
|
||||
|
||||
private const string _GroupNameAll = "__All";
|
||||
//private static string _QualifiedTypeName = typeof(LogLiveContext).FullName + ".";
|
||||
//private static string _QualifiedTypeNameAll = _QualifiedTypeName + "__All";
|
||||
//private static string LiveLogNameGroup(string LogName)
|
||||
//{
|
||||
// return string.Concat(_QualifiedTypeName, LogName);
|
||||
//}
|
||||
public static string LiveLogNameAll
|
||||
{
|
||||
get
|
||||
{
|
||||
//return _QualifiedTypeNameAll;
|
||||
return _GroupNameAll;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Data.Entity;
|
||||
using System.Data.Entity.Infrastructure;
|
||||
|
||||
namespace Disco.Services.Logging.Targets
|
||||
{
|
||||
public class LogPersistContext : DbContext
|
||||
{
|
||||
public LogPersistContext(string ConnectionString) : base(ConnectionString) { }
|
||||
|
||||
public DbSet<Models.LogModule> Modules { get; set; }
|
||||
public DbSet<Models.LogEventType> EventTypes { get; set; }
|
||||
public DbSet<Models.LogEvent> Events { get; set; }
|
||||
|
||||
protected override void OnModelCreating(DbModelBuilder modelBuilder)
|
||||
{
|
||||
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Data.Entity;
|
||||
using System.Data.Entity.Infrastructure;
|
||||
|
||||
namespace Disco.Services.Logging.Targets
|
||||
{
|
||||
public class LogPersistContext : DbContext
|
||||
{
|
||||
public LogPersistContext(string ConnectionString) : base(ConnectionString) { }
|
||||
|
||||
public DbSet<Models.LogModule> Modules { get; set; }
|
||||
public DbSet<Models.LogEventType> EventTypes { get; set; }
|
||||
public DbSet<Models.LogEvent> Events { get; set; }
|
||||
|
||||
protected override void OnModelCreating(DbModelBuilder modelBuilder)
|
||||
{
|
||||
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+266
-266
@@ -1,266 +1,266 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.IO;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public static class Utilities
|
||||
{
|
||||
|
||||
public const string LogEventCSVHeader = "Timestamp,ModuleId,ModuleName,ModuleDescription,EventTypeId,EventTypeName,Severity,Message";
|
||||
public static void ToCsvLine(this Models.LogLiveEvent e, TextWriter writer)
|
||||
{
|
||||
writer.Write(e.Timestamp.ToString("yyy-MM-dd HH:mm:ss"));
|
||||
writer.Write(",");
|
||||
writer.Write(e.ModuleId);
|
||||
writer.Write(",\"");
|
||||
writer.Write(e.ModuleName);
|
||||
writer.Write("\",\"");
|
||||
writer.Write(e.ModuleDescription);
|
||||
writer.Write("\",");
|
||||
writer.Write(e.EventTypeId);
|
||||
writer.Write(",\"");
|
||||
writer.Write(e.EventTypeName);
|
||||
writer.Write("\",");
|
||||
writer.Write(e.EventTypeSeverity);
|
||||
writer.Write(",\"");
|
||||
writer.Write(e.FormattedMessage.Replace("\"", "'"));
|
||||
writer.Write("\"");
|
||||
if (e.Arguments != null)
|
||||
{
|
||||
foreach (var arg in e.Arguments)
|
||||
{
|
||||
writer.Write(",\"");
|
||||
if (arg == null)
|
||||
writer.Write("null");
|
||||
else
|
||||
writer.Write(arg.ToString().Replace("\"", "'"));
|
||||
writer.Write("\"");
|
||||
}
|
||||
}
|
||||
writer.WriteLine();
|
||||
}
|
||||
public static MemoryStream ToCsv(this List<Models.LogLiveEvent> e)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
StreamWriter sw = new StreamWriter(ms);
|
||||
sw.WriteLine(LogEventCSVHeader);
|
||||
if (e != null)
|
||||
{
|
||||
foreach (var le in e)
|
||||
{
|
||||
le.ToCsvLine(sw);
|
||||
}
|
||||
}
|
||||
sw.Flush();
|
||||
ms.Position = 0;
|
||||
return ms;
|
||||
}
|
||||
|
||||
public static List<SelectListItem> ToSelectListItems(this List<Models.LogEventType> items)
|
||||
{
|
||||
return items.Select(et => new SelectListItem() { Value = et.Id.ToString(), Text = et.Name }).ToList();
|
||||
}
|
||||
|
||||
#region Win32 APIs
|
||||
/// <summary>
|
||||
/// The CreateFile function creates or opens a file, file stream, directory, physical disk, volume, console buffer, tape drive,
|
||||
/// communications resource, mailslot, or named pipe. The function returns a handle that can be used to access an object.
|
||||
/// </summary>
|
||||
/// <param name="lpFileName"></param>
|
||||
/// <param name="dwDesiredAccess"> access to the object, which can be read, write, or both</param>
|
||||
/// <param name="dwShareMode">The sharing mode of an object, which can be read, write, both, or none</param>
|
||||
/// <param name="SecurityAttributes">A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not the returned handle can
|
||||
/// be inherited by child processes. Can be null</param>
|
||||
/// <param name="dwCreationDisposition">An action to take on files that exist and do not exist</param>
|
||||
/// <param name="dwFlagsAndAttributes">The file attributes and flags. </param>
|
||||
/// <param name="hTemplateFile">A handle to a template file with the GENERIC_READ access right. The template file supplies file attributes
|
||||
/// and extended attributes for the file that is being created. This parameter can be null</param>
|
||||
/// <returns>If the function succeeds, the return value is an open handle to a specified file. If a specified file exists before the function
|
||||
/// all and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS, even when the function
|
||||
/// succeeds. If a file does not exist before the call, GetLastError returns 0 (zero).
|
||||
/// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
|
||||
/// </returns>
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
|
||||
private static extern SafeFileHandle CreateFile(
|
||||
string lpFileName,
|
||||
EFileAccess dwDesiredAccess,
|
||||
EFileShare dwShareMode,
|
||||
IntPtr SecurityAttributes,
|
||||
ECreationDisposition dwCreationDisposition,
|
||||
EFileAttributes dwFlagsAndAttributes,
|
||||
IntPtr hTemplateFile
|
||||
);
|
||||
[Flags]
|
||||
private enum EFileAccess : uint
|
||||
{
|
||||
Delete = 0x10000,
|
||||
ReadControl = 0x20000,
|
||||
WriteDAC = 0x40000,
|
||||
WriteOwner = 0x80000,
|
||||
Synchronize = 0x100000,
|
||||
|
||||
StandardRightsRequired = 0xF0000,
|
||||
StandardRightsRead = ReadControl,
|
||||
StandardRightsWrite = ReadControl,
|
||||
StandardRightsExecute = ReadControl,
|
||||
StandardRightsAll = 0x1F0000,
|
||||
SpecificRightsAll = 0xFFFF,
|
||||
|
||||
AccessSystemSecurity = 0x1000000, // AccessSystemAcl access type
|
||||
|
||||
MaximumAllowed = 0x2000000, // MaximumAllowed access type
|
||||
|
||||
GenericRead = 0x80000000,
|
||||
GenericWrite = 0x40000000,
|
||||
GenericExecute = 0x20000000,
|
||||
GenericAll = 0x10000000
|
||||
}
|
||||
[Flags]
|
||||
private enum EFileShare : uint
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
None = 0x00000000,
|
||||
/// <summary>
|
||||
/// Enables subsequent open operations on an object to request read access.
|
||||
/// Otherwise, other processes cannot open the object if they request read access.
|
||||
/// If this flag is not specified, but the object has been opened for read access, the function fails.
|
||||
/// </summary>
|
||||
Read = 0x00000001,
|
||||
/// <summary>
|
||||
/// Enables subsequent open operations on an object to request write access.
|
||||
/// Otherwise, other processes cannot open the object if they request write access.
|
||||
/// If this flag is not specified, but the object has been opened for write access, the function fails.
|
||||
/// </summary>
|
||||
Write = 0x00000002,
|
||||
/// <summary>
|
||||
/// Enables subsequent open operations on an object to request delete access.
|
||||
/// Otherwise, other processes cannot open the object if they request delete access.
|
||||
/// If this flag is not specified, but the object has been opened for delete access, the function fails.
|
||||
/// </summary>
|
||||
Delete = 0x00000004
|
||||
}
|
||||
private enum ECreationDisposition : uint
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new file. The function fails if a specified file exists.
|
||||
/// </summary>
|
||||
New = 1,
|
||||
/// <summary>
|
||||
/// Creates a new file, always.
|
||||
/// If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes,
|
||||
/// and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that the SECURITY_ATTRIBUTES structure specifies.
|
||||
/// </summary>
|
||||
CreateAlways = 2,
|
||||
/// <summary>
|
||||
/// Opens a file. The function fails if the file does not exist.
|
||||
/// </summary>
|
||||
OpenExisting = 3,
|
||||
/// <summary>
|
||||
/// Opens a file, always.
|
||||
/// If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.
|
||||
/// </summary>
|
||||
OpenAlways = 4,
|
||||
/// <summary>
|
||||
/// Opens a file and truncates it so that its size is 0 (zero) bytes. The function fails if the file does not exist.
|
||||
/// The calling process must open the file with the GENERIC_WRITE access right.
|
||||
/// </summary>
|
||||
TruncateExisting = 5
|
||||
}
|
||||
[Flags]
|
||||
private enum EFileAttributes : uint
|
||||
{
|
||||
None = 0x0000000,
|
||||
Readonly = 0x00000001,
|
||||
Hidden = 0x00000002,
|
||||
System = 0x00000004,
|
||||
Directory = 0x00000010,
|
||||
Archive = 0x00000020,
|
||||
Device = 0x00000040,
|
||||
Normal = 0x00000080,
|
||||
Temporary = 0x00000100,
|
||||
SparseFile = 0x00000200,
|
||||
ReparsePoint = 0x00000400,
|
||||
Compressed = 0x00000800,
|
||||
Offline = 0x00001000,
|
||||
NotContentIndexed = 0x00002000,
|
||||
Encrypted = 0x00004000,
|
||||
Write_Through = 0x80000000,
|
||||
Overlapped = 0x40000000,
|
||||
NoBuffering = 0x20000000,
|
||||
RandomAccess = 0x10000000,
|
||||
SequentialScan = 0x08000000,
|
||||
DeleteOnClose = 0x04000000,
|
||||
BackupSemantics = 0x02000000,
|
||||
PosixSemantics = 0x01000000,
|
||||
OpenReparsePoint = 0x00200000,
|
||||
OpenNoRecall = 0x00100000,
|
||||
FirstPipeInstance = 0x00080000
|
||||
}
|
||||
|
||||
private const int FSCTL_SET_COMPRESSION = 0x9C040;
|
||||
private const short COMPRESSION_FORMAT_DEFAULT = 1;
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern int DeviceIoControl(
|
||||
SafeFileHandle hDevice,
|
||||
int dwIoControlCode,
|
||||
ref short lpInBuffer,
|
||||
int nInBufferSize,
|
||||
IntPtr lpOutBuffer,
|
||||
int nOutBufferSize,
|
||||
ref int lpBytesReturned,
|
||||
IntPtr lpOverlapped);
|
||||
#endregion
|
||||
|
||||
public static void CompressDirectory(string DirectoryPath)
|
||||
{
|
||||
if (DirectoryPath.Length > 250)
|
||||
throw new InvalidOperationException(string.Format("Directory Path to Long (>250) to Compress: {0}", DirectoryPath));
|
||||
|
||||
DirectoryInfo dirInfo = new DirectoryInfo(DirectoryPath);
|
||||
if (dirInfo.Exists)
|
||||
{
|
||||
if ((dirInfo.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed)
|
||||
{
|
||||
var dirHandle = CreateFile(DirectoryPath, EFileAccess.GenericWrite, EFileShare.Read, IntPtr.Zero, ECreationDisposition.OpenExisting, EFileAttributes.None, IntPtr.Zero);
|
||||
if (dirHandle.IsInvalid)
|
||||
{
|
||||
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
|
||||
}
|
||||
else
|
||||
{
|
||||
EnableCompression(dirHandle);
|
||||
dirHandle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(string.Format("Directory doesn't exist: {0}", DirectoryPath));
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnableCompression(SafeFileHandle handle)
|
||||
{
|
||||
int lpBytesReturned = 0;
|
||||
short lpInBuffer = COMPRESSION_FORMAT_DEFAULT;
|
||||
|
||||
int result = DeviceIoControl(handle, FSCTL_SET_COMPRESSION,
|
||||
ref lpInBuffer, sizeof(short), IntPtr.Zero, 0,
|
||||
ref lpBytesReturned, IntPtr.Zero);
|
||||
|
||||
if (result != 0)
|
||||
{
|
||||
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.IO;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace Disco.Services.Logging
|
||||
{
|
||||
public static class Utilities
|
||||
{
|
||||
|
||||
public const string LogEventCSVHeader = "Timestamp,ModuleId,ModuleName,ModuleDescription,EventTypeId,EventTypeName,Severity,Message";
|
||||
public static void ToCsvLine(this Models.LogLiveEvent e, TextWriter writer)
|
||||
{
|
||||
writer.Write(e.Timestamp.ToString("yyy-MM-dd HH:mm:ss"));
|
||||
writer.Write(",");
|
||||
writer.Write(e.ModuleId);
|
||||
writer.Write(",\"");
|
||||
writer.Write(e.ModuleName);
|
||||
writer.Write("\",\"");
|
||||
writer.Write(e.ModuleDescription);
|
||||
writer.Write("\",");
|
||||
writer.Write(e.EventTypeId);
|
||||
writer.Write(",\"");
|
||||
writer.Write(e.EventTypeName);
|
||||
writer.Write("\",");
|
||||
writer.Write(e.EventTypeSeverity);
|
||||
writer.Write(",\"");
|
||||
writer.Write(e.FormattedMessage.Replace("\"", "'"));
|
||||
writer.Write("\"");
|
||||
if (e.Arguments != null)
|
||||
{
|
||||
foreach (var arg in e.Arguments)
|
||||
{
|
||||
writer.Write(",\"");
|
||||
if (arg == null)
|
||||
writer.Write("null");
|
||||
else
|
||||
writer.Write(arg.ToString().Replace("\"", "'"));
|
||||
writer.Write("\"");
|
||||
}
|
||||
}
|
||||
writer.WriteLine();
|
||||
}
|
||||
public static MemoryStream ToCsv(this List<Models.LogLiveEvent> e)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
StreamWriter sw = new StreamWriter(ms);
|
||||
sw.WriteLine(LogEventCSVHeader);
|
||||
if (e != null)
|
||||
{
|
||||
foreach (var le in e)
|
||||
{
|
||||
le.ToCsvLine(sw);
|
||||
}
|
||||
}
|
||||
sw.Flush();
|
||||
ms.Position = 0;
|
||||
return ms;
|
||||
}
|
||||
|
||||
public static List<SelectListItem> ToSelectListItems(this List<Models.LogEventType> items)
|
||||
{
|
||||
return items.Select(et => new SelectListItem() { Value = et.Id.ToString(), Text = et.Name }).ToList();
|
||||
}
|
||||
|
||||
#region Win32 APIs
|
||||
/// <summary>
|
||||
/// The CreateFile function creates or opens a file, file stream, directory, physical disk, volume, console buffer, tape drive,
|
||||
/// communications resource, mailslot, or named pipe. The function returns a handle that can be used to access an object.
|
||||
/// </summary>
|
||||
/// <param name="lpFileName"></param>
|
||||
/// <param name="dwDesiredAccess"> access to the object, which can be read, write, or both</param>
|
||||
/// <param name="dwShareMode">The sharing mode of an object, which can be read, write, both, or none</param>
|
||||
/// <param name="SecurityAttributes">A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not the returned handle can
|
||||
/// be inherited by child processes. Can be null</param>
|
||||
/// <param name="dwCreationDisposition">An action to take on files that exist and do not exist</param>
|
||||
/// <param name="dwFlagsAndAttributes">The file attributes and flags. </param>
|
||||
/// <param name="hTemplateFile">A handle to a template file with the GENERIC_READ access right. The template file supplies file attributes
|
||||
/// and extended attributes for the file that is being created. This parameter can be null</param>
|
||||
/// <returns>If the function succeeds, the return value is an open handle to a specified file. If a specified file exists before the function
|
||||
/// all and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS, even when the function
|
||||
/// succeeds. If a file does not exist before the call, GetLastError returns 0 (zero).
|
||||
/// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
|
||||
/// </returns>
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
|
||||
private static extern SafeFileHandle CreateFile(
|
||||
string lpFileName,
|
||||
EFileAccess dwDesiredAccess,
|
||||
EFileShare dwShareMode,
|
||||
IntPtr SecurityAttributes,
|
||||
ECreationDisposition dwCreationDisposition,
|
||||
EFileAttributes dwFlagsAndAttributes,
|
||||
IntPtr hTemplateFile
|
||||
);
|
||||
[Flags]
|
||||
private enum EFileAccess : uint
|
||||
{
|
||||
Delete = 0x10000,
|
||||
ReadControl = 0x20000,
|
||||
WriteDAC = 0x40000,
|
||||
WriteOwner = 0x80000,
|
||||
Synchronize = 0x100000,
|
||||
|
||||
StandardRightsRequired = 0xF0000,
|
||||
StandardRightsRead = ReadControl,
|
||||
StandardRightsWrite = ReadControl,
|
||||
StandardRightsExecute = ReadControl,
|
||||
StandardRightsAll = 0x1F0000,
|
||||
SpecificRightsAll = 0xFFFF,
|
||||
|
||||
AccessSystemSecurity = 0x1000000, // AccessSystemAcl access type
|
||||
|
||||
MaximumAllowed = 0x2000000, // MaximumAllowed access type
|
||||
|
||||
GenericRead = 0x80000000,
|
||||
GenericWrite = 0x40000000,
|
||||
GenericExecute = 0x20000000,
|
||||
GenericAll = 0x10000000
|
||||
}
|
||||
[Flags]
|
||||
private enum EFileShare : uint
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
None = 0x00000000,
|
||||
/// <summary>
|
||||
/// Enables subsequent open operations on an object to request read access.
|
||||
/// Otherwise, other processes cannot open the object if they request read access.
|
||||
/// If this flag is not specified, but the object has been opened for read access, the function fails.
|
||||
/// </summary>
|
||||
Read = 0x00000001,
|
||||
/// <summary>
|
||||
/// Enables subsequent open operations on an object to request write access.
|
||||
/// Otherwise, other processes cannot open the object if they request write access.
|
||||
/// If this flag is not specified, but the object has been opened for write access, the function fails.
|
||||
/// </summary>
|
||||
Write = 0x00000002,
|
||||
/// <summary>
|
||||
/// Enables subsequent open operations on an object to request delete access.
|
||||
/// Otherwise, other processes cannot open the object if they request delete access.
|
||||
/// If this flag is not specified, but the object has been opened for delete access, the function fails.
|
||||
/// </summary>
|
||||
Delete = 0x00000004
|
||||
}
|
||||
private enum ECreationDisposition : uint
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new file. The function fails if a specified file exists.
|
||||
/// </summary>
|
||||
New = 1,
|
||||
/// <summary>
|
||||
/// Creates a new file, always.
|
||||
/// If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes,
|
||||
/// and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that the SECURITY_ATTRIBUTES structure specifies.
|
||||
/// </summary>
|
||||
CreateAlways = 2,
|
||||
/// <summary>
|
||||
/// Opens a file. The function fails if the file does not exist.
|
||||
/// </summary>
|
||||
OpenExisting = 3,
|
||||
/// <summary>
|
||||
/// Opens a file, always.
|
||||
/// If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.
|
||||
/// </summary>
|
||||
OpenAlways = 4,
|
||||
/// <summary>
|
||||
/// Opens a file and truncates it so that its size is 0 (zero) bytes. The function fails if the file does not exist.
|
||||
/// The calling process must open the file with the GENERIC_WRITE access right.
|
||||
/// </summary>
|
||||
TruncateExisting = 5
|
||||
}
|
||||
[Flags]
|
||||
private enum EFileAttributes : uint
|
||||
{
|
||||
None = 0x0000000,
|
||||
Readonly = 0x00000001,
|
||||
Hidden = 0x00000002,
|
||||
System = 0x00000004,
|
||||
Directory = 0x00000010,
|
||||
Archive = 0x00000020,
|
||||
Device = 0x00000040,
|
||||
Normal = 0x00000080,
|
||||
Temporary = 0x00000100,
|
||||
SparseFile = 0x00000200,
|
||||
ReparsePoint = 0x00000400,
|
||||
Compressed = 0x00000800,
|
||||
Offline = 0x00001000,
|
||||
NotContentIndexed = 0x00002000,
|
||||
Encrypted = 0x00004000,
|
||||
Write_Through = 0x80000000,
|
||||
Overlapped = 0x40000000,
|
||||
NoBuffering = 0x20000000,
|
||||
RandomAccess = 0x10000000,
|
||||
SequentialScan = 0x08000000,
|
||||
DeleteOnClose = 0x04000000,
|
||||
BackupSemantics = 0x02000000,
|
||||
PosixSemantics = 0x01000000,
|
||||
OpenReparsePoint = 0x00200000,
|
||||
OpenNoRecall = 0x00100000,
|
||||
FirstPipeInstance = 0x00080000
|
||||
}
|
||||
|
||||
private const int FSCTL_SET_COMPRESSION = 0x9C040;
|
||||
private const short COMPRESSION_FORMAT_DEFAULT = 1;
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern int DeviceIoControl(
|
||||
SafeFileHandle hDevice,
|
||||
int dwIoControlCode,
|
||||
ref short lpInBuffer,
|
||||
int nInBufferSize,
|
||||
IntPtr lpOutBuffer,
|
||||
int nOutBufferSize,
|
||||
ref int lpBytesReturned,
|
||||
IntPtr lpOverlapped);
|
||||
#endregion
|
||||
|
||||
public static void CompressDirectory(string DirectoryPath)
|
||||
{
|
||||
if (DirectoryPath.Length > 250)
|
||||
throw new InvalidOperationException(string.Format("Directory Path to Long (>250) to Compress: {0}", DirectoryPath));
|
||||
|
||||
DirectoryInfo dirInfo = new DirectoryInfo(DirectoryPath);
|
||||
if (dirInfo.Exists)
|
||||
{
|
||||
if ((dirInfo.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed)
|
||||
{
|
||||
var dirHandle = CreateFile(DirectoryPath, EFileAccess.GenericWrite, EFileShare.Read, IntPtr.Zero, ECreationDisposition.OpenExisting, EFileAttributes.None, IntPtr.Zero);
|
||||
if (dirHandle.IsInvalid)
|
||||
{
|
||||
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
|
||||
}
|
||||
else
|
||||
{
|
||||
EnableCompression(dirHandle);
|
||||
dirHandle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(string.Format("Directory doesn't exist: {0}", DirectoryPath));
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnableCompression(SafeFileHandle handle)
|
||||
{
|
||||
int lpBytesReturned = 0;
|
||||
short lpInBuffer = COMPRESSION_FORMAT_DEFAULT;
|
||||
|
||||
int result = DeviceIoControl(handle, FSCTL_SET_COMPRESSION,
|
||||
ref lpInBuffer, sizeof(short), IntPtr.Zero, 0,
|
||||
ref lpBytesReturned, IntPtr.Zero);
|
||||
|
||||
if (result != 0)
|
||||
{
|
||||
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Disco.Data.Repository;
|
||||
using Disco.Models.Repository;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.CertificateProvider
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Certificate Providers")]
|
||||
public abstract class CertificateProviderFeature : PluginFeature
|
||||
{
|
||||
// Certificate Plugin Requirements
|
||||
public abstract string CertificateProviderId { get; }
|
||||
public abstract Tuple<DeviceCertificate, List<string>> AllocateCertificate(DiscoDataContext dbContext, Device Device);
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Disco.Data.Repository;
|
||||
using Disco.Models.Repository;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.CertificateProvider
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Certificate Providers")]
|
||||
public abstract class CertificateProviderFeature : PluginFeature
|
||||
{
|
||||
// Certificate Plugin Requirements
|
||||
public abstract string CertificateProviderId { get; }
|
||||
public abstract Tuple<DeviceCertificate, List<string>> AllocateCertificate(DiscoDataContext dbContext, Device Device);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,304 +1,304 @@
|
||||
using Disco.Services.Logging;
|
||||
using Disco.Services.Logging.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
namespace Disco.Services.Plugins.Features.CertificateProvider
|
||||
{
|
||||
public class CertificateProvidersLog : LogBase
|
||||
{
|
||||
public enum EventTypeIds
|
||||
{
|
||||
RetrievalStarting = 10,
|
||||
RetrievalProgress,
|
||||
RetrievalFinished,
|
||||
RetrievalWarning = 15,
|
||||
RetrievalError,
|
||||
RetrievalCertificateStarting = 20,
|
||||
RetrievalCertificateFinished = 22,
|
||||
RetrievalCertificateWarning = 25,
|
||||
RetrievalCertificateError,
|
||||
Allocated = 40,
|
||||
AllocationFailed = 50
|
||||
}
|
||||
private const int _ModuleId = 60;
|
||||
private static bool _IsCertificateRetrievalProcessing;
|
||||
private static string _CertificateRetrievalStatus;
|
||||
private static int _CertificateRetrievalProgress;
|
||||
public static CertificateProvidersLog Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return (CertificateProvidersLog)LogContext.LogModules[60];
|
||||
}
|
||||
}
|
||||
public static bool IsCertificateRetrievalProcessing
|
||||
{
|
||||
get
|
||||
{
|
||||
return CertificateProvidersLog._IsCertificateRetrievalProcessing;
|
||||
}
|
||||
}
|
||||
public override string ModuleDescription
|
||||
{
|
||||
get
|
||||
{
|
||||
return "Certificate Providers";
|
||||
}
|
||||
}
|
||||
public override int ModuleId
|
||||
{
|
||||
get
|
||||
{
|
||||
return 60;
|
||||
}
|
||||
}
|
||||
public override string ModuleName
|
||||
{
|
||||
get
|
||||
{
|
||||
return "CertificateProviders";
|
||||
}
|
||||
}
|
||||
[System.Diagnostics.DebuggerNonUserCode]
|
||||
public CertificateProvidersLog()
|
||||
{
|
||||
}
|
||||
private static void Log(CertificateProvidersLog.EventTypeIds EventTypeId, params object[] Args)
|
||||
{
|
||||
CertificateProvidersLog.Current.Log((int)EventTypeId, Args);
|
||||
}
|
||||
public static void LogRetrievalStarting(int CertificateCount, int CertificateIdFrom, int CertificateIdTo)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalStarting, new object[]
|
||||
{
|
||||
CertificateCount,
|
||||
CertificateIdFrom,
|
||||
CertificateIdTo
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalFinished()
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalFinished, new object[0]);
|
||||
}
|
||||
public static void LogRetrievalWarning(string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalWarning, new object[]
|
||||
{
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalError(string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalError, new object[]
|
||||
{
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateStarting(string CertificateId)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateStarting, new object[]
|
||||
{
|
||||
CertificateId
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateFinished(string CertificateId)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateFinished, new object[]
|
||||
{
|
||||
CertificateId
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateWarning(string CertificateId, string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateWarning, new object[]
|
||||
{
|
||||
CertificateId,
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateError(string CertificateId, string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateError, new object[]
|
||||
{
|
||||
CertificateId,
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogAllocated(string CertificateId, string DeviceSerialNumber)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.Allocated, new object[]
|
||||
{
|
||||
CertificateId,
|
||||
DeviceSerialNumber
|
||||
});
|
||||
}
|
||||
public static void LogAllocationFailed(string DeviceSerialNumber)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.AllocationFailed, new object[]
|
||||
{
|
||||
DeviceSerialNumber
|
||||
});
|
||||
}
|
||||
public static void LogCertificateRetrievalProgress(bool? IsProcessing, int? Progress, string Status)
|
||||
{
|
||||
bool flag = IsProcessing.HasValue;
|
||||
if (flag)
|
||||
{
|
||||
CertificateProvidersLog._IsCertificateRetrievalProcessing = IsProcessing.Value;
|
||||
}
|
||||
flag = CertificateProvidersLog._IsCertificateRetrievalProcessing;
|
||||
if (flag)
|
||||
{
|
||||
bool flag2 = Status != null;
|
||||
if (flag2)
|
||||
{
|
||||
CertificateProvidersLog._CertificateRetrievalStatus = Status;
|
||||
}
|
||||
flag2 = Progress.HasValue;
|
||||
if (flag2)
|
||||
{
|
||||
CertificateProvidersLog._CertificateRetrievalProgress = Progress.Value;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CertificateProvidersLog._CertificateRetrievalStatus = null;
|
||||
CertificateProvidersLog._CertificateRetrievalProgress = 0;
|
||||
}
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalProgress, new object[]
|
||||
{
|
||||
CertificateProvidersLog._IsCertificateRetrievalProcessing,
|
||||
CertificateProvidersLog._CertificateRetrievalProgress,
|
||||
CertificateProvidersLog._CertificateRetrievalStatus
|
||||
});
|
||||
}
|
||||
protected override System.Collections.Generic.List<LogEventType> LoadEventTypes()
|
||||
{
|
||||
return new System.Collections.Generic.List<LogEventType>
|
||||
{
|
||||
new LogEventType
|
||||
{
|
||||
Id = 10,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Starting",
|
||||
Format = "Starting retrieval of {0} certificate/s ({1} to {2})",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 11,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Progress",
|
||||
Format = "Processing: {0}; {1}% Complete; Status: {2}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = false,
|
||||
UseDisplay = false
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 12,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Finished",
|
||||
Format = "Retrieval of Certificates Complete",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 15,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Warning",
|
||||
Format = "Retrieval Warning: {0}",
|
||||
Severity = 1,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 16,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Error",
|
||||
Format = "Retrieval Error: {0}",
|
||||
Severity = 2,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 20,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Starting",
|
||||
Format = "Retrieving Certificate: {0}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 22,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Finished",
|
||||
Format = "Certificate Retrieved: {0}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 25,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Warning",
|
||||
Format = "{0} Certificate Warning: {1}",
|
||||
Severity = 1,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 26,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Error",
|
||||
Format = "{0} Certificate Error: {1}",
|
||||
Severity = 2,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 40,
|
||||
ModuleId = 60,
|
||||
Name = "Allocated",
|
||||
Format = "Certificate {0} allocated to {1}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 50,
|
||||
ModuleId = 60,
|
||||
Name = "Allocation Failed",
|
||||
Format = "No certificates available for Device: {0}",
|
||||
Severity = 2,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
using Disco.Services.Logging;
|
||||
using Disco.Services.Logging.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
namespace Disco.Services.Plugins.Features.CertificateProvider
|
||||
{
|
||||
public class CertificateProvidersLog : LogBase
|
||||
{
|
||||
public enum EventTypeIds
|
||||
{
|
||||
RetrievalStarting = 10,
|
||||
RetrievalProgress,
|
||||
RetrievalFinished,
|
||||
RetrievalWarning = 15,
|
||||
RetrievalError,
|
||||
RetrievalCertificateStarting = 20,
|
||||
RetrievalCertificateFinished = 22,
|
||||
RetrievalCertificateWarning = 25,
|
||||
RetrievalCertificateError,
|
||||
Allocated = 40,
|
||||
AllocationFailed = 50
|
||||
}
|
||||
private const int _ModuleId = 60;
|
||||
private static bool _IsCertificateRetrievalProcessing;
|
||||
private static string _CertificateRetrievalStatus;
|
||||
private static int _CertificateRetrievalProgress;
|
||||
public static CertificateProvidersLog Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return (CertificateProvidersLog)LogContext.LogModules[60];
|
||||
}
|
||||
}
|
||||
public static bool IsCertificateRetrievalProcessing
|
||||
{
|
||||
get
|
||||
{
|
||||
return CertificateProvidersLog._IsCertificateRetrievalProcessing;
|
||||
}
|
||||
}
|
||||
public override string ModuleDescription
|
||||
{
|
||||
get
|
||||
{
|
||||
return "Certificate Providers";
|
||||
}
|
||||
}
|
||||
public override int ModuleId
|
||||
{
|
||||
get
|
||||
{
|
||||
return 60;
|
||||
}
|
||||
}
|
||||
public override string ModuleName
|
||||
{
|
||||
get
|
||||
{
|
||||
return "CertificateProviders";
|
||||
}
|
||||
}
|
||||
[System.Diagnostics.DebuggerNonUserCode]
|
||||
public CertificateProvidersLog()
|
||||
{
|
||||
}
|
||||
private static void Log(CertificateProvidersLog.EventTypeIds EventTypeId, params object[] Args)
|
||||
{
|
||||
CertificateProvidersLog.Current.Log((int)EventTypeId, Args);
|
||||
}
|
||||
public static void LogRetrievalStarting(int CertificateCount, int CertificateIdFrom, int CertificateIdTo)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalStarting, new object[]
|
||||
{
|
||||
CertificateCount,
|
||||
CertificateIdFrom,
|
||||
CertificateIdTo
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalFinished()
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalFinished, new object[0]);
|
||||
}
|
||||
public static void LogRetrievalWarning(string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalWarning, new object[]
|
||||
{
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalError(string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalError, new object[]
|
||||
{
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateStarting(string CertificateId)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateStarting, new object[]
|
||||
{
|
||||
CertificateId
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateFinished(string CertificateId)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateFinished, new object[]
|
||||
{
|
||||
CertificateId
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateWarning(string CertificateId, string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateWarning, new object[]
|
||||
{
|
||||
CertificateId,
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogRetrievalCertificateError(string CertificateId, string Message)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalCertificateError, new object[]
|
||||
{
|
||||
CertificateId,
|
||||
Message
|
||||
});
|
||||
}
|
||||
public static void LogAllocated(string CertificateId, string DeviceSerialNumber)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.Allocated, new object[]
|
||||
{
|
||||
CertificateId,
|
||||
DeviceSerialNumber
|
||||
});
|
||||
}
|
||||
public static void LogAllocationFailed(string DeviceSerialNumber)
|
||||
{
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.AllocationFailed, new object[]
|
||||
{
|
||||
DeviceSerialNumber
|
||||
});
|
||||
}
|
||||
public static void LogCertificateRetrievalProgress(bool? IsProcessing, int? Progress, string Status)
|
||||
{
|
||||
bool flag = IsProcessing.HasValue;
|
||||
if (flag)
|
||||
{
|
||||
CertificateProvidersLog._IsCertificateRetrievalProcessing = IsProcessing.Value;
|
||||
}
|
||||
flag = CertificateProvidersLog._IsCertificateRetrievalProcessing;
|
||||
if (flag)
|
||||
{
|
||||
bool flag2 = Status != null;
|
||||
if (flag2)
|
||||
{
|
||||
CertificateProvidersLog._CertificateRetrievalStatus = Status;
|
||||
}
|
||||
flag2 = Progress.HasValue;
|
||||
if (flag2)
|
||||
{
|
||||
CertificateProvidersLog._CertificateRetrievalProgress = Progress.Value;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CertificateProvidersLog._CertificateRetrievalStatus = null;
|
||||
CertificateProvidersLog._CertificateRetrievalProgress = 0;
|
||||
}
|
||||
CertificateProvidersLog.Log(CertificateProvidersLog.EventTypeIds.RetrievalProgress, new object[]
|
||||
{
|
||||
CertificateProvidersLog._IsCertificateRetrievalProcessing,
|
||||
CertificateProvidersLog._CertificateRetrievalProgress,
|
||||
CertificateProvidersLog._CertificateRetrievalStatus
|
||||
});
|
||||
}
|
||||
protected override System.Collections.Generic.List<LogEventType> LoadEventTypes()
|
||||
{
|
||||
return new System.Collections.Generic.List<LogEventType>
|
||||
{
|
||||
new LogEventType
|
||||
{
|
||||
Id = 10,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Starting",
|
||||
Format = "Starting retrieval of {0} certificate/s ({1} to {2})",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 11,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Progress",
|
||||
Format = "Processing: {0}; {1}% Complete; Status: {2}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = false,
|
||||
UseDisplay = false
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 12,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Finished",
|
||||
Format = "Retrieval of Certificates Complete",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 15,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Warning",
|
||||
Format = "Retrieval Warning: {0}",
|
||||
Severity = 1,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 16,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Error",
|
||||
Format = "Retrieval Error: {0}",
|
||||
Severity = 2,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 20,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Starting",
|
||||
Format = "Retrieving Certificate: {0}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 22,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Finished",
|
||||
Format = "Certificate Retrieved: {0}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 25,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Warning",
|
||||
Format = "{0} Certificate Warning: {1}",
|
||||
Severity = 1,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 26,
|
||||
ModuleId = 60,
|
||||
Name = "Retrieval Certificate Error",
|
||||
Format = "{0} Certificate Error: {1}",
|
||||
Severity = 2,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 40,
|
||||
ModuleId = 60,
|
||||
Name = "Allocated",
|
||||
Format = "Certificate {0} allocated to {1}",
|
||||
Severity = 0,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = 50,
|
||||
ModuleId = 60,
|
||||
Name = "Allocation Failed",
|
||||
Format = "No certificates available for Device: {0}",
|
||||
Severity = 2,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-13
@@ -1,13 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.InteroperabilityProvider
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Interoperability Providers")]
|
||||
public abstract class InteroperabilityProviderFeature : PluginFeature
|
||||
{
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.InteroperabilityProvider
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Interoperability Providers")]
|
||||
public abstract class InteroperabilityProviderFeature : PluginFeature
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.Other
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Other")]
|
||||
public abstract class OtherFeature : PluginFeature
|
||||
{
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.Other
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Other")]
|
||||
public abstract class OtherFeature : PluginFeature
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
using Disco.Data.Repository;
|
||||
using Disco.Models.BI.Config;
|
||||
using Disco.Models.Repository;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.WarrantyProvider
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Warranty Providers")]
|
||||
public abstract class WarrantyProviderFeature : PluginFeature
|
||||
{
|
||||
// Warranty Plugin Requirements
|
||||
public abstract string WarrantyProviderId { get; }
|
||||
public abstract Type SubmitJobViewType { get; }
|
||||
public abstract dynamic SubmitJobViewModel(DiscoDataContext dbContext, Controller controller, Job Job, OrganisationAddress Address, User TechUser);
|
||||
public abstract Dictionary<string, string> SubmitJobParseProperties(DiscoDataContext dbContext, FormCollection form, Controller controller, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription);
|
||||
public abstract Dictionary<string, string> SubmitJobDiscloseInfo(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary<string, string> WarrantyProviderProperties);
|
||||
public abstract string SubmitJob(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary<string, string> WarrantyProviderProperties);
|
||||
|
||||
public abstract Type JobDetailsViewType { get; }
|
||||
public bool JobDetailsSupported { get { return this.JobDetailsViewType != null; } }
|
||||
public abstract dynamic JobDetailsViewModel(DiscoDataContext dbContext, Controller controller, Job Job);
|
||||
|
||||
public static PluginFeatureManifest FindPluginFeature(string PluginIdOrWarrantyProviderId)
|
||||
{
|
||||
var defs = Plugins.GetPluginFeatures(typeof(WarrantyProviderFeature));
|
||||
var def = defs.FirstOrDefault(d => d.PluginManifest.Id.Equals(PluginIdOrWarrantyProviderId, StringComparison.InvariantCultureIgnoreCase));
|
||||
if (def != null)
|
||||
return def;
|
||||
else
|
||||
foreach (var d in defs)
|
||||
{
|
||||
using (var providerInstance = d.CreateInstance<WarrantyProviderFeature>())
|
||||
{
|
||||
if (providerInstance.WarrantyProviderId != null && providerInstance.WarrantyProviderId.Equals(PluginIdOrWarrantyProviderId, StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
return d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
using Disco.Data.Repository;
|
||||
using Disco.Models.BI.Config;
|
||||
using Disco.Models.Repository;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.WarrantyProvider
|
||||
{
|
||||
[PluginFeatureCategory(DisplayName = "Warranty Providers")]
|
||||
public abstract class WarrantyProviderFeature : PluginFeature
|
||||
{
|
||||
// Warranty Plugin Requirements
|
||||
public abstract string WarrantyProviderId { get; }
|
||||
public abstract Type SubmitJobViewType { get; }
|
||||
public abstract dynamic SubmitJobViewModel(DiscoDataContext dbContext, Controller controller, Job Job, OrganisationAddress Address, User TechUser);
|
||||
public abstract Dictionary<string, string> SubmitJobParseProperties(DiscoDataContext dbContext, FormCollection form, Controller controller, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription);
|
||||
public abstract Dictionary<string, string> SubmitJobDiscloseInfo(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary<string, string> WarrantyProviderProperties);
|
||||
public abstract string SubmitJob(DiscoDataContext dbContext, Job Job, OrganisationAddress Address, User TechUser, string FaultDescription, Dictionary<string, string> WarrantyProviderProperties);
|
||||
|
||||
public abstract Type JobDetailsViewType { get; }
|
||||
public bool JobDetailsSupported { get { return this.JobDetailsViewType != null; } }
|
||||
public abstract dynamic JobDetailsViewModel(DiscoDataContext dbContext, Controller controller, Job Job);
|
||||
|
||||
public static PluginFeatureManifest FindPluginFeature(string PluginIdOrWarrantyProviderId)
|
||||
{
|
||||
var defs = Plugins.GetPluginFeatures(typeof(WarrantyProviderFeature));
|
||||
var def = defs.FirstOrDefault(d => d.PluginManifest.Id.Equals(PluginIdOrWarrantyProviderId, StringComparison.InvariantCultureIgnoreCase));
|
||||
if (def != null)
|
||||
return def;
|
||||
else
|
||||
foreach (var d in defs)
|
||||
{
|
||||
using (var providerInstance = d.CreateInstance<WarrantyProviderFeature>())
|
||||
{
|
||||
if (providerInstance.WarrantyProviderId != null && providerInstance.WarrantyProviderId.Equals(PluginIdOrWarrantyProviderId, StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
return d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
-12
@@ -1,12 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.WarrantyProvider
|
||||
{
|
||||
public class WarrantyProviderSubmitJobException : Exception
|
||||
{
|
||||
public WarrantyProviderSubmitJobException(string Message)
|
||||
: base(Message)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
|
||||
namespace Disco.Services.Plugins.Features.WarrantyProvider
|
||||
{
|
||||
public class WarrantyProviderSubmitJobException : Exception
|
||||
{
|
||||
public WarrantyProviderSubmitJobException(string Message)
|
||||
: base(Message)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public class InvalidFeatureCategoryTypeException : Exception
|
||||
{
|
||||
private string _pluginRequested;
|
||||
private Type _categoryType;
|
||||
|
||||
public string PluginRequested
|
||||
{
|
||||
get
|
||||
{
|
||||
return _pluginRequested;
|
||||
}
|
||||
}
|
||||
public Type CategoryType
|
||||
{
|
||||
get
|
||||
{
|
||||
return _categoryType;
|
||||
}
|
||||
}
|
||||
|
||||
public InvalidFeatureCategoryTypeException(Type CategoryType)
|
||||
: this(CategoryType, null)
|
||||
{
|
||||
}
|
||||
public InvalidFeatureCategoryTypeException(Type CategoryType, string PluginRequested)
|
||||
{
|
||||
this._categoryType = CategoryType;
|
||||
this._pluginRequested = PluginRequested;
|
||||
}
|
||||
|
||||
public override string Message
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrEmpty(_pluginRequested))
|
||||
return string.Format("Invalid Category Type [{0}]", _categoryType.Name);
|
||||
else
|
||||
return string.Format("Plugin [{1}] is not of the correct Category Type [{0}]", _categoryType.Name, _pluginRequested);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public class InvalidFeatureCategoryTypeException : Exception
|
||||
{
|
||||
private string _pluginRequested;
|
||||
private Type _categoryType;
|
||||
|
||||
public string PluginRequested
|
||||
{
|
||||
get
|
||||
{
|
||||
return _pluginRequested;
|
||||
}
|
||||
}
|
||||
public Type CategoryType
|
||||
{
|
||||
get
|
||||
{
|
||||
return _categoryType;
|
||||
}
|
||||
}
|
||||
|
||||
public InvalidFeatureCategoryTypeException(Type CategoryType)
|
||||
: this(CategoryType, null)
|
||||
{
|
||||
}
|
||||
public InvalidFeatureCategoryTypeException(Type CategoryType, string PluginRequested)
|
||||
{
|
||||
this._categoryType = CategoryType;
|
||||
this._pluginRequested = PluginRequested;
|
||||
}
|
||||
|
||||
public override string Message
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrEmpty(_pluginRequested))
|
||||
return string.Format("Invalid Category Type [{0}]", _categoryType.Name);
|
||||
else
|
||||
return string.Format("Plugin [{1}] is not of the correct Category Type [{0}]", _categoryType.Name, _pluginRequested);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
using Disco.Data.Repository;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public abstract class PluginConfigurationHandler : IDisposable
|
||||
{
|
||||
public PluginManifest Manifest { get; set; }
|
||||
|
||||
public abstract PluginConfigurationHandlerGetResponse Get(DiscoDataContext dbContext, Controller controller);
|
||||
public abstract bool Post(DiscoDataContext dbContext, FormCollection form, Controller controller);
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
// Nothing in Base Class
|
||||
}
|
||||
|
||||
protected PluginConfigurationHandlerGetResponse GetResponse(Type ViewType, dynamic ViewModel = null)
|
||||
{
|
||||
return new PluginConfigurationHandlerGetResponse(this.Manifest, ViewType, ViewModel);
|
||||
}
|
||||
public class PluginConfigurationHandlerGetResponse
|
||||
{
|
||||
public PluginManifest Manifest { get; set; }
|
||||
public Type ViewType { get; set; }
|
||||
public dynamic ViewModel { get; set; }
|
||||
|
||||
public PluginConfigurationHandlerGetResponse(PluginManifest Manifest, Type ViewType, dynamic ViewModel = null)
|
||||
{
|
||||
if (ViewType == null)
|
||||
throw new ArgumentNullException("ViewType");
|
||||
if (!typeof(WebViewPage).IsAssignableFrom(ViewType))
|
||||
throw new ArgumentException("The PluginConfigurationHandler ViewType must inherit System.Web.Mvc.WebViewPage", "ViewType");
|
||||
|
||||
this.Manifest = Manifest;
|
||||
|
||||
this.ViewType = ViewType;
|
||||
this.ViewModel = ViewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
using Disco.Data.Repository;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public abstract class PluginConfigurationHandler : IDisposable
|
||||
{
|
||||
public PluginManifest Manifest { get; set; }
|
||||
|
||||
public abstract PluginConfigurationHandlerGetResponse Get(DiscoDataContext dbContext, Controller controller);
|
||||
public abstract bool Post(DiscoDataContext dbContext, FormCollection form, Controller controller);
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
// Nothing in Base Class
|
||||
}
|
||||
|
||||
protected PluginConfigurationHandlerGetResponse GetResponse(Type ViewType, dynamic ViewModel = null)
|
||||
{
|
||||
return new PluginConfigurationHandlerGetResponse(this.Manifest, ViewType, ViewModel);
|
||||
}
|
||||
public class PluginConfigurationHandlerGetResponse
|
||||
{
|
||||
public PluginManifest Manifest { get; set; }
|
||||
public Type ViewType { get; set; }
|
||||
public dynamic ViewModel { get; set; }
|
||||
|
||||
public PluginConfigurationHandlerGetResponse(PluginManifest Manifest, Type ViewType, dynamic ViewModel = null)
|
||||
{
|
||||
if (ViewType == null)
|
||||
throw new ArgumentNullException("ViewType");
|
||||
if (!typeof(WebViewPage).IsAssignableFrom(ViewType))
|
||||
throw new ArgumentException("The PluginConfigurationHandler ViewType must inherit System.Web.Mvc.WebViewPage", "ViewType");
|
||||
|
||||
this.Manifest = Manifest;
|
||||
|
||||
this.ViewType = ViewType;
|
||||
this.ViewModel = ViewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
|
||||
public class PluginFeatureAttribute : Attribute
|
||||
{
|
||||
public string Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
|
||||
public class PluginFeatureAttribute : Attribute
|
||||
{
|
||||
public string Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
|
||||
public class PluginFeatureCategoryAttribute : Attribute
|
||||
{
|
||||
public string DisplayName { get; set; }
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
|
||||
public class PluginFeatureCategoryAttribute : Attribute
|
||||
{
|
||||
public string DisplayName { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,229 +1,229 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Routing;
|
||||
using RazorGenerator.Mvc;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public abstract class PluginWebHandler : IDisposable
|
||||
{
|
||||
public PluginManifest Manifest { get; set; }
|
||||
public Controller HostController { get; set; }
|
||||
|
||||
public abstract ActionResult ExecuteAction(string ActionName);
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
// Nothing in Base Class
|
||||
}
|
||||
|
||||
|
||||
#region Action Results
|
||||
|
||||
#region Compiled View
|
||||
private static string[] _viewFileNames = new string[] { "cshtml" };
|
||||
public ActionResult CompiledView(Type CompiledViewType, object Model, bool UseDiscoLayout)
|
||||
{
|
||||
string layoutPath = UseDiscoLayout ? "~/Views/Shared/_Layout.cshtml" : null;
|
||||
|
||||
IView v = new PrecompiledMvcView(this.HostController.Request.Path, layoutPath, CompiledViewType, false, _viewFileNames);
|
||||
|
||||
if (Model != null)
|
||||
this.HostController.ViewData.Model = Model;
|
||||
|
||||
return new ViewResult { View = v, ViewData = this.HostController.ViewData, TempData = this.HostController.TempData };
|
||||
}
|
||||
public ActionResult CompiledView(Type CompiledViewType, bool UseDiscoLayout)
|
||||
{
|
||||
return this.CompiledView(CompiledViewType, null, UseDiscoLayout);
|
||||
}
|
||||
public ActionResult CompiledView(Type CompiledViewType, object Model)
|
||||
{
|
||||
return this.CompiledView(CompiledViewType, Model, true);
|
||||
}
|
||||
public ActionResult CompiledView(Type CompiledViewType)
|
||||
{
|
||||
return this.CompiledView(CompiledViewType, false, true);
|
||||
}
|
||||
public ActionResult CompiledPartialView(Type PartialCompiledViewType, object Model)
|
||||
{
|
||||
IView v = new PrecompiledMvcView(this.HostController.Request.Path, PartialCompiledViewType, false, _viewFileNames);
|
||||
|
||||
if (Model != null)
|
||||
this.HostController.ViewData.Model = Model;
|
||||
|
||||
return new PartialViewResult { View = v, ViewData = this.HostController.ViewData, TempData = this.HostController.TempData };
|
||||
}
|
||||
public ActionResult CompiledPartialView(Type PartialCompiledViewType)
|
||||
{
|
||||
return this.CompiledView(PartialCompiledViewType, null);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Content
|
||||
public ActionResult Content(string content, string contentType, Encoding contentEncoding)
|
||||
{
|
||||
return new ContentResult { Content = content, ContentType = contentType, ContentEncoding = contentEncoding };
|
||||
}
|
||||
public ActionResult Content(string content, string contentType)
|
||||
{
|
||||
return this.Content(content, null, null);
|
||||
}
|
||||
public ActionResult Content(string content)
|
||||
{
|
||||
return this.Content(content, null);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Json
|
||||
public ActionResult Json(object data, JsonRequestBehavior behavior)
|
||||
{
|
||||
return new JsonResult { Data = data, ContentType = null, ContentEncoding = null, JsonRequestBehavior = behavior };
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region File
|
||||
public ActionResult File(Stream fileStream, string contentType)
|
||||
{
|
||||
return this.File(fileStream, contentType, null);
|
||||
}
|
||||
public ActionResult File(Stream fileStream, string contentType, string fileDownloadName)
|
||||
{
|
||||
return new FileStreamResult(fileStream, contentType) { FileDownloadName = fileDownloadName };
|
||||
}
|
||||
public ActionResult File(byte[] fileContents, string contentType)
|
||||
{
|
||||
return this.File(fileContents, contentType, null);
|
||||
}
|
||||
public ActionResult File(byte[] fileContents, string contentType, string fileDownloadName)
|
||||
{
|
||||
return new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region HttpNotFound
|
||||
public ActionResult HttpNotFound(string statusDescription)
|
||||
{
|
||||
return new HttpNotFoundResult(statusDescription);
|
||||
}
|
||||
public ActionResult HttpNotFound()
|
||||
{
|
||||
return this.HttpNotFound(null);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Redirect
|
||||
public ActionResult RedirectToScheduledTaskStatus(string SessionId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(SessionId))
|
||||
throw new ArgumentNullException(SessionId);
|
||||
|
||||
return this.RedirectToAction("TaskStatus", "Logging", "Config", new { id = SessionId });
|
||||
}
|
||||
public ActionResult Redirect(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
throw new ArgumentNullException("url");
|
||||
|
||||
return new RedirectResult(url);
|
||||
}
|
||||
public ActionResult RedirectPermanent(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
throw new ArgumentNullException("url");
|
||||
|
||||
return new RedirectResult(url, true);
|
||||
}
|
||||
public ActionResult RedirectToPluginAction(string PluginAction)
|
||||
{
|
||||
if (string.IsNullOrEmpty(PluginAction))
|
||||
throw new ArgumentNullException("PluginAction");
|
||||
|
||||
var routeValues = new RouteValueDictionary(new { PluginId = this.Manifest.Id, PluginAction = PluginAction });
|
||||
string pluginActionUrl = UrlHelper.GenerateUrl("Plugin", null, null, routeValues, RouteTable.Routes, this.HostController.Request.RequestContext, false);
|
||||
|
||||
return new RedirectResult(pluginActionUrl, false);
|
||||
}
|
||||
public ActionResult RedirectToPluginResource(string Resource, bool? Download)
|
||||
{
|
||||
var resourcePath = this.Manifest.WebResourcePath(Resource);
|
||||
|
||||
var routeValues = new RouteValueDictionary(new { PluginId = this.Manifest.Id, res = Resource });
|
||||
string pluginActionUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, this.HostController.Request.RequestContext, false);
|
||||
|
||||
pluginActionUrl += string.Format("?v={0}", resourcePath.Item2);
|
||||
|
||||
if (Download.HasValue && Download.Value)
|
||||
{
|
||||
pluginActionUrl += "&Download=true";
|
||||
}
|
||||
|
||||
return new RedirectResult(pluginActionUrl, false);
|
||||
}
|
||||
public ActionResult RedirectToPluginResource(string Resource)
|
||||
{
|
||||
return this.RedirectToPluginResource(Resource, null);
|
||||
}
|
||||
public ActionResult RedirectToRoute(string routeName, object routeValues)
|
||||
{
|
||||
RouteValueDictionary routeValueDictionary;
|
||||
if (routeValues != null)
|
||||
routeValueDictionary = new RouteValueDictionary(routeValues);
|
||||
else
|
||||
routeValueDictionary = new RouteValueDictionary();
|
||||
|
||||
return new RedirectToRouteResult(routeName, routeValueDictionary);
|
||||
}
|
||||
public ActionResult RedirectToRoute(string routeName)
|
||||
{
|
||||
return this.RedirectToRoute(routeName, null);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller, string areaName, object routeValues)
|
||||
{
|
||||
RouteValueDictionary routeValueDictionary;
|
||||
if (routeValues != null)
|
||||
routeValueDictionary = new RouteValueDictionary(routeValues);
|
||||
else
|
||||
routeValueDictionary = new RouteValueDictionary();
|
||||
|
||||
routeValueDictionary["action"] = actionName;
|
||||
routeValueDictionary["controller"] = controller;
|
||||
if (areaName != null)
|
||||
routeValueDictionary["area"] = areaName;
|
||||
|
||||
return new RedirectToRouteResult(routeValueDictionary);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller, string areaName)
|
||||
{
|
||||
return this.RedirectToAction(actionName, controller, areaName, null);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller, object routeValues)
|
||||
{
|
||||
return this.RedirectToAction(actionName, controller, null, routeValues);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller)
|
||||
{
|
||||
return this.RedirectToAction(actionName, controller, null, null);
|
||||
}
|
||||
public ActionResult RedirectToDiscoJob(int jobId)
|
||||
{
|
||||
return this.RedirectToAction("Show", "Job", null, new { id = jobId.ToString() });
|
||||
}
|
||||
public ActionResult RedirectToDiscoDevice(string DeviceSerialNumber)
|
||||
{
|
||||
return this.RedirectToAction("Show", "Device", null, new { id = DeviceSerialNumber });
|
||||
}
|
||||
public ActionResult RedirectToDiscoUser(string UserId)
|
||||
{
|
||||
return this.RedirectToAction("Show", "User", null, new { id = UserId });
|
||||
}
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Routing;
|
||||
using RazorGenerator.Mvc;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public abstract class PluginWebHandler : IDisposable
|
||||
{
|
||||
public PluginManifest Manifest { get; set; }
|
||||
public Controller HostController { get; set; }
|
||||
|
||||
public abstract ActionResult ExecuteAction(string ActionName);
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
// Nothing in Base Class
|
||||
}
|
||||
|
||||
|
||||
#region Action Results
|
||||
|
||||
#region Compiled View
|
||||
private static string[] _viewFileNames = new string[] { "cshtml" };
|
||||
public ActionResult CompiledView(Type CompiledViewType, object Model, bool UseDiscoLayout)
|
||||
{
|
||||
string layoutPath = UseDiscoLayout ? "~/Views/Shared/_Layout.cshtml" : null;
|
||||
|
||||
IView v = new PrecompiledMvcView(this.HostController.Request.Path, layoutPath, CompiledViewType, false, _viewFileNames);
|
||||
|
||||
if (Model != null)
|
||||
this.HostController.ViewData.Model = Model;
|
||||
|
||||
return new ViewResult { View = v, ViewData = this.HostController.ViewData, TempData = this.HostController.TempData };
|
||||
}
|
||||
public ActionResult CompiledView(Type CompiledViewType, bool UseDiscoLayout)
|
||||
{
|
||||
return this.CompiledView(CompiledViewType, null, UseDiscoLayout);
|
||||
}
|
||||
public ActionResult CompiledView(Type CompiledViewType, object Model)
|
||||
{
|
||||
return this.CompiledView(CompiledViewType, Model, true);
|
||||
}
|
||||
public ActionResult CompiledView(Type CompiledViewType)
|
||||
{
|
||||
return this.CompiledView(CompiledViewType, false, true);
|
||||
}
|
||||
public ActionResult CompiledPartialView(Type PartialCompiledViewType, object Model)
|
||||
{
|
||||
IView v = new PrecompiledMvcView(this.HostController.Request.Path, PartialCompiledViewType, false, _viewFileNames);
|
||||
|
||||
if (Model != null)
|
||||
this.HostController.ViewData.Model = Model;
|
||||
|
||||
return new PartialViewResult { View = v, ViewData = this.HostController.ViewData, TempData = this.HostController.TempData };
|
||||
}
|
||||
public ActionResult CompiledPartialView(Type PartialCompiledViewType)
|
||||
{
|
||||
return this.CompiledView(PartialCompiledViewType, null);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Content
|
||||
public ActionResult Content(string content, string contentType, Encoding contentEncoding)
|
||||
{
|
||||
return new ContentResult { Content = content, ContentType = contentType, ContentEncoding = contentEncoding };
|
||||
}
|
||||
public ActionResult Content(string content, string contentType)
|
||||
{
|
||||
return this.Content(content, null, null);
|
||||
}
|
||||
public ActionResult Content(string content)
|
||||
{
|
||||
return this.Content(content, null);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Json
|
||||
public ActionResult Json(object data, JsonRequestBehavior behavior)
|
||||
{
|
||||
return new JsonResult { Data = data, ContentType = null, ContentEncoding = null, JsonRequestBehavior = behavior };
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region File
|
||||
public ActionResult File(Stream fileStream, string contentType)
|
||||
{
|
||||
return this.File(fileStream, contentType, null);
|
||||
}
|
||||
public ActionResult File(Stream fileStream, string contentType, string fileDownloadName)
|
||||
{
|
||||
return new FileStreamResult(fileStream, contentType) { FileDownloadName = fileDownloadName };
|
||||
}
|
||||
public ActionResult File(byte[] fileContents, string contentType)
|
||||
{
|
||||
return this.File(fileContents, contentType, null);
|
||||
}
|
||||
public ActionResult File(byte[] fileContents, string contentType, string fileDownloadName)
|
||||
{
|
||||
return new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region HttpNotFound
|
||||
public ActionResult HttpNotFound(string statusDescription)
|
||||
{
|
||||
return new HttpNotFoundResult(statusDescription);
|
||||
}
|
||||
public ActionResult HttpNotFound()
|
||||
{
|
||||
return this.HttpNotFound(null);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Redirect
|
||||
public ActionResult RedirectToScheduledTaskStatus(string SessionId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(SessionId))
|
||||
throw new ArgumentNullException(SessionId);
|
||||
|
||||
return this.RedirectToAction("TaskStatus", "Logging", "Config", new { id = SessionId });
|
||||
}
|
||||
public ActionResult Redirect(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
throw new ArgumentNullException("url");
|
||||
|
||||
return new RedirectResult(url);
|
||||
}
|
||||
public ActionResult RedirectPermanent(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
throw new ArgumentNullException("url");
|
||||
|
||||
return new RedirectResult(url, true);
|
||||
}
|
||||
public ActionResult RedirectToPluginAction(string PluginAction)
|
||||
{
|
||||
if (string.IsNullOrEmpty(PluginAction))
|
||||
throw new ArgumentNullException("PluginAction");
|
||||
|
||||
var routeValues = new RouteValueDictionary(new { PluginId = this.Manifest.Id, PluginAction = PluginAction });
|
||||
string pluginActionUrl = UrlHelper.GenerateUrl("Plugin", null, null, routeValues, RouteTable.Routes, this.HostController.Request.RequestContext, false);
|
||||
|
||||
return new RedirectResult(pluginActionUrl, false);
|
||||
}
|
||||
public ActionResult RedirectToPluginResource(string Resource, bool? Download)
|
||||
{
|
||||
var resourcePath = this.Manifest.WebResourcePath(Resource);
|
||||
|
||||
var routeValues = new RouteValueDictionary(new { PluginId = this.Manifest.Id, res = Resource });
|
||||
string pluginActionUrl = UrlHelper.GenerateUrl("Plugin_Resources", null, null, routeValues, RouteTable.Routes, this.HostController.Request.RequestContext, false);
|
||||
|
||||
pluginActionUrl += string.Format("?v={0}", resourcePath.Item2);
|
||||
|
||||
if (Download.HasValue && Download.Value)
|
||||
{
|
||||
pluginActionUrl += "&Download=true";
|
||||
}
|
||||
|
||||
return new RedirectResult(pluginActionUrl, false);
|
||||
}
|
||||
public ActionResult RedirectToPluginResource(string Resource)
|
||||
{
|
||||
return this.RedirectToPluginResource(Resource, null);
|
||||
}
|
||||
public ActionResult RedirectToRoute(string routeName, object routeValues)
|
||||
{
|
||||
RouteValueDictionary routeValueDictionary;
|
||||
if (routeValues != null)
|
||||
routeValueDictionary = new RouteValueDictionary(routeValues);
|
||||
else
|
||||
routeValueDictionary = new RouteValueDictionary();
|
||||
|
||||
return new RedirectToRouteResult(routeName, routeValueDictionary);
|
||||
}
|
||||
public ActionResult RedirectToRoute(string routeName)
|
||||
{
|
||||
return this.RedirectToRoute(routeName, null);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller, string areaName, object routeValues)
|
||||
{
|
||||
RouteValueDictionary routeValueDictionary;
|
||||
if (routeValues != null)
|
||||
routeValueDictionary = new RouteValueDictionary(routeValues);
|
||||
else
|
||||
routeValueDictionary = new RouteValueDictionary();
|
||||
|
||||
routeValueDictionary["action"] = actionName;
|
||||
routeValueDictionary["controller"] = controller;
|
||||
if (areaName != null)
|
||||
routeValueDictionary["area"] = areaName;
|
||||
|
||||
return new RedirectToRouteResult(routeValueDictionary);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller, string areaName)
|
||||
{
|
||||
return this.RedirectToAction(actionName, controller, areaName, null);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller, object routeValues)
|
||||
{
|
||||
return this.RedirectToAction(actionName, controller, null, routeValues);
|
||||
}
|
||||
public ActionResult RedirectToAction(string actionName, string controller)
|
||||
{
|
||||
return this.RedirectToAction(actionName, controller, null, null);
|
||||
}
|
||||
public ActionResult RedirectToDiscoJob(int jobId)
|
||||
{
|
||||
return this.RedirectToAction("Show", "Job", null, new { id = jobId.ToString() });
|
||||
}
|
||||
public ActionResult RedirectToDiscoDevice(string DeviceSerialNumber)
|
||||
{
|
||||
return this.RedirectToAction("Show", "Device", null, new { id = DeviceSerialNumber });
|
||||
}
|
||||
public ActionResult RedirectToDiscoUser(string UserId)
|
||||
{
|
||||
return this.RedirectToAction("Show", "User", null, new { id = UserId });
|
||||
}
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,121 +1,121 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public abstract class PluginWebHandlerController : PluginWebHandler
|
||||
{
|
||||
|
||||
public override ActionResult ExecuteAction(string ActionName)
|
||||
{
|
||||
var handlerType = this.GetType();
|
||||
var methodDescriptor = FindControllerMethod(handlerType, ActionName);
|
||||
|
||||
if (methodDescriptor == null)
|
||||
return this.HttpNotFound("Unknown Plugin Method");
|
||||
|
||||
var methodParams = BuildMethodParameters(handlerType, methodDescriptor.MethodInfo, ActionName, this.HostController);
|
||||
|
||||
return (ActionResult)methodDescriptor.MethodInfo.Invoke(this, methodParams);
|
||||
}
|
||||
|
||||
private static WebHandlerCachedItem FindControllerMethod(Type Handler, string ActionName)
|
||||
{
|
||||
var descriptors = CacheWebHandler(Handler);
|
||||
WebHandlerCachedItem method;
|
||||
if (descriptors.TryGetValue(ActionName.ToLower(), out method))
|
||||
return method; // Not Found
|
||||
else
|
||||
return null; // Not Found
|
||||
}
|
||||
private static object[] BuildMethodParameters(Type Handler, MethodInfo methodInfo, string ActionName, Controller HostController)
|
||||
{
|
||||
var methodParams = methodInfo.GetParameters();
|
||||
var result = new object[methodParams.Length];
|
||||
|
||||
for (int i = 0; i < methodParams.Length; i++)
|
||||
{
|
||||
var methodParam = methodParams[i];
|
||||
|
||||
Type parameterType = methodParam.ParameterType;
|
||||
IModelBinder modelBinder = ModelBinders.Binders.GetBinder(parameterType);
|
||||
IValueProvider valueProvider = HostController.ValueProvider;
|
||||
string parameterName = methodParam.Name;
|
||||
|
||||
ModelBindingContext bindingContext = new ModelBindingContext()
|
||||
{
|
||||
FallbackToEmptyPrefix = true,
|
||||
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),
|
||||
ModelName = parameterName,
|
||||
ModelState = HostController.ViewData.ModelState,
|
||||
PropertyFilter = (p) => true,
|
||||
ValueProvider = valueProvider
|
||||
};
|
||||
|
||||
var parameterValue = modelBinder.BindModel(HostController.ControllerContext, bindingContext);
|
||||
|
||||
if (parameterValue == null && methodParam.HasDefaultValue)
|
||||
parameterValue = methodParam.DefaultValue;
|
||||
|
||||
result[i] = parameterValue;
|
||||
|
||||
//var paramInstance = Activator.CreateInstance(methodParam.ParameterType);
|
||||
|
||||
//IModelBinder binder = ModelBinders.Binders.GetBinder(methodParam.ParameterType);
|
||||
//ModelBindingContext bindingContext = new ModelBindingContext
|
||||
//{
|
||||
// ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => paramInstance, methodParam.ParameterType),
|
||||
// ModelName = methodParam.Name,
|
||||
// ModelState = HostController.ModelState,
|
||||
// PropertyFilter = (p) => true,
|
||||
// ValueProvider = HostController.ValueProvider
|
||||
//};
|
||||
//binder.BindModel(HostController.ControllerContext, bindingContext);
|
||||
|
||||
//if (methodParam.HasDefaultValue && paramInstance == null)
|
||||
// paramInstance = methodParam.DefaultValue;
|
||||
|
||||
//result[i] = paramInstance;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#region Method Cache
|
||||
private static Dictionary<Type, Dictionary<string, WebHandlerCachedItem>> WebHandlerCachedItems = new Dictionary<Type, Dictionary<string, WebHandlerCachedItem>>();
|
||||
private static Dictionary<string, WebHandlerCachedItem> CacheWebHandler(Type Handler)
|
||||
{
|
||||
Dictionary<string, WebHandlerCachedItem> result;
|
||||
|
||||
if (!WebHandlerCachedItems.TryGetValue(Handler, out result))
|
||||
{
|
||||
// Cache Miss
|
||||
result = new Dictionary<string, WebHandlerCachedItem>();
|
||||
var methods = Array.FindAll<MethodInfo>(Handler.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly), mi => { return !mi.IsSpecialName && typeof(ActionResult).IsAssignableFrom(mi.ReturnType); });
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var item = new WebHandlerCachedItem()
|
||||
{
|
||||
Method = method.Name,
|
||||
MethodInfo = method
|
||||
};
|
||||
result.Add(item.Method.ToLower(), item);
|
||||
}
|
||||
WebHandlerCachedItems[Handler] = result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
private class WebHandlerCachedItem
|
||||
{
|
||||
public string Method { get; set; }
|
||||
public MethodInfo MethodInfo { get; set; }
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public abstract class PluginWebHandlerController : PluginWebHandler
|
||||
{
|
||||
|
||||
public override ActionResult ExecuteAction(string ActionName)
|
||||
{
|
||||
var handlerType = this.GetType();
|
||||
var methodDescriptor = FindControllerMethod(handlerType, ActionName);
|
||||
|
||||
if (methodDescriptor == null)
|
||||
return this.HttpNotFound("Unknown Plugin Method");
|
||||
|
||||
var methodParams = BuildMethodParameters(handlerType, methodDescriptor.MethodInfo, ActionName, this.HostController);
|
||||
|
||||
return (ActionResult)methodDescriptor.MethodInfo.Invoke(this, methodParams);
|
||||
}
|
||||
|
||||
private static WebHandlerCachedItem FindControllerMethod(Type Handler, string ActionName)
|
||||
{
|
||||
var descriptors = CacheWebHandler(Handler);
|
||||
WebHandlerCachedItem method;
|
||||
if (descriptors.TryGetValue(ActionName.ToLower(), out method))
|
||||
return method; // Not Found
|
||||
else
|
||||
return null; // Not Found
|
||||
}
|
||||
private static object[] BuildMethodParameters(Type Handler, MethodInfo methodInfo, string ActionName, Controller HostController)
|
||||
{
|
||||
var methodParams = methodInfo.GetParameters();
|
||||
var result = new object[methodParams.Length];
|
||||
|
||||
for (int i = 0; i < methodParams.Length; i++)
|
||||
{
|
||||
var methodParam = methodParams[i];
|
||||
|
||||
Type parameterType = methodParam.ParameterType;
|
||||
IModelBinder modelBinder = ModelBinders.Binders.GetBinder(parameterType);
|
||||
IValueProvider valueProvider = HostController.ValueProvider;
|
||||
string parameterName = methodParam.Name;
|
||||
|
||||
ModelBindingContext bindingContext = new ModelBindingContext()
|
||||
{
|
||||
FallbackToEmptyPrefix = true,
|
||||
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),
|
||||
ModelName = parameterName,
|
||||
ModelState = HostController.ViewData.ModelState,
|
||||
PropertyFilter = (p) => true,
|
||||
ValueProvider = valueProvider
|
||||
};
|
||||
|
||||
var parameterValue = modelBinder.BindModel(HostController.ControllerContext, bindingContext);
|
||||
|
||||
if (parameterValue == null && methodParam.HasDefaultValue)
|
||||
parameterValue = methodParam.DefaultValue;
|
||||
|
||||
result[i] = parameterValue;
|
||||
|
||||
//var paramInstance = Activator.CreateInstance(methodParam.ParameterType);
|
||||
|
||||
//IModelBinder binder = ModelBinders.Binders.GetBinder(methodParam.ParameterType);
|
||||
//ModelBindingContext bindingContext = new ModelBindingContext
|
||||
//{
|
||||
// ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => paramInstance, methodParam.ParameterType),
|
||||
// ModelName = methodParam.Name,
|
||||
// ModelState = HostController.ModelState,
|
||||
// PropertyFilter = (p) => true,
|
||||
// ValueProvider = HostController.ValueProvider
|
||||
//};
|
||||
//binder.BindModel(HostController.ControllerContext, bindingContext);
|
||||
|
||||
//if (methodParam.HasDefaultValue && paramInstance == null)
|
||||
// paramInstance = methodParam.DefaultValue;
|
||||
|
||||
//result[i] = paramInstance;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#region Method Cache
|
||||
private static Dictionary<Type, Dictionary<string, WebHandlerCachedItem>> WebHandlerCachedItems = new Dictionary<Type, Dictionary<string, WebHandlerCachedItem>>();
|
||||
private static Dictionary<string, WebHandlerCachedItem> CacheWebHandler(Type Handler)
|
||||
{
|
||||
Dictionary<string, WebHandlerCachedItem> result;
|
||||
|
||||
if (!WebHandlerCachedItems.TryGetValue(Handler, out result))
|
||||
{
|
||||
// Cache Miss
|
||||
result = new Dictionary<string, WebHandlerCachedItem>();
|
||||
var methods = Array.FindAll<MethodInfo>(Handler.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly), mi => { return !mi.IsSpecialName && typeof(ActionResult).IsAssignableFrom(mi.ReturnType); });
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var item = new WebHandlerCachedItem()
|
||||
{
|
||||
Method = method.Name,
|
||||
MethodInfo = method
|
||||
};
|
||||
result.Add(item.Method.ToLower(), item);
|
||||
}
|
||||
WebHandlerCachedItems[Handler] = result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
private class WebHandlerCachedItem
|
||||
{
|
||||
public string Method { get; set; }
|
||||
public MethodInfo MethodInfo { get; set; }
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public class UnknownPluginException : Exception
|
||||
{
|
||||
private string _pluginRequested;
|
||||
|
||||
public string PluginRequested
|
||||
{
|
||||
get
|
||||
{
|
||||
return _pluginRequested;
|
||||
}
|
||||
}
|
||||
|
||||
public UnknownPluginException(string PluginRequested)
|
||||
{
|
||||
this._pluginRequested = PluginRequested;
|
||||
}
|
||||
public UnknownPluginException(string PluginRequested, string Message) : base(Message)
|
||||
{
|
||||
this._pluginRequested = PluginRequested;
|
||||
}
|
||||
|
||||
public override string Message
|
||||
{
|
||||
get
|
||||
{
|
||||
return string.Format("Unknown Plugin Id: [{0}]", _pluginRequested);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Plugins
|
||||
{
|
||||
public class UnknownPluginException : Exception
|
||||
{
|
||||
private string _pluginRequested;
|
||||
|
||||
public string PluginRequested
|
||||
{
|
||||
get
|
||||
{
|
||||
return _pluginRequested;
|
||||
}
|
||||
}
|
||||
|
||||
public UnknownPluginException(string PluginRequested)
|
||||
{
|
||||
this._pluginRequested = PluginRequested;
|
||||
}
|
||||
public UnknownPluginException(string PluginRequested, string Message) : base(Message)
|
||||
{
|
||||
this._pluginRequested = PluginRequested;
|
||||
}
|
||||
|
||||
public override string Message
|
||||
{
|
||||
get
|
||||
{
|
||||
return string.Format("Unknown Plugin Id: [{0}]", _pluginRequested);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,351 +1,351 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Quartz;
|
||||
using System.Web.Script.Serialization;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTaskStatus
|
||||
{
|
||||
#region Backing Fields
|
||||
|
||||
private string _sessionId;
|
||||
private string _triggerKey;
|
||||
private string _taskName;
|
||||
private Type _taskType;
|
||||
private bool _isSilent;
|
||||
|
||||
private byte _progress;
|
||||
private string _currentProcess;
|
||||
private string _currentDescription;
|
||||
|
||||
private Exception _taskException;
|
||||
private bool _cancelInitiallySupported;
|
||||
private bool _cancelSupported;
|
||||
private bool _isCanceling;
|
||||
|
||||
private DateTime? _startedTimestamp;
|
||||
private DateTime? _nextScheduledTimestamp;
|
||||
private DateTime? _finishedTimestamp;
|
||||
|
||||
private string _finishedMessage;
|
||||
private string _finishedUrl;
|
||||
|
||||
private int _statusVersion = 0;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
public string SessionId { get { return this._sessionId; } }
|
||||
public string TriggerKey { get { return this._triggerKey; } }
|
||||
public string TaskName { get { return this._taskName; } }
|
||||
public Type TaskType { get { return this._taskType; } }
|
||||
public bool IsSilent { get { return this._isSilent; } }
|
||||
|
||||
public byte Progress { get { return this._progress; } }
|
||||
public string CurrentProcess { get { return this._currentProcess; } }
|
||||
public string CurrentDescription { get { return this._currentDescription; } }
|
||||
|
||||
public Exception TaskException { get { return this._taskException; } }
|
||||
public bool CancelSupported { get { return this._cancelSupported; } }
|
||||
public bool IsCanceling { get { return this._isCanceling; } }
|
||||
|
||||
public DateTime? StartedTimestamp { get { return this._startedTimestamp; } }
|
||||
public DateTime? FinishedTimestamp { get { return this._finishedTimestamp; } }
|
||||
public DateTime? NextScheduledTimestamp { get { return this._nextScheduledTimestamp; } }
|
||||
|
||||
public string FinishedMessage { get { return this._finishedMessage; } }
|
||||
public string FinishedUrl { get { return this._finishedUrl; } }
|
||||
|
||||
public int StatusVersion { get { return this._statusVersion; } }
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get
|
||||
{
|
||||
return _startedTimestamp.HasValue && !_finishedTimestamp.HasValue;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Events
|
||||
public delegate void UpdatedEvent(ScheduledTaskStatus sender, string[] ChangedProperties);
|
||||
public delegate void CancelingEvent(ScheduledTaskStatus sender);
|
||||
public event UpdatedEvent Updated;
|
||||
public event CancelingEvent Canceling;
|
||||
#endregion
|
||||
|
||||
public ScheduledTaskStatus(ScheduledTask Task, string SessionId, string TriggerKey, string FinishedUrl = null)
|
||||
{
|
||||
this._taskName = Task.TaskName;
|
||||
this._taskType = Task.GetType();
|
||||
|
||||
this._sessionId = SessionId;
|
||||
this._triggerKey = TriggerKey;
|
||||
this._cancelInitiallySupported = Task.CancelInitiallySupported;
|
||||
this._cancelSupported = this._cancelInitiallySupported;
|
||||
|
||||
this._finishedUrl = FinishedUrl;
|
||||
|
||||
this._currentProcess = "Scheduled";
|
||||
this._currentDescription = "Scheduled Task for Execution";
|
||||
|
||||
this._progress = 0;
|
||||
}
|
||||
|
||||
#region Progress Actions
|
||||
public void UpdateStatus(byte Progress)
|
||||
{
|
||||
this._progress = Progress;
|
||||
UpdateTriggered(new string[] { "Progress" });
|
||||
}
|
||||
public void UpdateStatus(double Progress)
|
||||
{
|
||||
UpdateStatus((byte)Progress);
|
||||
}
|
||||
public void UpdateStatus(string CurrentDescription)
|
||||
{
|
||||
this._currentDescription = CurrentDescription;
|
||||
UpdateTriggered(new string[] { "CurrentDescription" });
|
||||
}
|
||||
public void UpdateStatus(byte Progress, string CurrentDescription)
|
||||
{
|
||||
this._progress = Progress;
|
||||
this._currentDescription = CurrentDescription;
|
||||
UpdateTriggered(new string[] { "Progress", "CurrentDescription" });
|
||||
}
|
||||
public void UpdateStatus(double Progress, string CurrentDescription)
|
||||
{
|
||||
UpdateStatus((byte)Progress, CurrentDescription);
|
||||
}
|
||||
public void UpdateStatus(byte Progress, string CurrentProcess, string CurrentDescription)
|
||||
{
|
||||
this._progress = Progress;
|
||||
this._currentProcess = CurrentProcess;
|
||||
this._currentDescription = CurrentDescription;
|
||||
UpdateTriggered(new string[] { "Progress", "CurrentProcess", "CurrentDescription" });
|
||||
}
|
||||
public void UpdateStatus(double Progress, string CurrentProcess, string CurrentDescription)
|
||||
{
|
||||
UpdateStatus((byte)Progress, CurrentProcess, CurrentDescription);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region State Actions
|
||||
public bool Canceled()
|
||||
{
|
||||
if (!this._isCanceling)
|
||||
{
|
||||
if (_cancelSupported)
|
||||
{ // Cancelling
|
||||
this._isCanceling = true;
|
||||
UpdateTriggered(new string[] { "IsCancelling" });
|
||||
if (this.Canceling != null)
|
||||
Canceling(this);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{ // Cancelling not supported
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{ // Already Cancelling
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public void SetCancelSupported(bool CancelSupported)
|
||||
{
|
||||
if (this._cancelSupported != CancelSupported)
|
||||
{
|
||||
this._cancelSupported = CancelSupported;
|
||||
UpdateTriggered(new string[] { "CancelSupported" });
|
||||
}
|
||||
}
|
||||
public void SetTaskException(Exception TaskException)
|
||||
{
|
||||
if (this._taskException != TaskException)
|
||||
{
|
||||
this._taskException = TaskException;
|
||||
UpdateTriggered(new string[] { "TaskException" });
|
||||
}
|
||||
}
|
||||
public void SetIsSilent(bool IsSilent)
|
||||
{
|
||||
if (this._isSilent != IsSilent)
|
||||
this._isSilent = IsSilent;
|
||||
}
|
||||
public void SetFinishedUrl(string FinishedUrl)
|
||||
{
|
||||
if (this._finishedUrl != FinishedUrl)
|
||||
{
|
||||
this._finishedUrl = FinishedUrl;
|
||||
UpdateTriggered(new string[] { "FinishedUrl" });
|
||||
}
|
||||
}
|
||||
public void SetFinishedMessage(string FinishedMessage)
|
||||
{
|
||||
if (this._finishedMessage != FinishedMessage)
|
||||
{
|
||||
this._finishedMessage = FinishedMessage;
|
||||
UpdateTriggered(new string[] { "FinishedMessage" });
|
||||
}
|
||||
}
|
||||
public void SetNextScheduledTimestamp(DateTime? NextScheduledTimestamp)
|
||||
{
|
||||
if (this._nextScheduledTimestamp != NextScheduledTimestamp)
|
||||
{
|
||||
this._nextScheduledTimestamp = NextScheduledTimestamp;
|
||||
UpdateTriggered(new string[] { "NextScheduledTimestamp" });
|
||||
}
|
||||
}
|
||||
public void Started()
|
||||
{
|
||||
List<string> changedProperties = new List<string>() { "IsRunning", "StartedTimestamp" };
|
||||
|
||||
this._startedTimestamp = DateTime.Now;
|
||||
|
||||
if (this._nextScheduledTimestamp != null)
|
||||
{
|
||||
this._nextScheduledTimestamp = null;
|
||||
changedProperties.Add("NextScheduledTimestamp");
|
||||
}
|
||||
if (this._finishedTimestamp != null)
|
||||
{
|
||||
this._finishedTimestamp = null;
|
||||
changedProperties.Add("FinishedTimestamp");
|
||||
}
|
||||
if (this._progress != 0)
|
||||
{
|
||||
this._progress = 0;
|
||||
changedProperties.Add("Progress");
|
||||
}
|
||||
if (this._currentProcess != "Starting")
|
||||
{
|
||||
this._currentProcess = "Starting";
|
||||
changedProperties.Add("CurrentProcess");
|
||||
}
|
||||
if (this._currentDescription != "Initializing Task for Execution")
|
||||
{
|
||||
this._currentDescription = "Initializing Task for Execution";
|
||||
changedProperties.Add("CurrentDescription");
|
||||
}
|
||||
if (this._taskException != null)
|
||||
{
|
||||
this._taskException = null;
|
||||
changedProperties.Add("TaskException");
|
||||
}
|
||||
if (this._cancelSupported != this._cancelInitiallySupported)
|
||||
{
|
||||
this._cancelSupported = this._cancelInitiallySupported;
|
||||
changedProperties.Add("CancelSupported");
|
||||
}
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
if (this._isCanceling)
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
UpdateTriggered(changedProperties.ToArray());
|
||||
}
|
||||
public void Finished()
|
||||
{
|
||||
Finished(this._finishedMessage, this._finishedUrl);
|
||||
}
|
||||
public void Finished(string FinishedMessage, string FinishedUrl)
|
||||
{
|
||||
List<string> changedProperties = new List<string>() { "IsRunning", "FinishedTimestamp" };
|
||||
|
||||
this._finishedTimestamp = DateTime.Now;
|
||||
|
||||
if (FinishedMessage != this._finishedMessage)
|
||||
{
|
||||
this._finishedMessage = FinishedMessage;
|
||||
changedProperties.Add("FinishedMessage");
|
||||
}
|
||||
if (FinishedUrl != this._finishedUrl)
|
||||
{
|
||||
this._finishedUrl = FinishedUrl;
|
||||
changedProperties.Add("FinishedUrl");
|
||||
}
|
||||
|
||||
if (this._isCanceling)
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
UpdateTriggered(changedProperties.ToArray());
|
||||
}
|
||||
public void Reset(DateTime? NextScheduledTimestamp)
|
||||
{
|
||||
List<string> changedProperties = new List<string>();
|
||||
|
||||
if (this._nextScheduledTimestamp != NextScheduledTimestamp)
|
||||
{
|
||||
this._nextScheduledTimestamp = NextScheduledTimestamp;
|
||||
changedProperties.Add("NextScheduledTimestamp");
|
||||
}
|
||||
|
||||
if (this._startedTimestamp != null)
|
||||
{
|
||||
this._startedTimestamp = null;
|
||||
changedProperties.Add("StartedTimestamp");
|
||||
}
|
||||
if (this._finishedTimestamp != null)
|
||||
{
|
||||
this._finishedTimestamp = null;
|
||||
changedProperties.Add("FinishedTimestamp");
|
||||
}
|
||||
if (this._finishedMessage != null)
|
||||
{
|
||||
this._finishedMessage = null;
|
||||
changedProperties.Add("FinishedMessage");
|
||||
}
|
||||
if (this._finishedUrl != null)
|
||||
{
|
||||
this._finishedUrl = null;
|
||||
changedProperties.Add("FinishedUrl");
|
||||
}
|
||||
if (this._progress != 0)
|
||||
{
|
||||
this._progress = 0;
|
||||
changedProperties.Add("Progress");
|
||||
}
|
||||
if (this._currentProcess != "Scheduled")
|
||||
{
|
||||
this._currentProcess = "Scheduled";
|
||||
changedProperties.Add("CurrentProcess");
|
||||
}
|
||||
if (this._currentDescription != "Scheduled Task for Execution")
|
||||
{
|
||||
this._currentDescription = "Scheduled Task for Execution";
|
||||
changedProperties.Add("CurrentDescription");
|
||||
}
|
||||
if (this._isCanceling)
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
UpdateTriggered(changedProperties.ToArray());
|
||||
}
|
||||
#endregion
|
||||
|
||||
private void UpdateTriggered(string[] ChangedProperties)
|
||||
{
|
||||
this._statusVersion++;
|
||||
|
||||
if (Updated != null)
|
||||
Updated(this, ChangedProperties);
|
||||
|
||||
if (!_isSilent)
|
||||
ScheduledTasksLiveStatusService.Broadcast(ScheduledTaskStatusLive.FromScheduledTaskStatus(this, ChangedProperties));
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Quartz;
|
||||
using System.Web.Script.Serialization;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTaskStatus
|
||||
{
|
||||
#region Backing Fields
|
||||
|
||||
private string _sessionId;
|
||||
private string _triggerKey;
|
||||
private string _taskName;
|
||||
private Type _taskType;
|
||||
private bool _isSilent;
|
||||
|
||||
private byte _progress;
|
||||
private string _currentProcess;
|
||||
private string _currentDescription;
|
||||
|
||||
private Exception _taskException;
|
||||
private bool _cancelInitiallySupported;
|
||||
private bool _cancelSupported;
|
||||
private bool _isCanceling;
|
||||
|
||||
private DateTime? _startedTimestamp;
|
||||
private DateTime? _nextScheduledTimestamp;
|
||||
private DateTime? _finishedTimestamp;
|
||||
|
||||
private string _finishedMessage;
|
||||
private string _finishedUrl;
|
||||
|
||||
private int _statusVersion = 0;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
public string SessionId { get { return this._sessionId; } }
|
||||
public string TriggerKey { get { return this._triggerKey; } }
|
||||
public string TaskName { get { return this._taskName; } }
|
||||
public Type TaskType { get { return this._taskType; } }
|
||||
public bool IsSilent { get { return this._isSilent; } }
|
||||
|
||||
public byte Progress { get { return this._progress; } }
|
||||
public string CurrentProcess { get { return this._currentProcess; } }
|
||||
public string CurrentDescription { get { return this._currentDescription; } }
|
||||
|
||||
public Exception TaskException { get { return this._taskException; } }
|
||||
public bool CancelSupported { get { return this._cancelSupported; } }
|
||||
public bool IsCanceling { get { return this._isCanceling; } }
|
||||
|
||||
public DateTime? StartedTimestamp { get { return this._startedTimestamp; } }
|
||||
public DateTime? FinishedTimestamp { get { return this._finishedTimestamp; } }
|
||||
public DateTime? NextScheduledTimestamp { get { return this._nextScheduledTimestamp; } }
|
||||
|
||||
public string FinishedMessage { get { return this._finishedMessage; } }
|
||||
public string FinishedUrl { get { return this._finishedUrl; } }
|
||||
|
||||
public int StatusVersion { get { return this._statusVersion; } }
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get
|
||||
{
|
||||
return _startedTimestamp.HasValue && !_finishedTimestamp.HasValue;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Events
|
||||
public delegate void UpdatedEvent(ScheduledTaskStatus sender, string[] ChangedProperties);
|
||||
public delegate void CancelingEvent(ScheduledTaskStatus sender);
|
||||
public event UpdatedEvent Updated;
|
||||
public event CancelingEvent Canceling;
|
||||
#endregion
|
||||
|
||||
public ScheduledTaskStatus(ScheduledTask Task, string SessionId, string TriggerKey, string FinishedUrl = null)
|
||||
{
|
||||
this._taskName = Task.TaskName;
|
||||
this._taskType = Task.GetType();
|
||||
|
||||
this._sessionId = SessionId;
|
||||
this._triggerKey = TriggerKey;
|
||||
this._cancelInitiallySupported = Task.CancelInitiallySupported;
|
||||
this._cancelSupported = this._cancelInitiallySupported;
|
||||
|
||||
this._finishedUrl = FinishedUrl;
|
||||
|
||||
this._currentProcess = "Scheduled";
|
||||
this._currentDescription = "Scheduled Task for Execution";
|
||||
|
||||
this._progress = 0;
|
||||
}
|
||||
|
||||
#region Progress Actions
|
||||
public void UpdateStatus(byte Progress)
|
||||
{
|
||||
this._progress = Progress;
|
||||
UpdateTriggered(new string[] { "Progress" });
|
||||
}
|
||||
public void UpdateStatus(double Progress)
|
||||
{
|
||||
UpdateStatus((byte)Progress);
|
||||
}
|
||||
public void UpdateStatus(string CurrentDescription)
|
||||
{
|
||||
this._currentDescription = CurrentDescription;
|
||||
UpdateTriggered(new string[] { "CurrentDescription" });
|
||||
}
|
||||
public void UpdateStatus(byte Progress, string CurrentDescription)
|
||||
{
|
||||
this._progress = Progress;
|
||||
this._currentDescription = CurrentDescription;
|
||||
UpdateTriggered(new string[] { "Progress", "CurrentDescription" });
|
||||
}
|
||||
public void UpdateStatus(double Progress, string CurrentDescription)
|
||||
{
|
||||
UpdateStatus((byte)Progress, CurrentDescription);
|
||||
}
|
||||
public void UpdateStatus(byte Progress, string CurrentProcess, string CurrentDescription)
|
||||
{
|
||||
this._progress = Progress;
|
||||
this._currentProcess = CurrentProcess;
|
||||
this._currentDescription = CurrentDescription;
|
||||
UpdateTriggered(new string[] { "Progress", "CurrentProcess", "CurrentDescription" });
|
||||
}
|
||||
public void UpdateStatus(double Progress, string CurrentProcess, string CurrentDescription)
|
||||
{
|
||||
UpdateStatus((byte)Progress, CurrentProcess, CurrentDescription);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region State Actions
|
||||
public bool Canceled()
|
||||
{
|
||||
if (!this._isCanceling)
|
||||
{
|
||||
if (_cancelSupported)
|
||||
{ // Cancelling
|
||||
this._isCanceling = true;
|
||||
UpdateTriggered(new string[] { "IsCancelling" });
|
||||
if (this.Canceling != null)
|
||||
Canceling(this);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{ // Cancelling not supported
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{ // Already Cancelling
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public void SetCancelSupported(bool CancelSupported)
|
||||
{
|
||||
if (this._cancelSupported != CancelSupported)
|
||||
{
|
||||
this._cancelSupported = CancelSupported;
|
||||
UpdateTriggered(new string[] { "CancelSupported" });
|
||||
}
|
||||
}
|
||||
public void SetTaskException(Exception TaskException)
|
||||
{
|
||||
if (this._taskException != TaskException)
|
||||
{
|
||||
this._taskException = TaskException;
|
||||
UpdateTriggered(new string[] { "TaskException" });
|
||||
}
|
||||
}
|
||||
public void SetIsSilent(bool IsSilent)
|
||||
{
|
||||
if (this._isSilent != IsSilent)
|
||||
this._isSilent = IsSilent;
|
||||
}
|
||||
public void SetFinishedUrl(string FinishedUrl)
|
||||
{
|
||||
if (this._finishedUrl != FinishedUrl)
|
||||
{
|
||||
this._finishedUrl = FinishedUrl;
|
||||
UpdateTriggered(new string[] { "FinishedUrl" });
|
||||
}
|
||||
}
|
||||
public void SetFinishedMessage(string FinishedMessage)
|
||||
{
|
||||
if (this._finishedMessage != FinishedMessage)
|
||||
{
|
||||
this._finishedMessage = FinishedMessage;
|
||||
UpdateTriggered(new string[] { "FinishedMessage" });
|
||||
}
|
||||
}
|
||||
public void SetNextScheduledTimestamp(DateTime? NextScheduledTimestamp)
|
||||
{
|
||||
if (this._nextScheduledTimestamp != NextScheduledTimestamp)
|
||||
{
|
||||
this._nextScheduledTimestamp = NextScheduledTimestamp;
|
||||
UpdateTriggered(new string[] { "NextScheduledTimestamp" });
|
||||
}
|
||||
}
|
||||
public void Started()
|
||||
{
|
||||
List<string> changedProperties = new List<string>() { "IsRunning", "StartedTimestamp" };
|
||||
|
||||
this._startedTimestamp = DateTime.Now;
|
||||
|
||||
if (this._nextScheduledTimestamp != null)
|
||||
{
|
||||
this._nextScheduledTimestamp = null;
|
||||
changedProperties.Add("NextScheduledTimestamp");
|
||||
}
|
||||
if (this._finishedTimestamp != null)
|
||||
{
|
||||
this._finishedTimestamp = null;
|
||||
changedProperties.Add("FinishedTimestamp");
|
||||
}
|
||||
if (this._progress != 0)
|
||||
{
|
||||
this._progress = 0;
|
||||
changedProperties.Add("Progress");
|
||||
}
|
||||
if (this._currentProcess != "Starting")
|
||||
{
|
||||
this._currentProcess = "Starting";
|
||||
changedProperties.Add("CurrentProcess");
|
||||
}
|
||||
if (this._currentDescription != "Initializing Task for Execution")
|
||||
{
|
||||
this._currentDescription = "Initializing Task for Execution";
|
||||
changedProperties.Add("CurrentDescription");
|
||||
}
|
||||
if (this._taskException != null)
|
||||
{
|
||||
this._taskException = null;
|
||||
changedProperties.Add("TaskException");
|
||||
}
|
||||
if (this._cancelSupported != this._cancelInitiallySupported)
|
||||
{
|
||||
this._cancelSupported = this._cancelInitiallySupported;
|
||||
changedProperties.Add("CancelSupported");
|
||||
}
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
if (this._isCanceling)
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
UpdateTriggered(changedProperties.ToArray());
|
||||
}
|
||||
public void Finished()
|
||||
{
|
||||
Finished(this._finishedMessage, this._finishedUrl);
|
||||
}
|
||||
public void Finished(string FinishedMessage, string FinishedUrl)
|
||||
{
|
||||
List<string> changedProperties = new List<string>() { "IsRunning", "FinishedTimestamp" };
|
||||
|
||||
this._finishedTimestamp = DateTime.Now;
|
||||
|
||||
if (FinishedMessage != this._finishedMessage)
|
||||
{
|
||||
this._finishedMessage = FinishedMessage;
|
||||
changedProperties.Add("FinishedMessage");
|
||||
}
|
||||
if (FinishedUrl != this._finishedUrl)
|
||||
{
|
||||
this._finishedUrl = FinishedUrl;
|
||||
changedProperties.Add("FinishedUrl");
|
||||
}
|
||||
|
||||
if (this._isCanceling)
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
UpdateTriggered(changedProperties.ToArray());
|
||||
}
|
||||
public void Reset(DateTime? NextScheduledTimestamp)
|
||||
{
|
||||
List<string> changedProperties = new List<string>();
|
||||
|
||||
if (this._nextScheduledTimestamp != NextScheduledTimestamp)
|
||||
{
|
||||
this._nextScheduledTimestamp = NextScheduledTimestamp;
|
||||
changedProperties.Add("NextScheduledTimestamp");
|
||||
}
|
||||
|
||||
if (this._startedTimestamp != null)
|
||||
{
|
||||
this._startedTimestamp = null;
|
||||
changedProperties.Add("StartedTimestamp");
|
||||
}
|
||||
if (this._finishedTimestamp != null)
|
||||
{
|
||||
this._finishedTimestamp = null;
|
||||
changedProperties.Add("FinishedTimestamp");
|
||||
}
|
||||
if (this._finishedMessage != null)
|
||||
{
|
||||
this._finishedMessage = null;
|
||||
changedProperties.Add("FinishedMessage");
|
||||
}
|
||||
if (this._finishedUrl != null)
|
||||
{
|
||||
this._finishedUrl = null;
|
||||
changedProperties.Add("FinishedUrl");
|
||||
}
|
||||
if (this._progress != 0)
|
||||
{
|
||||
this._progress = 0;
|
||||
changedProperties.Add("Progress");
|
||||
}
|
||||
if (this._currentProcess != "Scheduled")
|
||||
{
|
||||
this._currentProcess = "Scheduled";
|
||||
changedProperties.Add("CurrentProcess");
|
||||
}
|
||||
if (this._currentDescription != "Scheduled Task for Execution")
|
||||
{
|
||||
this._currentDescription = "Scheduled Task for Execution";
|
||||
changedProperties.Add("CurrentDescription");
|
||||
}
|
||||
if (this._isCanceling)
|
||||
{
|
||||
this._isCanceling = false;
|
||||
changedProperties.Add("IsCanceling");
|
||||
}
|
||||
UpdateTriggered(changedProperties.ToArray());
|
||||
}
|
||||
#endregion
|
||||
|
||||
private void UpdateTriggered(string[] ChangedProperties)
|
||||
{
|
||||
this._statusVersion++;
|
||||
|
||||
if (Updated != null)
|
||||
Updated(this, ChangedProperties);
|
||||
|
||||
if (!_isSilent)
|
||||
ScheduledTasksLiveStatusService.Broadcast(ScheduledTaskStatusLive.FromScheduledTaskStatus(this, ChangedProperties));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTaskStatusLive
|
||||
{
|
||||
public string TaskName { get; set; }
|
||||
public string SessionId { get; set; }
|
||||
|
||||
public byte Progress { get; set; }
|
||||
public string CurrentProcess { get; set; }
|
||||
public string CurrentDescription { get; set; }
|
||||
|
||||
public string TaskExceptionMessage { get; set; }
|
||||
public bool CancelSupported { get; set; }
|
||||
public bool IsCancelling { get; set; }
|
||||
|
||||
public bool IsRunning { get; set; }
|
||||
public DateTime? StartedTimestamp { get; set; }
|
||||
public DateTime? FinishedTimestamp { get; set; }
|
||||
public DateTime? NextScheduledTimestamp { get; set; }
|
||||
|
||||
public string FinishedMessage { get; set; }
|
||||
public string FinishedUrl { get; set; }
|
||||
|
||||
public int StatusVersion { get; set; }
|
||||
|
||||
public string[] ChangedProperties { get; set; }
|
||||
|
||||
public static ScheduledTaskStatusLive FromScheduledTaskStatus(ScheduledTaskStatus Status, string[] ChangedProperties)
|
||||
{
|
||||
return new ScheduledTaskStatusLive()
|
||||
{
|
||||
TaskName = Status.TaskName,
|
||||
SessionId = Status.SessionId,
|
||||
Progress = Status.Progress,
|
||||
CurrentProcess = Status.CurrentProcess,
|
||||
CurrentDescription = Status.CurrentDescription,
|
||||
CancelSupported = Status.CancelSupported,
|
||||
TaskExceptionMessage = (Status.TaskException == null ? null : Status.TaskException.Message),
|
||||
IsCancelling = Status.IsCanceling,
|
||||
IsRunning = Status.IsRunning,
|
||||
StartedTimestamp = Status.StartedTimestamp,
|
||||
FinishedTimestamp = Status.FinishedTimestamp,
|
||||
NextScheduledTimestamp = Status.NextScheduledTimestamp,
|
||||
FinishedMessage = Status.FinishedMessage,
|
||||
FinishedUrl = Status.FinishedUrl,
|
||||
StatusVersion = Status.StatusVersion,
|
||||
ChangedProperties = ChangedProperties
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTaskStatusLive
|
||||
{
|
||||
public string TaskName { get; set; }
|
||||
public string SessionId { get; set; }
|
||||
|
||||
public byte Progress { get; set; }
|
||||
public string CurrentProcess { get; set; }
|
||||
public string CurrentDescription { get; set; }
|
||||
|
||||
public string TaskExceptionMessage { get; set; }
|
||||
public bool CancelSupported { get; set; }
|
||||
public bool IsCancelling { get; set; }
|
||||
|
||||
public bool IsRunning { get; set; }
|
||||
public DateTime? StartedTimestamp { get; set; }
|
||||
public DateTime? FinishedTimestamp { get; set; }
|
||||
public DateTime? NextScheduledTimestamp { get; set; }
|
||||
|
||||
public string FinishedMessage { get; set; }
|
||||
public string FinishedUrl { get; set; }
|
||||
|
||||
public int StatusVersion { get; set; }
|
||||
|
||||
public string[] ChangedProperties { get; set; }
|
||||
|
||||
public static ScheduledTaskStatusLive FromScheduledTaskStatus(ScheduledTaskStatus Status, string[] ChangedProperties)
|
||||
{
|
||||
return new ScheduledTaskStatusLive()
|
||||
{
|
||||
TaskName = Status.TaskName,
|
||||
SessionId = Status.SessionId,
|
||||
Progress = Status.Progress,
|
||||
CurrentProcess = Status.CurrentProcess,
|
||||
CurrentDescription = Status.CurrentDescription,
|
||||
CancelSupported = Status.CancelSupported,
|
||||
TaskExceptionMessage = (Status.TaskException == null ? null : Status.TaskException.Message),
|
||||
IsCancelling = Status.IsCanceling,
|
||||
IsRunning = Status.IsRunning,
|
||||
StartedTimestamp = Status.StartedTimestamp,
|
||||
FinishedTimestamp = Status.FinishedTimestamp,
|
||||
NextScheduledTimestamp = Status.NextScheduledTimestamp,
|
||||
FinishedMessage = Status.FinishedMessage,
|
||||
FinishedUrl = Status.FinishedUrl,
|
||||
StatusVersion = Status.StatusVersion,
|
||||
ChangedProperties = ChangedProperties
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using SignalR;
|
||||
using SignalR.Hosting.AspNet;
|
||||
using SignalR.Infrastructure;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTasksLiveStatusService : PersistentConnection
|
||||
{
|
||||
|
||||
protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest request, string connectionId, string data)
|
||||
{
|
||||
// Add to Group
|
||||
if (!string.IsNullOrWhiteSpace(data) && data.StartsWith("/addToGroups:") && data.Length > 13)
|
||||
{
|
||||
var groups = data.Substring(13).Split(',');
|
||||
foreach (var g in groups)
|
||||
{
|
||||
this.Groups.Add(connectionId, g);
|
||||
}
|
||||
}
|
||||
|
||||
return base.OnReceivedAsync(request, connectionId, data);
|
||||
}
|
||||
|
||||
internal static void Broadcast(ScheduledTaskStatusLive SessionStatus)
|
||||
{
|
||||
//var message = Models.LogLiveEvent.Create(logModule, eventType, Timestamp, Arguments);
|
||||
|
||||
var connectionManager = GlobalHost.ConnectionManager; //AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
|
||||
var connectionContext = connectionManager.GetConnectionContext<ScheduledTasksLiveStatusService>();
|
||||
connectionContext.Groups.Send(_GroupNameAll, SessionStatus);
|
||||
connectionContext.Groups.Send(SessionStatus.SessionId, SessionStatus);
|
||||
}
|
||||
|
||||
private const string _GroupNameAll = "__All";
|
||||
//private static string _QualifiedSessionName = typeof(ScheduledTasksLiveStatusService).FullName + ".";
|
||||
//private static string _QualifiedSessionNameAll = _QualifiedSessionName + "__All";
|
||||
//private static string LiveStatusGroup(string SessionId)
|
||||
//{
|
||||
// return string.Concat(_QualifiedSessionName, SessionId);
|
||||
//}
|
||||
public static string LiveStatusAll
|
||||
{
|
||||
get
|
||||
{
|
||||
//return _QualifiedTypeNameAll;
|
||||
return _GroupNameAll;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using SignalR;
|
||||
using SignalR.Hosting.AspNet;
|
||||
using SignalR.Infrastructure;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTasksLiveStatusService : PersistentConnection
|
||||
{
|
||||
|
||||
protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest request, string connectionId, string data)
|
||||
{
|
||||
// Add to Group
|
||||
if (!string.IsNullOrWhiteSpace(data) && data.StartsWith("/addToGroups:") && data.Length > 13)
|
||||
{
|
||||
var groups = data.Substring(13).Split(',');
|
||||
foreach (var g in groups)
|
||||
{
|
||||
this.Groups.Add(connectionId, g);
|
||||
}
|
||||
}
|
||||
|
||||
return base.OnReceivedAsync(request, connectionId, data);
|
||||
}
|
||||
|
||||
internal static void Broadcast(ScheduledTaskStatusLive SessionStatus)
|
||||
{
|
||||
//var message = Models.LogLiveEvent.Create(logModule, eventType, Timestamp, Arguments);
|
||||
|
||||
var connectionManager = GlobalHost.ConnectionManager; //AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
|
||||
var connectionContext = connectionManager.GetConnectionContext<ScheduledTasksLiveStatusService>();
|
||||
connectionContext.Groups.Send(_GroupNameAll, SessionStatus);
|
||||
connectionContext.Groups.Send(SessionStatus.SessionId, SessionStatus);
|
||||
}
|
||||
|
||||
private const string _GroupNameAll = "__All";
|
||||
//private static string _QualifiedSessionName = typeof(ScheduledTasksLiveStatusService).FullName + ".";
|
||||
//private static string _QualifiedSessionNameAll = _QualifiedSessionName + "__All";
|
||||
//private static string LiveStatusGroup(string SessionId)
|
||||
//{
|
||||
// return string.Concat(_QualifiedSessionName, SessionId);
|
||||
//}
|
||||
public static string LiveStatusAll
|
||||
{
|
||||
get
|
||||
{
|
||||
//return _QualifiedTypeNameAll;
|
||||
return _GroupNameAll;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,196 +1,196 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Services.Logging;
|
||||
using Disco.Services.Logging.Models;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTasksLog : LogBase
|
||||
{
|
||||
private const int _ModuleId = 20;
|
||||
|
||||
public override string ModuleDescription { get { return "Scheduled Tasks"; } }
|
||||
public override int ModuleId { get { return _ModuleId; } }
|
||||
public override string ModuleName { get { return "ScheduledTasks"; } }
|
||||
|
||||
public enum EventTypeIds
|
||||
{
|
||||
InitializingScheduledTasks = 10,
|
||||
InitializeException = 15,
|
||||
InitializeExceptionWithInner,
|
||||
InitializeScheduledTasksException,
|
||||
InitializeScheduledTasksExceptionWithInner,
|
||||
ScheduledTasksException = 30,
|
||||
ScheduledTasksExceptionWithInner,
|
||||
ScheduledTaskExecuted = 50,
|
||||
ScheduledTaskFinished = 80,
|
||||
}
|
||||
public static ScheduledTasksLog Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return (ScheduledTasksLog)LogContext.LogModules[_ModuleId];
|
||||
}
|
||||
}
|
||||
private static void Log(EventTypeIds EventTypeId, params object[] Args)
|
||||
{
|
||||
Current.Log((int)EventTypeId, Args);
|
||||
}
|
||||
|
||||
public static void LogInitializingScheduledTasks()
|
||||
{
|
||||
Current.Log((int)EventTypeIds.InitializingScheduledTasks);
|
||||
}
|
||||
public static void LogScheduledTaskExecuted(string TaskName, string SessionId)
|
||||
{
|
||||
Current.Log((int)EventTypeIds.ScheduledTaskExecuted, TaskName, SessionId);
|
||||
}
|
||||
public static void LogScheduledTaskFinished(string TaskName, string SessionId)
|
||||
{
|
||||
Current.Log((int)EventTypeIds.ScheduledTaskFinished, TaskName, SessionId);
|
||||
}
|
||||
|
||||
public static void LogInitializeException(Exception ex)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.InitializeExceptionWithInner, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.InitializeException, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
public static void LogInitializeException(Exception ex, Type ScheduledTaskType)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.InitializeScheduledTasksExceptionWithInner, ScheduledTaskType.Name, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.InitializeScheduledTasksException, ScheduledTaskType.Name, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
public static void LogScheduledTaskException(string ScheduledTaskName, string SessionId, Type ScheduledTaskType, Exception ex)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.ScheduledTasksExceptionWithInner, ScheduledTaskName, SessionId, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.ScheduledTasksException, ScheduledTaskName, SessionId, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
protected override List<Logging.Models.LogEventType> LoadEventTypes()
|
||||
{
|
||||
return new System.Collections.Generic.List<LogEventType>
|
||||
{
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializingScheduledTasks,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initializing Scheduled Tasks",
|
||||
Format = "Starting Scheduled Task discovery and initialization",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeException,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Exception",
|
||||
Format = "Exception: {0}: {1}; {2}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Exception with Inner Exception",
|
||||
Format = "Exception: {0}: {1}; {2}; Inner: {3}: {4}; {5}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeScheduledTasksException,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Task Exception",
|
||||
Format = "[{0}] At '{1}'; Exception: {2}: {3}; {4}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeScheduledTasksExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Task Exception with Inner Exception",
|
||||
Format = "[{0}] At '{1}'; Exception: {2}: {3}; {4}; Inner: {5}: {6}; {7}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTasksException,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Exception",
|
||||
Format = "Task Name: {0}; SessionId: {1}; At: '{2}'; Exception: {3}: {4}; {5}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTasksExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Exception with Inner Exception",
|
||||
Format = "Task Name: {0}; SessionId: {1}; At: '{2}'; Exception: {3}: {4}; {5}; Inner: {6}: {7}; {8}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTaskExecuted,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Started",
|
||||
Format = "Scheduled Task Started: {0}; Session Id: {1}",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTaskFinished,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Finished",
|
||||
Format = "Scheduled Task Finished: {0}; Session Id: {1}",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Disco.Services.Logging;
|
||||
using Disco.Services.Logging.Models;
|
||||
|
||||
namespace Disco.Services.Tasks
|
||||
{
|
||||
public class ScheduledTasksLog : LogBase
|
||||
{
|
||||
private const int _ModuleId = 20;
|
||||
|
||||
public override string ModuleDescription { get { return "Scheduled Tasks"; } }
|
||||
public override int ModuleId { get { return _ModuleId; } }
|
||||
public override string ModuleName { get { return "ScheduledTasks"; } }
|
||||
|
||||
public enum EventTypeIds
|
||||
{
|
||||
InitializingScheduledTasks = 10,
|
||||
InitializeException = 15,
|
||||
InitializeExceptionWithInner,
|
||||
InitializeScheduledTasksException,
|
||||
InitializeScheduledTasksExceptionWithInner,
|
||||
ScheduledTasksException = 30,
|
||||
ScheduledTasksExceptionWithInner,
|
||||
ScheduledTaskExecuted = 50,
|
||||
ScheduledTaskFinished = 80,
|
||||
}
|
||||
public static ScheduledTasksLog Current
|
||||
{
|
||||
get
|
||||
{
|
||||
return (ScheduledTasksLog)LogContext.LogModules[_ModuleId];
|
||||
}
|
||||
}
|
||||
private static void Log(EventTypeIds EventTypeId, params object[] Args)
|
||||
{
|
||||
Current.Log((int)EventTypeId, Args);
|
||||
}
|
||||
|
||||
public static void LogInitializingScheduledTasks()
|
||||
{
|
||||
Current.Log((int)EventTypeIds.InitializingScheduledTasks);
|
||||
}
|
||||
public static void LogScheduledTaskExecuted(string TaskName, string SessionId)
|
||||
{
|
||||
Current.Log((int)EventTypeIds.ScheduledTaskExecuted, TaskName, SessionId);
|
||||
}
|
||||
public static void LogScheduledTaskFinished(string TaskName, string SessionId)
|
||||
{
|
||||
Current.Log((int)EventTypeIds.ScheduledTaskFinished, TaskName, SessionId);
|
||||
}
|
||||
|
||||
public static void LogInitializeException(Exception ex)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.InitializeExceptionWithInner, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.InitializeException, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
public static void LogInitializeException(Exception ex, Type ScheduledTaskType)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.InitializeScheduledTasksExceptionWithInner, ScheduledTaskType.Name, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.InitializeScheduledTasksException, ScheduledTaskType.Name, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
public static void LogScheduledTaskException(string ScheduledTaskName, string SessionId, Type ScheduledTaskType, Exception ex)
|
||||
{
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
Log(EventTypeIds.ScheduledTasksExceptionWithInner, ScheduledTaskName, SessionId, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace, ex.InnerException.GetType().Name, ex.InnerException.Message, ex.InnerException.StackTrace);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log(EventTypeIds.ScheduledTasksException, ScheduledTaskName, SessionId, ScheduledTaskType.Assembly.Location, ex.GetType().Name, ex.Message, ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
protected override List<Logging.Models.LogEventType> LoadEventTypes()
|
||||
{
|
||||
return new System.Collections.Generic.List<LogEventType>
|
||||
{
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializingScheduledTasks,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initializing Scheduled Tasks",
|
||||
Format = "Starting Scheduled Task discovery and initialization",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeException,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Exception",
|
||||
Format = "Exception: {0}: {1}; {2}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Exception with Inner Exception",
|
||||
Format = "Exception: {0}: {1}; {2}; Inner: {3}: {4}; {5}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeScheduledTasksException,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Task Exception",
|
||||
Format = "[{0}] At '{1}'; Exception: {2}: {3}; {4}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.InitializeScheduledTasksExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Initialize Task Exception with Inner Exception",
|
||||
Format = "[{0}] At '{1}'; Exception: {2}: {3}; {4}; Inner: {5}: {6}; {7}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = false,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTasksException,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Exception",
|
||||
Format = "Task Name: {0}; SessionId: {1}; At: '{2}'; Exception: {3}: {4}; {5}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTasksExceptionWithInner,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Exception with Inner Exception",
|
||||
Format = "Task Name: {0}; SessionId: {1}; At: '{2}'; Exception: {3}: {4}; {5}; Inner: {6}: {7}; {8}",
|
||||
Severity = (int)LogEventType.Severities.Error,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTaskExecuted,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Started",
|
||||
Format = "Scheduled Task Started: {0}; Session Id: {1}",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
},
|
||||
new LogEventType
|
||||
{
|
||||
Id = (int)EventTypeIds.ScheduledTaskFinished,
|
||||
ModuleId = _ModuleId,
|
||||
Name = "Scheduled Task Finished",
|
||||
Format = "Scheduled Task Finished: {0}; Session Id: {1}",
|
||||
Severity = (int)LogEventType.Severities.Information,
|
||||
UseLive = true,
|
||||
UsePersist = true,
|
||||
UseDisplay = true
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user