Exemple #1
0
 private void ReadData()
 {
     try
     {
         importedData = Directory.GetFiles(importPath, fileName).Select(GetDataTableFromCsvFile).ToList();
         if (!importedData.Any())
         {
             loggerWrapper.Log(LogLevel.Fatal, null, "Data not found to be imported!");
         }
     }
     catch (DirectoryNotFoundException exception)
     {
         loggerWrapper.Log(LogLevel.Fatal, exception, "Directory not found!");
     }
 }
Exemple #2
0
 /// <summary>
 /// Creates a unique group of key events identified by a key
 /// Key consists of : EmployeeId, EventType, MachineId
 /// </summary>
 /// <returns>Dictionary of unique key events</returns>
 public IDictionary <string, KeyEvent> GetKeyEventGrp()
 {
     try
     {
         if (this.KeyEvents == null || this.KeyEvents.Count() == 0)
         {
             return(null);
         }
         Dictionary <string, KeyEvent> keyevntsGrpDict = new Dictionary <string, KeyEvent>();
         foreach (var item in this.KeyEvents)
         {
             if (!keyevntsGrpDict.ContainsKey(item.Key))
             {
                 LogWrapper.Log($"Found new key to add to Group dictionary. Key is {item.Key}. Key event is {item.ToString()}", $"Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Verbose);
                 keyevntsGrpDict.Add(item.Key, new KeyEvent(item.KeyEventId, item.MachineId, item.StockNumber, item.EmployeeId, item.EventType, item.TimeStamp));
             }
             else
             {
                 LogWrapper.Log($"Key {item.Key} already exists in Group dictionary. Key event is {item.ToString()} not getting added", $"Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Verbose);
             }
         }
         return(keyevntsGrpDict);
     }
     catch (Exception ex)
     {
         LogWrapper.Log($"Error in creating key event group. Error message is {ex.Message}", $"Thread id is : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Error);
         return(null);
     }
 }
        public virtual void ExecuteReader()
        {
            SetUpProviderAndConnection();

            using (DBConnection)
            {
                DBCommand             = DBConnection.CreateCommand();
                DBCommand.CommandText = QueryString != null?QueryString:"Select * from State";
                DBCommand.CommandType = CommandType.Text;

                try
                {
                    //Open Connection
                    DBConnection.Open();
                    //Execute Reader
                    DBDataReader = DBCommand.ExecuteReader();

                    //SE: update this with something usable
                    var retList = new List <string>();

                    while (DBDataReader.Read())
                    {
                        retList.Add(DBDataReader[0].ToString());
                    }
                }
                catch (Exception ex)
                {
                    LogWrapper.Log(ex.Message);
                }
            }
        }
Exemple #4
0
        private void ReadApplicationConfig()
        {
            var appConfig = Utils.ReadJsonFromResources <ApplicationConfig>(Constants.PATH_APP_CONFIG);

            AddReadonly(Constants.DB_KEY_APP_CONFIG, appConfig, false);
            LogWrapper.Log("[{0}] loaded app config succesfully and added to the database with key: {1}", GetType(), Constants.DB_KEY_APP_CONFIG);
        }
 private IEnumerable <IntegrationLog> CreateIntegrationLog(KeyEventWrapper originalKeyEvents, KeyEventResponse response)
 {
     try
     {
         IList <IntegrationLog> logs = new List <IntegrationLog>();
         foreach (var item in originalKeyEvents.KeyEvents)
         {
             try
             {
                 IntegrationLog _log = new IntegrationLog();
                 _log.DateTimeSent            = response.RequestSentDateTime;
                 _log.IsSuccessFlg            = response.IsSuccessful;
                 _log.KeyEventId              = item.KeyEventId;
                 _log.RequestJsonDatainString = response.RequestJsonString;
                 _log.ResponseDescription     = response.ResponseMessage;
                 _log.ResponseReceivedinSecs  = response.ResponseTimeinSecs;
                 logs.Add(_log);
             }
             catch (Exception ex)
             {
                 LogWrapper.Log($"Error in generating Integration log for KeyeventId {item.KeyEventId}. Error is {ex.Message}. Skipping to next one", $"Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Error);
             }
         }
         return(logs as IEnumerable <IntegrationLog>);
     }
     catch (Exception ex)
     {
         LogWrapper.Log($"Error in generating Integration log. Error is {ex.Message}", $"Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Error);
         return(null);
     }
 }
Exemple #6
0
        public Dictionary <Int64, List <T> > LoadRequests()
        {
            string[] jsonKvp = _Repository.LoadLines();
            Dictionary <Int64, List <T> > ret = new Dictionary <long, List <T> >();

            try
            {
                foreach (string s in jsonKvp)
                {
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        continue;
                    }

                    T        request         = JsonConvert.DeserializeObject <T>(s);
                    List <T> listUserRequest = null;

                    if (!ret.TryGetValue(request._UserId, out listUserRequest))
                    {
                        listUserRequest      = new List <T>();
                        ret[request._UserId] = listUserRequest;
                    }
                    listUserRequest.Add(request);
                }
            }
            catch (Exception ex)
            {
                LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при десериализации заявок. {1}", ex.Message, ex.StackTrace));
                throw;
            }
            return(ret);
        }
Exemple #7
0
        //Saving memory stream to a new file with the given path
        private bool WriteFile(MemoryStream inputStream)
        {
            Directory.CreateDirectory(exportLocation);

            var exportPath = exportLocation + "\\" + fileType + "-" + DateTime.Now.ToShortDateString() + ".avro";

            if (!File.Exists(exportPath))
            {
                try
                {
                    using (var fs = File.Create(exportPath))
                    {
                        inputStream.Seek(0, SeekOrigin.Begin);
                        inputStream.CopyTo(fs);
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    logger.Log(LogLevel.Error, e,
                               $"The following exception was thrown during creation and writing to the file{exportLocation}");
                    return(false);
                }
            }

            return(true);
        }
 public DataExtractService()
 {
     LogWrapper.Log("Data Extract Service constructor started", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
     InitializeComponent();
     StartTimer();
     LogWrapper.Log("Data Extract Service constructor completed", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
 }
 public DataExtractServiceProcessor()
 {
     LogWrapper.Log("Enter DataExtractServiceProcess .ctor", $"Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
     _dal          = new DataAccessImpl();
     _serviceProxy = new ExternalServiceAgent();
     LogWrapper.Log("Exit DataExtractServiceProcess .ctor", $"Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
 }
Exemple #10
0
 public bool Register(Int64 aUserId)
 {
     if (_AccountValidator == null)
     {
         LogWrapper.Log(MessageType.MESSAGE_ERROR, "Ошибка регистрации : Валидатор аккаунтов не задан");
         throw new SecurityTokenException();
     }
     return(_AccountValidator.RegisterAccount(aUserId));
 }
Exemple #11
0
 public bool Create(Int64 UserId, RequestType requestType, object requestParams)
 {
     if (_RequestCreater == null)
     {
         LogWrapper.Log(MessageType.MESSAGE_ERROR, "Ошибка создания : Метод создания заявок не задан");
         return(false);
     }
     return(_RequestCreater.Create(UserId, requestType, requestParams));
 }
Exemple #12
0
 public UserRequestCollection GetRequests(Int64 UserId)
 {
     if (_RequestProvider == null)
     {
         LogWrapper.Log(MessageType.MESSAGE_ERROR, "Ошибка : Стратегии предоставления данных не заданы");
         return(new UserRequestCollection());
     }
     return(_RequestProvider.GetRequests(UserId));
 }
        protected void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;

            if ((ex != null))
            {
                LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при запуске сервиса {1}", ex.Message, ex.StackTrace));
                throw ex;
            }
        }
Exemple #14
0
        public void Initialize()
        {
            ReadAppVersion();
            ReadVersionLog();

            if (!HasVersion(APP_VERSION))
            {
                AddVersion(APP_VERSION);
                TryMigrateData();
                Utils.WriteBinary(appVersions, versionsPath);
            }

            LogWrapper.Log(this.ToString());
        }
Exemple #15
0
        public static void UninstallService(string filename = null)
        {
            Console.WriteLine("Uninstalling service...");
            string[] commandLine = new string[0];
            //commandLine[0] = "/u";
            IDictionary savedState = new Hashtable();

            AssemblyInstaller installer = new AssemblyInstaller(GetServiceFileName(), commandLine);

            installer.Uninstall(savedState);
            //installer.Commit(savedState);
            Console.WriteLine("Complete.");
            LogWrapper.Log(MessageType.MESSAGE_DEBUG, "Деинсталляция прошла успешно");
        }
Exemple #16
0
        public static void InstallService(string filename = null)
        {
            Console.WriteLine("Installing service...");
            string[] commandLine = commandLine = new string[1];
            commandLine[0] = "/servicename=" + GetServiceName(filename);
            IDictionary savedState = new Hashtable();

            AssemblyInstaller installer = new AssemblyInstaller(GetServiceFileName(), commandLine);

            installer.Install(savedState);
            installer.Commit(savedState);
            Console.WriteLine("Complete.");
            LogWrapper.Log(MessageType.MESSAGE_DEBUG, "Инсталляция завершена успешно)");
        }
 private void StartTimer()
 {
     try
     {
         int serviceInterval = 5000;
         int.TryParse(ConfigurationManager.AppSettings["ServiceRunInterval"], out serviceInterval);
         LogWrapper.Log($"Setting the timer interval at : {serviceInterval/1000/60} minutes.", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
         _timer          = new System.Timers.Timer(serviceInterval);
         _timer.Elapsed += new ElapsedEventHandler(TimerElapsedHandler);
     }
     catch (Exception ex)
     {
         LogWrapper.Log($"Error occurred in Start Timer method. Error message : {ex.Message}", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
     }
 }
Exemple #18
0
        private void ReadAssetManifest()
        {
            var appConfig     = dataBase.Get <ApplicationConfig>(Constants.DB_KEY_APP_CONFIG);
            var assetManifest = Utils.ReadJsonFromResources <AssetManifest>(appConfig.assetManifestPath);

            foreach (var asset in assetManifest.root)
            {
                dataBase.AddReadonly(asset.id, asset.path, false);

                #if LOG_ASSET_MANIFET
                LogWrapper.DebugLog("[{0}] add asset to the database with key: {1}, path: {2}", GetType(), asset.id, asset.path);
                #endif
            }

            LogWrapper.Log("[{0}] assets loaded successfully and all paths added to the database", GetType());
        }
        public async Task <KeyEventWrapper> GetKeyEventsToProcessAsync()
        {
            try
            {
                LogWrapper.Log($"Calling Repository to fetch key events to call the service", $" Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
                var recordsDbSet = await _repo.GetAsync("GetKeyEvents", null) as DataSet;

                var keyevents = MapDataSetToKeyEventWrapper(recordsDbSet) as KeyEventWrapper;
                return(keyevents);
            }
            catch (Exception ex)
            {
                LogWrapper.Log($"Error in retrieving key events from repository. Error message is {ex.Message}", $" Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Error);
                return(null);
            }
        }
Exemple #20
0
        private void TryMigrateData()
        {
            if (appVersions.Count > 0)
            {
                var fromVersion = appVersions[appVersions.Count - 1].version;
                var toVersion   = APP_VERSION;

                foreach (var block in migratorBlocks)
                {
                    if (block.CanExecute(fromVersion, toVersion))
                    {
                        block.Execute();
                        LogWrapper.Log("[{0}] executed migrator block for {1}", GetType(), block.version);
                    }
                }
            }
        }
Exemple #21
0
 // http://stackoverflow.com/questions/23522258/writing-to-file-in-a-thread-safe-manner
 private void DoSave()
 {
     foreach (var Str in this._Conveyer.GetConsumingEnumerable())
     {
         try
         {
             lock (_Locker)
             {
                 File.AppendAllLines(_Storage, new string[] { Str }, Encoding.UTF8);
             }
         }
         catch (Exception ex)
         {
             LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при сохранении экземпляра данных. {1}", ex.Message, ex.StackTrace));
             throw;
         }
     }
 }
Exemple #22
0
        public override string[] LoadLines()
        {
            string[] arrStr = null;

            try
            {
                lock (_Locker)
                {
                    arrStr = File.ReadAllLines(_Storage);
                }
            }
            catch (Exception ex)
            {
                LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при загрузке коллекции данных. {1}", ex.Message, ex.StackTrace));
                throw;
            }
            return(arrStr);
        }
 public bool SaveRequest(BaseRequest aUserRequest)
 {
     if (_Repository == null)
     {
         return(false);
     }
     try
     {
         string line = JsonConvert.SerializeObject(aUserRequest);
         _Repository.SaveLine(line);
     }
     catch (Exception ex)
     {
         LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Ошибка {0} при сохранении заявки {1}", ex.Message, ex.StackTrace));
         throw;
     }
     return(true);
 }
 private void TimerElapsedHandler(object sender, ElapsedEventArgs eventArguments)
 {
     _timer.Enabled = false;
     try
     {
         LogWrapper.Log($"Timer Elapsed event triggered. Running data extract processor at : {eventArguments.SignalTime} ", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
         IDataExtractProcessor backGroundProcessor = new DataExtractServiceProcessor();
         backGroundProcessor.Run();
         LogWrapper.Log($"Data Extract processor completed", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
     }
     catch (Exception ex)
     {
         LogWrapper.Log($"Error occurred in calling data extract method. Error message : {ex.Message}", $"Thread id: {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Information);
     }
     finally
     {
         _timer.Enabled = true;
     }
 }
Exemple #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("RequestServiceHost");
            Console.WriteLine();

            try
            {
                if ((args == null) || (args.Length == 0))
                {
                    RequestServiceHost serviceWrapper = new RequestServiceHost();
                    serviceWrapper.Start(null);
                    Console.WriteLine("Started");
                    Console.WriteLine();
                    Console.WriteLine("Press Enter for exit");
                    Console.ReadLine();
                    serviceWrapper.Stop();
                }
                else
                {
                    string cmd      = args[0].ToLower().Trim();
                    string fileName = args.Length > 1 ? args[1].ToLower().Trim() : null;
                    switch (cmd)
                    {
                    case "/install":
                        InstallService(fileName);
                        break;

                    case "/uninstall":
                        UninstallService(fileName);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} на старте : {1}", ex.Message, ex.StackTrace));
                Console.ReadLine();
            }

            Console.ReadLine();
        }
Exemple #26
0
 public override void Validate(string UserName, string Password)
 {
     if (this._AccountValidator == null)
     {
         LogWrapper.Log(MessageType.MESSAGE_ERROR, "Ошибка проверки входа пользователя : Валидатор аккаунтов не задан");
         throw new SecurityTokenException();
     }
     try
     {
         if (_AccountValidator.Validate(UserName, Password) == false)
         {
             throw new SecurityTokenException();
         }
     }
     catch (Exception ex)
     {
         LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при попытке валидации пользователя {1} : {2}", ex.Message, UserName, ex.StackTrace));
         throw;
     }
 }
Exemple #27
0
        public FileRepository(string ClearFileName)
        {
            try
            {
                lock (_Locker)
                {
                    _Storage = AppDomain.CurrentDomain.BaseDirectory + ClearFileName;

                    if (File.Exists(_Storage) == false)
                    {
                        File.Create(_Storage).Close();
                    }
                    Task.Factory.StartNew(DoSave, TaskCreationOptions.LongRunning);
                }
            }
            catch (Exception ex)
            {
                LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при создании FileAccessProvider. {1}", ex.Message, ex.StackTrace));
                throw;
            }
        }
Exemple #28
0
        public HashSet <Int64> LoadAccounts()
        {
            string[]        acc = null;
            HashSet <Int64> ret = new HashSet <long>();

            try
            {
                acc = _Repository.LoadLines();

                foreach (string s in acc)
                {
                    ret.Add(Convert.ToInt64(s));
                }
            }
            catch (Exception ex)
            {
                LogWrapper.Log(MessageType.MESSAGE_FATALERROR, string.Format("Исключение {0} при загрузке аккаунтов. {1}", ex.Message, ex.StackTrace));
                throw;
            }
            return(ret);
        }
 private KeyEventWrapper MapDataSetToKeyEventWrapper(DataSet recordsDbSet)
 {
     try
     {
         KeyEventWrapper wrapperObj = null;
         for (int i = 0; i < recordsDbSet?.Tables?[0]?.Rows?.Count; i++)
         {
             try
             {
                 KeyEvent key = new KeyEvent();
                 key.KeyEventId  = recordsDbSet?.Tables[0]?.Rows?[i].ItemArray[0].ToString();
                 key.MachineId   = recordsDbSet?.Tables[0]?.Rows?[i].ItemArray[1].ToString();
                 key.StockNumber = recordsDbSet?.Tables[0]?.Rows?[i].ItemArray[2].ToString();
                 key.EmployeeId  = recordsDbSet?.Tables[0]?.Rows?[i].ItemArray[3].ToString();
                 key.EventType   = recordsDbSet?.Tables[0]?.Rows?[i].ItemArray[4].ToString();
                 key.TimeStamp   = Convert.ToDateTime(recordsDbSet?.Tables[0]?.Rows?[i].ItemArray[5].ToString());
                 if (wrapperObj == null)
                 {
                     wrapperObj = new KeyEventWrapper();
                 }
                 if (wrapperObj.KeyEvents == null)
                 {
                     wrapperObj.KeyEvents = new List <KeyEvent>();
                 }
                 wrapperObj.KeyEvents.Add(key);
             }
             catch (Exception ex)
             {
                 LogWrapper.Log($"Error in constructing keyevent from dataset at row count {i}. Skipping to next row. Error message is {ex.Message}", $" Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Error);
             }
         }
         return(wrapperObj);
     }
     catch (Exception ex)
     {
         LogWrapper.Log($"Error in constructing key events from recordset. Error message is {ex.Message}", $" Thread id : {System.Threading.Thread.CurrentThread.ManagedThreadId}", 1, System.Diagnostics.TraceEventType.Error);
         return(null);
     }
 }
Exemple #30
0
        public void SaveToLogFileOnly_WithAppConfigPresent()
        {
            var configWRapperTest = new LogConfigWrapperTests();

            configWRapperTest.SerializeToXMLTest();

            LoggingSettings.Instance.Config.Database.IsEnabled           = false;
            LoggingSettings.Instance.Config.EmailConfiguration.IsEnabled = false;

            LogWrapper.Log(SeverityLevel.Debug, "testing",
                           new Exception("Is this real or just a fantasy"),
                           LoggerInstanceConstants.MainLoggerInstance,
                           @"1021391480þ923703585þ1þ605þ605þ3þ0þZþþþþþþ05/04/2016 15:52:59.6942þ12þVIDAKOVIC, LYNNþþMEDICAL SERVICES RICþþþþ0þR-ZþüPAYER NAME MATCHING REQUIRED.üýüBILLING NAME MATCHING REQUIRED.üþ05/04/2016þ15:52:59.6942þ1021391480.1þþ114X67712481þ246.00þREHAB INST OF CHICAGOþPþþ3þ1244þþ1205879095þ1659306587þ1114933660þ0þ605þþþþþþþþþþþþ20160504þZ1ýZ1þþPAYER NAME MATCHING REQUIREDýBILLING NAME MATCHING REQUIRED",
                           new Dictionary <string, string> {
                { "Additional Data 1", "SomeImportantValue" }, { "TheAnswer", "42" }, { "HAP Status", "I am online, Dave" }
            },
                           new Dictionary <string, string> {
                { "InputParamter1", "True" }, { "NextParam", "String" }, { "NullableParm", null }
            },
                           "UnitTest.SaveToALogFileOnly");

            log4net.Config.XmlConfigurator.Configure();

            LogManager.GetLogger("").Debug("something");


            LogWrapper.Log(SeverityLevel.Debug, "testing",
                           new Exception("Is this real or just a fantasy"),
                           LoggerInstanceConstants.MainLoggerInstance,
                           @"1021391480þ923703585þ1þ605þ605þ3þ0þZþþþþþþ05/04/2016 15:52:59.6942þ12þVIDAKOVIC, LYNNþþMEDICAL SERVICES RICþþþþ0þR-ZþüPAYER NAME MATCHING REQUIRED.üýüBILLING NAME MATCHING REQUIRED.üþ05/04/2016þ15:52:59.6942þ1021391480.1þþ114X67712481þ246.00þREHAB INST OF CHICAGOþPþþ3þ1244þþ1205879095þ1659306587þ1114933660þ0þ605þþþþþþþþþþþþ20160504þZ1ýZ1þþPAYER NAME MATCHING REQUIREDýBILLING NAME MATCHING REQUIRED",
                           new Dictionary <string, string> {
                { "Additional Data 1", "SomeImportantValue" }, { "TheAnswer", "42" }, { "HAP Status", "I am online, Dave" }
            },
                           new Dictionary <string, string> {
                { "InputParamter1", "True" }, { "NextParam", "String" }, { "NullableParm", null }
            },
                           "UnitTest.SaveToALogFileOnly");
        }