From 2aaa26f0c1da96df50d0f8232f48c2ededd3c525 Mon Sep 17 00:00:00 2001 From: Roman <48102089+romanlryji@users.noreply.github.com> Date: Wed, 2 Oct 2019 11:18:07 +0300 Subject: [PATCH] C# application --- EventLogApp/App.config | 6 + EventLogApp/ConfigSetting.cs | 22 + EventLogApp/ConfigSettings.cs | 30 + .../ElasticSearchFieldSynonymsClass.cs | 26 + EventLogApp/EventElements/Application.cs | 9 + EventLogApp/EventElements/CodeNameGuidType.cs | 12 + EventLogApp/EventElements/CodeNameType.cs | 22 + EventLogApp/EventElements/Computer.cs | 9 + EventLogApp/EventElements/ESRecord.cs | 28 + .../EventElements/EventElementsDictionary.cs | 27 + EventLogApp/EventElements/EventType.cs | 9 + EventLogApp/EventElements/MainPort.cs | 9 + EventLogApp/EventElements/Metadata.cs | 9 + EventLogApp/EventElements/OneEventRecord.cs | 198 + EventLogApp/EventElements/SecondPort.cs | 9 + EventLogApp/EventElements/Server.cs | 9 + EventLogApp/EventElements/StringExtension.cs | 22 + EventLogApp/EventElements/User.cs | 9 + EventLogApp/EventLogApp.csproj | 161 + EventLogApp/EventLogLoaderService.cs | 338 ++ EventLogApp/EventLogProcessor.cs | 1369 +++++++ EventLogApp/EventLogService.Designer.cs | 37 + EventLogApp/EventLogService.cs | 32 + .../EventLogServiceInstaller.Designer.cs | 36 + EventLogApp/EventLogServiceInstaller.cs | 33 + EventLogApp/InfobaseSetting.cs | 12 + EventLogApp/NLog.config | 41 + EventLogApp/NLog.xsd | 3481 +++++++++++++++++ EventLogApp/ParserServices.cs | 51 + EventLogApp/Program.cs | 26 + EventLogApp/Properties/AssemblyInfo.cs | 36 + EventLogApp/ReadParameters.cs | 10 + EventLogApp/config.json | 39 + EventLogApp/packages.config | 11 + EventLogLoader.sln | 21 +- 35 files changed, 6197 insertions(+), 2 deletions(-) create mode 100644 EventLogApp/App.config create mode 100644 EventLogApp/ConfigSetting.cs create mode 100644 EventLogApp/ConfigSettings.cs create mode 100644 EventLogApp/ElasticSearchFieldSynonymsClass.cs create mode 100644 EventLogApp/EventElements/Application.cs create mode 100644 EventLogApp/EventElements/CodeNameGuidType.cs create mode 100644 EventLogApp/EventElements/CodeNameType.cs create mode 100644 EventLogApp/EventElements/Computer.cs create mode 100644 EventLogApp/EventElements/ESRecord.cs create mode 100644 EventLogApp/EventElements/EventElementsDictionary.cs create mode 100644 EventLogApp/EventElements/EventType.cs create mode 100644 EventLogApp/EventElements/MainPort.cs create mode 100644 EventLogApp/EventElements/Metadata.cs create mode 100644 EventLogApp/EventElements/OneEventRecord.cs create mode 100644 EventLogApp/EventElements/SecondPort.cs create mode 100644 EventLogApp/EventElements/Server.cs create mode 100644 EventLogApp/EventElements/StringExtension.cs create mode 100644 EventLogApp/EventElements/User.cs create mode 100644 EventLogApp/EventLogApp.csproj create mode 100644 EventLogApp/EventLogLoaderService.cs create mode 100644 EventLogApp/EventLogProcessor.cs create mode 100644 EventLogApp/EventLogService.Designer.cs create mode 100644 EventLogApp/EventLogService.cs create mode 100644 EventLogApp/EventLogServiceInstaller.Designer.cs create mode 100644 EventLogApp/EventLogServiceInstaller.cs create mode 100644 EventLogApp/InfobaseSetting.cs create mode 100644 EventLogApp/NLog.config create mode 100644 EventLogApp/NLog.xsd create mode 100644 EventLogApp/ParserServices.cs create mode 100644 EventLogApp/Program.cs create mode 100644 EventLogApp/Properties/AssemblyInfo.cs create mode 100644 EventLogApp/ReadParameters.cs create mode 100644 EventLogApp/config.json create mode 100644 EventLogApp/packages.config diff --git a/EventLogApp/App.config b/EventLogApp/App.config new file mode 100644 index 0000000..8fc0551 --- /dev/null +++ b/EventLogApp/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/EventLogApp/ConfigSetting.cs b/EventLogApp/ConfigSetting.cs new file mode 100644 index 0000000..ca07611 --- /dev/null +++ b/EventLogApp/ConfigSetting.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace EventLogApp +{ + public class ConfigSetting + { + public string ConnectionString { get; set; } + public string DBType { get; set; } + public int RepeatTime { get; set; } + public string ESIndexName { get; set; } + public bool ESUseSynonymsForFieldsNames { get; set; } + public ElasticSearchFieldSynonymsClass ESFieldSynonyms { get; set; } + public List Infobases { get; set; } + + + public ConfigSetting() + { + Infobases = new List(); + ESFieldSynonyms = new ElasticSearchFieldSynonymsClass(); + } + } +} diff --git a/EventLogApp/ConfigSettings.cs b/EventLogApp/ConfigSettings.cs new file mode 100644 index 0000000..673aa82 --- /dev/null +++ b/EventLogApp/ConfigSettings.cs @@ -0,0 +1,30 @@ +using Newtonsoft.Json; +using System.IO; + +namespace EventLogApp +{ + class ConfigSettings + { + public static ConfigSetting LoadConfigSettingFromFile(string ConfigFilePath) + { + if (File.Exists(ConfigFilePath)) + { + string JsonText = File.ReadAllText(ConfigFilePath); + + ConfigSetting ConfigSettingObj = JsonConvert.DeserializeObject(JsonText); + + return ConfigSettingObj; + } + + return new ConfigSetting(); + } + + + public static void SaveConfigSettingToFile(ConfigSetting ConfigSettingObj, string ConfigFilePath) + { + string JsonText = JsonConvert.SerializeObject(ConfigSettingObj, Formatting.Indented); + + File.WriteAllText(ConfigFilePath, JsonText); + } + } +} diff --git a/EventLogApp/ElasticSearchFieldSynonymsClass.cs b/EventLogApp/ElasticSearchFieldSynonymsClass.cs new file mode 100644 index 0000000..09eb71d --- /dev/null +++ b/EventLogApp/ElasticSearchFieldSynonymsClass.cs @@ -0,0 +1,26 @@ +namespace EventLogApp +{ + public class ElasticSearchFieldSynonymsClass + { + public string ServerName { get; set; } + public string DatabaseName { get; set; } + public string RowID { get; set; } + public string Severity { get; set; } + public string DateTime { get; set; } + public string ConnectID { get; set; } + public string DataType { get; set; } + public string SessionNumber { get; set; } + public string DataStructure { get; set; } + public string DataString { get; set; } + public string Comment { get; set; } + public string SessionDataSplitCode { get; set; } + public string EventType { get; set; } + public string Metadata { get; set; } + public string Computer { get; set; } + public string PrimaryPort { get; set; } + public string Server { get; set; } + public string SecondaryPort { get; set; } + public string Application { get; set; } + public string UserName { get; set; } + } +} diff --git a/EventLogApp/EventElements/Application.cs b/EventLogApp/EventElements/Application.cs new file mode 100644 index 0000000..43426da --- /dev/null +++ b/EventLogApp/EventElements/Application.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class Application : CodeNameType + { + public Application(long code, string name) : base(code, name) + { + } + } +} diff --git a/EventLogApp/EventElements/CodeNameGuidType.cs b/EventLogApp/EventElements/CodeNameGuidType.cs new file mode 100644 index 0000000..d9f4493 --- /dev/null +++ b/EventLogApp/EventElements/CodeNameGuidType.cs @@ -0,0 +1,12 @@ +namespace EventLogApp +{ + internal class CodeNameGuidType : CodeNameType + { + public string Guid; + + public CodeNameGuidType(long code, string name, string guid) : base(code, name) + { + this.Guid = guid; + } + } +} diff --git a/EventLogApp/EventElements/CodeNameType.cs b/EventLogApp/EventElements/CodeNameType.cs new file mode 100644 index 0000000..aba82f0 --- /dev/null +++ b/EventLogApp/EventElements/CodeNameType.cs @@ -0,0 +1,22 @@ +namespace EventLogApp +{ + internal class CodeNameType + { + public long Code; + public string Name; + + public CodeNameType(long code, string name) + { + this.Code = code; + + if (string.IsNullOrEmpty(name)) + { + this.Name = string.Empty; + } + else + { + this.Name = name; + } + } + } +} diff --git a/EventLogApp/EventElements/Computer.cs b/EventLogApp/EventElements/Computer.cs new file mode 100644 index 0000000..8ed0e37 --- /dev/null +++ b/EventLogApp/EventElements/Computer.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class Computer : CodeNameType + { + public Computer(long code, string name) : base(code, name) + { + } + } +} diff --git a/EventLogApp/EventElements/ESRecord.cs b/EventLogApp/EventElements/ESRecord.cs new file mode 100644 index 0000000..9e30291 --- /dev/null +++ b/EventLogApp/EventElements/ESRecord.cs @@ -0,0 +1,28 @@ +using System; + +namespace EventLogApp +{ + internal class ESRecord + { + public long RowID { get; set; } + public string ServerName { get; set; } + public string DatabaseName { get; set; } + public DateTime DateTime { get; set; } + public string Severity { get; set; } + public EventType EventType { get; set; } + public string Computer { get; set; } + public string Application { get; set; } + public Metadata Metadata { get; set; } + public User UserName { get; set; } + public int SessionNumber { get; set; } + public int ConnectID { get; set; } + public int DataType { get; set; } + public string DataStructure { get; set; } + public string DataString { get; set; } + public string Comment { get; set; } + public string PrimaryPort { get; set; } + public string SecondaryPort { get; set; } + public string Server { get; set; } + public int SessionDataSplitCode { get; set; } + } +} diff --git a/EventLogApp/EventElements/EventElementsDictionary.cs b/EventLogApp/EventElements/EventElementsDictionary.cs new file mode 100644 index 0000000..0fb2efe --- /dev/null +++ b/EventLogApp/EventElements/EventElementsDictionary.cs @@ -0,0 +1,27 @@ +//using Nest; +using System.Collections.Generic; + +namespace EventLogApp +{ + internal class EventElementsDictionary : Dictionary where T : CodeNameType + { + //private Dictionary dictionary = new Dictionary(); + + public EventElementsDictionary() : base() { } + + EventElementsDictionary(int capacity) : base(capacity) { } + + public void Add(T item) + { + if (typeof(T).IsSubclassOf(typeof(CodeNameGuidType))) + { + if (base.ContainsKey(item.Code)) + { + base.Remove(item.Code); + } + } + + base.Add(item.Code, item); + } + } +} diff --git a/EventLogApp/EventElements/EventType.cs b/EventLogApp/EventElements/EventType.cs new file mode 100644 index 0000000..69b7278 --- /dev/null +++ b/EventLogApp/EventElements/EventType.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class EventType : CodeNameType + { + public EventType(long code, string name) : base(code, name) + { + } + } +} diff --git a/EventLogApp/EventElements/MainPort.cs b/EventLogApp/EventElements/MainPort.cs new file mode 100644 index 0000000..e31794b --- /dev/null +++ b/EventLogApp/EventElements/MainPort.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class MainPort : CodeNameType + { + public MainPort(long code, string name) : base(code, name) + { + } + } +} diff --git a/EventLogApp/EventElements/Metadata.cs b/EventLogApp/EventElements/Metadata.cs new file mode 100644 index 0000000..87fe232 --- /dev/null +++ b/EventLogApp/EventElements/Metadata.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class Metadata : CodeNameGuidType + { + public Metadata(long code, string name, string guid) : base(code, name, guid) + { + } + } +} diff --git a/EventLogApp/EventElements/OneEventRecord.cs b/EventLogApp/EventElements/OneEventRecord.cs new file mode 100644 index 0000000..1e21a97 --- /dev/null +++ b/EventLogApp/EventElements/OneEventRecord.cs @@ -0,0 +1,198 @@ +//using Nest; +using System; +using System.Collections.Generic; +using System.Data.SQLite; +using System.Globalization; + +namespace EventLogApp +{ + public class OneEventRecord + { + public NLog.Logger Log; + + public long RowID { get; set; } + public DateTime DateTime { get; set; } + public long ConnectID { get; set; } + public long Severity { get; set; } + public string TransactionStatus { get; set; } + public string Transaction { get; set; } + public DateTime TransactionStartTime { get; set; } + public long TransactionMark { get; set; } + public long UserName { get; set; } + public long ComputerName { get; set; } + public long AppName { get; set; } + public long EventID { get; set; } + public string EventType { get; set; } + public string Comment { get; set; } + public int MetadataID; + public long SessionDataSplitCode { get; set; } + public string DataStructure { get; set; } + public string DataString { get; set; } + public long DataType { get; set; } + public long ServerID { get; set; } + public long MainPortID { get; set; } + public long SecondPortID { get; set; } + public long SessionNumber { get; set; } + + private string eventString; + + public OneEventRecord() + { + Log = NLog.LogManager.GetLogger("CurrentThread"); + } + + + public OneEventRecord(string eventString) + { + CultureInfo provider = CultureInfo.InvariantCulture; + + this.eventString = eventString; + + List parsedEvent = ParserServices.ParseEventLogString(eventString); + DateTime = DateTime.ParseExact(parsedEvent[0], "yyyyMMddHHmmss", provider); + TransactionStatus = parsedEvent[1]; + + string transactionString = parsedEvent[2].ToString().Replace("}", "").Replace("{", ""); + + long transactionDate = From16To10(transactionString.Substring(0, transactionString.IndexOf(","))); + + TransactionStartTime = new DateTime().AddYears(2000); + + try + { + if (transactionDate != 0) + { + TransactionStartTime = new DateTime().AddSeconds(Convert.ToInt64(transactionDate / 10000)); + } + } + catch (Exception ex) + { + Log.Error(ex, this.GetType().ToString()); + } + + TransactionMark = From16To10(transactionString.Substring(transactionString.IndexOf(",") + 1)); + + Transaction = parsedEvent[2]; + UserName = Convert.ToInt32(parsedEvent[3]); + ComputerName = Convert.ToInt32(parsedEvent[4]); + AppName = Convert.ToInt32(parsedEvent[5]); + EventID = Convert.ToInt32(parsedEvent[7]); + EventType = parsedEvent[8]; + Comment = parsedEvent[9].RemoveQuotes(); + MetadataID = Convert.ToInt32(parsedEvent[10]); + DataStructure = parsedEvent[11]; + DataString = parsedEvent[12].RemoveQuotes(); + ServerID = Convert.ToInt32(parsedEvent[13]); + MainPortID = Convert.ToInt32(parsedEvent[14]); + SecondPortID = Convert.ToInt32(parsedEvent[15]); + SessionNumber = Convert.ToInt32(parsedEvent[16]); + + if (DataStructure == "{\"U\"}") //'empty reference + { + DataStructure = string.Empty; + } + else if (DataStructure.StartsWith("{")) + { + //'internal representation for different objects. + List ParsedObject = ParserServices.ParseEventLogString(DataStructure); + + if (ParsedObject.Count == 2) + { + if (ParsedObject[0] == "\"S\"" || ParsedObject[0] == "\"R\"") //'this is string or reference + DataStructure = ParsedObject[1].RemoveQuotes(); //'string value + } + } + + switch (EventType) + { + case "I": + Severity = 1;// '"Information"; + break; + case "W": + Severity = 2;// '"Warning" + break; + case "E": + Severity = 3;// '"Error" + break; + case "N": + Severity = 4;// '"Note" + break; + } + } + + public OneEventRecord(SQLiteDataReader reader) + { + System.Text.Encoding ANSI = System.Text.Encoding.GetEncoding(1252); + System.Text.Encoding UTF8 = System.Text.Encoding.UTF8; + + RowID = (long)reader["rowID"]; + Severity = (long)reader["severity"]; + ConnectID = (long)reader["connectID"]; + DateTime = new DateTime().AddSeconds(Convert.ToInt64((long)reader["date"] / 10000)); + TransactionStatus = reader["transactionStatus"].ToString(); + TransactionMark = (long)reader["transactionID"]; + TransactionStartTime = new DateTime().AddYears(2000); + + try + { + if ((long)reader["transactionDate"] != 0) + { + TransactionStartTime = new DateTime().AddSeconds(Convert.ToInt64((long)reader["transactionDate"] / 10000)); + } + } + catch (Exception ex) + { + Log.Error(ex, this.GetType().ToString()); + } + + UserName = (long)reader["userCode"]; + ComputerName = (long)reader["computerCode"]; + AppName = (long)reader["appCode"]; + EventID = (long)reader["eventCode"]; + Comment = (string)reader["comment"]; + + string MDCodes = (string)reader["metadataCodes"]; + + if (string.IsNullOrEmpty(MDCodes)) + { + MetadataID = 0; + } + else if (MDCodes.Contains(",")) + { + string MDCode = MDCodes.Split(',')[0]; + int.TryParse(MDCode, out MetadataID); + } + else + { + int.TryParse(MDCodes, out MetadataID); + } + + string s = string.Empty; + + if (!string.IsNullOrEmpty((string)reader["data"])) + { + s = UTF8.GetString(ANSI.GetBytes((string)reader["data"])); + } + + DataStructure = s; + + DataType = (long)reader["dataType"]; + DataString = (string)reader["dataPresentation"]; + ServerID = (long)reader["workServerCode"]; + MainPortID = (long)reader["primaryPortCode"]; + SecondPortID = (long)reader["secondaryPortCode"]; + SessionNumber = (long)reader["session"]; + SessionDataSplitCode = (long)reader["sessionDataSplitCode"]; + + Transaction = string.Empty; + EventType = string.Empty; + } + + + private long From16To10(string str) + { + return long.Parse(str, NumberStyles.HexNumber); + } + + } +} diff --git a/EventLogApp/EventElements/SecondPort.cs b/EventLogApp/EventElements/SecondPort.cs new file mode 100644 index 0000000..1ee5b91 --- /dev/null +++ b/EventLogApp/EventElements/SecondPort.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class SecondPort : CodeNameType + { + public SecondPort(long code, string name) : base(code, name) + { + } + } +} diff --git a/EventLogApp/EventElements/Server.cs b/EventLogApp/EventElements/Server.cs new file mode 100644 index 0000000..d7db3bc --- /dev/null +++ b/EventLogApp/EventElements/Server.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class Server : CodeNameType + { + public Server(long code, string name) : base(code, name) + { + } + } +} diff --git a/EventLogApp/EventElements/StringExtension.cs b/EventLogApp/EventElements/StringExtension.cs new file mode 100644 index 0000000..21a3605 --- /dev/null +++ b/EventLogApp/EventElements/StringExtension.cs @@ -0,0 +1,22 @@ +namespace EventLogApp +{ + public static class StringExtension + { + public static string RemoveQuotes(this string str) + { + string retval = str; + + if (retval.StartsWith("\"")) + { + retval = retval.Substring(1); + } + + if (retval.EndsWith("\"")) + { + retval = retval.Substring(0, retval.Length - 1); + } + + return retval; + } + } +} diff --git a/EventLogApp/EventElements/User.cs b/EventLogApp/EventElements/User.cs new file mode 100644 index 0000000..6c03802 --- /dev/null +++ b/EventLogApp/EventElements/User.cs @@ -0,0 +1,9 @@ +namespace EventLogApp +{ + internal class User : CodeNameGuidType + { + public User(long code, string name, string guid) : base(code, name, guid) + { + } + } +} diff --git a/EventLogApp/EventLogApp.csproj b/EventLogApp/EventLogApp.csproj new file mode 100644 index 0000000..5ef76bd --- /dev/null +++ b/EventLogApp/EventLogApp.csproj @@ -0,0 +1,161 @@ + + + + + Debug + AnyCPU + {036F352B-E448-47E0-BB91-F98D4896C6CA} + Exe + EventLogApp + EventLogApp + v4.7.1 + 512 + true + true + + + + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + x64 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\BouncyCastle.1.8.3.1\lib\BouncyCastle.Crypto.dll + + + ..\packages\Google.Protobuf.3.6.1\lib\net45\Google.Protobuf.dll + + + ..\packages\MySql.Data.8.0.16\lib\net452\MySql.Data.dll + + + ..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll + + + ..\packages\NLog.4.6.2\lib\net45\NLog.dll + + + + + + + + + ..\packages\System.Data.SQLite.Core.1.0.110.0\lib\net451\System.Data.SQLite.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Component + + + EventLogService.cs + + + Component + + + EventLogServiceInstaller.cs + + + + + + + + + + + + + + + + + + + PreserveNewest + + + Designer + + + + + + False + Microsoft .NET Framework 4.7.1 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + \ No newline at end of file diff --git a/EventLogApp/EventLogLoaderService.cs b/EventLogApp/EventLogLoaderService.cs new file mode 100644 index 0000000..2f6f13e --- /dev/null +++ b/EventLogApp/EventLogLoaderService.cs @@ -0,0 +1,338 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.IO; +using System.Threading; + +namespace EventLogApp +{ + public class EventLogLoaderService + { + List ListOfProcessors = new List(); + List ArrayThread; + + public ConfigSetting ConfigSettingObj = new ConfigSetting(); + string ConnectionString; + string DBType; + bool ItIsMySQL; + bool ItIsMSSQL; + bool ItIsElasticSearch; + public int SleepTime = 60 * 1000; //1 мин + + public Thread WorkerThread; + private NLog.Logger Log; + + public EventLogLoaderService() + { + //InitializeComponent(); + + Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); + + Log = NLog.LogManager.GetLogger("CurrentThread"); + + ArrayThread = new List(); + + WorkerThread = new Thread(DoWork); + WorkerThread.SetApartmentState(ApartmentState.STA); + } + + + public void DoWork() + { + if (!LoadConfigSetting()) + { + Log.Error("Error while working with config.json file in application folder"); + Environment.Exit(-1); + } + + CreateTables(); + + foreach (EventLogProcessor IB in ListOfProcessors) + { + try + { + IB.GetInfobaseIDFromDatabase(); + } + catch (Exception ex) + { + Log.Error(ex, $"Error occurred while getting infobase ID from target database ({IB.InfobaseName})"); + + continue; + } + + try + { + var Thead = new Thread(IB.DoWork) + { + IsBackground = false + }; + + Thead.Start(); + + ArrayThread.Add(Thead); + + //------------------------------------- + + //IB.DoWork(); + } + catch (Exception ex) + { + Log.Error(ex, $"Error occurred while starting new thread ({IB.InfobaseName})"); + } + } + } + + + public void CreateTables() + { + try + { + if (ItIsMSSQL) + { + SqlConnection objConn = new SqlConnection(ConnectionString); + objConn.Open(); + + var command = new SqlCommand(@"IF NOT EXISTS (select * from sysobjects where id = object_id(N'Events')) + BEGIN + CREATE TABLE[dbo].[Events]([InfobaseCode] int Not NULL, [DateTime][datetime] Not NULL, + [TransactionStatus][varchar](1) NULL, + [TransactionStartTime][datetime] NULL, + + [TransactionMark] bigint NULL, + [Transaction][varchar](100) NULL, + + [UserName] int NULL, + + [ComputerName] int NULL, + + [AppName] Int NULL, + [EventID] int NULL, + + [EventType][varchar](1) NULL, + [Comment][nvarchar](max) NULL, + + [MetadataID] int NULL, + + [DataStructure][nvarchar](max) NULL, + + [DataString][nvarchar](max) NULL, + [ServerID] int NULL, + + [MainPortID] int NULL, + [SecondPortID] int NULL, + + [Seance] int NULL); + CREATE CLUSTERED INDEX[CIX_Events] ON[dbo].[Events]([InfobaseCode], [DateTime]) + END", objConn); + command.ExecuteNonQuery(); + + command.CommandText = "IF NOT EXISTS (select * from sysobjects where id = object_id(N'Infobases'))" + Environment.NewLine + + " CREATE TABLE [dbo].[Infobases] ([Guid] [char](40) NOT NULL, [Code] int NOT NULL, [Name] [char](100))" + Environment.NewLine + + " IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'Infobases') AND Name = 'ClusteredIndex')" + Environment.NewLine + + " CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[Infobases] ([Guid] ASC);"; + command.ExecuteNonQuery(); + + command.CommandText = + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'Users'))" + Environment.NewLine + + "CREATE TABLE [dbo].[Users]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](100), [Guid] [varchar](40));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'Users') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[Users] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'Metadata'))" + Environment.NewLine + + "CREATE TABLE [dbo].[Metadata]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](100), [Guid] [varchar](40));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'Metadata') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[Metadata] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'Computers'))" + Environment.NewLine + + "CREATE TABLE [dbo].[Computers]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](100));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'Computers') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[Computers] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'Applications'))" + Environment.NewLine + + "CREATE TABLE [dbo].[Applications]([InfobaseCode] int NOT NULL, [Code] int NOT NULL,[Name] [nvarchar](100));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'Applications') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[Applications] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'EventsType'))" + Environment.NewLine + + "CREATE TABLE [dbo].[EventsType]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](max));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'EventsType') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[EventsType] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'Servers'))" + Environment.NewLine + + "CREATE TABLE [dbo].[Servers]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](100));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'Servers') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[Servers] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'MainPorts'))" + Environment.NewLine + + "CREATE TABLE [dbo].[MainPorts]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](100));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'MainPorts') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[MainPorts] ([InfobaseCode] ASC, [Code] ASC);" + Environment.NewLine + + "" + + "IF NOT EXISTS (select * from sysobjects where id = object_id(N'SecondPorts'))" + Environment.NewLine + + "CREATE TABLE [dbo].[SecondPorts]([InfobaseCode] int NOT NULL, [Code] int NOT NULL, [Name] [nvarchar](100));" + Environment.NewLine + + "IF NOT EXISTS (select * from sys.indexes where object_id = object_id(N'SecondPorts') AND Name = 'ClusteredIndex')" + Environment.NewLine + + "CREATE UNIQUE CLUSTERED INDEX [ClusteredIndex] ON [dbo].[SecondPorts] ([InfobaseCode] ASC, [Code] ASC);"; + + command.ExecuteNonQuery(); + + command.CommandText = "SELECT TOP 1 * FROM Events"; + command.ExecuteReader(); + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + else if (ItIsMySQL) + { + MySql.Data.MySqlClient.MySqlConnection objConn = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString); + objConn.Open(); + + string DBName = objConn.Database; + + MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand + { + Connection = objConn, + CommandText = "CREATE TABLE IF NOT EXISTS `Events` (`InfobaseCode` int(11) NOT NULL, `DateTime` int(11) NOT NULL," + + "`TransactionStatus` varchar(1) NULL, `TransactionStartTime` datetime NULL, " + + "`TransactionMark` bigint NULL, `Transaction` varchar(100) NULL, `UserName` int(11) NULL, `ComputerName` int(11) NULL, " + + "`AppName` int(11) NULL, `EventID` int(11) NULL, `EventType` varchar(1) NULL, " + + "`Comment` text NULL, `MetadataID` int(11) NULL, `DataStructure` text NULL, `DataString` text NULL, " + + "`ServerID` int(11) NULL, `MainPortID` int(11) NULL, `SecondPortID` int(11) NULL, `Seance` int(11) NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;" + }; + + command.ExecuteNonQuery(); + + command.CommandText = "CREATE TABLE IF NOT EXISTS `Infobases` (`Guid` varchar(40) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100)," + + "PRIMARY KEY `Guid` (`Guid`));"; + command.ExecuteNonQuery(); + + command.CommandText = + "CREATE TABLE IF NOT EXISTS `Users`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), `Guid` varchar(40), PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `Metadata`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), `Guid` varchar(40), PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `Computers`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `Applications`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `EventsType`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` text, PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `Servers`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `MainPorts`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), PRIMARY KEY (`InfobaseCode`, `Code`));" + Environment.NewLine + + "" + + "CREATE TABLE IF NOT EXISTS `SecondPorts`(`InfobaseCode` int(11) NOT NULL, `Code` int(11) NOT NULL, `Name` varchar(100), PRIMARY KEY (`InfobaseCode`, `Code`));"; + + command.ExecuteNonQuery(); + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + + Log.Info("Target database tables have been verified!"); + } + catch (Exception ex) + { + Log.Error(ex, "Error occurred while during target database tables verification"); + } + } + + + public bool LoadConfigSetting() + { + try + { + string PathConfigFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"); + + if (File.Exists(PathConfigFile)) + { + ConfigSettingObj = ConfigSettings.LoadConfigSettingFromFile(PathConfigFile); + + ConnectionString = ConfigSettingObj.ConnectionString; + DBType = ConfigSettingObj.DBType; + + if (DBType == "MySQL") + { + ItIsMySQL = true; + } + else if (DBType == "MS SQL Server") + { + ItIsMSSQL = true; + } + else if (DBType == "ElasticSearch") + { + ItIsElasticSearch = true; + } + + this.SleepTime = this.ConfigSettingObj.RepeatTime * 1000; + + foreach (InfobaseSetting IBConfig in ConfigSettingObj.Infobases) + { + string IB_ID = IBConfig.DatabaseID; + string IB_Name = IBConfig.DatabaseName; + string IB_Catalog = IBConfig.DatabaseCatalog; + + EventLogProcessor EventLogProcessorObj = new EventLogProcessor + { + Log = NLog.LogManager.GetLogger("CurrentThread"), + InfobaseGuid = IB_ID, + InfobaseName = IB_Name, + Catalog = IB_Catalog, + ConnectionString = this.ConnectionString, + SleepTime = this.SleepTime, + ItIsMSSQL = this.ItIsMSSQL, + ItIsMySQL = this.ItIsMySQL, + ItIsElasticSearch = this.ItIsElasticSearch, + ESIndexName = this.ConfigSettingObj.ESIndexName, + ESServerName = IBConfig.ESServerName, + ESUseSynonymsForFieldsNames = this.ConfigSettingObj.ESUseSynonymsForFieldsNames, + ESFieldSynonyms = this.ConfigSettingObj.ESFieldSynonyms + }; + + try + { + EventLogProcessorObj.LoadEventsStartingAt = DateTime.Parse(IBConfig.StartDate); + } + catch (Exception ex) + { + EventLogProcessorObj.LoadEventsStartingAt = new DateTime(1900, 1, 1); + + Log.Error(ex, this.GetType().ToString()); + } + + ListOfProcessors.Add(EventLogProcessorObj); + } + + return true; + } + else + { + Log.Error("File config.json was not found!"); + + return false; + } + } + catch (Exception ex) + { + Log.Error(ex, "Parameters cannot be load from config.json file (it may be corrupted)"); + + throw ex; + } + } + + + public void SubStart() + { + WorkerThread.Start(); + } + + + public void SubStop() + { + WorkerThread.Abort(); + } + + } +} diff --git a/EventLogApp/EventLogProcessor.cs b/EventLogApp/EventLogProcessor.cs new file mode 100644 index 0000000..da2cfd1 --- /dev/null +++ b/EventLogApp/EventLogProcessor.cs @@ -0,0 +1,1369 @@ +using MySql.Data.MySqlClient; +//using Nest; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Data.SQLite; +using System.Globalization; +using System.IO; +using System.Threading; + +namespace EventLogApp +{ + partial class EventLogProcessor + { + public EventElementsDictionary UsersDictionary = new EventElementsDictionary(); + public EventElementsDictionary ComputersDictionary = new EventElementsDictionary(); + public EventElementsDictionary ApplicationsDictionary = new EventElementsDictionary(); + public EventElementsDictionary EventsDictionary = new EventElementsDictionary(); + public EventElementsDictionary MetadataDictionary = new EventElementsDictionary(); + public EventElementsDictionary ServersDictionary = new EventElementsDictionary(); + public EventElementsDictionary MainPortsDictionary = new EventElementsDictionary(); + public EventElementsDictionary SecondPortsDictionary = new EventElementsDictionary(); + + public List EventsList = new List(); + + public string ESIndexName; + public string ESServerName; + + public string InfobaseName; + public string InfobaseGuid; + public int InfobaseID; + public string ConnectionString; + public bool ItIsMSSQL; + public bool ItIsMySQL; + public bool ItIsElasticSearch; + public bool ESUseSynonymsForFieldsNames; + public DateTime LoadEventsStartingAt; + public ElasticSearchFieldSynonymsClass ESFieldSynonyms = new ElasticSearchFieldSynonymsClass(); + public int SleepTime = 60 * 1000;// '1 минута + + public NLog.Logger Log; + + public string Catalog; + long CurrentPosition; + string CurrentFilename; + long LastEventNumber83; + public DateTime LastReferenceUpdate; + + + public void AddUser(long code, string guid, string name) + { + this.UsersDictionary.Add(new User(code, name, guid)); + } + + + public void AddComputer(long code, string name) + { + this.ComputersDictionary.Add(new Computer(code, name)); + } + + + public void AddApplication(long code, string name) + { + this.ApplicationsDictionary.Add(new Application(code, name)); + } + + + public void AddEvent(long code, string name) + { + this.EventsDictionary.Add(new EventType(code, name)); + } + + + public void AddMetadata(long code, string guid, string name) + { + this.MetadataDictionary.Add(new Metadata(code, name, guid)); + } + + + public void AddServer(long code, string name) + { + this.ServersDictionary.Add(new Server(code, name)); + } + + + public void AddMainPort(long code, string name) + { + this.MainPortsDictionary.Add(new MainPort(code, name)); + } + + + public void AddSecondPort(long code, string name) + { + this.SecondPortsDictionary.Add(new SecondPort(code, name)); + } + + + public void SaveReferenceValuesToDatabase() + { + if (ItIsMSSQL) + { + SqlConnection objConn = new SqlConnection(ConnectionString); + objConn.Open(); + + SqlCommand command = new SqlCommand("IF NOT EXISTS (select * from [dbo].[Applications] where [Code] = @v1 AND [InfobaseCode] = @v3) " + + "INSERT INTO [dbo].[Applications] ([InfobaseCode],[Code],[Name]) VALUES(@v3, @v1, @v2)", objConn); + + foreach (var item in ApplicationsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "IF NOT EXISTS (select * from [dbo].[Computers] where [Code] = @v1 AND [InfobaseCode] = @v3) " + + "INSERT INTO [dbo].[Computers] ([InfobaseCode],[Code],[Name]) VALUES(@v3, @v1,@v2)"; + + foreach (var item in ComputersDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "IF NOT EXISTS (select * from [dbo].[EventsType] where [Code] = @v1 AND [InfobaseCode] = @v3) " + + "INSERT INTO [dbo].[EventsType] ([InfobaseCode],[Code],[Name]) VALUES(@v3, @v1,@v2)"; + + foreach (var item in EventsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "IF NOT EXISTS (select * from [dbo].[MainPorts] where [Code] = @v1 AND [InfobaseCode] = @v3) " + + "INSERT INTO [dbo].[MainPorts] ([InfobaseCode],[Code],[Name]) VALUES(@v3, @v1,@v2)"; + + foreach (var item in MainPortsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = @"MERGE INTO [dbo].[Metadata] AS Target + USING(SELECT @v1 AS[Code], + @v4 AS[InfobaseCode], + @v3 AS[Guid]) AS Source + ON(Target.[Code] = Source.[Code] + + AND Target.[InfobaseCode] = Source.[InfobaseCode] + + AND Target.[Guid] = Source.[Guid]) + WHEN MATCHED AND NOT([Name] = @v2) THEN UPDATE + SET[Name] = @v2 + WHEN NOT MATCHED THEN INSERT([InfobaseCode], [Code], [Name], [Guid]) VALUES(@v4, @v1, @v2, @v3);"; + + foreach (var item in MetadataDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Char)).Value = item.Value.Guid; + command.Parameters.Add(new SqlParameter("@v4", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = @"MERGE INTO [dbo].[Users] AS Target + USING(SELECT @v1 AS[Code], + @v4 AS[InfobaseCode], + @v3 AS[Guid]) AS Source + ON(Target.[Code] = Source.[Code] + + AND Target.[InfobaseCode] = Source.[InfobaseCode] + + AND Target.[Guid] = Source.[Guid]) + WHEN MATCHED AND NOT([Name] = @v2) THEN UPDATE + SET[Name] = @v2 + WHEN NOT MATCHED THEN INSERT([InfobaseCode], [Code], [Name], [Guid]) VALUES(@v4, @v1, @v2, @v3);"; + + foreach (var item in UsersDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Char)).Value = item.Value.Guid; + command.Parameters.Add(new SqlParameter("@v4", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "IF NOT EXISTS (select * from [dbo].[SecondPorts] where [Code] = @v1 AND [InfobaseCode] = @v3) " + + "INSERT INTO [dbo].[SecondPorts] ([InfobaseCode],[Code],[Name]) VALUES(@v3, @v1,@v2)"; + + foreach (var item in SecondPortsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "IF NOT EXISTS (select * from [dbo].[Servers] where [Code] = @v1 AND [InfobaseCode] = @v3) " + + "INSERT INTO [dbo].[Servers] ([InfobaseCode],[Code],[Name]) VALUES(@v3, @v1,@v2)"; + + foreach (var item in ServersDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = item.Value.Code; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = item.Value.Name; + command.Parameters.Add(new SqlParameter("@v3", SqlDbType.Int)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "IF NOT EXISTS (select * from [dbo].[Infobases] where [Guid] = @v0) " + + "INSERT INTO [dbo].[Infobases] ([Guid],[Code],[Name]) VALUES(@v0,@v1,@v2)"; + + try + { + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v0", SqlDbType.Char)).Value = InfobaseGuid; + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Int)).Value = InfobaseID; + command.Parameters.Add(new SqlParameter("@v2", SqlDbType.Char)).Value = InfobaseName; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + else if (ItIsMySQL) + { + MySqlConnection objConn = new MySqlConnection(ConnectionString); + objConn.Open(); + + MySqlCommand command = new MySqlCommand("REPLACE INTO `Applications`(`InfobaseCode`, `Code`, `Name`) VALUES(@v3, @v1, @v2)", objConn); + + foreach (var item in ApplicationsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "REPLACE INTO `Computers` (`InfobaseCode`,`Code`,`Name`) VALUES(@v3, @v1, @v2)"; + + foreach (var item in ComputersDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "REPLACE INTO `EventsType` (`InfobaseCode`,`Code`,`Name`) VALUES(@v3, @v1,@v2)"; + + foreach (var item in EventsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "REPLACE INTO `MainPorts` (`InfobaseCode`,`Code`,`Name`) VALUES(@v3, @v1,@v2)"; + + foreach (var item in MainPortsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = @"REPLACE INTO `Metadata` (`InfobaseCode`,`Code`,`Name`,`Guid`) VALUES(@v4, @v1,@v2,@v3)"; + + foreach (var item in MetadataDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.VarChar)).Value = item.Value.Guid; + command.Parameters.Add(new MySqlParameter("@v4", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = @"REPLACE INTO `Users` (`InfobaseCode`,`Code`,`Name`,`Guid`) VALUES(@v4, @v1,@v2,@v3)"; + + foreach (var item in UsersDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.VarChar)).Value = item.Value.Guid; + command.Parameters.Add(new MySqlParameter("@v4", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "REPLACE INTO `SecondPorts` (`InfobaseCode`,`Code`,`Name`) VALUES(@v3, @v1,@v2)"; + + foreach (var item in SecondPortsDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "REPLACE INTO `Servers` (`InfobaseCode`,`Code`,`Name`) VALUES(@v3, @v1,@v2)"; + + foreach (var item in ServersDictionary) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = item.Value.Code; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = item.Value.Name; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.Int32)).Value = InfobaseID; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + command.CommandText = "REPLACE INTO `Infobases` (`Guid`,`Code`,`Name`) VALUES(@v0,@v1,@v2)"; + + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v0", MySqlDbType.VarChar)).Value = InfobaseGuid; + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.Int32)).Value = InfobaseID; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = InfobaseName; + command.ExecuteNonQuery(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + + LastReferenceUpdate = DateTime.Now; + } + + + public void GetInfobaseIDFromDatabase() + { + if (ItIsMSSQL) + { + SqlConnection objConn = new SqlConnection(ConnectionString); + objConn.Open(); + + SqlCommand command = new SqlCommand("SELECT [Code] FROM [dbo].[Infobases] WHERE [Guid] = @v1", objConn); + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Char)).Value = InfobaseGuid; + + SqlDataReader rs = command.ExecuteReader(); + + if (rs.Read()) + { + InfobaseID = Convert.ToInt32(rs[0]); + } + + rs.Close(); + + if (InfobaseID == 0) + { + command.CommandText = @"INSERT INTO Infobases ([Code], [Name], [guid]) + SELECT MAX(f) AS[Code], + @v0 AS[Name], + @v1 AS[guid] + FROM(SELECT MAX(Code) + 1 AS f + FROM Infobases + UNION ALL + SELECT 1 AS Expr1) AS T; "; + + command.Parameters.Clear(); + command.Parameters.Add(new SqlParameter("@v0", SqlDbType.Char)).Value = InfobaseName; + command.Parameters.Add(new SqlParameter("@v1", SqlDbType.Char)).Value = InfobaseGuid; + command.ExecuteNonQuery(); + + command.CommandText = "SELECT [Code] FROM [dbo].[Infobases] WHERE [Guid] = @v1"; + rs = command.ExecuteReader(); + + if (rs.Read()) + { + InfobaseID = Convert.ToInt32(rs[0]); + } + + rs.Close(); + } + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + else if (ItIsMySQL) + { + MySqlConnection objConn = new MySqlConnection(ConnectionString); + objConn.Open(); + + MySqlCommand command = new MySqlCommand("SELECT `Code` FROM `Infobases` WHERE `Guid` = @v1", objConn); + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.VarChar)).Value = InfobaseGuid; + + MySqlDataReader rs = command.ExecuteReader(); + + if (rs.Read()) + { + InfobaseID = Convert.ToInt32(rs[0]); + } + + rs.Close(); + + if (InfobaseID == 0) + { + command.CommandText = "INSERT INTO Infobases (`Code`,`Name`,`guid`)" + + " SELECT MAX(f) AS `Code`, @v0 as `Name`, @v1 as `guid` FROM " + + " (SELECT MAX(Code) + 1 AS f FROM `Infobases` UNION ALL" + + " SELECT 1 AS `Expr1`) AS T"; + + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v0", MySqlDbType.VarChar)).Value = InfobaseName; + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.VarChar)).Value = InfobaseGuid; + command.ExecuteNonQuery(); + + command.CommandText = "SELECT `Code` FROM `Infobases` WHERE `Guid` = @v1"; + + rs = command.ExecuteReader(); + + if (rs.Read()) + { + InfobaseID = Convert.ToInt32(rs[0]); + } + + rs.Close(); + } + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + } + + + public void SaveReadParametersToFile() + { + string readParametersFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"read-setting-{InfobaseGuid}.json"); + + ReadParameters ConfigSettingObj = new ReadParameters + { + CurrentPosition = this.CurrentPosition, + CurrentFilename = this.CurrentFilename, + LastEventNumber83 = this.LastEventNumber83 + }; + + string JsonText = JsonConvert.SerializeObject(ConfigSettingObj, Formatting.Indented); + + //Console.WriteLine(readParametersFile); + //Console.WriteLine(JsonText); + + File.WriteAllText(readParametersFile, JsonText); + } + + + public void GetReadParametersFromFile() + { + string ReadParametersFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"read-setting-{InfobaseGuid}.json"); + + if (File.Exists(ReadParametersFile)) + { + string JsonText = File.ReadAllText(ReadParametersFile); + + ReadParameters ConfigSettingObj = JsonConvert.DeserializeObject(JsonText); + + this.CurrentPosition = Convert.ToInt64(ConfigSettingObj.CurrentPosition); + this.CurrentFilename = ConfigSettingObj.CurrentFilename; + this.LastEventNumber83 = ConfigSettingObj.LastEventNumber83; + } + } + + + public void SaveEventsToSQL() + { + if (EventsList.Count == 0) + return; + + if (ItIsMSSQL) + { + SqlConnection objConn = new SqlConnection(ConnectionString); + objConn.Open(); + + DataTable dt = new DataTable(); + + /* + [InfobaseCode] [int] NOT NULL, + [DateTime] [datetime] NOT NULL, + [TransactionStatus] [varchar](1) NULL, + [TransactionStartTime] [datetime] NULL, + [TransactionMark] [bigint] NULL, + [Transaction] [varchar](100) NULL, + [UserName] [int] NULL, + [ComputerName] [int] NULL, + [AppName] [int] NULL, + [EventID] [int] NULL, + [EventType] [varchar](1) NULL, + [Comment] [nvarchar](max) NULL, + [MetadataID] [int] NULL, + [DataStructure] [nvarchar](max) NULL, + [DataString] [nvarchar](max) NULL, + [ServerID] [int] NULL, + [MainPortID] [int] NULL, + [SecondPortID] [int] NULL, + [Seance] [int] NULL + */ + + dt.Columns.Add(new DataColumn("InfobaseCode", typeof(int))); + dt.Columns.Add(new DataColumn("DateTime", typeof(DateTime))); + dt.Columns.Add(new DataColumn("TransactionStatus", typeof(string))); + dt.Columns.Add(new DataColumn("TransactionStartTime", typeof(DateTime))); + dt.Columns.Add(new DataColumn("TransactionMark", typeof(long))); + dt.Columns.Add(new DataColumn("Transaction", typeof(string))); + dt.Columns.Add(new DataColumn("UserName", typeof(int))); + dt.Columns.Add(new DataColumn("ComputerName", typeof(int))); + dt.Columns.Add(new DataColumn("AppName", typeof(int))); + dt.Columns.Add(new DataColumn("EventID", typeof(int))); + dt.Columns.Add(new DataColumn("EventType", typeof(string))); + dt.Columns.Add(new DataColumn("Comment", typeof(string))); + dt.Columns.Add(new DataColumn("MetadataID", typeof(int))); + dt.Columns.Add(new DataColumn("DataStructure", typeof(string))); + dt.Columns.Add(new DataColumn("DataString", typeof(string))); + dt.Columns.Add(new DataColumn("ServerID", typeof(int))); + dt.Columns.Add(new DataColumn("MainPortID", typeof(int))); + dt.Columns.Add(new DataColumn("SecondPortID", typeof(int))); + dt.Columns.Add(new DataColumn("Seance", typeof(int))); + + foreach (OneEventRecord eventRecord in EventsList) + { + if (eventRecord.AppName == 0) + continue; + + DataRow row = dt.NewRow(); + + try + { + row[0] = InfobaseID; + row[1] = eventRecord.DateTime; + row[2] = eventRecord.TransactionStatus; + row[3] = eventRecord.TransactionStartTime; + row[4] = eventRecord.TransactionMark; + row[5] = eventRecord.Transaction; + row[6] = eventRecord.UserName; + row[7] = eventRecord.ComputerName; + row[8] = eventRecord.AppName; + row[9] = eventRecord.EventID; + row[10] = eventRecord.EventType; + row[11] = eventRecord.Comment; + row[12] = eventRecord.MetadataID; + row[13] = eventRecord.DataStructure; + row[14] = eventRecord.DataString; + row[15] = eventRecord.ServerID; + row[16] = eventRecord.MainPortID; + row[17] = eventRecord.SecondPortID; + row[18] = eventRecord.SessionNumber; + + dt.Rows.Add(row); + } + catch (Exception ex) + { + Log.Error(ex, this.GetType().ToString()); + } + } + + + + using (SqlBulkCopy copy = new SqlBulkCopy(objConn)) + { + for (int jj = 0; jj <= 18; jj++) + { + copy.ColumnMappings.Add(jj, jj); + } + + copy.DestinationTableName = "Events"; + copy.WriteToServer(dt); + } + + SaveReadParametersToFile(); + + Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", + CultureInfo.InvariantCulture) + $" New records have been processed: {EventsList.Count.ToString()} ({InfobaseName})"); + + objConn.Close(); + objConn.Dispose(); + } + else if (ItIsMySQL) + { + MySqlConnection objConn = new MySqlConnection(ConnectionString); + objConn.Open(); + + MySqlCommand command = new MySqlCommand("START TRANSACTION", objConn); + command.ExecuteNonQuery(); + + command.CommandText = "INSERT INTO `Events` (`InfobaseCode`,`DateTime`,`TransactionStatus`,`Transaction`,`UserName`,`ComputerName`" + + ",`AppName`,`EventID`,`EventType`,`Comment`,`MetadataID`,`DataStructure`,`DataString`" + + ",`ServerID`,`MainPortID`,`SecondPortID`,`Seance`,`TransactionStartTime`,`TransactionMark`)" + + " VALUES(@v0,@v1,@v2,@v3,@v4,@v5,@v6,@v7,@v8,@v9,@v10,@v11,@v12,@v13,@v14,@v15,@v16,@v17,@v18)"; + + int i = 0; + + foreach (OneEventRecord eventRecord in EventsList) + { + try + { + command.Parameters.Clear(); + command.Parameters.Add(new MySqlParameter("@v0", MySqlDbType.Int32)).Value = InfobaseID; + command.Parameters.Add(new MySqlParameter("@v1", MySqlDbType.DateTime)).Value = eventRecord.DateTime; + command.Parameters.Add(new MySqlParameter("@v2", MySqlDbType.VarChar)).Value = eventRecord.TransactionStatus; + command.Parameters.Add(new MySqlParameter("@v3", MySqlDbType.VarChar)).Value = eventRecord.Transaction; + command.Parameters.Add(new MySqlParameter("@v4", MySqlDbType.Int32)).Value = eventRecord.UserName; + command.Parameters.Add(new MySqlParameter("@v5", MySqlDbType.Int32)).Value = eventRecord.ComputerName; + command.Parameters.Add(new MySqlParameter("@v6", MySqlDbType.Int32)).Value = eventRecord.AppName; + command.Parameters.Add(new MySqlParameter("@v7", MySqlDbType.Int32)).Value = eventRecord.EventID; + command.Parameters.Add(new MySqlParameter("@v8", MySqlDbType.VarChar)).Value = eventRecord.EventType; + command.Parameters.Add(new MySqlParameter("@v9", MySqlDbType.VarChar)).Value = eventRecord.Comment; + command.Parameters.Add(new MySqlParameter("@v10", MySqlDbType.Int32)).Value = eventRecord.MetadataID; + command.Parameters.Add(new MySqlParameter("@v11", MySqlDbType.VarChar)).Value = eventRecord.DataStructure; + command.Parameters.Add(new MySqlParameter("@v12", MySqlDbType.VarChar)).Value = eventRecord.DataString; + command.Parameters.Add(new MySqlParameter("@v13", MySqlDbType.Int32)).Value = eventRecord.ServerID; + command.Parameters.Add(new MySqlParameter("@v14", MySqlDbType.Int32)).Value = eventRecord.MainPortID; + command.Parameters.Add(new MySqlParameter("@v15", MySqlDbType.Int32)).Value = eventRecord.SecondPortID; + command.Parameters.Add(new MySqlParameter("@v16", MySqlDbType.Int32)).Value = eventRecord.SessionNumber; + command.Parameters.Add(new MySqlParameter("@v17", MySqlDbType.DateTime)).Value = eventRecord.TransactionStartTime; + command.Parameters.Add(new MySqlParameter("@v18", MySqlDbType.Int64)).Value = eventRecord.TransactionMark; + + command.ExecuteNonQuery(); + + i += 1; + } + catch (Exception ex) + { + Log.Error($"Ошибка сохранения в БД записи от {eventRecord.DateTime.ToString()} по ИБ {InfobaseName} : {ex.Message}"); + } + } + + Console.WriteLine($"{DateTime.Now.ToShortTimeString()} New records have been processed: {i.ToString()}"); + + SaveReadParametersToFile(); + + command.CommandText = "COMMIT"; + command.Parameters.Clear(); + command.ExecuteNonQuery(); + + command.Dispose(); + objConn.Close(); + objConn.Dispose(); + } + //else if (ItIsES) + //{ + // var node = new Uri(ConnectionString); + + // var _settings = new ConnectionSettings(node).DefaultIndex(ESIndexName).MaximumRetries(2).MaxRetryTimeout(TimeSpan.FromSeconds(150)); + // var _current = new ElasticClient(_settings); + + // //'Let's create proper array for ES + // List NewRecords = new List(); + + // foreach (var EventRecord in EventsList) + // { + // ESRecord ESRecord = new ESRecord { ServerName = ESServerName, DatabaseName = InfobaseName }; + // ESRecord.RowID = EventRecord.RowID; + + // switch (EventRecord.Severity) + // { + // case 1: + // ESRecord.Severity = "Information"; + // break; + // case 2: + // ESRecord.Severity = "Warning"; + // break; + // case 3: + // ESRecord.Severity = "Error"; + // break; + // case 4: + // ESRecord.Severity = "Note"; + // break; + // } + + // ESRecord.DateTime = EventRecord.DateTime; + // ESRecord.ConnectID = EventRecord.ConnectID; + // ESRecord.DataType = EventRecord.DataType; + // ESRecord.SessionNumber = EventRecord.SessionNumber; + // ESRecord.DataStructure = EventRecord.DataStructure; + // ESRecord.DataString = EventRecord.DataString; + // ESRecord.Comment = EventRecord.Comment; + // ESRecord.SessionDataSplitCode = EventRecord.SessionDataSplitCode; + + + // var EventObj = new EventType(); + // if (DictEvents.TryGetValue(EventRecord.EventID, out EventObj)) + // { + // ESRecord.EventType = EventObj; + // } + + // var MetadataObj = new Metadata(); + // if (DictMetadata.TryGetValue(EventRecord.MetadataID, out MetadataObj)) + // { + // ESRecord.Metadata = MetadataObj; + // } + + // var ComputerObj = new Computer(); + // if (DictComputers.TryGetValue(EventRecord.ComputerName, out ComputerObj)) + // { + // ESRecord.Computer = ComputerObj.Name; + // } + + // var MainPortObj = new MainPort(); + // if (DictMainPorts.TryGetValue(EventRecord.MainPortID, out MainPortObj)) + // { + // ESRecord.PrimaryPort = MainPortObj.Name; + // } + + // var ServerObj = new Server(); + // if (DictServers.TryGetValue(EventRecord.ServerID, out ServerObj)) + // { + // ESRecord.Server = ServerObj.Name; + // } + + // var SecondPortObj = new SecondPort(); + // if (DictSecondPorts.TryGetValue(EventRecord.SecondPortID, out SecondPortObj)) + // { + // ESRecord.SecondaryPort = SecondPortObj.Name; + // } + + // var ApplicationObj = new Application(); + // if (DictApplications.TryGetValue(EventRecord.AppName, out ApplicationObj)) + // { + // ESRecord.Application = ApplicationObj.Name; + // } + + // var UserNameObj = new User(); + // if (DictUsers.TryGetValue(EventRecord.UserName, out UserNameObj)) + // { + // ESRecord.UserName = UserNameObj; + // } + + // if (ESUseSynonymsForFieldsNames) + // { + // var ESRecordUserFields = new Dictionary(); + // ESRecordUserFields.Add(ESFieldSynonyms.ServerName, ESRecord.ServerName); + // ESRecordUserFields.Add(ESFieldSynonyms.DatabaseName, ESRecord.DatabaseName); + // ESRecordUserFields.Add(ESFieldSynonyms.RowID, ESRecord.RowID); + // ESRecordUserFields.Add(ESFieldSynonyms.Severity, ESRecord.Severity); + // ESRecordUserFields.Add(ESFieldSynonyms.DateTime, ESRecord.DateTime); + // ESRecordUserFields.Add(ESFieldSynonyms.ConnectID, ESRecord.ConnectID); + // ESRecordUserFields.Add(ESFieldSynonyms.DataType, ESRecord.DataType); + // ESRecordUserFields.Add(ESFieldSynonyms.SessionNumber, ESRecord.SessionNumber); + // ESRecordUserFields.Add(ESFieldSynonyms.DataStructure, ESRecord.DataStructure); + // ESRecordUserFields.Add(ESFieldSynonyms.DataString, ESRecord.DataString); + // ESRecordUserFields.Add(ESFieldSynonyms.Comment, ESRecord.Comment); + // ESRecordUserFields.Add(ESFieldSynonyms.SessionDataSplitCode, ESRecord.SessionDataSplitCode); + // ESRecordUserFields.Add(ESFieldSynonyms.EventType, ESRecord.EventType); + // ESRecordUserFields.Add(ESFieldSynonyms.Metadata, ESRecord.Metadata); + // ESRecordUserFields.Add(ESFieldSynonyms.Computer, ESRecord.Computer); + // ESRecordUserFields.Add(ESFieldSynonyms.PrimaryPort, ESRecord.PrimaryPort); + // ESRecordUserFields.Add(ESFieldSynonyms.Server, ESRecord.Server); + // ESRecordUserFields.Add(ESFieldSynonyms.SecondaryPort, ESRecord.SecondaryPort); + // ESRecordUserFields.Add(ESFieldSynonyms.Application, ESRecord.Application); + // ESRecordUserFields.Add(ESFieldSynonyms.UserName, ESRecord.UserName); + + // NewRecords.Add(ESRecordUserFields); + // } + // else + // { + // NewRecords.Add(ESRecord); + // } + // } + + // var Result = _current.IndexMany(NewRecords, ESIndexName, "event-log-record"); + + // Console.WriteLine(DateTime.Now.ToShortTimeString() + " New records have been processed " + NewRecords.Count.ToString()); + + // SaveReadParametersToFile(); + //} + + EventsList.Clear(); + } + + + public void LoadReferenceFromTheTextFile(string FileName, ref string LastProcessedObjectForDebug) + { + FileStream FS = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + StreamReader SR = new StreamReader(FS); + + string Text = SR.ReadToEnd(); + + SR.Close(); + FS.Close(); + + Text = Text.Substring(Text.IndexOf("{")); + + List ObjectTexts = ParserServices.ParseEventLogString("{" + Text + "}"); + + foreach (string textObject in ObjectTexts) + { + LastProcessedObjectForDebug = textObject; + + List a = ParserServices.ParseEventLogString(textObject); + + if (a != null) + { + switch (a[0]) + { + case "1": + AddUser(Convert.ToInt32(a[3]), a[1], a[2]); + break; + + case "2": + AddComputer(Convert.ToInt32(a[2]), a[1]); + break; + + case "3": + AddApplication(Convert.ToInt32(a[2]), a[1]); + break; + + case "4": + AddEvent(Convert.ToInt32(a[2]), a[1]); + break; + + case "5": + AddMetadata(Convert.ToInt32(a[3]), a[1], a[2]); + break; + + case "6": + AddServer(Convert.ToInt32(a[2]), a[1]); + break; + + case "7": + AddMainPort(Convert.ToInt32(a[2]), a[1]); + break; + + case "8": + AddSecondPort(Convert.ToInt32(a[2]), a[1]); + break; + + //'Case "9" - не видел этих в файле + //'Case "10" + case "11": + case "12": + case "13": + //'в числе последних трех должны быть статус транзакции и важность + break; + } + } + } + + SaveReferenceValuesToDatabase(); + } + + + public void LoadReference() + { + //'Clear all reference dictionaries + UsersDictionary.Clear(); + ComputersDictionary.Clear(); + ApplicationsDictionary.Clear(); + EventsDictionary.Clear(); + MetadataDictionary.Clear(); + ServersDictionary.Clear(); + MainPortsDictionary.Clear(); + SecondPortsDictionary.Clear(); + + string fileName = Path.Combine(Catalog, "1Cv8.lgd"); + + if (File.Exists(fileName)) + { + try + { + SQLiteConnection connection = new SQLiteConnection("Data Source=" + fileName); + connection.Open(); + + SQLiteCommand command = new SQLiteCommand + { + Connection = connection, + CommandText = "SELECT [code], [name] FROM [AppCodes]" + }; + + SQLiteDataReader rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddApplication((long)rs[0], ((string)rs[1]).RemoveQuotes()); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [name] FROM [ComputerCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddComputer((long)rs[0], ((string)rs[1]).RemoveQuotes()); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [name] FROM [EventCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddEvent((long)rs[0], ((string)rs[1]).RemoveQuotes()); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [uuid], [name] FROM [UserCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddUser((long)rs[0], (string)rs[1], (string)rs[2]); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [name] FROM [WorkServerCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddServer((long)rs[0], ((string)rs[1]).RemoveQuotes()); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [uuid], [name] FROM [MetadataCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddMetadata((long)rs[0], (string)rs[1], (string)rs[2]); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [name] FROM [PrimaryPortCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddMainPort((long)rs[0], (string)rs[1]); + } + + rs.Close(); + + command.CommandText = "SELECT [code], [name] FROM [SecondaryPortCodes]"; + rs = command.ExecuteReader(); + + while (rs.Read()) + { + AddSecondPort((long)rs[0], (string)rs[1]); + } + + rs.Close(); + + command.Dispose(); + connection.Close(); + connection.Dispose(); + + SaveReferenceValuesToDatabase(); + } + catch (Exception ex) + { + Log.Error(ex, "Error occurred while working with reference tables"); + } + } + else + { + string lastProcessedObjectForDebug = string.Empty; + fileName = Path.Combine(Catalog, "1Cv8.lgf"); + + if (File.Exists(fileName)) + { + try + { + FileInfo FI = new FileInfo(fileName); + + if (FI.LastWriteTime >= LastReferenceUpdate) + { + LoadReferenceFromTheTextFile(fileName, ref lastProcessedObjectForDebug); + } + } + catch (Exception ex) + { + string AdditionalString = string.Empty; + + if (!string.IsNullOrEmpty(lastProcessedObjectForDebug)) + { + AdditionalString = $"Attempted to process this object: {lastProcessedObjectForDebug}"; + } + + Log.Error(ex, $"Error occurred while working with reference file. {AdditionalString}"); + } + } + } + } + + + public void FindAndStartParseFiles() + { + string v83File = Path.Combine(Catalog, "1Cv8.lgd"); + + if (File.Exists(v83File)) + { + LoadEvents83(v83File); + + SaveEventsToSQL(); + } + else + { + List ArrayFiles = new List(); + + if (Directory.Exists(Catalog)) + { + string[] files = Directory.GetFiles(Catalog); + + foreach (string file in files) + { + if (file.EndsWith(".lgp")) + { + ArrayFiles.Add(file); + } + } + + ArrayFiles.Sort(); + + foreach (string file in ArrayFiles) + { + if (file != null) + { + try + { + FileInfo fileInfo = new FileInfo(file); + + if (string.Compare(fileInfo.Name, CurrentFilename) >= 0) + { + if (!(fileInfo.Name == CurrentFilename)) + { + CurrentPosition = 2;// ' start position for log-file 1C + } + + CurrentFilename = fileInfo.Name; + + LoadEvents2(file); + } + else if (string.Compare(fileInfo.Name, CurrentFilename) < 0) + { + //File.Delete(file); + } + } + catch (Exception ex) + { + Log.Error(ex, "Error in FindAndStartParseFiles"); + } + } + } + + SaveEventsToSQL(); + } + } + } + + + public void LoadEvents83(string fileName) + { + try + { + SQLiteConnection connection = new SQLiteConnection($"Data Source={fileName}"); + connection.Open(); + + SQLiteCommand command = new SQLiteCommand + { + Connection = connection + }; + + while (true) + { + command.CommandText = @"SELECT + [rowID], + [severity], + [date], + [connectID], + [session], + [transactionStatus], + [transactionDate], + [transactionID], + [userCode], + [computerCode], + [appCode], + [eventCode], + [comment], + [metadataCodes], + [sessionDataSplitCode], + [dataType], + [data], + [dataPresentation], + [workServerCode], + [primaryPortCode], + [secondaryPortCode] + FROM[EventLog] + WHERE[rowID] > @LastEventNumber83 AND[date] >= @MinimumDate + ORDER BY 1 + LIMIT 10"; + + command.Parameters.AddWithValue("LastEventNumber83", LastEventNumber83); + + double noOfSeconds = (LoadEventsStartingAt - new DateTime()).TotalSeconds; + command.Parameters.AddWithValue("MinimumDate", noOfSeconds * 10000); + + SQLiteDataReader reader = command.ExecuteReader(); + + bool hasData = reader.HasRows; + + while (reader.Read()) + { + OneEventRecord eventRecord = new OneEventRecord(reader); + + EventsList.Add(eventRecord); + + this.LastEventNumber83 = eventRecord.RowID; + } + + reader.Close(); + + if (EventsList.Count > 0) + { + SaveEventsToSQL(); + } + + if (!hasData) + break; + } + + command.Dispose(); + connection.Close(); + connection.Dispose(); + } + catch (Exception ex) + { + Log.Error(ex, "Error while working with EventLog table (SQLite)"); + } + } + + + public void LoadEvents2(string FileName) + { + File.Copy(FileName, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"logCopy_{InfobaseGuid.ToString()}.log"), true); + + TextReader reader = File.OpenText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"logCopy_{InfobaseGuid.ToString()}.log")); + //string[] fileLines = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); + + string eventString = string.Empty; + + //пропуск уже загруженных строк + long lineNumber; + string newline = string.Empty; + for (lineNumber = 1; lineNumber <= this.CurrentPosition; lineNumber++) + { + newline = reader.ReadLine(); + } + + //загрузка новых строк + while (newline != null) + { + eventString += newline; + + if (newline == "}" || newline == "},") + { + try + { + this.CurrentPosition = lineNumber + 1; + + AddEvent(eventString); + } + catch (Exception ex) + { + Log.Error(ex, this.GetType().ToString()); + } + + eventString = string.Empty; + } + + newline = reader.ReadLine(); + lineNumber++; + } + + reader.Close(); + } + + + public void AddEvent(string eventString) + { + OneEventRecord eventRecord = new OneEventRecord(eventString); + + if (eventRecord.DateTime < LoadEventsStartingAt) + return; + + EventsList.Add(eventRecord); + + if (EventsList.Count >= 10) + { + SaveEventsToSQL(); + } + } + + + public void DoWork() + { + while (true) + { + Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)} Start new iteration... ({InfobaseName})"); + + try + { + LoadReference(); + + GetReadParametersFromFile(); + + FindAndStartParseFiles(); + } + catch (Exception ex) + { + Log.Error(ex, $"Error occurred during log file processing ({InfobaseName})"); + } + + Thread.Sleep(SleepTime); + } + } + } +} diff --git a/EventLogApp/EventLogService.Designer.cs b/EventLogApp/EventLogService.Designer.cs new file mode 100644 index 0000000..51c9457 --- /dev/null +++ b/EventLogApp/EventLogService.Designer.cs @@ -0,0 +1,37 @@ +namespace EventLogApp +{ + partial class EventLogService + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.ServiceName = "EventLogService"; + } + + #endregion + } +} diff --git a/EventLogApp/EventLogService.cs b/EventLogApp/EventLogService.cs new file mode 100644 index 0000000..6e18ae7 --- /dev/null +++ b/EventLogApp/EventLogService.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Linq; +using System.ServiceProcess; +using System.Text; +using System.Threading.Tasks; + +namespace EventLogApp +{ + partial class EventLogService : ServiceBase + { + public EventLogService() + { + InitializeComponent(); + } + + protected override void OnStart(string[] args) + { + EventLogLoaderService service = new EventLogLoaderService(); + + service.DoWork(); + } + + protected override void OnStop() + { + // TODO: Add code here to perform any tear-down necessary to stop your service. + } + } +} diff --git a/EventLogApp/EventLogServiceInstaller.Designer.cs b/EventLogApp/EventLogServiceInstaller.Designer.cs new file mode 100644 index 0000000..e297d64 --- /dev/null +++ b/EventLogApp/EventLogServiceInstaller.Designer.cs @@ -0,0 +1,36 @@ +namespace EventLogApp +{ + partial class EventLogServiceInstaller + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} \ No newline at end of file diff --git a/EventLogApp/EventLogServiceInstaller.cs b/EventLogApp/EventLogServiceInstaller.cs new file mode 100644 index 0000000..372dcda --- /dev/null +++ b/EventLogApp/EventLogServiceInstaller.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration.Install; +using System.Linq; +using System.ServiceProcess; +using System.Threading.Tasks; + +namespace EventLogApp +{ + [RunInstaller(true)] + public partial class EventLogServiceInstaller : System.Configuration.Install.Installer + { + ServiceInstaller serviceInstaller; + ServiceProcessInstaller processInstaller; + + + public EventLogServiceInstaller() + { + InitializeComponent(); + + serviceInstaller = new ServiceInstaller(); + processInstaller = new ServiceProcessInstaller(); + + processInstaller.Account = ServiceAccount.LocalSystem; + serviceInstaller.StartType = ServiceStartMode.Manual; + serviceInstaller.ServiceName = "EventLogService"; + Installers.Add(processInstaller); + Installers.Add(serviceInstaller); + } + } +} diff --git a/EventLogApp/InfobaseSetting.cs b/EventLogApp/InfobaseSetting.cs new file mode 100644 index 0000000..6fdb135 --- /dev/null +++ b/EventLogApp/InfobaseSetting.cs @@ -0,0 +1,12 @@ +namespace EventLogApp +{ + public class InfobaseSetting + { + public string ESServerName { get; set; } + public string DatabaseID { get; set; } + public string DatabaseName { get; set; } + public string DatabaseCatalog { get; set; } + public string StartDate { get; set; } + public bool Found { get; set; } + } +} diff --git a/EventLogApp/NLog.config b/EventLogApp/NLog.config new file mode 100644 index 0000000..7a0f3aa --- /dev/null +++ b/EventLogApp/NLog.config @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/EventLogApp/NLog.xsd b/EventLogApp/NLog.xsd new file mode 100644 index 0000000..193cb6b --- /dev/null +++ b/EventLogApp/NLog.xsd @@ -0,0 +1,3481 @@ + + + + + + + + + + + + + + + Watch config file for changes and reload automatically. + + + + + Print internal NLog messages to the console. Default value is: false + + + + + Print internal NLog messages to the console error output. Default value is: false + + + + + Write internal NLog messages to the specified file. + + + + + Log level threshold for internal log messages. Default value is: Info. + + + + + Global log level threshold for application log messages. Messages below this level won't be logged.. + + + + + Throw an exception when there is an internal error. Default value is: false. + + + + + Throw an exception when there is a configuration error. If not set, determined by throwExceptions. + + + + + Gets or sets a value indicating whether Variables should be kept on configuration reload. Default value is: false. + + + + + Write internal NLog messages to the System.Diagnostics.Trace. Default value is: false. + + + + + Write timestamps for internal NLog messages. Default value is: true. + + + + + Use InvariantCulture as default culture instead of CurrentCulture. Default value is: false. + + + + + Perform mesage template parsing and formatting of LogEvent messages (true = Always, false = Never, empty = Auto Detect). Default value is: empty. + + + + + + + + + + + + + + Make all targets within this section asynchronous (creates additional threads but the calling thread isn't blocked by any target writes). + + + + + + + + + + + + + + + + + Prefix for targets/layout renderers/filters/conditions loaded from this assembly. + + + + + Load NLog extensions from the specified file (*.dll) + + + + + Load NLog extensions from the specified assembly. Assembly name should be fully qualified. + + + + + + + + + + Name of the logger. May include '*' character which acts like a wildcard. Allowed forms are: *, Name, *Name, Name* and *Name* + + + + + Comma separated list of levels that this rule matches. + + + + + Minimum level that this rule matches. + + + + + Maximum level that this rule matches. + + + + + Level that this rule matches. + + + + + Comma separated list of target names. + + + + + Ignore further rules if this one matches. + + + + + Enable or disable logging rule. Disabled rules are ignored. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the file to be included. You could use * wildcard. The name is relative to the name of the current config file. + + + + + Ignore any errors in the include file. + + + + + + + Variable name. + + + + + Variable value. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Number of log events that should be processed in a batch by the lazy writer thread. + + + + + Whether to use the locking queue, instead of a lock-free concurrent queue The locking queue is less concurrent when many logger threads, but reduces memory allocation + + + + + Limit of full s to write before yielding into Performance is better when writing many small batches, than writing a single large batch + + + + + Action to be taken when the lazy writer thread request queue count exceeds the set limit. + + + + + Limit on the number of requests in the lazy writer thread request queue. + + + + + Time in milliseconds to sleep between batches. (1 or less means trigger on new activity) + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + Delay the flush until the LogEvent has been confirmed as written + + + + + Condition expression. Log events who meet this condition will cause a flush on the wrapped target. + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Number of log events to be buffered. + + + + + Timeout (in milliseconds) after which the contents of buffer will be flushed if there's no write in the specified period of time. Use -1 to disable timed flushes. + + + + + Action to take if the buffer overflows. + + + + + Indicates whether to use sliding timeout. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Encoding to be used. + + + + + Instance of that is used to format log messages. + + + + + End of line value if a newline is appended at the end of log message . + + + + + Maximum message size in bytes. + + + + + Indicates whether to append newline at the end of log message. + + + + + Network address. + + + + + Size of the connection cache (number of connections which are kept alive). + + + + + Indicates whether to keep connection open whenever possible. + + + + + Maximum current connections. 0 = no maximum. + + + + + Action that should be taken if the will be more connections than . + + + + + Action that should be taken if the message is larger than maxMessageSize. + + + + + Get or set the SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. + + + + + Maximum queue size. + + + + + The number of seconds a connection will remain idle before the first keep-alive probe is sent + + + + + NDLC item separator. + + + + + Indicates whether to include source info (file name and line number) in the information sent over the network. + + + + + Renderer for log4j:event logger-xml-attribute (Default ${logger}) + + + + + Indicates whether to include NLog-specific extensions to log4j schema. + + + + + Indicates whether to include contents of the stack. + + + + + Indicates whether to include stack contents. + + + + + Indicates whether to include dictionary contents. + + + + + Indicates whether to include dictionary contents. + + + + + Indicates whether to include call site (class and method name) in the information sent over the network. + + + + + Option to include all properties from the log events + + + + + AppInfo field. By default it's the friendly name of the current AppDomain. + + + + + NDC item separator. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Layout that should be use to calcuate the value for the parameter. + + + + + Viewer parameter name. + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Text to be rendered. + + + + + Header. + + + + + Footer. + + + + + Indicates whether to auto-check if the console is available. - Disables console writing if Environment.UserInteractive = False (Windows Service) - Disables console writing if Console Standard Input is not available (Non-Console-App) + + + + + Enables output using ANSI Color Codes + + + + + The encoding for writing messages to the . + + + + + Indicates whether the error stream (stderr) should be used instead of the output stream (stdout). + + + + + Indicates whether to use default row highlighting rules. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Condition that must be met in order to set the specified foreground and background color. + + + + + Background color. + + + + + Foreground color. + + + + + + + + + + + + + + + + Compile the ? This can improve the performance, but at the costs of more memory usage. If false, the Regex Cache is used. + + + + + Indicates whether to ignore case when comparing texts. + + + + + Regular expression to be matched. You must specify either text or regex. + + + + + Text to be matched. You must specify either text or regex. + + + + + Indicates whether to match whole words only. + + + + + Background color. + + + + + Foreground color. + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Text to be rendered. + + + + + Header. + + + + + Footer. + + + + + Indicates whether to auto-check if the console is available - Disables console writing if Environment.UserInteractive = False (Windows Service) - Disables console writing if Console Standard Input is not available (Non-Console-App) + + + + + The encoding for writing messages to the . + + + + + Indicates whether to send the log messages to the standard error instead of the standard output. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Obsolete - value will be ignored! The logging code always runs outside of transaction. Gets or sets a value indicating whether to use database transactions. Some data providers require this. + + + + + Database user name. If the ConnectionString is not provided this value will be used to construct the "User ID=" part of the connection string. + + + + + Name of the database provider. + + + + + Database password. If the ConnectionString is not provided this value will be used to construct the "Password=" part of the connection string. + + + + + Indicates whether to keep the database connection open between the log events. + + + + + Database name. If the ConnectionString is not provided this value will be used to construct the "Database=" part of the connection string. + + + + + Name of the connection string (as specified in <connectionStrings> configuration section. + + + + + Connection string. When provided, it overrides the values specified in DBHost, DBUserName, DBPassword, DBDatabase. + + + + + Database host name. If the ConnectionString is not provided this value will be used to construct the "Server=" part of the connection string. + + + + + Connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + Text of the SQL command to be run on each log level. + + + + + Type of the SQL command to be run on each log level. + + + + + + + + + + + + + + + + + + + + + + + Type of the command. + + + + + Connection string to run the command against. If not provided, connection string from the target is used. + + + + + Indicates whether to ignore failures. + + + + + Command text. + + + + + + + + + + + + + + + + + + Database parameter name. + + + + + Layout that should be use to calcuate the value for the parameter. + + + + + Database parameter DbType. + + + + + Database parameter size. + + + + + Database parameter precision. + + + + + Database parameter scale. + + + + + Type of the parameter. + + + + + Convert format of the database parameter value . + + + + + Culture used for parsing parameter string-value for type-conversion + + + + + + + + + + + + + + + + Name of the target. + + + + + Text to be rendered. + + + + + Header. + + + + + Footer. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Layout that renders event Category. + + + + + Optional entrytype. When not set, or when not convertible to then determined by + + + + + Layout that renders event ID. + + + + + Name of the Event Log to write to. This can be System, Application or any user-defined name. + + + + + Name of the machine on which Event Log service is running. + + + + + Maximum Event log size in kilobytes. + + + + + Message length limit to write to the Event Log. + + + + + Value to be used as the event Source. + + + + + Action to take if the message is larger than the option. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Indicates whether to return to the first target after any successful write. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Text to be rendered. + + + + + Header. + + + + + Footer. + + + + + File encoding. + + + + + Line ending mode. + + + + + Indicates whether to compress archive files into the zip archive format. + + + + + Way file archives are numbered. + + + + + Name of the file to be used for an archive. + + + + + Is the an absolute or relative path? + + + + + Indicates whether to automatically archive log files every time the specified time passes. + + + + + Size in bytes above which log files will be automatically archived. Warning: combining this with isn't supported. We cannot create multiple archive files, if they should have the same name. Choose: + + + + + Maximum number of archive files that should be kept. + + + + + Indicates whether the footer should be written only when the file is archived. + + + + + Maximum number of log filenames that should be stored as existing. + + + + + Is the an absolute or relative path? + + + + + Gets or set a value indicating whether a managed file stream is forced, instead of using the native implementation. + + + + + Value indicationg whether file creation calls should be synchronized by a system global mutex. + + + + + Indicates whether to replace file contents on each write instead of appending log message at the end. + + + + + Indicates whether to write BOM (byte order mark) in created files + + + + + Indicates whether to enable log file(s) to be deleted. + + + + + Name of the file to write to. + + + + + Value specifying the date format to use when archiving files. + + + + + Indicates whether to archive old log file on startup. + + + + + Cleanup invalid values in a filename, e.g. slashes in a filename. If set to true, this can impact the performance of massive writes. If set to false, nothing gets written when the filename is wrong. + + + + + Indicates whether to create directories if they do not exist. + + + + + Indicates whether to delete old log file on startup. + + + + + File attributes (Windows only). + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + Indicates whether concurrent writes to the log file by multiple processes on different network hosts. + + + + + Maximum number of seconds that files are kept open. If this number is negative the files are not automatically closed after a period of inactivity. + + + + + Number of files to be kept open. Setting this to a higher value may improve performance in a situation where a single File target is writing to many files (such as splitting by level or by logger). + + + + + Indicates whether to keep log file open instead of opening and closing it on each logging event. + + + + + Whether or not this target should just discard all data that its asked to write. Mostly used for when testing NLog Stack except final write + + + + + Indicates whether concurrent writes to the log file by multiple processes on the same host. + + + + + Number of times the write is appended on the file before NLog discards the log message. + + + + + Delay in milliseconds to wait before attempting to write to the file again. + + + + + Log file buffer size in bytes. + + + + + Maximum number of seconds before open files are flushed. If this number is negative or zero the files are not flushed by timer. + + + + + Indicates whether to automatically flush the file buffers after each log message. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Condition expression. Log events who meet this condition will be forwarded to the wrapped target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Windows domain name to change context to. + + + + + Required impersonation level. + + + + + Type of the logon provider. + + + + + Logon Type. + + + + + User account password. + + + + + Indicates whether to revert to the credentials of the process instead of impersonating another user. + + + + + Username to change context to. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Interval in which messages will be written up to the number of messages. + + + + + Maximum allowed number of messages written per . + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Endpoint address. + + + + + Name of the endpoint configuration in WCF configuration file. + + + + + Indicates whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply) + + + + + Client ID. + + + + + Indicates whether to include per-event properties in the payload sent to the server. + + + + + Indicates whether to use binary message encoding. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + Layout that should be use to calculate the value for the parameter. + + + + + Name of the parameter. + + + + + Type of the parameter. + + + + + Type of the parameter. Obsolete alias for + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Text to be rendered. + + + + + Header. + + + + + Footer. + + + + + Indicates whether NewLine characters in the body should be replaced with tags. + + + + + Priority used for sending mails. + + + + + Encoding to be used for sending e-mail. + + + + + BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). + + + + + CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). + + + + + Indicates whether to add new lines between log entries. + + + + + Indicates whether to send message as HTML instead of plain text. + + + + + Sender's email address (e.g. joe@domain.com). + + + + + Mail message body (repeated for each log message send in one mail). + + + + + Mail subject. + + + + + Recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + Indicates the SMTP client timeout. + + + + + SMTP Server to be used for sending. + + + + + SMTP Authentication mode. + + + + + Username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). + + + + + Password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). + + + + + Indicates whether SSL (secure sockets layer) should be used when communicating with SMTP server. + + + + + Port number that SMTP Server is listening on. + + + + + Indicates whether the default Settings from System.Net.MailSettings should be used. + + + + + Folder where applications save mail messages to be processed by the local SMTP server. + + + + + Specifies how outgoing email messages will be handled. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Max number of items to have in memory + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Class name. + + + + + Method name. The method must be public and static. Use the AssemblyQualifiedName , https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx e.g. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Encoding to be used. + + + + + End of line value if a newline is appended at the end of log message . + + + + + Maximum message size in bytes. + + + + + Indicates whether to append newline at the end of log message. + + + + + Network address. + + + + + Size of the connection cache (number of connections which are kept alive). + + + + + Indicates whether to keep connection open whenever possible. + + + + + Maximum current connections. 0 = no maximum. + + + + + Maximum queue size. + + + + + Action that should be taken if the will be more connections than . + + + + + Action that should be taken if the message is larger than maxMessageSize. + + + + + Get or set the SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. + + + + + The number of seconds a connection will remain idle before the first keep-alive probe is sent + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Encoding to be used. + + + + + Instance of that is used to format log messages. + + + + + End of line value if a newline is appended at the end of log message . + + + + + Maximum message size in bytes. + + + + + Indicates whether to append newline at the end of log message. + + + + + Network address. + + + + + Size of the connection cache (number of connections which are kept alive). + + + + + Indicates whether to keep connection open whenever possible. + + + + + Maximum current connections. 0 = no maximum. + + + + + Action that should be taken if the will be more connections than . + + + + + Action that should be taken if the message is larger than maxMessageSize. + + + + + Get or set the SSL/TLS protocols. Default no SSL/TLS is used. Currently only implemented for TCP. + + + + + Maximum queue size. + + + + + The number of seconds a connection will remain idle before the first keep-alive probe is sent + + + + + NDLC item separator. + + + + + Indicates whether to include source info (file name and line number) in the information sent over the network. + + + + + Renderer for log4j:event logger-xml-attribute (Default ${logger}) + + + + + Indicates whether to include NLog-specific extensions to log4j schema. + + + + + Indicates whether to include contents of the stack. + + + + + Indicates whether to include stack contents. + + + + + Indicates whether to include dictionary contents. + + + + + Indicates whether to include dictionary contents. + + + + + Indicates whether to include call site (class and method name) in the information sent over the network. + + + + + Option to include all properties from the log events + + + + + AppInfo field. By default it's the friendly name of the current AppDomain. + + + + + NDC item separator. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Indicates whether to perform layout calculation. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Indicates whether performance counter should be automatically created. + + + + + Name of the performance counter category. + + + + + Counter help text. + + + + + Name of the performance counter. + + + + + Performance counter type. + + + + + The value by which to increment the counter. + + + + + Performance counter instance name. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Default filter to be applied when no specific rule matches. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + Condition to be tested. + + + + + Resulting filter to be applied when the condition matches. + + + + + + + + + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + Number of times to repeat each log message. + + + + + + + + + + + + + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + Number of retries that should be attempted on the wrapped target in case of a failure. + + + + + Time to wait between retries in milliseconds. + + + + + + + + + + + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + Name of the target. + + + + + Layout used to format log messages. + + + + + Always use independent of + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Name of the target. + + + + + Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit + + + + + Should we include the BOM (Byte-order-mark) for UTF? Influences the property. This will only work for UTF-8. + + + + + Web service method name. Only used with Soap. + + + + + Web service namespace. Only used with Soap. + + + + + Protocol to be used when calling web service. + + + + + Custom proxy address, include port separated by a colon + + + + + Encoding. + + + + + Web service URL. + + + + + Value whether escaping be done according to the old NLog style (Very non-standard) + + + + + Value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs) + + + + + Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in parameters) + + + + + Name of the root XML element, if POST of XML document chosen. If so, this property must not be null. (see and ). + + + + + (optional) root namespace of the XML document, if POST of XML document chosen. (see and ). + + + + + Proxy configuration when calling web service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Footer layout. + + + + + Header layout. + + + + + Body layout (can be repeated multiple times). + + + + + Custom column delimiter value (valid when ColumnDelimiter is set to 'Custom'). + + + + + Column delimiter. + + + + + Quote Character. + + + + + Quoting mode. + + + + + Indicates whether CVS should include header. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Layout of the column. + + + + + Name of the column. + + + + + Override of Quoting mode + + + + + + + + + + + + + + + + + + + + List of property names to exclude when is true + + + + + Option to include all properties from the log event (as JSON) + + + + + Indicates whether to include contents of the dictionary. + + + + + Indicates whether to include contents of the dictionary. + + + + + Indicates whether to include contents of the dictionary. + + + + + How far should the JSON serializer follow object references before backing off + + + + + Option to render the empty object value {} + + + + + Option to suppress the extra spaces in the output json + + + + + + + + + + + + + + + + Layout that will be rendered as the attribute's value. + + + + + Name of the attribute. + + + + + Determines wether or not this attribute will be Json encoded. + + + + + Indicates whether to escape non-ascii characters + + + + + Whether an attribute with empty value should be included in the output + + + + + + + + + + + + + + Footer layout. + + + + + Header layout. + + + + + Body layout (can be repeated multiple times). + + + + + + + + + + + + + + + + + + Option to include all properties from the log events + + + + + Indicates whether to include contents of the dictionary. + + + + + Indicates whether to include contents of the dictionary. + + + + + Indicates whether to include contents of the stack. + + + + + Indicates whether to include contents of the stack. + + + + + + + + + + + + + + Layout text. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + List of property names to exclude when is true + + + + + Option to include all properties from the log event (as XML) + + + + + Indicates whether to include contents of the dictionary. + + + + + Indicates whether to include contents of the dictionary. + + + + + How far should the XML serializer follow object references before backing off + + + + + XML element name to use for rendering IList-collections items + + + + + XML attribute name to use when rendering property-key When null (or empty) then key-attribute is not included + + + + + XML element name to use when rendering properties + + + + + XML attribute name to use when rendering property-value When null (or empty) then value-attribute is not included and value is formatted as XML-element-value + + + + + Name of the root XML element + + + + + Value inside the root XML element + + + + + Whether a ElementValue with empty value should be included in the output + + + + + Auto indent and create new lines + + + + + Determines wether or not this attribute will be Xml encoded. + + + + + + + + + + + + + + + Layout that will be rendered as the attribute's value. + + + + + Name of the attribute. + + + + + Determines wether or not this attribute will be Xml encoded. + + + + + Whether an attribute with empty value should be included in the output + + + + + + + + + + + + + + + + + + + + + + + + + Determines wether or not this attribute will be Xml encoded. + + + + + Name of the element + + + + + Value inside the element + + + + + Whether a ElementValue with empty value should be included in the output + + + + + Auto indent and create new lines + + + + + List of property names to exclude when is true + + + + + Option to include all properties from the log event (as XML) + + + + + Indicates whether to include contents of the dictionary. + + + + + Indicates whether to include contents of the dictionary. + + + + + How far should the XML serializer follow object references before backing off + + + + + XML element name to use for rendering IList-collections items + + + + + XML attribute name to use when rendering property-key When null (or empty) then key-attribute is not included + + + + + XML element name to use when rendering properties + + + + + XML attribute name to use when rendering property-value When null (or empty) then value-attribute is not included and value is formatted as XML-element-value + + + + + + + + + + + + + Action to be taken when filter matches. + + + + + Condition expression. + + + + + + + + + + + + + + + + + + + + + + + + + + Action to be taken when filter matches. + + + + + Indicates whether to ignore case when comparing strings. + + + + + Layout to be used to filter log messages. + + + + + Substring to be matched. + + + + + + + + + + + + + + + + + Action to be taken when filter matches. + + + + + String to compare the layout to. + + + + + Indicates whether to ignore case when comparing strings. + + + + + Layout to be used to filter log messages. + + + + + + + + + + + + + + + + + Action to be taken when filter matches. + + + + + Indicates whether to ignore case when comparing strings. + + + + + Layout to be used to filter log messages. + + + + + Substring to be matched. + + + + + + + + + + + + + + + + + Action to be taken when filter matches. + + + + + String to compare the layout to. + + + + + Indicates whether to ignore case when comparing strings. + + + + + Layout to be used to filter log messages. + + + + + + + + + + + + + + + + + + + + + + + + Action to be taken when filter matches. + + + + + Default number of unique filter values to expect, will automatically increase if needed + + + + + Applies the configured action to the initial logevent that starts the timeout period. Used to configure that it should ignore all events until timeout. + + + + + Layout to be used to filter log messages. + + + + + Max number of unique filter values to expect simultaneously + + + + + Max length of filter values, will truncate if above limit + + + + + How long before a filter expires, and logging is accepted again + + + + + Default buffer size for the internal buffers + + + + + Reuse internal buffers, and doesn't have to constantly allocate new buffers + + + + + Append FilterCount to the when an event is no longer filtered + + + + + Insert FilterCount value into when an event is no longer filtered + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/EventLogApp/ParserServices.cs b/EventLogApp/ParserServices.cs new file mode 100644 index 0000000..6ce1568 --- /dev/null +++ b/EventLogApp/ParserServices.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; + +namespace EventLogApp +{ + class ParserServices + { + public static List ParseEventLogString(string Text) + { + List ArrayLines = new List(); + + var Text2 = Text.Substring(1, Text.EndsWith(",") ? Text.Length - 3 : Text.Length - 2) + ","; + + var Delim = Text2.IndexOf(","); + + string str = ""; + + while (Delim > 0) + { + str = str + Text2.Substring(0, Delim).Trim(); + Text2 = Text2.Substring(Delim + 1); + + if (CountSubstringInString(str, "{") == CountSubstringInString(str, "}") && Math.IEEERemainder(CountSubstringInString(str, "\""), 2) == 0) + { + if (str.StartsWith("\"") && str.EndsWith("\"")) + { + str = str.Substring(1, str.Length - 2); + } + + ArrayLines.Add(str); + + str = ""; + } + else + { + str = str + ","; + } + + Delim = Text2.IndexOf(","); + } + + return ArrayLines; + } + + + public static int CountSubstringInString(string Str, string SubStr) + { + return (Str.Length - Str.Replace(SubStr, "").Length) / SubStr.Length; + } + } +} \ No newline at end of file diff --git a/EventLogApp/Program.cs b/EventLogApp/Program.cs new file mode 100644 index 0000000..b128cde --- /dev/null +++ b/EventLogApp/Program.cs @@ -0,0 +1,26 @@ +using System.ServiceProcess; + +namespace EventLogApp +{ + class Program + { + static void Main(string[] args) + { + EventLogLoaderService service = new EventLogLoaderService(); + + service.DoWork(); + + //------------------------------------------------------ + + //ServiceBase[] ServicesToRun; + + //ServicesToRun = new ServiceBase[] + //{ + // new EventLogService() + //}; + + //ServiceBase.Run(ServicesToRun); + } + + } +} diff --git a/EventLogApp/Properties/AssemblyInfo.cs b/EventLogApp/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bf8df5c --- /dev/null +++ b/EventLogApp/Properties/AssemblyInfo.cs @@ -0,0 +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("EventLogApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("EventLogApp")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[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("036f352b-e448-47e0-bb91-f98d4896c6ca")] + +// 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.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/EventLogApp/ReadParameters.cs b/EventLogApp/ReadParameters.cs new file mode 100644 index 0000000..7dadeca --- /dev/null +++ b/EventLogApp/ReadParameters.cs @@ -0,0 +1,10 @@ +namespace EventLogApp +{ + internal class ReadParameters + { + public int InfobaseId { get; set; } + public long CurrentPosition { get; set; } + public string CurrentFilename { get; set; } + public long LastEventNumber83 { get; set; } + } +} diff --git a/EventLogApp/config.json b/EventLogApp/config.json new file mode 100644 index 0000000..28ae626 --- /dev/null +++ b/EventLogApp/config.json @@ -0,0 +1,39 @@ +{ + "ConnectionString": "Data Source=MSSQLSERVER;Server=srv-1cdata;Database=log1c;Password=1ccthdth;User ID=sa;", + "DBType": "MS SQL Server", + "RepeatTime": 60, + "ESIndexName": "event-log", + "ESUseSynonymsForFieldsNames": false, + "ESFieldSynonyms": { + "ServerName": "Сервер1С", + "DatabaseName": "ИнформационнаяБаза", + "RowID": "НомерСтроки", + "Severity": "УровеньСобытия", + "DateTime": "ДатаВремя", + "ConnectID": "НомерСоединения", + "DataType": "ТипДанных", + "SessionNumber": "НомерСессии", + "DataStructure": "СтруктураДанных", + "DataString": "ПредставлениеДанных", + "Comment": "Комментарий", + "SessionDataSplitCode": "Разделитель", + "EventType": "ТипСобытия", + "Metadata": "Метаданные", + "Computer": "Компьютер", + "PrimaryPort": "ОсновнойПорт", + "Server": "СерверПриложений", + "SecondaryPort": "ВторичныйПорт", + "Application": "Приложение", + "UserName": "ИмяПользователя" + }, + "Infobases": [ + { + "ESServerName": "", + "DatabaseID": "221faa36-9bda-4aa5-a5d6-a425e10d2955", + "DatabaseName": "un_acc30", + "DatabaseCatalog": "e:\\dev\\\1cLog\\1Cv8Log\\", + "StartDate": "", + "Found": false + } + ] +} \ No newline at end of file diff --git a/EventLogApp/packages.config b/EventLogApp/packages.config new file mode 100644 index 0000000..ca419b6 --- /dev/null +++ b/EventLogApp/packages.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/EventLogLoader.sln b/EventLogLoader.sln index 3ec81eb..f4eca25 100644 --- a/EventLogLoader.sln +++ b/EventLogLoader.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.852 MinimumVisualStudioVersion = 10.0.40219.1 Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "EventLogLoaderDebug", "EventLogLoader\EventLogLoaderDebug.vbproj", "{2CE569B2-834D-4FE6-A23F-ACC68E8BDA9E}" EndProject @@ -9,6 +9,8 @@ Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "EventLogLoaderManager", "Ev EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "EventLogLoaderService", "EventLogLoaderService\EventLogLoaderService.vbproj", "{F7EF5930-B310-4697-B522-2325EAF247F2}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventLogApp", "EventLogApp\EventLogApp.csproj", "{036F352B-E448-47E0-BB91-F98D4896C6CA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -49,8 +51,23 @@ Global {F7EF5930-B310-4697-B522-2325EAF247F2}.Release|Mixed Platforms.Build.0 = Release|x86 {F7EF5930-B310-4697-B522-2325EAF247F2}.Release|x86.ActiveCfg = Release|x86 {F7EF5930-B310-4697-B522-2325EAF247F2}.Release|x86.Build.0 = Release|x86 + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Debug|x86.ActiveCfg = Debug|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Debug|x86.Build.0 = Debug|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Release|Any CPU.Build.0 = Release|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Release|x86.ActiveCfg = Release|Any CPU + {036F352B-E448-47E0-BB91-F98D4896C6CA}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5078F9AA-9CF7-46CF-BF5C-57C79E90A04A} + EndGlobalSection EndGlobal