Error() public method

public Error ( string message ) : void
message string
return void
コード例 #1
0
        /// <summary>
        /// Keep track if we have sent an error popup notification, if so use this value to supress future popups, under the assumption that the first one is the most important and probably the originator of the future popups.
        /// </summary>
        public MainForm()
        {
            // Machine number
            m_strMachineNumber = System.Configuration.ConfigurationManager.AppSettings["machineNumber"];

            //Setup the Logging system
            m_logAndErr = new LogAndErrorsUtils(AutoDialIcon, ToolTipIcon.Error);
            m_imgManUtils = new ImageManipulationUtils(m_logAndErr);
            m_logger = m_logAndErr.getLogger();

            // Give the admins a chance to change the path of tessdata
            string TESSERACT_DATA_PATH = System.Configuration.ConfigurationManager.AppSettings["tessdataPath"];
            if (TESSERACT_DATA_PATH == null)
            {

                TESSERACT_DATA_PATH = @"C:\\Autodial\\Dialing\\tessdata";
                m_logger.Error("No Config Tesseract path. Setting to: {0}", TESSERACT_DATA_PATH);
            }

            // Initilialise event for timer tick
            m_timer.Tick += new EventHandler(timerTick);

            //Initialise the Form
            InitializeComponent();

            m_logger.Info("###################################################################");
            m_logger.Info("Starting Program");

            // Checking for tesseract data path
            if (!System.IO.Directory.Exists(TESSERACT_DATA_PATH))
            {
                string strError = "Couldn't find tesseract in " + TESSERACT_DATA_PATH;
                m_logger.Error(strError);
                m_logger.Info(MailUtils.MailUtils.sendit("*****@*****.**", m_strMachineNumber, strError, m_strDailyLogFilename));
            }

            // Set the Talk Log Monitor Util
            Regex regEx = new Regex("answered|disconnected");
            string strTalkLogPath = System.Configuration.ConfigurationManager.AppSettings["talkLogPath"];
            m_logger.Info("Talk Log path: " + strTalkLogPath);
            string strLogFilePath = TalkLogMonitorUtil.getTalkLogFileNameFromTalkLogDirectory(DateTime.Today, strTalkLogPath);
            m_logger.Info("Talk File Log path: " + strLogFilePath);
            m_talkLogMonitor = new TalkLogMonitorUtil(strLogFilePath, stopAlertTimer, regEx);

            string strYear = DateTime.Today.Year.ToString();
            string strMonth = (DateTime.Today.Month < 10) ? ("0" + DateTime.Today.Month.ToString()) : DateTime.Today.Month.ToString();
            string strDay = (DateTime.Today.Day < 10) ? ("0" + DateTime.Today.Day.ToString()) : DateTime.Today.Day.ToString();

            m_strDailyLogFilename = @"C:\AutoDial\Log\AutoDial_" +
                                    strYear + "-" +
                                    strMonth + "-" +
                                    strDay + "_trace.log"; // AutoDial_2015-10-28_trace.log

            registerHotkey();
            customHide();
        }
コード例 #2
0
 static void Main(string[] args)
 {
     try
     {
         log = LogManager.GetCurrentClassLogger();
         BookListService bls = new BookListService();
         log.Debug("Старт записи в двоичный файл");
             WriteDefaultValues(fileName);
         log.Debug("Окончание записи в двоичный файл");
         log.Debug("Старт чтения данных из двоичног файла");
         bls = ReadDefaultValues(fileName);
         log.Debug("Окончание чтения данных из двоичног файла");
         Book[] find = bls.FindByTag("1999", EnumTag.Year); //Поиск
         foreach (Book b in find)
         Console.WriteLine(b);
         Console.WriteLine("-------------------------");
         Book[] sort = bls.SortBooksByTag(EnumTag.Page);//Сортировка
         foreach (Book b in sort)
             Console.WriteLine(b);
         //log.Warn("Попытка добавить уже существующую книгу");
         //bls.AddBook(sort[0]); 
         bls.RemoveBook(sort[0]);//Удаление книги
         log.Warn("Попытка удаления книги отсутствующей в каталоге");
         bls.RemoveBook(sort[0]);
     }
     catch (Exception e)
     {
         log.Error(e.Message);
     }
     
 }
コード例 #3
0
        public static ABIExitCode Compile(ABIFileSystemOptions options, LogFactory factory)
        {
            #region Argument exceptions

            if (options == null)
                throw new ArgumentNullException("options");

            if (factory == null)
                throw new ArgumentNullException("factory");

            #endregion

            _logger = factory.GetCurrentClassLogger();
            _logger.Debug(options);
            try
            {
                if (!Validate(options))
                    return ABIExitCode.ErrorDuringValidation;

                var engine = new CompilerEngine(options, factory);

                var result = engine.Compile();
                Debug.Assert(result != ABIExitCode.ErrorExitCodeUnassigned);
                return result;
            }
            catch (Exception ex) // avoid external unhandled exceptions
            {
                _logger.Error(ex);
            }

            return ABIExitCode.ErrorUnhandledException;
        }
コード例 #4
0
        private void TraceMessageInternal(LogLvl level, string message)
        {
            if (level > desiredLogLevel)
            {
                return;
            }

            switch (level)
            {
            case LogLvl.Debug:
                variableLogger?.Debug(message);
                break;

            case LogLvl.Info:
                variableLogger?.Info(message);
                break;

            case LogLvl.Warning:
                variableLogger?.Warn(message);
                break;

            case LogLvl.Error:
                variableErrorLogger?.Error(message);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }
コード例 #5
0
ファイル: OnPremADHelper.cs プロジェクト: spSlaine/ADCST
        public DirectoryEntry GetADDirectoryEntry(string FQDomainName, string LDAPPath, Logger Logger)
        {
            Logger.Debug(string.Format(@"Getting Directory Entry for LDAP Path {0}", LDAPPath));

            //DirectoryEntry LDAPConnection = new DirectoryEntry(FQDomainName);
            DirectoryEntry LDAPConnection = new DirectoryEntry("LDAP://"+FQDomainName);

            LDAPConnection.Path = "LDAP://"+LDAPPath;
            LDAPConnection.AuthenticationType = AuthenticationTypes.Secure;

               try
               {
               //Try fetch to Native ADSI Object  - if this passes Then we know that we
               //are authenticated. If an exception is thrown then we know we are using an Invalid Account.

               object DirEntryNativeObject = LDAPConnection.NativeObject;

               }
               catch (Exception ex)
               {
               Logger.Error(String.Format("Error authenticating to Active Directory with current running user. {0} {1}.",
                   ex.Message, ex.InnerException != null ? ex.InnerException.Message : ""));

               throw new Exception(String.Format("Error authenticating to Active Directory with current running user. {0} {1}.",
                   ex.Message, ex.InnerException != null ? ex.InnerException.Message : "" ));
               }

               return LDAPConnection;
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: dogtbh/sensu-client
        static void Main()
        {
            _log = LogManager.GetCurrentClassLogger();
            _log.Warn("Service is about to start");
#if DEBUG
            LogManager.GlobalThreshold = LogLevel.Trace;
#endif
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;

            try
            {
                var container = new Container(new SensuClientRegistry());
                var sensuClient = container.GetInstance<ISensuClient>() as ServiceBase;
                
                ServiceBase[] servicesToRun;
                servicesToRun = new ServiceBase[] 
                {
                    sensuClient
                 };

                if (Environment.UserInteractive)
                {
                    RunInteractive(servicesToRun);
                }
                else
                {
                    ServiceBase.Run(servicesToRun);
                }
            }
            catch (Exception exception)
            {
                _log.Error(exception, "Error in startup sensu-client.");
            }
            
        }
コード例 #7
0
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler"/> when a <see cref="T:Quartz.ITrigger"/>
        ///             fires that is associated with the <see cref="T:Quartz.IJob"/>.
        /// </summary>
        /// <remarks>
        /// The implementation may wish to set a  result object on the
        ///             JobExecutionContext before this method exits.  The result itself
        ///             is meaningless to Quartz, but may be informative to
        ///             <see cref="T:Quartz.IJobListener"/>s or
        ///             <see cref="T:Quartz.ITriggerListener"/>s that are watching the job's
        ///             execution.
        /// </remarks>
        /// <param name="context">The execution context.</param>
        public void Execute(IJobExecutionContext context)
        {
            _logger = LogManager.GetCurrentClassLogger();

            JobDataMap dataMap = context.JobDetail.JobDataMap;
            EconomicReleaseUpdateJobSettings settings;
            try
            {
                settings = JsonConvert.DeserializeObject<EconomicReleaseUpdateJobSettings>((string)dataMap["settings"]);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Failed to deserialize data update job settings");
                return;
            }

            _logger.Info($"Data Update job {settings.Name} triggered.");

            _broker.Error += _broker_Error;

            var startDate = DateTime.Now.AddBusinessDays(-settings.BusinessDaysBack);
            var endDate = DateTime.Now.AddBusinessDays(settings.BusinessDaysAhead);
            var req = new EconomicReleaseRequest(startDate, endDate, dataLocation: DataLocation.ExternalOnly, dataSource: settings.DataSource);
            var releases = _broker.RequestEconomicReleases(req).Result; //no async support in Quartz, and no need for it anyway, this runs on its own thread
            _logger.Trace($"Economic release update job downloaded {releases.Count} items");

            JobComplete();
        }
コード例 #8
0
ファイル: Controller.cs プロジェクト: andreigec/Happy-Diff
 public static void ProcessResults(JSONDiff jd, Logger l)
 {
     if (jd.Messages.Any())
     {
         l.Info("--Issues--");
         jd.Messages.ForEach(s2 =>
         {
             var mess = s2.Message?.Trim();
             var exp = s2.Exception?.Trim();
             var m = $"{s2.ProblemType} | {mess} | {exp}";
             m = m.Replace("\r\n", "");
             switch (s2.WarnLevel)
             {
                 case JSONWarnLevel.Warn:
                     l.Warn(m);
                     break;
                 case JSONWarnLevel.Error:
                     l.Error(m);
                     break;
                 case JSONWarnLevel.Fatal:
                     l.Fatal(m);
                     break;
                 default:
                     throw new ArgumentOutOfRangeException();
             }
         });
         l.Info("-----------");
     }
     else
     {
         l.Info("--Success--");
         l.Info("-----------");
     }
 }
コード例 #9
0
        public QueueProcessor(Logger log, IDataStore dataStore, IHubContext<IMatchmakingClient> hub, ITracker tracker, IMatchEvaluator matchBuilder, CircularBuffer<TimeSpan> timeToMatch)
        {
            _log = log;
            _dataStore = dataStore;
            _hub = hub;
            _tracker = tracker;
            _matchBuilder = matchBuilder;
            _timeToMatch = timeToMatch;

            _queueSleepMin = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepMin") );
            _queueSleepMax = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepMax") );
            _queueSleepLength = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepLength") );

            Task.Run( async () =>
            {
                _log.Info("Running QueueProcessor...");

                while( true )
                {
                    var sleepTime = _queueSleepMax;

                    try
                    {
                        await processQueue();
                        sleepTime = _queueSleepMax - (_dataStore.DocumentDbPopulation * (_queueSleepMax/_queueSleepLength));
                    }
                    catch(Exception ex)
                    {
                        _log.Error(ex);
                    }

                    Thread.Sleep(sleepTime < _queueSleepMin ? _queueSleepMin : sleepTime);
                }
            });
        }
コード例 #10
0
ファイル: Global.asax.cs プロジェクト: skalinkin/WPAgent
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception lastError = this.Server.GetLastError();
            Exception originalError = lastError.InnerException ?? lastError;

            logger = LogManager.GetCurrentClassLogger();
            logger.Error(originalError.Message, originalError);
        }
コード例 #11
0
        /// <summary>
        /// Takes the screenshot.
        /// </summary>
        /// <returns>An image of the page currently loaded in the browser.</returns>
        public Screenshot TakeScreenshot()
        {
            try
            {
                var screenshotDriver = (ITakesScreenshot)this.driver;
                var screenshot       = screenshotDriver.GetScreenshot();
                return(screenshot);
            }
            catch (NullReferenceException)
            {
                Logger.Error("Test failed but was unable to get webdriver screenshot.");
            }
            catch (UnhandledAlertException)
            {
                Logger.Error("Test failed but was unable to get webdriver screenshot.");
            }

            return(null);
        }
コード例 #12
0
        private void Application_DispatcherUnhandledException1(object sender,
                                                               System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Logger.Error(e.Exception, $"Unhandled exception {e.Exception}");
            Exception        inner = e.Exception.InnerException;
            HashSet <object> seen  = new HashSet <object>();

            while (inner != null && !seen.Contains(inner))
            {
                Logger.Debug(inner, inner.Message);
                inner = inner.InnerException;
            }

            ErrorExit(ExitCode.GeneralError);
            // foreach (var window in Windows)
            // {
            //     ((Window) window).Close();
            // }
        }
コード例 #13
0
        public TaskFile(string path)
        {
            Tickets  = new List <Ticket>();
            filePath = path;

            try
            {
                StreamReader sr = new StreamReader(filePath);
                if (sr.EndOfStream)
                {
                    sr.Close();
                    StreamWriter sw = new StreamWriter(filePath);
                    sw.WriteLine("TicketID, Summary, Status, Priority, Submitter, Assigned, Watching");
                    sw.Close();
                }
                else
                {
                    sr.ReadLine();
                    while (!sr.EndOfStream)
                    {
                        Ticket   ticket      = new Ticket();
                        string   line        = sr.ReadLine();
                        string[] ticketStuff = line.Split(',');
                        ticket.ticketId  = int.Parse(ticketStuff[0]);
                        ticket.summary   = ticketStuff[1];
                        ticket.status    = ticketStuff[2];
                        ticket.priority  = ticketStuff[3];
                        ticket.submitter = ticketStuff[4];
                        ticket.assigned  = ticketStuff[5];
                        ticket.watchers  = ticketStuff[6].Split('|').ToList();
                        // ticket.projectName = ticketStuff[7];
                        // ticket.dueDate = ticketStuff[8];
                        Tickets.Add(ticket);
                    }
                    sr.Close();
                }
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
            }
            logger.Info("{Count} tickets on file", Tickets.Count);
        }
コード例 #14
0
        // RANDOM_MUTAION
        //
        public override void randomMutation(DataElement obj)
        {
            if (obj.Value.LengthBytes <= 1)
            {
                logger.Error("Error, length is " + length + ", unable to perform mutation.");
                return;
            }

            performMutation(obj, context.Random.Next((int)obj.Value.LengthBytes));
        }
コード例 #15
0
        private int TryBindBreakpoints()
        {
            int countBounded = 0;

            try
            {
                AD7PendingBreakpoint[] pendingList;
                lock (_pendingBreakpoints)
                    pendingList = _pendingBreakpoints.Where(x => !x.Bound).ToArray();

                foreach (AD7PendingBreakpoint bp in pendingList)
                {
                    MonoBreakpointLocation location;
                    if (bp.TryBind(_types, out location))
                    {
                        try
                        {
                            int ilOffset;
                            RoslynHelper.GetILOffset(bp, location.Method, out ilOffset);

                            BreakpointEventRequest request = _vm.SetBreakpoint(location.Method, ilOffset);
                            request.Enable();
                            bp.Bound       = true;
                            bp.LastRequest = request;
                            _engine.Callback.BoundBreakpoint(bp);
                            //_vm.Resume();
                            bp.CurrentThread = _mainThread;
                            countBounded++;
                        }
                        catch (Exception ex)
                        {
                            logger.Error("Cant bind breakpoint: " + ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Cant bind breakpoint: " + ex);
            }

            return(countBounded);
        }
コード例 #16
0
        public void Error(string message, params object[] args)
        {
            logger.Error(message, args);
            Console.WriteLine(string.Format("Error: " + message, args));

            if (SendEmail)
            {
                EmailSender.SendLogFile();
            }
        }
コード例 #17
0
ファイル: Form1.cs プロジェクト: ZhenghaoFang/zhefang
        // Declear a delegate variable
        //public delegate void UpdateProgressBarDelegate(int progress);


        public UserInterface()
        {
            UserVerify.VerifyUser verifyUser = new UserVerify.VerifyUser();
            verifyUser.UserID = Environment.UserName;
            bool userVerify = false;

            try
            {
                userVerify = verifyUser.getUserVerify("dbo.TransferDataToSQLApp_User");
            }
            catch (Exception e)
            {
                logger = LogManager.GetCurrentClassLogger();
                logger.Error(e, "UserVerify String Error");
                MessageBox.Show("Error loading UserVerify String", "ERROR");
            }
            string permissionLevel = verifyUser.PermissionLevel;

            try
            {
                string success = userTables.GetJobTasksTables(verifyUser.UserID);
            }
            catch (Exception se)
            {
                logger = LogManager.GetCurrentClassLogger();
                logger.Error(se, "Error loading database");
                MessageBox.Show("Error loading database", "ERROR");
            }
            DataTable JobsList     = userTables.JobsList;
            DataTable JobTasksList = userTables.JobTasksList;


            if (userVerify)
            {
                InitializeComponent();
                //InitializeBackgroundWorker();

                //populate job postings drop-down menu
                for (int r = 0; r < JobsList.Rows.Count; r++)
                {
                    this.JobPos.Items.Add(JobsList.Rows[r][1].ToString());
                }
                if (JobPos.Items.Count == 1)
                {
                    JobPos.Text = JobsList.Rows[0][1].ToString();
                }
            }

            else
            {
                MessageBox.Show("No Permission", "WARNING");
                Load += (s, e) => Close();
                return;
            }
        }
コード例 #18
0
ファイル: UDPConnector.cs プロジェクト: AnhTu18294/3DMachine
        public override bool Connect()
        {
            if (mIsSendConnected || mIsRevConnected)
            {
                Disconnect();
            }

            try
            {
                mSendIPEP = new IPEndPoint(IPAddress.Parse(mSendIP), mSendPort);
                mSender   = new UdpClient();
                mSender.Connect(mSendIPEP);
                this.mIsSendConnected = true;
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                this.mIsSendConnected = false;
                Disconnect();
                return(false);
            }

            try
            {
                mReceiveIPEP = new IPEndPoint(IPAddress.Parse(mReceiveIP), mReceivePort);
                mRevSock     = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                mRevSock.Bind(mReceiveIPEP);
                mReceiver = new Thread(ReceiverTask);
                mReceiver.Start();
                this.mIsRevConnected = true;
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                this.mIsRevConnected = false;
                Disconnect();
                return(false);
            }

            onConnectionStatusChanged(new ConnectionStatusChangedEventArgs(true));
            return(true);
        }
コード例 #19
0
ファイル: ProgramLogger.cs プロジェクト: yzx2001/Wox
        /// <summary>
        /// Logs an exception
        /// </summary>
        internal static void LogException(string classname, string callingMethodName, string loadingProgramPath,
                                          string interpretationMessage, Exception e)
        {
            Debug.WriteLine($"ERROR|{classname}|{callingMethodName}|{loadingProgramPath}|{interpretationMessage}");

            var innerExceptionNumber = 1;

            var possibleResolution = "Not yet known";
            var errorStatus        = "UNKNOWN";

            Logger.Error("------------- BEGIN Wox.Plugin.Program exception -------------");

            do
            {
                if (IsKnownWinProgramError(e, callingMethodName) || IsKnownUWPProgramError(e, callingMethodName))
                {
                    possibleResolution = "Can be ignored and Wox should still continue, however the program may not be loaded";
                    errorStatus        = "KNOWN";
                }

                var calledMethod = e.TargetSite != null?e.TargetSite.ToString() : e.StackTrace;

                calledMethod = string.IsNullOrEmpty(calledMethod) ? "Not available" : calledMethod;

                Logger.Error($"\nException full name: {e.GetType().FullName}"
                             + $"\nError status: {errorStatus}"
                             + $"\nClass name: {classname}"
                             + $"\nCalling method: {callingMethodName}"
                             + $"\nProgram path: {loadingProgramPath}"
                             + $"\nInnerException number: {innerExceptionNumber}"
                             + $"\nException message: {e.Message}"
                             + $"\nException error type: HResult {e.HResult}"
                             + $"\nException thrown in called method: {calledMethod}"
                             + $"\nPossible interpretation of the error: {interpretationMessage}"
                             + $"\nPossible resolution: {possibleResolution}");

                innerExceptionNumber++;
                e = e.InnerException;
            } while (e != null);

            Logger.Error("------------- END Wox.Plugin.Program exception -------------");
        }
コード例 #20
0
        public void connect_reader(object sender, System.EventArgs e)
        {
            String result;

            try
            {
                if (meReaderInterface == ComInterface.enumTCPIP)
                {
                    mReader.InitOnNetwork("127.0.0.1", 22);
                }
                else
                {
                    mReader.InitOnCom();
                }

                txtLogger.Info("Start connect to reader: {}:{}", m_reader_ip, m_reader_port);
                result = mReader.Connect();
                if (mReader.IsConnected)
                {
                    if (meReaderInterface == ComInterface.enumTCPIP)
                    {
                        if (!mReader.Login("alien", "password"))
                        {
                            txtLogger.Error("connect to reader: {}:{} failed with alien and password", m_reader_ip, m_reader_port);
                            mReader.Disconnect();
                            return;
                        }
                    }

                    txtLogger.Info("connect to reader: {}:{}", m_reader_ip, m_reader_port);

                    // to make it faster and not to lose any tag
                    mReader.AutoMode = "On";

                    // TODO: 其他参数设置
                }
            }
            catch (Exception ex)
            {
                txtLogger.Error("Exception in btnConnect_Click(): " + ex.Message);
            }
        }
コード例 #21
0
 public IEnumerable <Product> GetItems()
 {
     try
     {
         var products = (from p in db.Product select p);
         return(products);
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
         return(null);
     }
 }
コード例 #22
0
 private static void DisplayError(string error, NLog.Logger logger = null)
 {
     if (null != logger)
     {
         logger.Error(error);
     }
     else
     {
         Console.Error.WriteLine(error);
     }
 }
コード例 #23
0
ファイル: Binding.cs プロジェクト: mcgrady1/peachfuzz-code
        public void Resolve()
        {
            if (of == null && OfName != null)
            {
                var elem = From.find(OfName);

                if (elem == null)
                {
                    logger.Error("Error, unable to resolve binding '" + OfName + "' attached to '" + From.fullName + "'.");
                }
                else if (From.CommonParent(elem) is Choice)
                {
                    logger.Error("Error, binding '" + OfName + "' attached to '" + From.fullName + "' cannot share a common parent that is of type 'Choice'.");
                }
                else
                {
                    SetOf(elem);
                }
            }
        }
コード例 #24
0
        public ActionResult Remove(int Id)
        {
            var client     = new HttpClient();
            var deleteTask = client.DeleteAsync("http://127.0.0.1:8080/api/employee/" + Id.ToString());

            deleteTask.Wait();

            var result = deleteTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return(Redirect(Request.UrlReferrer.ToString()));
            }
            else
            {
                _logger.Error("Remove Employee " + Id.ToString() + " Unsuccessful");
            }

            return(RedirectToAction("Index"));
        }
コード例 #25
0
        /// <summary>
        /// 输出错误日志到NLog
        /// </summary>
        /// <param name="t"></param>
        /// <param name="ex"></param>
        #region static void WriteLog( Exception ex)

        public static void WriteLog(Type t, Exception ex)
        {
            try
            {
                NLog.Logger log = LogManager.GetCurrentClassLogger(t);
                log.Error(ex.Message.ToString());
            }
            catch (System.Exception ex1)
            {
            }
        }
コード例 #26
0
ファイル: Logger.cs プロジェクト: mauriciogentile/reconfig
 public void Error(string message, Exception exc = null)
 {
     if (exc == null)
     {
         InternalLogger.Error(message);
     }
     else
     {
         InternalLogger.ErrorException(message, exc);
     }
 }
コード例 #27
0
        /// <summary>
        /// Сохранение сущности в RX.
        /// </summary>
        /// <param name="shift">Сдвиг по горизонтали в XLSX документе. Необходим для обработки документов, составленных из элементов разных сущностей.</param>
        /// <param name="logger">Логировщик.</param>
        /// <returns>Число запрашиваемых параметров.</returns>
        public override IEnumerable <Structures.ExceptionsStruct> SaveToRX(NLog.Logger logger, int shift = 0)
        {
            var exceptionList = new List <Structures.ExceptionsStruct>();

            using (var session = new Session())
            {
                var name = this.Parameters[shift + 0].Trim();
                if (string.IsNullOrEmpty(name))
                {
                    var message = string.Format("Не заполнено поле \"Наименование\".");
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = Constants.ErrorTypes.Error, Message = message
                    });
                    logger.Error(message);
                    return(exceptionList);
                }
                var shortName    = this.Parameters[shift + 1].Trim();
                var code         = this.Parameters[shift + 2].Trim();
                var businessUnit = BusinessLogic.GetBusinessUnit(session, this.Parameters[shift + 3].Trim(), exceptionList, logger);
                var headOffice   = BusinessLogic.GetDepartment(session, this.Parameters[shift + 4].Trim(), exceptionList, logger);
                var manager      = BusinessLogic.GetEmployee(session, this.Parameters[shift + 5].Trim(), exceptionList, logger);
                var phone        = this.Parameters[shift + 6].Trim();
                var note         = this.Parameters[shift + 7].Trim();

                try
                {
                    var departments = Enumerable.ToList(session.GetAll <Sungero.Company.IDepartment>().Where(x => x.Name == name));
                    var department  = (Enumerable.FirstOrDefault <Sungero.Company.IDepartment>(departments));
                    if (department == null)
                    {
                        department = session.Create <Sungero.Company.IDepartment>();
                    }

                    department.Name         = name;
                    department.ShortName    = shortName;
                    department.Code         = code;
                    department.BusinessUnit = businessUnit;
                    department.HeadOffice   = headOffice;
                    department.Manager      = manager;
                    department.Phone        = phone;
                    department.Note         = note;
                    department.Save();
                }
                catch (Exception ex)
                {
                    exceptionList.Add(new Structures.ExceptionsStruct {
                        ErrorType = "Error", Message = ex.Message
                    });
                    return(exceptionList);
                }
                session.SubmitChanges();
            }
            return(exceptionList);
        }
コード例 #28
0
        public Form1()
        {
            InitializeComponent();

            dataGridView1.SelectionMode      = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.ReadOnly           = true;
            var connection = new SqlConnection(connectionString);

            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings.Add(

                    new ConnectionStringSettings("ConnectionStr", "SomeConnectionString")
                    );
                config.Save();
                ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;

                if (section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.UnprotectSection();
                }
                else
                {
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                }

                config.Save();

                connection.Open();
                adapter = new SqlDataAdapter(strcom, connection);

                ds = new DataSet();
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                // делаем недоступным столбец id для изменения
                dataGridView1.Columns["Id"].ReadOnly = true;
            }
            catch
            {
                NLog.Logger logger = LogManager.GetCurrentClassLogger();
                logger.Trace("trace message");
                logger.Debug("debug message");
                logger.Info("info message");
                logger.Warn("warn message");
                logger.Error("error message");
                logger.Fatal("fatal message");
            }
            finally
            {
                connection.Close();
            }
        }
コード例 #29
0
        public override Variant CalculateFromValue()
        {
            if (_isRecursing)
            {
                return(new Variant(0));
            }

            try
            {
                if (Of == null)
                {
                    logger.Error("Error, Of returned null");
                    return(null);
                }

                _isRecursing = true;
                long size = Of.Value.LengthBits;

                if (lengthType == LengthType.Bytes)
                {
                    if (_expressionSet != null)
                    {
                        Dictionary <string, object> state = new Dictionary <string, object>();
                        state["size"]  = size / 8;
                        state["value"] = size / 8;
                        state["self"]  = From;

                        object newValue = Scripting.EvalExpression(_expressionSet, state);
                        size = Convert.ToInt64(newValue) * 8;
                    }

                    size = size / 8;
                }
                else
                {
                    if (_expressionSet != null)
                    {
                        Dictionary <string, object> state = new Dictionary <string, object>();
                        state["size"]  = size;
                        state["value"] = size;
                        state["self"]  = From;

                        object newValue = Scripting.EvalExpression(_expressionSet, state);
                        size = Convert.ToInt64(newValue);
                    }
                }

                return(new Variant(size));
            }
            finally
            {
                _isRecursing = false;
            }
        }
コード例 #30
0
 private void ProcessRequest(object sender, TcpRequest req)
 {
     Logger.Trace("Begin ProcessRequest");
     Logger.Info("Requested command: {0}", req.PlayerRequest);
     if (!req.ResponseRequired)
     {
         _commandDictionary[(int)req.PlayerRequest].DynamicInvoke(req.Arguments);
         return;
     }
     try
     {
         var res = _commandDictionary[(int)req.PlayerRequest].DynamicInvoke(req.Arguments);
         _mbTcpHelper.SendResponse(req.PlayerRequest, res);
     }
     catch (Exception e)
     {
         Logger.Error(e, "Sending response failed");
     }
     Logger.Trace("End ProcessRequest");
 }
コード例 #31
0
ファイル: EvnexV2.cs プロジェクト: ankohanse/EVNEX
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////


        private async Task <bool> _Login()
        {
            try
            {
                // Already authenticated?
                if (m_idToken != null &&
                    m_accessToken != null &&
                    m_refreshToken != null)
                {
                    return(true);
                }

                // Autheticate to Amazon to get access token
                AWSCredentials credentials = new Amazon.Runtime.AnonymousAWSCredentials();
                string         systemName  = COGNITO_USER_POOL_ID.Split('_')[0];
                RegionEndpoint region      = RegionEndpoint.GetBySystemName(systemName);
                using (IAmazonCognitoIdentityProvider provider = new AmazonCognitoIdentityProviderClient(credentials, region))
                {
                    CognitoUserPool userPool = new CognitoUserPool(COGNITO_USER_POOL_ID, COGNITO_CLIENT_ID, provider);
                    CognitoUser     user     = new CognitoUser(m_evnexUsername, COGNITO_CLIENT_ID, userPool, provider);

                    InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                    {
                        Password = m_evnexPassword
                    };

                    AuthFlowResponse response = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                    m_idToken      = response.AuthenticationResult.IdToken;
                    m_accessToken  = response.AuthenticationResult.AccessToken;
                    m_refreshToken = response.AuthenticationResult.RefreshToken;
                }
                logger.Info("EvnexV2 Login succeeded");
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "EvnexV2 Login failed. " + ex.Message);
            }
            return(false);
        }
コード例 #32
0
        /// <summary>
        /// Calculates and returns the factorial of the input integer
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>


        public static int Factorial(int input)
        {
            logger.Trace($"calculating: {input}");
            try
            {
                if (input < 1)
                {
                    throw new NumberTooLowException(input);
                }
                if (input > 30)
                {
                    throw new NumberTooHighException(input);
                }

                int result = input;
                for (int i = input - 1; i > 1; i--)
                {
                    result *= i;
                }
                return(result);
            }
            catch (NumberTooLowException ex)
            {
                logger.Debug($"v too low: {input}");
                throw ex;
            }
            catch (NumberTooHighException ex)
            {
                logger.Debug($"Value too high: {input}");
                throw ex;
            }
            catch (Exception ex)
            {
                logger.Error($"message unknown error msg: {ex.Message}");
                throw ex;
            }


            // this method should:

            // return the factorial of the integer enetered (or a recursive step toward it)
            // in this normal operation, every step / recursion should be logged (Trace) in the following format
            // (if for example an input of 5 was received)
            // "Calcuator.Factorial: calculating: 5"

            // if the number entered is < 1 this should throw a NumberTooLowException.
            // if this occurs it should be logged (Debug) with the message as below:
            // "Calcuator.Factorial: input too low: -5"

            // if the number entered is >30 this should throw a NumberTooHighException.
            // if this occurs it should be logged (Debug) with the message as below:
            // "Calcuator.Factorial: input too high: 45"
        }
コード例 #33
0
        private void Awake()
        {
            var player = GetComponentInParent <Player>();

            if (player == null)
            {
                Logger.Error($"Cannot find player for step rotator {name}.");
                return;
            }

            player.RegisterStepRotator(this);
        }
コード例 #34
0
 public static IList<PriorityType> GetAllPriorityType(this AmarisEntities db, Logger log)
 {
     try
     {
         return db.PriorityTypes.ToList();
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return new List<PriorityType>();
     }
 }
コード例 #35
0
 public static IList<PriorityType> GetAllPriorityType(this AmarisEntities db, Logger log, bool isDeleted)
 {
     try
     {
         return db.PriorityTypes.Where(x => x.IsDeleted == isDeleted).ToList();
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return new List<PriorityType>();
     }
 }
コード例 #36
0
        public int convertStringToInt(string name, string source, Logger logger)
        {
            if (source == null)
            {
                logger.Error("Error: " + name + " Is Null, Check config file.");
                m_logAndErr.errorPopup("Config error", "Error: " + name + " is null, check config file.");

                return 0;
            }

            return Convert.ToInt32(source);
        }
コード例 #37
0
 public void Fill(SPClientContext clientContext, Logger logger)
 {
     if (logger != null)
     {
         _viewModel.FailEvent += (senser, e) => Dispatcher.Invoke(() => logger.Error(e.Exception.Message));
     }
     //if (IsMulti)
     //{
     _viewModel.Add(clientContext);
     DataContext = _viewModel;
     //}
 }
コード例 #38
0
 private void FindMaxIdFromSql()
 {
     if (idMaxSql == 0)
     {
         using (var db = new SqlContext())
         {
             statusConnSql = true;
             try
             {
                 // find MAX ID in the SQL
                 idMaxSql = db.model_dateTime.Max(p => p.Id_DateTime);
             }
             catch (Exception ex)
             {
                 logger.Error(ex.Message, "FindMaxIdFromSql() --> idMaxSql");
                 Thread.Sleep(Properties.Settings.Default.timerException);
                 statusConnSql = false;
             }
         }
     }
 }
コード例 #39
0
ファイル: Helper.cs プロジェクト: RobboVariwn/VarBot
        public static bool IsResponseGood(ResponseApi requestResponse)
        {
            if (requestResponse.Status != "error")
            {
                return(true);
            }

            _logger.Error($"Response has error! {requestResponse.Message}");
            VRErrorManager.Instance.Show(requestResponse.Message);

            return(false);
        }
コード例 #40
0
ファイル: Logger.cs プロジェクト: kasik1/PlaywrightSharp
        private void Log(string log, LogLevel level = LogLevel.INFO)
        {
            switch (level)
            {
            case LogLevel.DEBUG:
                logger.Debug(log);
                break;

            case LogLevel.ERROR:
                logger.Error(log);
                break;

            case LogLevel.WARN:
                logger.Warn(log);
                break;

            default:
                logger.Info(log);
                break;
            }
        }
コード例 #41
0
ファイル: MSWText.cs プロジェクト: paColor/Colorization
        private static void ErrorMsgACTR(CharFormatting cf, Range toR, string msg, Exception e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Ouups, désolé. Un problème vient de se produire avec la mise en ");
            sb.Append(msg);
            sb.AppendLine(".");
            sb.Append("Si vous utilisez un ancien format de fichier (par ex. \'.doc\"), il est ");
            sb.AppendLine("possible que la fonctionalité ne soit pas disponible.");
            sb.Append("Texte: \'");
            sb.Append(toR.Text);
            sb.Append("\' cf: ");
            sb.AppendLine(cf.ToString());
            sb.Append("N'hésitez pas à nous ");
            sb.AppendLine("envoyer une description de votre problème à [email protected].");
            sb.AppendLine(e.Message);
            sb.AppendLine(e.StackTrace);
            logger.Error(sb.ToString());
            MessageBox.Show(sb.ToString(), ConfigBase.ColorizationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            Debug.Assert(false);
        }
コード例 #42
0
 public IList<DeadlineType> GetAllDeadlineType(AmarisEntities db, Logger log, bool isDeleted)
 {
     try
     {
         return db.DeadlineTypes.Where(x => x.IsDeleted == isDeleted).ToList();
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return new List<DeadlineType>();
     }
 }
コード例 #43
0
 public static IEnumerable<Priority> GetAllPriority(this AmarisEntities db, Logger log)
 {
     try
     {
         return db.Priorities;
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return null;
     }
 }
コード例 #44
0
 // w tym przypadku wyjątkowo musimy pozostawić void zamiast Task
 // bo nie będziemy mogli się podpiąć do _timer.Elapsed
 private async void DoWork(object sender, ElapsedEventArgs e)
 {
     try
     {
         await SendError();
     }
     catch (Exception ex)
     {
         Logger.Error(ex, ex.Message);
         throw new Exception(ex.Message);
     }
 }
コード例 #45
0
 public void writeToFile(string[] dataLine, string fileName)
 {
     try {
         StreamWriter sw      = new StreamWriter(fileName, true);
         string       newLine = string.Join(",", dataLine);
         sw.WriteLine(newLine);
         sw.Close();
     } catch (Exception e) {
         logger.Error(e.Message);
         Console.WriteLine(e);
     }
 }
コード例 #46
0
 public static IEnumerable<Priority> GetAllPriority(this DbSet<Priority> priorities, Logger log, bool isDeleted)
 {
     try
     {
         return priorities
             .Where(x => x.IsDeleted == isDeleted);
     }
     catch (Exception ex)
     {
         log.Error(ex);
         return null;
     }
 }
コード例 #47
0
 static public void LogFailure(this ElasticsearchResponse<string> response, Logger logger, string message = "")
 {
     if (string.IsNullOrEmpty(message))
         message = "request failed";
     
     logger.Error("{0}: {1}, {2}, {3}, {4}, {5}, '{6}'; request={7}", 
         message, 
         response.HttpStatusCode,
         response.RequestMethod,
         response.RequestUrl,
         response.ServerError,
         response.OriginalException,
         response.Response,
         System.Text.Encoding.Default.GetString(response.Request));
 }
コード例 #48
0
ファイル: RegistryBase.cs プロジェクト: seandiviney/Registry
        public RegistryBase(byte[] rawBytes)
        {
            FileBytes = rawBytes;
            HivePath = "None";

          _logger=  LogManager.GetLogger("rawBytes");

            if (!HasValidSignature())
            {
                _logger.Error("Data in byte array is not a Registry hive (bad signature)");

                throw new ArgumentException("Data in byte array is not a Registry hive (bad signature)");
            }

            Initialize();
        }
コード例 #49
0
ファイル: ConsulAgent.cs プロジェクト: jango2015/Consulate
 public ConsulAgent(string consulPath, ConsulConfig config, Process consulProcess)
 {
     _consulPath = consulPath;
     _config = config;
     _logger = LogManager.GetLogger(typeof(ConsulAgent).FullName + ":PID" + consulProcess.Id);
     _consulProcess = consulProcess;
     _consulProcess.Exited += (_, __) =>
     {
         _logger.Info("Shutdown");
     };
     _consulProcess.ErrorDataReceived += (s, a) =>
     {
         _logger.Error(a.Data);
     };
     _consulProcess.OutputDataReceived += (s2, a2) =>
     {
         _logger.Info(a2.Data);
     };
     _consulProcess.BeginErrorReadLine();
     _consulProcess.BeginOutputReadLine();
 }
コード例 #50
0
        static void Main(string[] args)
        {            
            ConfigurationItemFactory.Default.Targets.RegisterDefinition("SignalTarget", typeof(SignalTarget));
            Logger = LogManager.GetCurrentClassLogger(typeof(SignalTarget));
            var rnd = new Random((int)DateTime.Now.Ticks);

            for (int i = 0; i < 100; i++) {
                Logger.Trace("Sample trace message from NLog");
                Logger.Debug("Sample debug message from NLog");
                Logger.Info("Sample informational message from NLog");
                Logger.Warn("Sample warning message from NLog");
                Logger.Error("Sample error message from NLog", new Exception("Something bad happened!"));
                Logger.Fatal("Sample fatal error message from NLog");

                var sleep = rnd.Next(20, 250);
                Console.WriteLine(string.Concat("Sleeping...:", sleep, "ms"));
                Thread.Sleep(sleep);
            }

            Console.WriteLine("Logging Complete. Press enter to continue...");
            Console.ReadLine();
        }
コード例 #51
0
ファイル: RegistryBase.cs プロジェクト: seandiviney/Registry
        public RegistryBase(string hivePath)
        {
            if (hivePath == null)
            {
                throw new ArgumentNullException("hivePath cannot be null");
            }

            if (!File.Exists(hivePath))
            {
                throw new FileNotFoundException();
            }

            var fileStream = new FileStream(hivePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var binaryReader = new BinaryReader(fileStream);

            binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);

            FileBytes = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);

            binaryReader.Close();
            fileStream.Close();

            _logger = LogManager.GetLogger(hivePath);

            if (!HasValidSignature())
            {
                _logger.Error("'{0}' is not a Registry hive (bad signature)", hivePath);

                throw new Exception($"'{hivePath}' is not a Registry hive (bad signature)");
            }

            HivePath = hivePath;

            _logger.Debug("Set HivePath to {0}", hivePath);

            Initialize();
        }
コード例 #52
0
        /// <summary>
        /// Запуск скрипта
        /// </summary>
        private static void ExecuteScript(UserScript script, ScriptHost scriptHost, Logger logger, object[] args)
        {
            //Debugger.Launch();
            try
            {
                //var engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging);
                var engine = new JScriptEngine();
                engine.AddHostObject("host", scriptHost);

                string initArgsScript = string.Format("var arguments = {0};", args.ToJson("[]"));
                engine.Execute(initArgsScript);
                engine.Execute(script.Body);
            }
            catch (Exception ex)
            {
                var messge = string.Format("Error in user script {0}", script.Name);
                logger.Error(ex, messge);
            }
        }
コード例 #53
0
ファイル: Program.cs プロジェクト: EricZimmerman/PECmd
        private static void Main(string[] args)
        {
            Licensing.RegisterLicenseFromFileIfExists(SSLicenseFile);

            SetupNLog();

            _keywords = new HashSet<string> {"temp", "tmp"};

            _logger = LogManager.GetCurrentClassLogger();

            if (!CheckForDotnet46())
            {
                _logger.Warn(".net 4.6 not detected. Please install .net 4.6 and try again.");
                return;
            }

            _fluentCommandLineParser = new FluentCommandLineParser<ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.File)
                .As('f')
                .WithDescription("File to process. Either this or -d is required");

            _fluentCommandLineParser.Setup(arg => arg.Directory)
                .As('d')
                .WithDescription("Directory to recursively process. Either this or -f is required");

            _fluentCommandLineParser.Setup(arg => arg.Keywords)
                .As('k')
                .WithDescription(
                    "Comma separated list of keywords to highlight in output. By default, 'temp' and 'tmp' are highlighted. Any additional keywords will be added to these.");

            _fluentCommandLineParser.Setup(arg => arg.Quiet)
                .As('q')
                .WithDescription(
                    "Do not dump full details about each file processed. Speeds up processing when using --json or --csv\r\n")
                .SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
                .As("json")
                .WithDescription(
                    "Directory to save json representation to. Use --pretty for a more human readable layout");

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
                .As("csv")
                .WithDescription(
                    "Directory to save CSV (tab separated) results to. Be sure to include the full path in double quotes");

//            _fluentCommandLineParser.Setup(arg => arg.XmlDirectory)
//               .As("xml")
//               .WithDescription(
//                   "Directory to save XML formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.xHtmlDirectory)
                .As("html")
                .WithDescription(
                    "Directory to save xhtml formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.JsonPretty)
                .As("pretty")
                .WithDescription(
                    "When exporting to json, use a more human readable layout\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.LocalTime)
                .As("local")
                .WithDescription(
                    "Display dates using timezone of machine PECmd is running on vs. UTC\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
.As("dt")
.WithDescription(
  "The custom date/time format to use when displaying time stamps. Default is: yyyy-MM-dd HH:mm:ss K").SetDefault("yyyy-MM-dd HH:mm:ss K");

            _fluentCommandLineParser.Setup(arg => arg.PreciseTimestamps)
   .As("mp")
   .WithDescription(
       "When true, display higher precision for time stamps. Default is false").SetDefault(false);


            var header =
                $"PECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
                "\r\nhttps://github.com/EricZimmerman/PECmd";

            var footer = @"Examples: PECmd.exe -f ""C:\Temp\CALC.EXE-3FBEF7FD.pf""" + "\r\n\t " +
                         @" PECmd.exe -f ""C:\Temp\CALC.EXE-3FBEF7FD.pf"" --json ""D:\jsonOutput"" --jsonpretty" +
                         "\r\n\t " +
                         @" PECmd.exe -d ""C:\Temp"" -k ""system32, fonts""" + "\r\n\t " +
                         @" PECmd.exe -d ""C:\Temp"" --csv ""c:\temp"" --local --json c:\temp\json" +
                         "\r\n\t " +
//                         @" PECmd.exe -f ""C:\Temp\someOtherFile.txt"" --lr cc -sa" + "\r\n\t " +
//                         @" PECmd.exe -f ""C:\Temp\someOtherFile.txt"" --lr cc -sa -m 15 -x 22" + "\r\n\t " +
                         @" PECmd.exe -d ""C:\Windows\Prefetch""" + "\r\n\t " +
                         "\r\n\t" +
                         "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
                .WithHeader(header)
                .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) &&
                UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory))
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("Either -f or -d is required. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) == false &&
                !File.Exists(_fluentCommandLineParser.Object.File))
            {
                _logger.Warn($"File '{_fluentCommandLineParser.Object.File}' not found. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory) == false &&
                !Directory.Exists(_fluentCommandLineParser.Object.Directory))
            {
                _logger.Warn($"Directory '{_fluentCommandLineParser.Object.Directory}' not found. Exiting");
                return;
            }

            if (_fluentCommandLineParser.Object.Keywords?.Length > 0)
            {
                var kws = _fluentCommandLineParser.Object.Keywords.Split(new[] {','},
                    StringSplitOptions.RemoveEmptyEntries);

                foreach (var kw in kws)
                {
                    _keywords.Add(kw.Trim());
                }
            }



            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}");
            _logger.Info("");
            _logger.Info($"Keywords: {string.Join(", ", _keywords)}");
            _logger.Info("");

            if (_fluentCommandLineParser.Object.PreciseTimestamps)
            {
                _fluentCommandLineParser.Object.DateTimeFormat = _preciseTimeFormat;
            }

            _processedFiles = new List<IPrefetch>();

            _failedFiles = new List<string>();

            if (_fluentCommandLineParser.Object.File?.Length > 0)
            {
                IPrefetch pf = null;

                try
                {
                    pf = LoadFile(_fluentCommandLineParser.Object.File);
                    if (pf != null)
                    {
                        _processedFiles.Add(pf);
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.File}'. Are you running as an administrator? Error: {ex.Message}");
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting prefetch files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                }
            }
            else
            {
                _logger.Info($"Looking for prefetch files in '{_fluentCommandLineParser.Object.Directory}'");
                _logger.Info("");

                string[] pfFiles = null;

              

                try
                {
                    pfFiles = Directory.GetFiles(_fluentCommandLineParser.Object.Directory, "*.pf",
                        SearchOption.AllDirectories);
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.Directory}'. Are you running as an administrator? Error: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting prefetch files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                    return;
                }

                _logger.Info($"Found {pfFiles.Length:N0} Prefetch files");
                _logger.Info("");

                var sw = new Stopwatch();
                sw.Start();

                foreach (var file in pfFiles)
                {
                    var pf = LoadFile(file);
                    if (pf != null)
                    {
                        _processedFiles.Add(pf);
                    }
                }

                sw.Stop();

                if (_fluentCommandLineParser.Object.Quiet)
                {
                    _logger.Info("");
                }

                _logger.Info(
                    $"Processed {pfFiles.Length - _failedFiles.Count:N0} out of {pfFiles.Length:N0} files in {sw.Elapsed.TotalSeconds:N4} seconds");

                if (_failedFiles.Count > 0)
                {
                    _logger.Info("");
                    _logger.Warn("Failed files");
                    foreach (var failedFile in _failedFiles)
                    {
                        _logger.Info($"  {failedFile}");
                    }
                }

            }

            if (_processedFiles.Count > 0)
            {
                _logger.Info("");

                try
                {
                    CsvWriter csv = null;
                    StreamWriter streamWriter = null;

                    CsvWriter csvTl = null;
                    StreamWriter streamWriterTl = null;


                    if (_fluentCommandLineParser.Object.CsvDirectory?.Length > 0)
                    {
                        var outName = $"{DateTimeOffset.Now.ToString("yyyyMMddHHmmss")}_PECmd_Output.tsv";
                        var outNameTl = $"{DateTimeOffset.Now.ToString("yyyyMMddHHmmss")}_PECmd_Output_Timeline.tsv";
                        var outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);
                        var outFileTl = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outNameTl);


                        if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                        {
                            _logger.Warn($"Path to '{_fluentCommandLineParser.Object.CsvDirectory}' doesn't exist. Creating...");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                        }

                        _logger.Warn($"CSV (tab separated) output will be saved to '{outFile}'");
                        _logger.Warn($"CSV time line (tab separated) output will be saved to '{outFileTl}'");

                        try
                        {
                            streamWriter = new StreamWriter(outFile);
                            csv = new CsvWriter(streamWriter);
                            csv.Configuration.Delimiter = $"{'\t'}";
                            csv.WriteHeader(typeof(CsvOut));

                            streamWriterTl = new StreamWriter(outFileTl);
                            csvTl = new CsvWriter(streamWriterTl);
                            csvTl.Configuration.Delimiter = $"{'\t'}";
                            csvTl.WriteHeader(typeof(CsvOutTl));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Unable to open '{outFile}' for writing. CSV export canceled. Error: {ex.Message}");
                        }
                    }

                    if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                    {
                        _logger.Warn($"Saving json output to '{_fluentCommandLineParser.Object.JsonDirectory}'");
                    }

                    XmlTextWriter xml = null;

                    if (_fluentCommandLineParser.Object.xHtmlDirectory?.Length > 0)
                    {
                        var outDir = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory,
                            $"{DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss")}_PECmd_Output_for_{_fluentCommandLineParser.Object.xHtmlDirectory.Replace(@":\", "_").Replace(@"\", "_")}");

                        if (Directory.Exists(outDir) == false)
                        {
                            Directory.CreateDirectory(outDir);
                        }

                        var styleDir = Path.Combine(outDir, "styles");
                        if (Directory.Exists(styleDir) == false)
                        {
                            Directory.CreateDirectory(styleDir);
                        }

                        File.WriteAllText(Path.Combine(styleDir, "normalize.css"), Resources.normalize);
                        File.WriteAllText(Path.Combine(styleDir, "style.css"), Resources.style);

                        Resources.directories.Save(Path.Combine(styleDir, "directories.png"));
                        Resources.filesloaded.Save(Path.Combine(styleDir, "filesloaded.png"));

                        var outFile = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory, outDir,
                            "index.xhtml");

                        _logger.Warn($"Saving HTML output to '{outFile}'");

                        xml = new XmlTextWriter(outFile, Encoding.UTF8)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 4
                        };

                        xml.WriteStartDocument();

                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"styles/normalize.css\"");
                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"styles/style.css\"");

                        xml.WriteStartElement("document");
                    }

                    foreach (var processedFile in _processedFiles)
                    {
                        var o = GetCsvFormat(processedFile);

                        try
                        {
                            foreach (var dateTimeOffset in processedFile.LastRunTimes)
                            {
                                var t = new CsvOutTl();

                                var exePath =
                                    processedFile.Filenames.FirstOrDefault(
                                        y => y.EndsWith(processedFile.Header.ExecutableFilename));

                                if (exePath == null)
                                {
                                    exePath = processedFile.Header.ExecutableFilename;
                                }

                                t.ExecutableName = exePath;
                                t.RunTime = dateTimeOffset.ToString(_fluentCommandLineParser.Object.DateTimeFormat);

                                csvTl?.WriteRecord(t);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Error getting time line record for '{processedFile.SourceFilename}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");

                        }

                        try
                        {
                            csv?.WriteRecord(o);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Error writing CSV record for '{processedFile.SourceFilename}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");
                        }

                        if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                        {
                            SaveJson(processedFile, _fluentCommandLineParser.Object.JsonPretty,
                                _fluentCommandLineParser.Object.JsonDirectory);
                        }

                        //XHTML
                        xml?.WriteStartElement("Container");
                        xml?.WriteElementString("SourceFile", o.SourceFilename);
                        xml?.WriteElementString("SourceCreated", o.SourceCreated);
                        xml?.WriteElementString("SourceModified", o.SourceModified);
                        xml?.WriteElementString("SourceAccessed", o.SourceAccessed);

                        xml?.WriteElementString("LastRun", o.LastRun);

                        xml?.WriteElementString("PreviousRun0", $"{o.PreviousRun0}");
                        xml?.WriteElementString("PreviousRun1", $"{o.PreviousRun1}");
                        xml?.WriteElementString("PreviousRun2", $"{o.PreviousRun2}");
                        xml?.WriteElementString("PreviousRun3", $"{o.PreviousRun3}");
                        xml?.WriteElementString("PreviousRun4", $"{o.PreviousRun4}");
                        xml?.WriteElementString("PreviousRun5", $"{o.PreviousRun5}");
                        xml?.WriteElementString("PreviousRun6", $"{o.PreviousRun6}");

                        xml?.WriteStartElement("ExecutableName");
                        xml?.WriteAttributeString("title", "Note: The name of the executable tracked by the pf file");
                        xml?.WriteString(o.ExecutableName);
                        xml?.WriteEndElement();

                        xml?.WriteElementString("RunCount", $"{o.RunCount}");

                        xml?.WriteStartElement("Size");
                        xml?.WriteAttributeString("title", "Note: The size of the executable in bytes");
                        xml?.WriteString(o.Size);
                        xml?.WriteEndElement();

                        xml?.WriteStartElement("Hash");
                        xml?.WriteAttributeString("title", "Note: The calculated hash for the pf file that should match the hash in the source file name");
                        xml?.WriteString(o.Hash);
                        xml?.WriteEndElement();

                        xml?.WriteStartElement("Version");
                        xml?.WriteAttributeString("title", "Note: The operating system that generated the prefetch file");
                        xml?.WriteString(o.Version);
                        xml?.WriteEndElement();

                        xml?.WriteElementString("Note", o.Note);

                        xml?.WriteElementString("Volume0Name", o.Volume0Name);
                        xml?.WriteElementString("Volume0Serial", o.Volume0Serial);
                        xml?.WriteElementString("Volume0Created", o.Volume0Created);

                        xml?.WriteElementString("Volume1Name", o.Volume1Name);
                        xml?.WriteElementString("Volume1Serial", o.Volume1Serial);
                        xml?.WriteElementString("Volume1Created", o.Volume1Created);


                        xml?.WriteStartElement("Directories");
                        xml?.WriteAttributeString("title", "A comma separated list of all directories accessed by the executable");
                        xml?.WriteString(o.Directories);
                        xml?.WriteEndElement();

                        xml?.WriteStartElement("FilesLoaded");
                        xml?.WriteAttributeString("title", "A comma separated list of all files that were loaded by the executable");
                        xml?.WriteString(o.FilesLoaded);
                        xml?.WriteEndElement();

                        xml?.WriteEndElement();

                    }


                    //Close CSV stuff
                    streamWriter?.Flush();
                    streamWriter?.Close();

                    streamWriterTl?.Flush();
                    streamWriterTl?.Close();

                    //Close XML
                    xml?.WriteEndElement();
                    xml?.WriteEndDocument();
                    xml?.Flush();
                }
                catch (Exception ex)
                {
                    _logger.Error($"Error exporting data! Error: {ex.Message}");
                }
            }
        }
コード例 #54
0
ファイル: LogHelper.cs プロジェクト: 3guy/GameTrans
 private static void DoWrite(Logger logger, LogLevel level, string message)
 {
     switch (level)
     {
         case LogLevel.Debug:
             logger.Debug(message);
             break;
         case LogLevel.Info:
             logger.Info(message);
             break;
         case LogLevel.Trace:
             logger.Trace(message);
             break;
         case LogLevel.Error:
         default:
             logger.Error(message);
             break;
     }
 }
コード例 #55
0
        private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey)
        {
            aiLogger.Trace("Sample trace message");
            aiLogger.Debug("Sample debug message");
            aiLogger.Info("Sample informational message");
            aiLogger.Warn("Sample warning message");
            aiLogger.Error("Sample error message");
            aiLogger.Fatal("Sample fatal error message");

            AdapterHelper.ValidateChannel(this.adapterHelper, instrumentationKey, 6);
        }
コード例 #56
0
ファイル: App.xaml.cs プロジェクト: growse/Feedling
 static void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     Log = LogManager.GetCurrentClassLogger();
     Log.Error("Exception thrown by application", e.Exception);
 }
コード例 #57
0
ファイル: ServiceRunner.cs プロジェクト: c0d3m0nky/mty
        private static void VerifyConfiguration(Logger log)
        {
            bool isValid = true;

            if (Settings.DownloaderBatchWaitTime < 0)
            {
                log.Error("Service setting \"DownloaderTimerInterval\" needs a value of 0 or more.");
                isValid = false;
            }

            if (Settings.ParserBatchWaitTime < 0)
            {
                log.Error("Service setting \"ParserTimerInterval\" needs a value of 0 or more.");
                isValid = false;
            }

            if (Settings.ParserProcessingDelay < 0)
            {
                log.Error("Service setting \"ParserProcessingDelay\" needs a value of 0 or more.");
                isValid = false;
            }

            if (string.IsNullOrWhiteSpace(Settings.Passphrase))
            {
                log.Error("Service setting \"Passphrase\" needs a value.");
                isValid = false;
            }

            if (string.IsNullOrWhiteSpace(Settings.WorkingDirectory))
            {
                log.Error("Service setting \"WorkingDirectory\" needs a value.");
                isValid = false;
            }
            else
            {
                if (!Directory.Exists(Settings.WorkingDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(Settings.WorkingDirectory);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Failed to create working directory " + Settings.WorkingDirectory);
                        log.Error(ex.UnwrapForLog(Settings.LogVerbose));
                        isValid = false;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(Settings.ArchiveDirectory))
            {
                log.Error("Service setting \"ArchiveDirectory\" needs a value.");
                isValid = false;
            }
            else
            {
                if (!Directory.Exists(Settings.ArchiveDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(Settings.ArchiveDirectory);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Failed to create archive directory " + Settings.ArchiveDirectory);
                        log.Error(ex.UnwrapForLog(Settings.LogVerbose));
                        isValid = false;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(Settings.ErrorDirectory))
            {
                log.Error("Service setting \"ErrorDirectory\" needs a value.");
                isValid = false;
            }
            else
            {
                if (!Directory.Exists(Settings.ErrorDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(Settings.ErrorDirectory);
                    }
                    catch (Exception ex)
                    {
                        log.Error("Failed to create error directory " + Settings.ErrorDirectory);
                        log.Error(ex.UnwrapForLog(Settings.LogVerbose));
                        isValid = false;
                    }
                }
            }

            if (Settings.PopMaxDownload <= 0)
            {
                isValid = false;
                log.Error("PopMaxDownload must be greater than 0");
            }

            if (Settings.ImapMaxDownload <= 0)
            {
                isValid = false;
                log.Error("ImapMaxDownload needs be greater than 0");
            }

            if (string.IsNullOrWhiteSpace(Settings.ImapFolders))
            {
                log.Error("Service setting \"ImapFolders\" needs a value.");
                isValid = false;
            }

            if (Settings.ServerID < 1)
            {
                isValid = false;
                log.Error("Service setting \"ServerID\" needs a value of 1 or more.");
            }

            if (Settings.MinAccountsBeforeNewIp < 1)
            {
                isValid = false;
                log.Error(string.Format("MinAccountsBeforeNewIp setting must be greater or equal to 1"));
            }

            if (Settings.NewIpWaitSeconds < 30)
            {
                isValid = false;
                log.Error(string.Format("MinAccountsBeforeNewIp setting must be greater or equal to 30"));
            }

            if (Settings.MinSecondsBeforeNewIp < Settings.NewIpWaitSeconds)
            {
                isValid = false;
                log.Error("MinSecondsBeforeNewIp setting must be greater or equal to NewIpWaitSeconds");
            }

            if (Settings.MaxSecondsBeforeNewIp < Settings.MinSecondsBeforeNewIp)
            {
                isValid = false;
                log.Error("MaxSecondsBeforeNewIp setting must be greater or equal to MinSecondsBeforeNewIp");
            }

            if (Settings.NewIpFailureCountBeforeKickInAss < 3)
            {
                isValid = false;
                log.Error("NewIpFailureCountBeforeKickInAss setting must be greater or equal to 3");
            }


            if (!isValid)
                throw new Exception("There were configuration errors, please check service's log");
        }
コード例 #58
0
ファイル: Scheduler.cs プロジェクト: BiYiTuan/FIM-Scheduler
        protected override void OnStart(string[] args)
        {
            if (!string.IsNullOrEmpty(workingDirectory))
            {
                string logConfigurationfile = Path.Combine(workingDirectory, LOG_CONFIG_FILE);
                if (!string.IsNullOrEmpty(logConfigurationfile) && File.Exists(logConfigurationfile))
                {
                    LogManager.Configuration = new XmlLoggingConfiguration(logConfigurationfile);
                    logger = LogManager.GetLogger("");
                    string jobConfigurationFile = Path.Combine(workingDirectory, CONFIG_FILE);
                    if (!string.IsNullOrEmpty(jobConfigurationFile) && File.Exists(jobConfigurationFile))
                    {
                        NameValueCollection properties = new NameValueCollection();
                        properties["quartz.scheduler.instanceName"] = "XmlConfiguredInstance";

                        // set thread pool info
                        properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
                        properties["quartz.threadPool.threadCount"] = "5";
                        properties["quartz.threadPool.threadPriority"] = "Normal";

                        // plugin handles reading xml configuration
                        properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz";
                        properties["quartz.plugin.xml.fileNames"] = jobConfigurationFile;
                        properties["quartz.plugin.xml.scanInterval"] = "120";

                        ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties);
                        logger.Info("Scheduler factory initialized.");
                        scheduler = schedulerFactory.GetScheduler();
                        scheduler.Start();
                        logger.Info("Scheduler started.");
                    }
                    else
                    {
                        logger.Error(string.Format("Job configuration file not found in '{0}' folder.", workingDirectory));
                        throw new Exception("Job configuration file not found.");
                    }
                }
                else
                {
                    throw new Exception("Log configuration file not found.");
                }
            }
            else
            {
                throw new Exception("Working directory not found.");
            }
        }
コード例 #59
0
        public Amcache(string hive, bool recoverDeleted)
        {
            _logger = LogManager.GetCurrentClassLogger();

            var reg = new RegistryHive(hive)
            {
                RecoverDeleted = recoverDeleted
            };
            reg.ParseHive();

            var fileKey = reg.GetKey(@"Root\File");
            var programsKey = reg.GetKey(@"Root\Programs");

            UnassociatedFileEntries = new List<FileEntry>();
            ProgramsEntries = new List<ProgramsEntry>();

            if (fileKey == null || programsKey == null)
            {
                _logger.Error($"Hive does not contain a File and/or Programs key. Processing cannot continue");
                return;
            }

            //First, we get data for all the Program entries under Programs key

            foreach (var registryKey in programsKey.SubKeys)
            {
                var ProgramName0 = "";
                var ProgramVersion1 = "";
                var Guid10 = "";
                var UninstallGuid11 = "";
                var Guid12 = "";
                var Dword13 = 0;
                var Dword14 = 0;
                var Dword15 = 0;
                var UnknownBytes = new byte[0];
                long Qword17 = 0;
                var Dword18 = 0;
                var VenderName2 = "";
                var LocaleID3 = "";
                var Dword5 = 0;
                var InstallSource6 = "";
                var UninstallKey7 = "";
                DateTimeOffset? EpochA = null;
                DateTimeOffset? EpochB = null;
                var PathListd = "";
                var Guidf = "";
                var RawFiles = "";

                try
                {
                    foreach (var value in registryKey.Values)
                    {
                        switch (value.ValueName)
                        {
                            case "0":
                                ProgramName0 = value.ValueData;
                                break;
                            case "1":
                                ProgramVersion1 = value.ValueData;
                                break;
                            case "2":
                                VenderName2 = value.ValueData;
                                break;
                            case "3":
                                LocaleID3 = value.ValueData;
                                break;
                            case "5":
                                Dword5 = int.Parse(value.ValueData);
                                break;
                            case "6":
                                InstallSource6 = value.ValueData;
                                break;
                            case "7":
                                UninstallKey7 = value.ValueData;
                                break;
                            case "a":
                                try
                                {
                                    var seca = long.Parse(value.ValueData);
                                    if (seca > 0)
                                    {
                                        EpochA = DateTimeOffset.FromUnixTimeSeconds(seca).ToUniversalTime();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //sometimes the number is way too big
                                }

                                break;
                            case "b":
                                var seconds = long.Parse(value.ValueData);
                                if (seconds > 0)
                                {
                                    EpochB =
                                        DateTimeOffset.FromUnixTimeSeconds(seconds).ToUniversalTime();
                                }

                                break;
                            case "d":
                                PathListd = value.ValueData;
                                break;
                            case "f":
                                Guidf = value.ValueData;
                                break;
                            case "10":
                                Guid10 = value.ValueData;
                                break;
                            case "11":
                                UninstallGuid11 = value.ValueData;
                                break;
                            case "12":
                                Guid12 = value.ValueData;
                                break;
                            case "13":
                                Dword13 = int.Parse(value.ValueData);
                                break;
                            case "14":
                                Dword13 = int.Parse(value.ValueData);
                                break;
                            case "15":
                                Dword13 = int.Parse(value.ValueData);
                                break;
                            case "16":
                                UnknownBytes = value.ValueDataRaw;
                                break;
                            case "17":
                                Qword17 = long.Parse(value.ValueData);
                                break;
                            case "18":
                                Dword18 = int.Parse(value.ValueData);
                                break;
                            case "Files":
                                RawFiles = value.ValueData;
                                break;
                            default:
                                _logger.Warn(
                                    $"Unknown value name in Program at path {registryKey.KeyPath}: {value.ValueName}");
                                break;
                        }
                    }

                    var pe = new ProgramsEntry(ProgramName0, ProgramVersion1, VenderName2, LocaleID3, InstallSource6,
                        UninstallKey7, Guid10, Guid12, UninstallGuid11, Dword5, Dword13, Dword14, Dword15, UnknownBytes,
                        Qword17, Dword18, EpochA, EpochB, PathListd, Guidf, RawFiles, registryKey.KeyName,
                        registryKey.LastWriteTime.Value);

                    ProgramsEntries.Add(pe);
                }
                catch (Exception ex)
                {
                    _logger.Error($"Error parsing ProgramsEntry at {registryKey.KeyPath}. Error: {ex.Message}");
                    _logger.Error(
                        $"Please send the following text to [email protected]. \r\n\r\nKey data: {registryKey}");
                }
            }

            //For each Programs entry, add the related Files entries from Files\Volume subkey, put the rest in unassociated

            foreach (var registryKey in fileKey.SubKeys)
            {
                //These are the guids for volumes
                foreach (var subKey in registryKey.SubKeys)
                {
                    var prodName = "";
                    int? langId = null;
                    var fileVerString = "";
                    var fileVerNum = "";
                    var fileDesc = "";
                    var compName = "";
                    var fullPath = "";
                    var switchBack = "";
                    var peHash = "";
                    var progID = "";
                    var sha = "";

                    long unknown1 = 0;
                    long unknown2 = 0;
                    var unknown3 = 0;
                    var unknown4 = 0;
                    var unknown5 = 0;
                    var unknown6 = 0;
                    int? fileSize = null;
                    int? peHeaderSize = null;
                    int? peHeaderChecksum = null;

                    DateTimeOffset? created = null;
                    DateTimeOffset? lm = null;
                    DateTimeOffset? lm2 = null;
                    DateTimeOffset? compTime = null;

                    var hasLinkedProgram = false;

                    try
                    {
                        //these are the files executed from the volume
                        foreach (var keyValue in subKey.Values)
                        {
                            var keyVal = int.Parse(keyValue.ValueName, NumberStyles.HexNumber);

                            switch (keyVal)
                            {
                                case ProductName:
                                    prodName = keyValue.ValueData;
                                    break;
                                case CompanyName:
                                    compName = keyValue.ValueData;
                                    break;
                                case FileVersionNumber:
                                    fileVerNum = keyValue.ValueData;
                                    break;
                                case LanguageCode:
                                    langId = int.Parse(keyValue.ValueData);
                                    break;
                                case SwitchBackContext:
                                    switchBack = keyValue.ValueData;
                                    break;
                                case FileVersionString:
                                    fileVerString = keyValue.ValueData;
                                    break;
                                case FileSize:
                                    fileSize = int.Parse(keyValue.ValueData);
                                    break;
                                case PEHeaderSize:
                                    peHeaderSize = int.Parse(keyValue.ValueData);
                                    break;
                                case PEHeaderHash:
                                    peHash = keyValue.ValueData;
                                    break;
                                case PEHeaderChecksum:
                                    peHeaderChecksum = int.Parse(keyValue.ValueData);
                                    break;
                                case Unknown1:
                                    unknown1 = long.Parse(keyValue.ValueData);
                                    break;
                                case Unknown2:
                                    unknown2 = long.Parse(keyValue.ValueData);
                                    break;
                                case FileDescription:
                                    fileDesc = keyValue.ValueData;
                                    break;
                                case Unknown3:
                                    unknown3 = int.Parse(keyValue.ValueData);
                                    break;
                                case CompileTime:
                                    compTime =
                                        DateTimeOffset.FromUnixTimeSeconds(long.Parse(keyValue.ValueData))
                                            .ToUniversalTime();
                                    break;
                                case Unknown4:
                                    unknown4 = int.Parse(keyValue.ValueData);
                                    break;
                                case LastModified:
                                    lm = DateTimeOffset.FromFileTime(long.Parse(keyValue.ValueData)).ToUniversalTime();
                                    break;
                                case Created:
                                    created =
                                        DateTimeOffset.FromFileTime(long.Parse(keyValue.ValueData)).ToUniversalTime();
                                    break;
                                case FullPath:
                                    fullPath = keyValue.ValueData;
                                    break;
                                case Unknown5:
                                    unknown5 = int.Parse(keyValue.ValueData);
                                    break;
                                case Unknown6:
                                    unknown6 = int.Parse(keyValue.ValueData);
                                    break;
                                case LastModified2:
                                    lm2 = DateTimeOffset.FromFileTime(long.Parse(keyValue.ValueData)).ToUniversalTime();
                                    break;
                                case ProgramID:
                                    progID = keyValue.ValueData;

                                    var program = ProgramsEntries.SingleOrDefault(t => t.ProgramID == progID);
                                    if (program != null)
                                    {
                                        hasLinkedProgram = true;
                                    }

                                    break;
                                case SHA1:
                                    sha = keyValue.ValueData;
                                    break;
                                default:
                                    _logger.Warn(
                                        $"Unknown value name when processing FileEntry at path '{subKey.KeyPath}': 0x{keyVal:X}");
                                    break;
                            }
                        }

                        if (fullPath.Length == 0)
                        {
                            continue;
                        }

                        TotalFileEntries += 1;

                        var fe = new FileEntry(prodName, progID, sha, fullPath, lm2, registryKey.KeyName,
                            registryKey.LastWriteTime.Value, subKey.KeyName, subKey.LastWriteTime.Value,
                            unknown5, compName, langId, fileVerString, peHash, fileVerNum, fileDesc, unknown1, unknown2,
                            unknown3, unknown4, switchBack, fileSize, compTime, peHeaderSize,
                            lm, created, peHeaderChecksum, unknown6, subKey.KeyName);

                        if (hasLinkedProgram)
                        {
                            var program = ProgramsEntries.SingleOrDefault(t => t.ProgramID == fe.ProgramID);
                            fe.ProgramName = program.ProgramName_0;
                            program.FileEntries.Add(fe);
                        }
                        else
                        {
                            fe.ProgramName = "Unassociated";
                            UnassociatedFileEntries.Add(fe);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"Error parsing FileEntry at {subKey.KeyPath}. Error: {ex.Message}");
                        _logger.Error(
                            $"Please send the following text to [email protected]. \r\n\r\nKey data: {subKey}");
                    }
                }
            }
        }
コード例 #60
-1
ファイル: Program.cs プロジェクト: EricZimmerman/LECmd
        private static void Main(string[] args)
        {
            Licensing.RegisterLicenseFromFileIfExists(SSLicenseFile);

            LoadMACs();

            SetupNLog();

            _logger = LogManager.GetCurrentClassLogger();

            if (!CheckForDotnet46())
            {
                _logger.Warn(".net 4.6 not detected. Please install .net 4.6 and try again.");
                return;
            }

            _fluentCommandLineParser = new FluentCommandLineParser<ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.File)
                .As('f')
                .WithDescription("File to process. Either this or -d is required");

            _fluentCommandLineParser.Setup(arg => arg.Directory)
                .As('d')
                .WithDescription("Directory to recursively process. Either this or -f is required");

            _fluentCommandLineParser.Setup(arg => arg.AllFiles)
                .As("all")
                .WithDescription(
                    "Process all files in directory vs. only files matching *.lnk\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
                .As("csv")
                .WithDescription(
                    "Directory to save CSV (tab separated) formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.XmlDirectory)
                .As("xml")
                .WithDescription(
                    "Directory to save XML formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.xHtmlDirectory)
                .As("html")
                .WithDescription(
                    "Directory to save xhtml formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
                .As("json")
                .WithDescription(
                    "Directory to save json representation to. Use --pretty for a more human readable layout");

            _fluentCommandLineParser.Setup(arg => arg.JsonPretty)
                .As("pretty")
                .WithDescription(
                    "When exporting to json, use a more human readable layout\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.Quiet)
                .As('q')
                .WithDescription(
                    "Only show the filename being processed vs all output. Useful to speed up exporting to json and/or csv\r\n")
                .SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.NoTargetIDList)
                .As("nid")
                .WithDescription(
                    "Suppress Target ID list details from being displayed. Default is false.").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.NoExtraBlocks)
                .As("neb")
                .WithDescription(
                    "Suppress Extra blocks information from being displayed. Default is false.\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
            .As("dt")
            .WithDescription(
            "The custom date/time format to use when displaying time stamps. Default is: yyyy-MM-dd HH:mm:ss K").SetDefault("yyyy-MM-dd HH:mm:ss K");

            _fluentCommandLineParser.Setup(arg => arg.PreciseTimestamps)
               .As("mp")
               .WithDescription(
               "Display higher precision for time stamps. Default is false").SetDefault(false);

            var header =
                $"LECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
                "\r\nhttps://github.com/EricZimmerman/LECmd";

            var footer = @"Examples: LECmd.exe -f ""C:\Temp\foobar.lnk""" + "\r\n\t " +
                         @" LECmd.exe -f ""C:\Temp\somelink.lnk"" --json ""D:\jsonOutput"" --jsonpretty" + "\r\n\t " +
                         @" LECmd.exe -d ""C:\Temp"" --csv ""c:\temp"" --html c:\temp --xml c:\temp\xml -q" + "\r\n\t " +
                         @" LECmd.exe -f ""C:\Temp\some other link.lnk"" --nid --neb " + "\r\n\t " +
                         @" LECmd.exe -d ""C:\Temp"" --all" + "\r\n\t" +
                         "\r\n\t"+
                         "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
                .WithHeader(header)
                .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) &&
                UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory))
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("Either -f or -d is required. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) == false &&
                !File.Exists(_fluentCommandLineParser.Object.File))
            {
                _logger.Warn($"File '{_fluentCommandLineParser.Object.File}' not found. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory) == false &&
                !Directory.Exists(_fluentCommandLineParser.Object.Directory))
            {
                _logger.Warn($"Directory '{_fluentCommandLineParser.Object.Directory}' not found. Exiting");
                return;
            }

            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}\r\n");

            if (_fluentCommandLineParser.Object.PreciseTimestamps)
            {
                _fluentCommandLineParser.Object.DateTimeFormat = _preciseTimeFormat;
            }

            _processedFiles = new List<LnkFile>();

            _failedFiles = new List<string>();

            if (_fluentCommandLineParser.Object.File?.Length > 0)
            {
                LnkFile lnk = null;

                try
                {
                    lnk = ProcessFile(_fluentCommandLineParser.Object.File);
                    if (lnk != null)
                    {
                        _processedFiles.Add(lnk);
                    }
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.File}'. Are you running as an administrator? Error: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error processing file '{_fluentCommandLineParser.Object.Directory}' Please send it to [email protected]. Error: {ex.Message}");
                    return;
                }
            }
            else
            {
                _logger.Info($"Looking for lnk files in '{_fluentCommandLineParser.Object.Directory}'");
                _logger.Info("");

                string[] lnkFiles = null;

                try
                {
                    var mask = "*.lnk";
                    if (_fluentCommandLineParser.Object.AllFiles)
                    {
                        mask = "*";
                    }

                    lnkFiles = Directory.GetFiles(_fluentCommandLineParser.Object.Directory, mask,
                        SearchOption.AllDirectories);
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.Directory}'. Error message: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting lnk files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                    return;
                }

                _logger.Info($"Found {lnkFiles.Length:N0} files");
                _logger.Info("");

                var sw = new Stopwatch();
                sw.Start();

                foreach (var file in lnkFiles)
                {
                    var lnk = ProcessFile(file);
                    if (lnk != null)
                    {
                        _processedFiles.Add(lnk);
                    }
                }

                sw.Stop();

                if (_fluentCommandLineParser.Object.Quiet)
                {
                    _logger.Info("");
                }

                _logger.Info(
                    $"Processed {lnkFiles.Length - _failedFiles.Count:N0} out of {lnkFiles.Length:N0} files in {sw.Elapsed.TotalSeconds:N4} seconds");
                if (_failedFiles.Count > 0)
                {
                    _logger.Info("");
                    _logger.Warn("Failed files");
                    foreach (var failedFile in _failedFiles)
                    {
                        _logger.Info($"  {failedFile}");
                    }
                }
            }

            if (_processedFiles.Count > 0)
            {
                _logger.Info("");

                try
                {
                    CsvWriter csv = null;
                    StreamWriter sw = null;

                    if (_fluentCommandLineParser.Object.CsvDirectory?.Length > 0)
                    {
                        if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                        {
                            _logger.Warn($"'{_fluentCommandLineParser.Object.CsvDirectory} does not exist. Creating...'");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                        }

                        var outName = $"{DateTimeOffset.Now.ToString("yyyyMMddHHmmss")}_LECmd_Output.tsv";
                        var outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                        _fluentCommandLineParser.Object.CsvDirectory =
                            Path.GetFullPath(outFile);
                        _logger.Warn(
                            $"CSV (tab separated) output will be saved to '{Path.GetFullPath(outFile)}'");

                        try
                        {
                            sw = new StreamWriter(outFile);
                            csv = new CsvWriter(sw);
                            csv.Configuration.Delimiter = $"{'\t'}";
                            csv.WriteHeader(typeof(CsvOut));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Unable to open '{outFile}' for writing. CSV export canceled. Error: {ex.Message}");
                        }
                    }

                    if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                    {
                        if (Directory.Exists(_fluentCommandLineParser.Object.JsonDirectory) == false)
                        {
                            _logger.Warn($"'{_fluentCommandLineParser.Object.JsonDirectory} does not exist. Creating...'");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.JsonDirectory);
                        }
                        _logger.Warn($"Saving json output to '{_fluentCommandLineParser.Object.JsonDirectory}'");
                    }
                    if (_fluentCommandLineParser.Object.XmlDirectory?.Length > 0)
                    {
                        {
                            if (Directory.Exists(_fluentCommandLineParser.Object.XmlDirectory) == false)
                            {
                                _logger.Warn($"'{_fluentCommandLineParser.Object.XmlDirectory} does not exist. Creating...'");
                                Directory.CreateDirectory(_fluentCommandLineParser.Object.XmlDirectory);
                            }

                        }
                        _logger.Warn($"Saving XML output to '{_fluentCommandLineParser.Object.XmlDirectory}'");
                    }

                    XmlTextWriter xml = null;

                    if (_fluentCommandLineParser.Object.xHtmlDirectory?.Length > 0)
                    {

                        var outDir = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory,
                            $"{DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss")}_LECmd_Output_for_{_fluentCommandLineParser.Object.xHtmlDirectory.Replace(@":\", "_").Replace(@"\", "_")}");

                        if (Directory.Exists(outDir) == false)
                        {
                            Directory.CreateDirectory(outDir);
                        }

                        File.WriteAllText(Path.Combine(outDir, "normalize.css"), Resources.normalize);
                        File.WriteAllText(Path.Combine(outDir, "style.css"), Resources.style);

                        var outFile = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory, outDir, "index.xhtml");

                        _logger.Warn($"Saving HTML output to '{outFile}'");

                        xml = new XmlTextWriter(outFile, Encoding.UTF8)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 4
                        };

                        xml.WriteStartDocument();

                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"normalize.css\"");
                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"style.css\"");

                        xml.WriteStartElement("document");
                    }

                    foreach (var processedFile in _processedFiles)
                    {
                        var o = GetCsvFormat(processedFile);

                        try
                        {
                            csv?.WriteRecord(o);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Error writing record for '{processedFile.SourceFile}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");
                        }

                        if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                        {
                            SaveJson(processedFile, _fluentCommandLineParser.Object.JsonPretty,
                                _fluentCommandLineParser.Object.JsonDirectory);
                        }

                        //XHTML
                        xml?.WriteStartElement("Container");
                        xml?.WriteElementString("SourceFile", o.SourceFile);
                        xml?.WriteElementString("SourceCreated", o.SourceCreated);
                        xml?.WriteElementString("SourceModified", o.SourceModified);
                        xml?.WriteElementString("SourceAccessed", o.SourceAccessed);

                        xml?.WriteElementString("TargetCreated", o.TargetCreated);
                        xml?.WriteElementString("TargetModified", o.TargetModified);
                        xml?.WriteElementString("TargetAccessed", o.TargetModified);

                        xml?.WriteElementString("FileSize", o.FileSize.ToString());
                        xml?.WriteElementString("RelativePath", o.RelativePath);
                        xml?.WriteElementString("WorkingDirectory", o.WorkingDirectory);
                        xml?.WriteElementString("FileAttributes", o.FileAttributes);
                        xml?.WriteElementString("HeaderFlags", o.HeaderFlags);
                        xml?.WriteElementString("DriveType", o.DriveType);
                        xml?.WriteElementString("DriveSerialNumber", o.DriveSerialNumber);
                        xml?.WriteElementString("DriveLabel", o.DriveLabel);
                        xml?.WriteElementString("LocalPath", o.LocalPath);
                        xml?.WriteElementString("CommonPath", o.CommonPath);
                        xml?.WriteElementString("Arguments", o.Arguments);

                        xml?.WriteElementString("TargetIDAbsolutePath", o.TargetIDAbsolutePath);

                        xml?.WriteElementString("TargetMFTEntryNumber", $"{o.TargetMFTEntryNumber}");
                        xml?.WriteElementString("TargetMFTSequenceNumber", $"{o.TargetMFTSequenceNumber}");

                        xml?.WriteElementString("MachineID", o.MachineID);
                        xml?.WriteElementString("MachineMACAddress", o.MachineMACAddress);
                        xml?.WriteElementString("MACVendor", o.MACVendor);

                        xml?.WriteElementString("TrackerCreatedOn", o.TrackerCreatedOn);

                        xml?.WriteElementString("ExtraBlocksPresent", o.ExtraBlocksPresent);

                        xml?.WriteEndElement();

                        if (_fluentCommandLineParser.Object.XmlDirectory?.Length > 0)
                        {
                            SaveXML(o, _fluentCommandLineParser.Object.XmlDirectory);
                        }
                    }

                    //Close CSV stuff
                    sw?.Flush();
                    sw?.Close();

                    //Close XML
                    xml?.WriteEndElement();
                    xml?.WriteEndDocument();
                    xml?.Flush();
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error exporting data! Error: {ex.Message}");
                }
            }
            }