Exemplo n.º 1
0
        private static void LogObject(string message, object obj, string preName)
        {
            string msg = message + ParseObject(obj);

            logerImp.Log(preName + " " + msg);
            OnWriteLog?.Invoke(msg);
        }
        public void Generate(string excelFileName, string wordFileName, string folderPath)
        {
            bool needReturn = false;

            if (string.IsNullOrEmpty(excelFileName))
            {
                OnWriteLog?.Invoke("Укажите имя Excel файла.\r\n");
                needReturn = true;
            }
            if (string.IsNullOrEmpty(wordFileName))
            {
                OnWriteLog?.Invoke("Укажите имя файла шаблона Word.\r\n");
                needReturn = true;
            }
            if (string.IsNullOrEmpty(folderPath))
            {
                OnWriteLog?.Invoke("Укажите выходную папку для заявлений на отпуск.\r\n");
                needReturn = true;
            }
            if (needReturn)
            {
                OnGenerateAppForLeaveEnd?.Invoke();
                return;
            }
            string[] parametrs = new string[3];
            parametrs[0] = excelFileName;
            parametrs[1] = wordFileName;
            parametrs[2] = folderPath;
            Task GenExcelTask = new Task(GenAppForLeave, parametrs);

            GenExcelTask.Start();
        }
Exemplo n.º 3
0
 private MoonLogger()
 {
     //开启一个定时写日志的任务
     Task.Run(new Action(() =>
     {
         while (true)
         {
             lock (SynObject)
             {
                 if (infoList.Count > 0)
                 {
                     StringBuilder stringBuilder = new StringBuilder();
                     for (int i = 0; i < infoList.Count; i++)
                     {
                         if (i < 200)
                         {
                             stringBuilder.Append(infoList[i] + "\r\n");
                         }
                         WriteLine(infoList[i]);
                     }
                     OnWriteLog?.Invoke(stringBuilder.ToString());
                     OnWriteStatus?.Invoke(infoList[0]);
                     infoList.Clear();
                 }
             }
             Thread.Sleep(WriteInterval);
         }
     }));
 }
Exemplo n.º 4
0
        private static void LogExecption(Exception ex, string preName)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(ex.Message);
            sb.AppendLine(ex.StackTrace);
            var stacktrace = new StackTrace();

            for (var i = 0; i < stacktrace.FrameCount; i++)
            {
                sb.AppendLine(stacktrace.GetFrame(i).GetFileName() + ":" + stacktrace.GetFrame(i).GetFileLineNumber() + ":" + stacktrace.GetFrame(i).GetMethod());
            }
            logerImp.Log(preName + " " + sb.ToString());
            OnWriteLog?.Invoke(sb.ToString());
        }
Exemplo n.º 5
0
        public void Write(CmdLogType type, string msg, CommLogType CommType = CommLogType.None)
        {
            if (null == PrdtLog)
            {
                return;
            }
            string logmsg = string.Empty;

            logmsg = $"{DateTime.Now.ToString("HH:mm:ss.fff")} : {msg}";
            PrdtLog.StrAdd(type, logmsg, CommType);
            Debug.WriteLine($"{type.ToString()} : {msg}");
            OnWriteLog?.Invoke(this, new WriteLogArgs()
            {
                name = "", type = type, msg = logmsg, CommType = CommType
            });
        }
 public virtual void WriteLine(LogInfo log)
 {
     pipeTask.Excute(() => {
         OnWriteLog?.Invoke(this, log);
     });
     if (filterAction != null && filterAction(log))
     {
         m_logList.Enqueue(log);
     }
     if (m_curTask == null)
     {
         lock (m_obj)
         {
             if (m_curTask == null)
             {
                 m_curTask = m_taskFactory.StartNew(() => DoWriteLine());
             }
         }
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Writes the trace with exception object
 /// </summary>
 /// <param name="ex">The ex.</param>
 public static void WriteTrace(Exception ex)
 {
     OnWriteLog?.Invoke("Exception: " + ex.Message);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Writes the trace with message
 /// </summary>
 /// <param name="message">The message.</param>
 public static void WriteTrace(string message)
 {
     OnWriteLog?.Invoke(message);
 }
Exemplo n.º 9
0
 private static void LogString(string message, string preName)
 {
     logerImp.Log(preName + " " + message);
     OnWriteLog?.Invoke(message);
 }
Exemplo n.º 10
0
        private void GenAppForLeave(object parametrs)
        {
            Random gen = new Random();

            string[] paramsData       = (string[])parametrs;
            string   filename         = paramsData[0];
            string   templateFileName = paramsData[1];
            string   newPdfFilePath   = paramsData[2];
            string   tempDirectory    = "temp";

            ObjExcel = new Excel.Application();
            //Открываем книгу.
            try
            {
                xlWorkbook = ObjExcel.Workbooks.Open(filename, 0, true, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            }
            catch (Exception ex)
            {
                OnWriteLog?.Invoke(ex.Message + "\r\n");
            }
            if (xlWorkbook == null)
            {
                OnWriteLog?.Invoke("Не удалось открыть файл " + filename + "\r\n");
                OnGenerateAppForLeaveEnd?.Invoke();
                return;
            }
            //Выбираем таблицу(лист).
            ObjExcel.Visible = false;
            xlWorksheet      = (Excel.Worksheet)xlWorkbook.Sheets[1];
            xlRange          = xlWorksheet.UsedRange;

            //Создаём новый Word.Application
            app = new Word.Application();
            //Загружаем документ
            object wordFileName = templateFileName;
            object falseValue   = false;
            object trueValue    = true;
            object missing      = Type.Missing;

            try
            {
                doc = app.Documents.Open(ref wordFileName, ref missing, ref trueValue,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                OnWriteLog?.Invoke(ex.Message + "\r\n");
            }
            if (doc == null)
            {
                OnWriteLog?.Invoke("Не удалось открыть файл " + wordFileName + "\r\n");
                app.Quit();
                OnGenerateAppForLeaveEnd?.Invoke();
                return;
            }

            int rowCount = xlRange.Rows.Count;

            //int colCount = 4;
            Directory.CreateDirectory(newPdfFilePath + "\\" + tempDirectory);
            for (int i = 2; i <= rowCount; i++)
            {
                if (isClose)
                {
                    break;
                }
                object times = 1;
                while (doc.Undo(ref times))
                {
                }

                string chiefNumber    = xlRange.Cells[i, "C"].Value2.ToString();
                string chiefFIO       = xlRange.Cells[i, "D"].Value2.ToString();
                string employeeFIO    = xlRange.Cells[i, "B"].Value2.ToString();
                string employeeNumber = xlRange.Cells[i, "A"].Value2.ToString();

                string pdfFileName = newPdfFilePath + "\\" + tempDirectory + "\\" + employeeNumber + "_" + chiefNumber + ".pdf";
                OnWriteLog?.Invoke("Save file " + pdfFileName);
                //Console.Write("Save file " + pdfFileName);

                //Очищаем параметры поиска
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                //Задаём параметры замены и выполняем замену.
                object findText    = "<ФИО Руководителя>";
                object replaceWith = chiefFIO;
                object replace     = Word.WdReplace.wdReplaceAll;

                app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                           ref replace, ref missing, ref missing, ref missing, ref missing);

                findText    = "<ФИО Сотрудника>";
                replaceWith = employeeFIO;

                app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                           ref replace, ref missing, ref missing, ref missing, ref missing);


                //Генерация даты отпуска
                DateTime DateStart = new DateTime(2018, 1, 1);
                DateTime DateEnd   = new DateTime(2019, 1, 1);
                int      range     = (DateEnd - DateStart).Days;
                DateTime LeaveDate = DateStart.AddDays(gen.Next(range));

                findText    = "<Дата начала отпуска>";
                replaceWith = LeaveDate.ToShortDateString();

                app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                           ref replace, ref missing, ref missing, ref missing, ref missing);

                //Количество дней отпуска
                int DaysCount = gen.Next(40);
                findText    = "<N>";
                replaceWith = DaysCount.ToString();

                app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                           ref replace, ref missing, ref missing, ref missing, ref missing);

                //Генерация даты написания заявления
                if (LeaveDate.AddDays(-14) <= DateStart)
                {
                    DateStart = DateStart.AddDays(-14);
                }
                range = (LeaveDate.AddDays(-14) - DateStart).Days;
                DateTime SignDate = DateStart.AddDays(gen.Next(range));
                findText    = "<Дата написания заявления>";
                replaceWith = SignDate.ToShortDateString();

                app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                           ref replace, ref missing, ref missing, ref missing, ref missing);

                findText    = "<Таб.№ работника>";
                replaceWith = employeeNumber;

                app.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
                                           ref replace, ref missing, ref missing, ref missing, ref missing);

                app.Visible = false;
                //Сохраняем pdf
                object fileName2  = pdfFileName;
                object saveFormat = Word.WdSaveFormat.wdFormatPDF;
                try
                {
                    app.ActiveDocument.SaveAs2(ref fileName2,
                                               ref saveFormat, ref missing, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing);

                    //Создаём архив и добавляем в него файл
                    string zipPath = newPdfFilePath + "\\" + chiefNumber + ".zip";
                    if (!File.Exists(zipPath))
                    {
                        string directoryPath = newPdfFilePath + "\\" + chiefNumber;
                        Directory.CreateDirectory(directoryPath);
                        ZipFile.CreateFromDirectory(directoryPath, zipPath);
                        Directory.Delete(directoryPath);
                    }
                    using (ZipArchive modFile = ZipFile.Open(zipPath, ZipArchiveMode.Update))
                    {
                        modFile.CreateEntryFromFile((string)fileName2, employeeNumber + "_" + chiefNumber + ".pdf");
                    }
                }
                catch (Exception ex)
                {
                    OnWriteLog?.Invoke("\r\n" + ex.Message + "\r\n");
                    break;
                }
                File.Delete((string)fileName2);

                OnWriteLog?.Invoke(" OK\r\n");
                OnRecordProcessed?.Invoke();
            }

            Directory.Delete(newPdfFilePath + "\\" + tempDirectory);
            object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

            doc.Close(ref saveChanges, ref missing, ref missing);
            doc = null;
            app.Quit();

            OnGenerateAppForLeaveEnd?.Invoke();
        }
Exemplo n.º 11
0
        private static void WriteLogToFile()
        {
            _logConfiguration = LogConfiguration.GetConfiguration();
            if (_logQueue.Count < 1)
            {
                return;
            }
            StreamWriter writer = null;

            if (!_logConfiguration.NoLocalFile)
            {
                string logFileFullName = string.Format("{0}/{1}", _logConfiguration.LogPath, _logConfiguration.LogFileName);
                string logPath         = Path.GetDirectoryName(logFileFullName);
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }
                writer = new StreamWriter(logFileFullName, true, Encoding.Default);
            }
            do
            {
                try
                {
                    if (_logQueue.Count == 0)
                    {
                        break;
                    }
                    LogInfo logInfo = null;
                    lock (_logQueue)
                    {
                        logInfo = _logQueue.Dequeue();
                    }
                    if (logInfo == null)
                    {
                        continue;
                    }
                    if (logInfo.LogLevel < _logConfiguration.LogLevel)
                    {
                        continue;
                    }
                    if (logInfo.InnerException != null)
                    {
                        if (string.IsNullOrEmpty(logInfo.LogMessage))
                        {
                            logInfo.LogMessage = string.Format("{0}\r\n{1}", logInfo.InnerException.Message, logInfo.InnerException.StackTrace);
                        }
                        else
                        {
                            logInfo.LogMessage = string.Format("{0}\r\n错误信息:{1}\r\n异常堆栈:{2}", logInfo.LogMessage, logInfo.InnerException.Message, logInfo.InnerException.StackTrace);
                        }
                        string  cacheKey  = EncryptionUtil.EncryptMD5(logInfo.LogMessage);
                        LogInfo cacheInfo = DictionaryUtil.Get <LogInfo>(_logCache, cacheKey);
                        if (cacheInfo == null)
                        {
                            _logCache[cacheKey] = cacheInfo;
                        }
                        else
                        {
                            cacheInfo.LogCount++;
                            if ((logInfo.LogTime - cacheInfo.LogTime).TotalMinutes < 5)
                            {
                                continue;
                            }
                            logInfo.LogMessage = string.Format("{0}(5分钟内触发了{1}次)", logInfo.LogMessage, cacheInfo.LogCount);
                            cacheInfo.LogCount = 0;
                            cacheInfo.LogTime  = logInfo.LogTime;
                        }
                    }
                    if (string.IsNullOrEmpty(logInfo.LogMessage))
                    {
                        continue;
                    }
                    string logMessage = string.Format("[{0:HH:mm:ss}][{1}]:\r\n{2}", logInfo.LogTime, logInfo.LogLevel, logInfo.LogMessage);
                    if (_logConfiguration.AddConsole)
                    {
                        Console.WriteLine(logMessage);
                    }
                    if (_logConfiguration.AddDebug)
                    {
                        Debug.Print(logMessage);
                    }
                    if (writer != null)
                    {
                        writer.WriteLine(logMessage);
                    }
                    if (CanUseEventLog && _logConfiguration.WriteToEventLog)
                    {
                        EventLogEntryType logType = EventLogEntryType.Information;
                        switch (logInfo.LogLevel)
                        {
                        case LogLevel.Warning:
                            logType = EventLogEntryType.Warning;
                            break;

                        case LogLevel.Exception:
                            logType = EventLogEntryType.Error;
                            break;

                        case LogLevel.Information:
                        default:
                            logType = EventLogEntryType.Information;
                            break;
                        }
                        if (logInfo.LogLevel != LogLevel.Track)
                        {
                            _log.WriteEntry(logMessage, logType);
                        }
                    }
                    OnWriteLog?.Invoke(logInfo.LogLevel, logMessage);
                }
                catch (Exception ex)
                {
                    WriteException(ex);
                }
                finally
                {
                    if (writer != null && _logQueue.Count == 0)
                    {
                        Thread.Sleep(100);
                    }
                }
            } while (true);
            if (writer != null)
            {
                writer.Close();
                writer.Dispose();
                writer = null;
            }
        }
Exemplo n.º 12
0
 private void WriteLog(string msg)
 {
     OnWriteLog?.Invoke($"{nameof(TwitterFinder)} {msg}");
 }