Added Ninject, configuration and default logger.

Made DefaultLogger use the eventlog rather than debug.writeline(..)
renamed service1 to CardReaderService
#22
This commit is contained in:
chris.watts90@outlook.com 2017-02-18 09:09:19 +00:00
parent 1335dbddc7
commit 9dc4832471
10 changed files with 309 additions and 38 deletions

View File

@ -1,6 +1,6 @@
namespace CardReaderService namespace CardReaderService
{ {
partial class Service1 partial class CardReaderService
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.

View File

@ -1,23 +1,26 @@
using PCSC; using PCSC;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration;
using System.Linq; using System.Linq;
using System.ServiceProcess; using System.ServiceProcess;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using Interfaces;
namespace CardReaderService namespace CardReaderService
{ {
public partial class Service1 : ServiceBase public partial class CardReaderService : ServiceBase
{ {
private Thread _mainWorkThread; private Thread _mainWorkThread;
private bool _stopMainWorkerThread; private bool _stopMainWorkerThread;
private string _readerName = ""; private string _readerName = "";
//private SCardReader _reader;
private SCardMonitor _cardMonitor; private SCardMonitor _cardMonitor;
public Service1() private ILogger _logger;
public CardReaderService()
{ {
InitializeComponent(); InitializeComponent();
} }
@ -26,21 +29,40 @@ namespace CardReaderService
{ {
OnStart(new string[] {}); OnStart(new string[] {});
} }
//
protected override void OnStart(string[] args) protected override void OnStart(string[] args)
{ {
Console.WriteLine("Starting.. Getting available readers"); _logger = NinjectHelper.GetInstance().Get<ILogger>();
_logger.Trace("Starting Service.. Getting available readers");
var ctxFactory = ContextFactory.Instance; var ctxFactory = ContextFactory.Instance;
using(var context = ctxFactory.Establish(SCardScope.System)) using(var context = ctxFactory.Establish(SCardScope.System))
{ {
var readerNames = context.GetReaders(); var readerNames = context.GetReaders();
if (NoReaderAvailable(readerNames)) if (NoReaderAvailable(readerNames))
{ {
Console.WriteLine("No Card Reader is available, Exiting.."); _logger.Trace("No Card Reader is available, Exiting..");
return; throw new ApplicationException("A card reader must be provided in order to operate.");
} }
Console.WriteLine("Choosing first available reader: " + readerNames.First()); foreach (var reader in readerNames)
_readerName = readerNames.First(); {
_logger.Trace("Found reader: {0}", reader);
}
var readerNameConfig = ConfigurationManager.AppSettings["ReaderName"];
if (string.IsNullOrEmpty(readerNameConfig))
{
if (!readerNames.Contains(readerNameConfig))
{
_logger.Warn("No reader found with the name: {0}, defaulting to first available reader {1}",
readerNameConfig, readerNames.First());
readerNameConfig=readerNames.First();
}
}
_logger.Trace("Choosing reader: {0}", readerNameConfig);
_readerName = readerNameConfig;
_cardMonitor = new SCardMonitor(ctxFactory, SCardScope.System); _cardMonitor = new SCardMonitor(ctxFactory, SCardScope.System);
_cardMonitor.CardInserted += _cardMonitor_CardInserted; _cardMonitor.CardInserted += _cardMonitor_CardInserted;
_cardMonitor.Start(_readerName); _cardMonitor.Start(_readerName);
@ -49,7 +71,7 @@ namespace CardReaderService
} }
} }
public void Stop() public void StopService()
{ {
OnStop(); OnStop();
} }
@ -65,13 +87,12 @@ namespace CardReaderService
_mainWorkThread.Interrupt(); _mainWorkThread.Interrupt();
} }
} }
if (_cardMonitor != null) if (_cardMonitor == null) return;
{
_cardMonitor.Cancel(); _cardMonitor.Cancel();
_cardMonitor.Dispose(); _cardMonitor.Dispose();
_cardMonitor = null; _cardMonitor = null;
} }
}
private void StartWorkerThread() private void StartWorkerThread()
{ {
@ -91,11 +112,11 @@ namespace CardReaderService
{ {
var reader = new SCardReader(ctx); var reader = new SCardReader(ctx);
var pioSendPci = new IntPtr(); var pioSendPci = new IntPtr();
byte[] rcvBuffer = new byte[256]; var rcvBuffer = new byte[256];
if (_readerName == string.Empty) if (_readerName == string.Empty)
{ {
Console.WriteLine("Reader name is somehow empty... WTF!"); _logger.Fatal("Reader name is somehow empty...exiting");
_stopMainWorkerThread = true; _stopMainWorkerThread = true;
return; return;
} }
@ -107,20 +128,19 @@ namespace CardReaderService
var uIdcmd = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 }; var uIdcmd = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 };
err = reader.Transmit(pioSendPci, uIdcmd, ref rcvBuffer); err = reader.Transmit(pioSendPci, uIdcmd, ref rcvBuffer);
if (err == SCardError.Success) if (err != SCardError.Success) return;
{
var uid = ConvertByteUIDToString(rcvBuffer); var uid = ConvertByteUIDToString(rcvBuffer);
var atrString = ConvertByteUIDToString(e.Atr); var atrString = ConvertByteUIDToString(e.Atr);
Console.WriteLine("Card Inserted, ATR: " + atrString + ", and UID is: " + uid); _logger.Trace("Card Inserted, ATR: " + atrString + ", and UID is: " + uid);
CardDataPost postObj = new CardDataPost {CardUId = uid}; var postObj = new CardDataPost {CardUId = uid};
DataCenterHelper.PostAsync(postObj, "/api/swipedata"); DataCenterHelper.PostAsync(postObj, "/api/swipedata");
Console.WriteLine("Posted to Server"); _logger.Trace("Posted to Server");
}
} }
else else
{ {
Console.WriteLine("Reader failed to connect, error: " + Enum.GetName(typeof(SCardError), err)); _logger.Trace("Reader failed to connect, error: " + Enum.GetName(typeof(SCardError), err));
} }
} }
@ -137,13 +157,11 @@ namespace CardReaderService
private string ConvertByteUIDToString(byte[] uid) private string ConvertByteUIDToString(byte[] uid)
{ {
StringBuilder sb = new StringBuilder(); var sb = new StringBuilder();
foreach(var b in uid) foreach(var b in uid)
{ {
sb.AppendFormat("{0:X2}", b); sb.AppendFormat("{0:X2}", b);
} }
return sb.ToString(); return sb.ToString();
} }

View File

@ -37,6 +37,10 @@
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath> <HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="Ninject, Version=3.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7, processorArchitecture=MSIL">
<HintPath>..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="pcsc-sharp, Version=3.6.0.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="pcsc-sharp, Version=3.6.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\PCSC.3.6.0\lib\net40\pcsc-sharp.dll</HintPath> <HintPath>..\packages\PCSC.3.6.0\lib\net40\pcsc-sharp.dll</HintPath>
<Private>True</Private> <Private>True</Private>
@ -53,13 +57,16 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Configuration.cs" />
<Compile Include="ConfigureService.cs" /> <Compile Include="ConfigureService.cs" />
<Compile Include="DataCenterHelper.cs" /> <Compile Include="DataCenterHelper.cs" />
<Compile Include="Service1.cs"> <Compile Include="DefaultComponents\DefaultLogger.cs" />
<Compile Include="NinjectHelper.cs" />
<Compile Include="CardReaderService.cs">
<SubType>Component</SubType> <SubType>Component</SubType>
</Compile> </Compile>
<Compile Include="Service1.Designer.cs"> <Compile Include="CardReaderService.Designer.cs">
<DependentUpon>Service1.cs</DependentUpon> <DependentUpon>CardReaderService.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
@ -68,6 +75,17 @@
<None Include="App.config" /> <None Include="App.config" />
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Interfaces\Interfaces.csproj">
<Project>{B7347B72-E208-423A-9D99-723B558EA3D7}</Project>
<Name>Interfaces</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="NinjectConfig.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -0,0 +1,35 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using CardReaderService.DefaultComponents;
using Interfaces;
using Ninject;
namespace CardReaderService
{
public static class Configuration
{
public static StandardKernel ConfigureNinject()
{
var kernel = new StandardKernel();
var ninjectConfigPath =
new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().CodeBase), "NinjectConfig.xml"))
.LocalPath;
if (File.Exists(ninjectConfigPath))
{
kernel.Load(ninjectConfigPath);
}
var logger = kernel.TryGet<ILogger>();
if (logger == null)
{
kernel.Bind<ILogger>().To<DefaultLogger>();
logger = kernel.Get<ILogger>();
}
logger.Fatal("test message - ninject stuff loaded.");
return kernel;
}
}
}

View File

@ -0,0 +1,151 @@
using System;
using System.Diagnostics;
using Interfaces;
namespace CardReaderService.DefaultComponents
{
public class DefaultLogger : ILogger
{
private string _eventLogSource = "CardRdrSvc";
private string _logName = "CardReaderServiceLog";
private EventLog _eventLog;
public DefaultLogger()
{
if (!EventLog.SourceExists(_eventLogSource))
{
EventLog.CreateEventSource(_eventLogSource, _logName);
}
}
public bool IsDebugEnabled { get { return true; } }
public bool IsErrorEnabled { get { return true; } }
public bool IsFatalEnabled { get { return true; } }
public bool IsInfoEnabled { get { return true; } }
public bool IsTraceEnabled { get { return true; } }
public bool IsWarnEnabled { get { return true; } }
public void Debug(Exception exception)
{
CheckEventLog();
_eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Information);
}
public void Debug(string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(format, args), EventLogEntryType.Information);
}
public void Debug(Exception exception, string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(exception + ", " + format, args),
EventLogEntryType.Information);
}
public void Error(Exception exception)
{
CheckEventLog();
_eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Error);
}
public void Error(string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(format, args), EventLogEntryType.Error);
}
public void Error(Exception exception, string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(exception + ", " + format, args),
EventLogEntryType.Error);
}
public void Fatal(Exception exception)
{
CheckEventLog();
_eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Error);
}
public void Fatal(string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(format, args), EventLogEntryType.Error);
}
public void Fatal(Exception exception, string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(exception + ", " + format, args),
EventLogEntryType.Error);
}
public void Info(Exception exception)
{
CheckEventLog();
_eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Information);
}
public void Info(string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(format, args), EventLogEntryType.Information);
}
public void Info(Exception exception, string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(exception + ", " + format, args),
EventLogEntryType.Information);
}
public void Trace(Exception exception)
{
CheckEventLog();
_eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Information);
}
public void Trace(string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(format, args), EventLogEntryType.Information);
}
public void Trace(Exception exception, string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(exception + ", " + format, args),
EventLogEntryType.Information);
}
public void Warn(Exception exception)
{
CheckEventLog();
_eventLog.WriteEntry(exception.ToString(), EventLogEntryType.Warning);
}
public void Warn(string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(format, args), EventLogEntryType.Warning);
}
public void Warn(Exception exception, string format, params object[] args)
{
CheckEventLog();
_eventLog.WriteEntry(string.Format(exception + ", " + format, args),
EventLogEntryType.Warning);
}
private void CheckEventLog()
{
if (_eventLog == null)
{
_eventLog = new EventLog();
_eventLog.Source = _eventLogSource;
_eventLog.Log = _logName;
}
}
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8" ?>
<module name="NinjectAssemblies">
<bind service="Interfaces.ILogger, Interfaces"
to="NLogLogger.NLogger, NLogLogger" scope="singleton" />
</module>

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject;
namespace CardReaderService
{
public class NinjectHelper
{
private static NinjectHelper _instance;
private static readonly object LockObject = new object();
public StandardKernel Kernel { get; private set; }
public static NinjectHelper GetInstance()
{
if (_instance != null)
return _instance;
lock (LockObject)
{
_instance = new NinjectHelper();
return _instance;
}
}
private NinjectHelper()
{
Kernel = Configuration.ConfigureNinject();
}
public T Get<T>()
{
return Kernel.Get<T>();
}
public IEnumerable<T> GetAll<T>()
{
return Kernel.GetAll<T>();
}
}
}

View File

@ -18,7 +18,7 @@ namespace CardReaderService
ServiceBase[] ServicesToRun; ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] ServicesToRun = new ServiceBase[]
{ {
new Service1() new CardReaderService()
}; };
ServiceBase.Run(ServicesToRun); ServiceBase.Run(ServicesToRun);
} }

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" /> <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" />
<package id="Ninject" version="3.2.2.0" targetFramework="net452" />
<package id="PCSC" version="3.6.0" targetFramework="net452" /> <package id="PCSC" version="3.6.0" targetFramework="net452" />
</packages> </packages>

View File

@ -7,11 +7,11 @@ namespace CardReaderServiceHost
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
Service1 service1 = new Service1(); CardReaderService.CardReaderService service1 = new CardReaderService.CardReaderService();
service1.Start(); service1.Start();
Console.WriteLine("Service Running..."); Console.WriteLine("Service Running...");
Console.ReadLine(); Console.ReadLine();
service1.Stop(); service1.StopService();
} }
} }
} }