ScriptCSSession( IScriptEngine engine, ScriptPackSession scriptPackSession, CurrentCmdletScriptPack currentCmdletScriptPack, CurrentLogger logger)
 {
     _engine = engine;
     _scriptPackSession = scriptPackSession;
     _currentCmdletScriptPack = currentCmdletScriptPack;
     _logger = logger;
 }
        private static string GenerateMessageAccordingToType(object logObject, string callerInfo)
        {
            string resultLogString = string.Empty;

            try
            {
                //Doing fake bug fix
                if (logObject is ILoggable)
                {
                    resultLogString = ((ILoggable)logObject).ToLogString();
                }
                else
                {
                    resultLogString = logObject.ToString();
                }
            }
            //these catches indicate an error in the our logger code or in the calling parameters
            //so these should be rethrown to protect the caller from silent failure
            catch (Exception ex)
            {
                CurrentLogger.Error(ex, string.Format("{0}:Error inside custom logger at GenerateMessageAccordingToType while called from {1}", LOCAL_MODULE_NAME, callerInfo));
                throw;
            }
            return(resultLogString);
        }
Esempio n. 3
0
        public void CreateOrUpdateDatabase()
        {
            using (var connection = new MySqlConnection($"Server={_serverAddress};{_authenticationString}"))
            {
                connection.Open();
                var exists = connection.Query($"SHOW DATABASES LIKE '{_databaseNamePattern}'").Any();

                if (exists)
                {
                    CurrentLogger.Log($"Using MySQL database {_databaseNamePattern}");
                }
                else
                {
                    CurrentLogger.Log($"Creating new MySQL database {_databaseNamePattern}");

                    CreateDatabase(connection);
                    CreateTables(connection);
                }

                using (var t = connection.BeginTransaction())
                {
                    connection.Execute($"USE {_databaseNamePattern}");
                    Migrate(connection).Wait();
                    t.Commit();
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Выполянть функции из аргументов, пока не встретиться функция не кидающая исключения, возвращающая подходящщее
        /// предикату IsSuitValue значение или функции не закончатся.
        /// Если IsSuitValue == null, то предикат подтверждает любые значения не равные default(T) (например null).
        /// Исключения всех функций записываются в лог с warning левел. Исключение из последней доступной функции летит ниже.
        /// Если не нашли ни одну функцию удовлетворяющую предикату, то летит исключение по нехватки функций
        /// </summary>
        public static T TryWhileNotPredicate <T>(string operation, Predicate <T> IsSuitValue, params Func <T>[] funcs)
        {
            var _ = funcs ?? throw new ArgumentNullException(nameof(funcs));

            IsSuitValue = IsSuitValue ?? new Predicate <T> (result => !Object.Equals(result, default(T)));
            var remainFuncAmount = funcs.Count();

            foreach (var func in funcs)
            {
                try
                {
                    --remainFuncAmount;
                    var __     = func ?? throw new NullReferenceException(nameof(func));
                    var result = func();
                    if (IsSuitValue(result))
                    {
                        return(result);
                    }
                }
                catch (Exception ex)
                {
                    var opName = $"{nameof(TryChain)} with function number {funcs.Count() - remainFuncAmount} for operation " + operation;
                    if (remainFuncAmount <= 0)
                    {
                        CurrentLogger.LogEx(opName, ex);
                        throw ex;
                    }
                    CurrentLogger.WriteLog(opName + ": " + CurrentLogger.ExtractExceptionMessage(ex), System.Diagnostics.TraceEventType.Warning);
                }
            }
            throw new Exception($"{nameof(funcs)} for {nameof(TryChain)} list is exceeded");
        }
Esempio n. 5
0
 ScriptCSSession(IScriptEngine engine, ScriptPackSession scriptPackSession, CurrentCmdletScriptPack currentCmdletScriptPack, CurrentLogger logger)
 {
     _engine                  = engine;
     _scriptPackSession       = scriptPackSession;
     _currentCmdletScriptPack = currentCmdletScriptPack;
     _logger                  = logger;
 }
Esempio n. 6
0
        /// <summary>
        /// Выполянть функции из аргументов, пока не встретиться функция не кидающая исключения или функции не закончатся.
        /// Исключения всех функций записываются в лог с warning левел. Исключение из последней доступной функции летит ниже.
        /// </summary>
        public static T Try <T>(string operation, IEnumerable <Func <T> > funcs)
        {
            var       _ = funcs ?? throw new ArgumentNullException(nameof(funcs));
            Exception lastIterationException = null;
            int       iteration = 0;

            foreach (var func in funcs)
            {
                try
                {
                    lastIterationException = null;
                    ++iteration;
                    var __ = func ?? throw new NullReferenceException(nameof(func));
                    return(func());
                }
                catch (Exception ex)
                {
                    var opName = $"{nameof(TryChain)} for operation " + operation + " on iteration " + iteration;
                    lastIterationException = ex;
                    CurrentLogger.WriteLog(opName + ": " + CurrentLogger.ExtractExceptionMessage(ex), System.Diagnostics.TraceEventType.Warning);
                }
            }
            if (!(lastIterationException is null))
            {
                var opName = $"{nameof(TryChain)} for operation " + operation + " on iteration " + iteration;
                CurrentLogger.LogEx(opName, lastIterationException);
                throw lastIterationException;
            }
            throw new ArgumentException($"{nameof(funcs)} for {nameof(TryChain)} with empty list");
        }
Esempio n. 7
0
 public void Start()
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         lock (SyncRoot)
         {
             if (_disposed)
             {
                 throw new ObjectDisposedException(nameof(LongRunningTask));
             }
             var task = _workerTask;
             if (task != null)
             {
                 return;
             }
             _cancelSource?.Dispose();
             _cancelSource = new CancellationTokenSource();
             var cancelToken = _cancelSource.Token;
             CancelToken            = cancelToken;
             Scheduling.TaskName    = GetType().ToString();
             Scheduling.ProcessBody = (token) => Process(token);
             task = new Task(() => Scheduling.SchedulingRun(cancelToken), cancelToken, TaskCreationOptions.LongRunning);
             task.Start();
             _workerTask = task;
         }
     }
 }
Esempio n. 8
0
        /// <summary>
        /// Выполянть функции из аргументов, пока не встретиться функция не кидающая исключения или функции не закончатся.
        /// Исключения всех функций записываются в лог с warning левел. Исключение из последней доступной функции летит ниже.
        /// </summary>
        public static T Try <T>(string operation, params Func <T>[] funcs)
        {
            var _ = funcs ?? throw new ArgumentNullException(nameof(funcs));
            var remainFuncAmount = funcs.Count();

            foreach (var func in funcs)
            {
                try
                {
                    --remainFuncAmount;
                    var __ = func ?? throw new NullReferenceException(nameof(func));
                    return(func());
                }
                catch (Exception ex)
                {
                    var opName = $"{nameof(TryChain)} with function number {funcs.Count() - remainFuncAmount} for operation " + operation;
                    if (remainFuncAmount <= 0)
                    {
                        CurrentLogger.LogEx(opName, ex);
                        throw ex;
                    }
                    CurrentLogger.WriteLog(opName + ": " + CurrentLogger.ExtractExceptionMessage(ex), System.Diagnostics.TraceEventType.Warning);
                }
            }
            throw new ArgumentException($"{nameof(funcs)} for {nameof(TryChain)} with empty list");
        }
Esempio n. 9
0
 private void RunNext(Guid guid, string jsonData)
 {
     _internalCollection.Add(new BlockItem {
         SessionId = guid, Data = jsonData
     });
     CurrentLogger.LogInformation("Hub incoming message - {0}.", guid);
 }
Esempio n. 10
0
 protected void Cancel()
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         _cancelSource.Cancel();
     }
 }
Esempio n. 11
0
        /// <summary>
        /// log using warn log level
        /// </summary>
        /// <param name="ex"> the exception to be logged</param>
        /// <param name="logParaemtersArr">array of objects to log their values for custom message user must override toSting() method</param>
        /// <param name="messageFormat">format of the message to be logged</param>
        /// <param name="messageParameters">the parameters to fill the message placeholders</param>
        public static void LogWarn(string messageFormat, object[] messageParameters = null
                                   , Exception ex = null, object[] logObjectsArr = null
                                   , [CallerMemberName] string callerInfo = "")
        {
            string finalMessage = CreateLogMessage(logObjectsArr, messageFormat, callerInfo, messageParameters);

            CurrentLogger.Warn(ex, finalMessage);
        }
Esempio n. 12
0
        private async Task Closed(Exception arg)
        {
            if (Connection == null)
            {
                CurrentLogger.LogInformation("Hub connection state is empty! Not initialised. Please check if the URL is correct.");
            }
            else
            {
                CurrentLogger.LogInformation("Hub connection state - Closed - {0}", Connection.State);
            }

            await Task.Delay(5000);
        }
Esempio n. 13
0
        private Task Reconnected(string arg)
        {
            if (Connection == null)
            {
                CurrentLogger.LogInformation("Hub connection state is empty! Not initialised. Please check if the URL is correct.");
            }
            else
            {
                CurrentLogger.LogInformation("Hub connection state - Reconnected - {0}", Connection.State);
            }

            return(Task.CompletedTask);
        }
Esempio n. 14
0
        public static bool IsThrowAnyException(Action checkedAction, string operation = null)
        {
            try
            {
                checkedAction();

                return(false);
            }
            catch (Exception ex)
            {
                CurrentLogger.Trace($"Operation {operation} with error {ex.Message}");
            }
            return(true);
        }
Esempio n. 15
0
 public void StopNoThrow()
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         lock (SyncRoot)
         {
             if (_disposed)
             {
                 return;
             }
             ExceptionHelper.ExceptionCatcher(InternalStop, where : nameof(LongRunningTask) + ":" + GetType() + "." + nameof(StopNoThrow));
         }
     }
 }
Esempio n. 16
0
 public void Stop()
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         lock (SyncRoot)
         {
             if (_disposed)
             {
                 throw new ObjectDisposedException(nameof(LongRunningTask));
             }
             InternalStop();
         }
     }
 }
Esempio n. 17
0
 public void Dispose()
 {
     FileFetcher.CancelDownload();
     lock (machLock)
     {
         PauseAll();
         Array.ForEach(machs.Rights, x => x.Dispose());
         machs.Clear();
         MasterTimeSource.Dispose();
         ExternalsManager.Clear();
         HostMachine.Dispose();
         CurrentLogger.Dispose();
         BackendManager.Dispose();
     }
 }
Esempio n. 18
0
 public virtual void Dispose()
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         lock (SyncRoot)
         {
             if (_disposed)
             {
                 return;
             }
             _disposed = true;
             ExceptionHelper.ExceptionCatcher(InternalStop, where : nameof(LongRunningTask) + ":" + GetType() + "." + nameof(Dispose));
             _cancelSource?.Dispose();
         }
     }
 }
Esempio n. 19
0
 public void Dispose()
 {
     FileFetcher.CancelDownload();
     lock (machLock)
     {
         var toDispose = machs.Rights.ToArray();
         //Although a single machine does not have to be paused before its disposal,
         //disposing multiple entities has to ensure that all are stopped.
         ExternalsManager.Pause();
         Array.ForEach(toDispose, x => x.Pause());
         Array.ForEach(toDispose, x => x.Dispose());
         machs.Clear();
         ExternalsManager.Clear();
         HostMachine.Dispose();
         CurrentLogger.Dispose();
         BackendManager.Dispose();
     }
 }
Esempio n. 20
0
 private void InternalStop()
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         var task = _workerTask;
         if (task == null)
         {
             return;
         }
         _workerTask = null;
         _cancelSource.Cancel();
         using (new RAII(task.Dispose))
         {
             CurrentLogger.Trace($"Начинаем ожидание окончания задачи {GetType().Name}");
             task.Wait(_stopTimeout);
         }
     }
 }
Esempio n. 21
0
        static public ScriptCSSession Create(Cmdlet cmdlet)
        {
            ScriptCSSession session = null;
            var             logger  = new CurrentLogger();

            using (logger.CreateActiveLoggerSession(new CmdletLogger(cmdlet)))
            {
                IScriptHostFactory factory = new ScriptHostFactory();
                var engine = new RoslynScriptEngine(factory, logger);
                engine.BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var currentCmdletScriptPack = new CurrentCmdletScriptPack();
                var scriptPackSession       = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack });
                scriptPackSession.InitializePacks();

                session = new ScriptCSSession(engine, scriptPackSession, currentCmdletScriptPack, logger);
            }

            return(session);
        }
        public static ScriptCSSession Create(Cmdlet cmdlet)
        {
            ScriptCSSession session = null;
            var logger = new CurrentLogger();

            using (logger.CreateActiveLoggerSession(new CmdletLogger(cmdlet)))
            {
                IScriptHostFactory factory = new ScriptHostFactory();
                var engine = new RoslynScriptEngine(factory, logger);
                engine.BaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var currentCmdletScriptPack = new CurrentCmdletScriptPack();
                var scriptPackSession = new ScriptPackSession(new IScriptPack[] { currentCmdletScriptPack });
                scriptPackSession.InitializePacks();

                session = new ScriptCSSession( engine, scriptPackSession, currentCmdletScriptPack, logger );
            }

            return session;
        }
Esempio n. 23
0
        public void StartService()
        {
            while (true)
            {
                try
                {
                    Execute();
                }
                catch (Exception ex)
                {
                    if (CurrentLogger != null)
                    {
                        CurrentLogger.LogError(ex, ex.Message);
                    }
                    else
                    {
                        Logger.Log(ex, false);
                    }
                }

                Thread.Sleep(SleepTime);
            }
        }
Esempio n. 24
0
 public void WaitForStopNoThrow(TimeSpan?stopTimeout = null)
 {
     using (CurrentLogger.ScopedTrace($"{GetType()}.{MethodBase.GetCurrentMethod()}"))
     {
         lock (SyncRoot)
         {
             if (_disposed)
             {
                 return;
             }
             ExceptionHelper.ExceptionCatcher(() =>
             {
                 var task = _workerTask;
                 if (task == null)
                 {
                     return;
                 }
                 CurrentLogger.Trace($"Начинаем ожидание окончания задачи {GetType().Name} без её завершения ");
                 task.Wait(stopTimeout ?? TimeSpanConstants.Infinite);
             }, where : nameof(LongRunningTask) + ":" + GetType() + "." + nameof(StopNoThrow));
         }
     }
 }
Esempio n. 25
0
        private void SendMailList(List <Mail> mailList)
        {
            foreach (Mail mail in mailList)
            {
                try
                {
                    mail.Send();
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    mail.SetError();

                    if (CurrentLogger != null)
                    {
                        CurrentLogger.LogError(ex, ex.Message);
                    }
                    else
                    {
                        Logger.Log(ex, false);
                    }
                }
            }
        }
Esempio n. 26
0
 /// <summary>
 /// 记录错误信息
 /// </summary>
 /// <param name="msg"></param>
 public static void Error(string msg)
 {
     CurrentLogger.Error(msg);
 }
Esempio n. 27
0
 public static void Warn(string msg)
 {
     CurrentLogger.Warn(msg);
 }
Esempio n. 28
0
 public static void Info(string msg)
 {
     CurrentLogger.Info(msg);
 }
Esempio n. 29
0
 /// <summary>
 /// 记录调试信息
 /// </summary>
 /// <param name="msg"></param>
 public static void Debug(string msg)
 {
     CurrentLogger.Debug(msg);
 }
Esempio n. 30
0
        static void Init()
        {
            lock (initializationLocker)
            {
                if (_currentLogger == null)
                {
                    if (string.IsNullOrEmpty(AbsoluteConfigurationFilePath))
                    {
                        throw new LoggerExcetion(string.Format("{0}:Configuration file name is not set in application configuration", LOCAL_MODULE_NAME),
                                                 LoggerFailureType.ConfigFailure);
                    }
                    if (!File.Exists(AbsoluteConfigurationFilePath))
                    {
                        throw new LoggerExcetion(string.Format("{0}:Configuration file named {1} does not exist", LOCAL_MODULE_NAME, AbsoluteConfigurationFilePath),
                                                 LoggerFailureType.ConfigFailure);
                    }
                    try
                    {
                        LogManager.ThrowConfigExceptions = true;
                        LogManager.Configuration         = new NLog.Config.XmlLoggingConfiguration(AbsoluteConfigurationFilePath, false);

                        _currentLogger = LogManager.GetCurrentClassLogger();

                        string rootpath = LogManager.Configuration.Variables[ROOTPATH_VAR_NAME] == null ? null : LogManager.Configuration.Variables[ROOTPATH_VAR_NAME].Text;

                        if (string.IsNullOrEmpty(rootpath))
                        {
                            throw new LoggerExcetion(string.Format("{0}:Root Directory path variable is null or empty", LOCAL_MODULE_NAME),
                                                     LoggerFailureType.ConfigFailure);
                        }

                        if (!Directory.Exists(rootpath))
                        {
                            try
                            {
                                Directory.CreateDirectory(rootpath);
                            }
                            catch (Exception ex)
                            {
                                throw new LoggerExcetion(string.Format("{0}:Failed to create root logging folder with path {1}", LOCAL_MODULE_NAME, rootpath), ex,
                                                         LoggerFailureType.ConfigFailure);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new LoggerExcetion(string.Format("{0}:failed to initialize log configuration from file {1}", LOCAL_MODULE_NAME, AbsoluteConfigurationFilePath), ex,
                                                 LoggerFailureType.ConfigFailure);
                    }
                    try
                    {
                        CurrentLogger.Info("Logging Started");
                    }
                    catch (Exception ex)
                    {
                        throw new LoggerExcetion(string.Format("{0}:failed to write initializarion log message", LOCAL_MODULE_NAME), ex,
                                                 LoggerFailureType.WriteFailure);
                    }
                }
            }
        }
Esempio n. 31
0
 public static void Fatal(string msg)
 {
     CurrentLogger.Fatal(msg);
 }
Esempio n. 32
0
        /// <summary>
        /// builds the message string according to message format and parameters and the logParamwers objects
        /// </summary>
        /// <param name="logObjectsArr">array of objects to log their values for custom message user must override toSting() method</param>
        /// <param name="messageFormat">format of the message to be logged</param>
        /// <param name="messageParameters"> the parameters to fill the message placeholders</param>
        /// <returns>returns the complete message to be logged</returns>
        private static string CreateLogMessage(object[] logObjectsArr, string messageFormat, string callerInfo, object[] messageParameters)
        {
            string finalMessage = string.Empty;

            //Test Shelv
            #region create formatted message
            try
            {
                if (messageFormat != null)
                {
                    #region generate parameters string list
                    string[] textParametersList = new string[messageParameters.Length];
                    if (messageParameters != null && messageParameters.Length > 0)
                    {
                        textParametersList = new string[messageParameters.Length];
                        for (int i = 0; i < messageParameters.Length; i++)
                        {
                            if (messageParameters[i] != null)
                            {
                                textParametersList[i] = GenerateMessageAccordingToType(messageParameters[i], callerInfo);
                            }
                            else
                            {
                                textParametersList[i] = "";
                                CurrentLogger.Warn(string.Format("{0}:Null is invalid parameter for the formatted string at parameter index {1} while called from {2}", LOCAL_MODULE_NAME, i, callerInfo));
                            }
                        }
                    }
                    #endregion
                    finalMessage = string.Format(callerInfo + ":" + messageFormat, textParametersList.ToArray <object>());
                }
                else
                {
                    #region log warnings
                    if (messageFormat == null)
                    {
                        CurrentLogger.Warn(string.Format("{0}:Message format is null while called from {1}", LOCAL_MODULE_NAME, callerInfo));
                    }
                    if (messageParameters == null)
                    {
                        CurrentLogger.Warn(string.Format("{0}:Message parameters is null while called from {1}", LOCAL_MODULE_NAME, callerInfo));
                    }
                    if (messageParameters.Count() == 0)
                    {
                        CurrentLogger.Warn(string.Format("{0}:Message parameters count is 0 while called from {1}", LOCAL_MODULE_NAME, callerInfo));
                    }
                    #endregion
                }
                #region create logs for passed separate array of objects
                if (logObjectsArr != null)
                {
                    foreach (object currentParameterObject in logObjectsArr)
                    {
                        if (currentParameterObject != null)
                        {
                            finalMessage += "\n logged parameter " + GenerateMessageAccordingToType(currentParameterObject, callerInfo);
                        }
                    }
                }
                #endregion
            }
            //these catches indicate an error in the our logger code or in the calling parameters
            //so these should be rethrown to protect the caller from silent failure
            catch (FormatException ex)
            {
                CurrentLogger.Error(ex, string.Format("{0}:Error because of string.Format while called from {1}", LOCAL_MODULE_NAME, callerInfo));
                throw;
            }
            catch (Exception ex)
            {
                CurrentLogger.Error(ex, string.Format("{0}:Error inside custom logger while called from {1}", LOCAL_MODULE_NAME, callerInfo));
                throw;
            }
            #endregion
            return(finalMessage);
        }