GIT: perform LF normalization

This commit is contained in:
Gary Sharp
2013-02-28 17:15:46 +11:00
parent 989f08a24d
commit 7d9be5620d
729 changed files with 300734 additions and 300712 deletions
+13 -13
View File
@@ -1,14 +1,14 @@
<?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=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<?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=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
+124 -124
View File
@@ -1,125 +1,125 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BD16C575-70C2-4DDE-A572-FC79EF028CB2}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Disco.Logging</RootNamespace>
<AssemblyName>Disco.Logging</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\EntityFramework.4.3.1\lib\net40\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="fastJSON, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Resources\Libraries\fastJSON\fastJSON.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.4.5.1\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Quartz">
<HintPath>..\..\Resources\Libraries\Quartz\Quartz.dll</HintPath>
</Reference>
<Reference Include="SignalR, Version=0.4.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\SignalR.Server.0.4.0.0\lib\net40\SignalR.dll</HintPath>
</Reference>
<Reference Include="SignalR.Hosting.AspNet">
<HintPath>..\packages\SignalR.Hosting.AspNet.0.4.0.0\lib\net40\SignalR.Hosting.AspNet.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.Entity" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\SqlServerCompact.4.0.8482.1\lib\System.Data.SqlServerCe.dll</HintPath>
</Reference>
<Reference Include="System.Management" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="LogReInitalizeJob.cs" />
<Compile Include="ReadLogContext.cs" />
<Compile Include="Utilities.cs" />
<Compile Include="LogContext.cs" />
<Compile Include="Models\LogLiveEvent.cs" />
<Compile Include="Targets\LogLiveContext.cs" />
<Compile Include="LogBase.cs" />
<Compile Include="Models\LogEvent.cs" />
<Compile Include="Models\LogEventType.cs" />
<Compile Include="Targets\LogPersistContext.cs" />
<Compile Include="Models\LogModule.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SystemLog.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Disco.Data\Disco.Data.csproj">
<Project>{85A6BD19-2C64-4746-8F2C-A68A86E8C2D7}</Project>
<Name>Disco.Data</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Models\Disco.Models.csproj">
<Project>{FBC05512-FCCA-4B16-9E76-8C413C5DE6C9}</Project>
<Name>Disco.Models</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<UserProperties BuildVersion_UseGlobalSettings="True" />
</VisualStudio>
</ProjectExtensions>
<PropertyGroup>
<PostBuildEvent>
REM if not exist "$(TargetDir)x86" md "$(TargetDir)x86"
REM xcopy /s /y "$(SolutionDir)packages\SqlServerCompact.4.0.8482.1\NativeBinaries\x86\*.*" "$(TargetDir)x86"
REM if not exist "$(TargetDir)amd64" md "$(TargetDir)amd64"
REM xcopy /s /y "$(SolutionDir)packages\SqlServerCompact.4.0.8482.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64"</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BD16C575-70C2-4DDE-A572-FC79EF028CB2}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Disco.Logging</RootNamespace>
<AssemblyName>Disco.Logging</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\EntityFramework.4.3.1\lib\net40\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="fastJSON, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Resources\Libraries\fastJSON\fastJSON.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.4.5.1\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Quartz">
<HintPath>..\..\Resources\Libraries\Quartz\Quartz.dll</HintPath>
</Reference>
<Reference Include="SignalR, Version=0.4.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\SignalR.Server.0.4.0.0\lib\net40\SignalR.dll</HintPath>
</Reference>
<Reference Include="SignalR.Hosting.AspNet">
<HintPath>..\packages\SignalR.Hosting.AspNet.0.4.0.0\lib\net40\SignalR.Hosting.AspNet.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.Entity" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\SqlServerCompact.4.0.8482.1\lib\System.Data.SqlServerCe.dll</HintPath>
</Reference>
<Reference Include="System.Management" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="LogReInitalizeJob.cs" />
<Compile Include="ReadLogContext.cs" />
<Compile Include="Utilities.cs" />
<Compile Include="LogContext.cs" />
<Compile Include="Models\LogLiveEvent.cs" />
<Compile Include="Targets\LogLiveContext.cs" />
<Compile Include="LogBase.cs" />
<Compile Include="Models\LogEvent.cs" />
<Compile Include="Models\LogEventType.cs" />
<Compile Include="Targets\LogPersistContext.cs" />
<Compile Include="Models\LogModule.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SystemLog.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Disco.Data\Disco.Data.csproj">
<Project>{85A6BD19-2C64-4746-8F2C-A68A86E8C2D7}</Project>
<Name>Disco.Data</Name>
</ProjectReference>
<ProjectReference Include="..\Disco.Models\Disco.Models.csproj">
<Project>{FBC05512-FCCA-4B16-9E76-8C413C5DE6C9}</Project>
<Name>Disco.Models</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<UserProperties BuildVersion_UseGlobalSettings="True" />
</VisualStudio>
</ProjectExtensions>
<PropertyGroup>
<PostBuildEvent>
REM if not exist "$(TargetDir)x86" md "$(TargetDir)x86"
REM xcopy /s /y "$(SolutionDir)packages\SqlServerCompact.4.0.8482.1\NativeBinaries\x86\*.*" "$(TargetDir)x86"
REM if not exist "$(TargetDir)amd64" md "$(TargetDir)amd64"
REM xcopy /s /y "$(SolutionDir)packages\SqlServerCompact.4.0.8482.1\NativeBinaries\amd64\*.*" "$(TargetDir)amd64"</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
+43 -43
View File
@@ -1,43 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Disco.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.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;
}
}
}
}
+311 -311
View File
@@ -1,311 +1,311 @@
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;
namespace Disco.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);
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;
namespace Disco.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);
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));
}
}
}
+20 -20
View File
@@ -1,20 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz;
using Disco.Data.Repository;
namespace Disco.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.Logging
{
class LogReInitalizeJob : IJob
{
public void Execute(IJobExecutionContext context)
{
using (DiscoDataContext DiscoContext = new DiscoDataContext())
{
LogContext.ReInitalize(DiscoContext);
}
}
}
}
+22 -22
View File
@@ -1,22 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Disco.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;
namespace Disco.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; }
}
}
+66 -66
View File
@@ -1,66 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Disco.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;
namespace Disco.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;
}
}
}
+57 -57
View File
@@ -1,57 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Disco.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;
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;
namespace Disco.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;
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
};
}
}
}
+21 -21
View File
@@ -1,21 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace Disco.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;
namespace Disco.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; }
}
}
+36 -36
View File
@@ -1,36 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Disco - Logging")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Disco")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03a4a5bf-60c6-4dff-b623-387043b8be86")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2012.0627.1427")]
[assembly: AssemblyFileVersion("1.2012.0627.1427")]
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Disco - Logging")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Disco")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03a4a5bf-60c6-4dff-b623-387043b8be86")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2012.0627.1427")]
[assembly: AssemblyFileVersion("1.2012.0627.1427")]
+179 -179
View File
@@ -1,179 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Logging.Targets;
using Disco.Data.Repository;
using System.IO;
using System.Text.RegularExpressions;
using System.Data.SqlServerCe;
using Disco.Logging.Models;
namespace Disco.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.Logging.Targets;
using Disco.Data.Repository;
using System.IO;
using System.Text.RegularExpressions;
using System.Data.SqlServerCe;
using Disco.Logging.Models;
namespace Disco.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;
}
}
}
+126 -126
View File
@@ -1,126 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Logging.Models;
namespace Disco.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
}
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 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 }
};
return eventTypes;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Disco.Logging.Models;
namespace Disco.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
}
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 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 }
};
return eventTypes;
}
}
}
+55 -55
View File
@@ -1,55 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SignalR;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
namespace Disco.Logging.Targets
{
public class LogLiveContext : PersistentConnection
{
protected override System.Threading.Tasks.Task OnReceivedAsync(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.AddToGroup(connectionId, g);
}
}
return base.OnReceivedAsync(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 = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
var connection = connectionManager.GetConnection<LogLiveContext>();
connection.Broadcast(_QualifiedTypeNameAll, message);
connection.Broadcast(LiveLogNameGroup(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.Logging.Targets
{
public class LogLiveContext : PersistentConnection
{
protected override System.Threading.Tasks.Task OnReceivedAsync(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.AddToGroup(connectionId, g);
}
}
return base.OnReceivedAsync(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 = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
var connection = connectionManager.GetConnection<LogLiveContext>();
connection.Broadcast(_QualifiedTypeNameAll, message);
connection.Broadcast(LiveLogNameGroup(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;
}
}
}
}
+23 -23
View File
@@ -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.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.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>();
}
}
}
+263 -263
View File
@@ -1,263 +1,263 @@
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.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(",\"");
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.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(",\"");
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());
}
}
}
}
+8 -8
View File
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="4.3.1" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" />
<package id="Newtonsoft.Json" version="4.5.1" />
<package id="SignalR.Hosting.AspNet" version="0.4.0.0" />
<package id="SignalR.Server" version="0.4.0.0" />
<package id="SqlServerCompact" version="4.0.8482.1" />
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="4.3.1" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" />
<package id="Newtonsoft.Json" version="4.5.1" />
<package id="SignalR.Hosting.AspNet" version="0.4.0.0" />
<package id="SignalR.Server" version="0.4.0.0" />
<package id="SqlServerCompact" version="4.0.8482.1" />
</packages>