Exemple #1
0
        static void Main(string [] args)
        {
            ProcessRunning = true;

            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
            {
                FinderLog.Log($"알 수 없는 오류 발생: {( e.ExceptionObject as Exception ).Message}");
                FinderLog.Flush();
            };

            if (args.Length >= 1 && args [0] == "--startuputil")
            {
                DoStartupUtility(args);
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainWindow());

            ProcessRunning = false;

            FinderLog.Flush();
        }
        public ClipboardAutomator()
        {
            InitializeComponent();

            nextClipboardViewer = ( IntPtr )SetClipboardViewer(( int )this.Handle);

            ClipboardChanged += (sender, e) =>
            {
                Debug.WriteLine("ClipboardChanged ()");

                if (!checkBoxUseAutomation.Checked)
                {
                    return;
                }

                if (checkBoxOnlyFromWebBrowser.Checked)
                {
                    IntPtr activeWindow = GetForegroundWindow();
                    GetWindowThreadProcessId(activeWindow, out uint pid);
                    Process process = Process.GetProcessById(( int )pid);
                    if (!AllowedProcessNames.Contains(process.ProcessName))
                    {
                        Debug.WriteLine("Clipboard Cut/Copy from No Web Browser.");
                        return;
                    }
                }

                if (!(e.DataObject.GetData("Text") is string text))
                {
                    return;
                }

                var trimmed = text.Trim();
                if (trimmed != text)
                {
                    text      = trimmed;
                    e.Changed = text;
                }

                text = Regex.Replace(text, "(\\[출처\\] .* \\(.*\\) \\|작성자 .*)$", "");
                text = Regex.Replace(text, "(\\[출처\\] .*\n\\[링크\\] .*)$", "");

                if (checkBoxLineMerger.Checked)
                {
                    if (text.IndexOf('\n') >= 0)
                    {
                        e.Changed = Regex.Replace(Regex.Replace(text, "[\r\n]+", " "), "( [ ]+)", "");
                        FinderLog.Log("클립보드 내용이 여러 줄로 구성되어 병합함");
                    }
                }
                if (checkBoxDateRearrange.Checked)
                {
                    if (!Regex.IsMatch(text.Trim(), "^[1-2][09][0-9][0-9]-[0-1][0-9]-[0-3][0-9]$"))
                    {
                        if (DateTime.TryParse(text, out DateTime result))
                        {
                            e.Changed = result.ToString("yyyy-MM-dd");
                            FinderLog.Log("클립보드 내용이 날짜여서 yyyy-MM-dd로 재구성함");
                        }
                        else if (Regex.IsMatch(text, "[0-1][0-9]-[0-3][0-9]"))
                        {
                            e.Changed = $"{DateTime.Today.Year}-{text}";
                            FinderLog.Log("클립보드 내용이 날짜여서 yyyy-MM-dd로 재구성함");
                        }
                    }
                    else
                    {
                        FinderLog.Log("클립보드 내용이 날짜이지만 이미 yyyy-MM-dd임");
                    }
                }
                if (checkBoxFixURL.Checked && ExcelIndexer.SharedExcelIndexer != null)
                {
                    if (Regex.IsMatch(text, "^https?://[a-zA-Z0-9가-힣./?&=%#+%_:\\-\\\\]+$"))
                    {
                        BaseProcessor processor = ProcessorFinder.FindProcessor(text);
                        e.Changed = processor?.ConvertUrl(text);
                        if (e.Changed != text)
                        {
                            FinderLog.Log("클립보드 내용이 URL로 확인되어 교정함");
                        }
                        else
                        {
                            e.Changed = null;
                            FinderLog.Log("클립보드 내용이 URL이지만 교정할 필요가 없음");
                        }
                    }
                }
            };

            RegisterHotKey(Handle, 0, 1, ( int )Keys.C);
            RegisterHotKey(Handle, 1, 1, ( int )Keys.W);
        }
Exemple #3
0
        public static async Task <ExcelIndexer> ToIndexer(ExcelIndexerBuilderState state = null)
        {
            IndexedItem [] indexedItems = null;
            DateTime []    indexedDates = null;

            await Task.Run(() =>
            {
                using (LiteDatabase db = new LiteDatabase($"Filename=\"{Path.Combine ( Program.ProgramPath, "ExcelFilesCache.litedb" )}\"; Journal=true; Mode=Shared; Flush=true;"))
                {
                    var cacheFilesCollection  = db.GetCollection <CacheFiles> ("cachefiles");
                    var cachedItemsCollection = db.GetCollection <IndexedItem> ("indexed");

                    var newFile   = new ConcurrentQueue <CacheFiles> ();
                    var newRecord = new ConcurrentQueue <IndexedItem> ();

                    Parallel.ForEach(FilesEnumerator.EnumerateFiles(CustomizedValue.WorkingDirectory, "엑셀자료-*.xlsx", false).AsParallel(), (file) =>
                    {
                        if (file.Contains("일지 양식") || file.Contains("샘플") || Regex.IsMatch(file, todayRegexString))
                        {
                            return;
                        }
                        var fileItem = cacheFilesCollection.FindOne(Query.EQ("Filename", file));
                        if (fileItem != null)
                        {
                            if (fileItem.LastModifiedDateTime.ToString() == File.GetLastWriteTime(file).ToString())
                            {
                                if (state != null)
                                {
                                    Interlocked.Increment(ref state.excelFileCount);
                                    int recordCount = cachedItemsCollection.Find(Query.EQ("Filename", file)).Count();
                                    Interlocked.Add(ref state.totalItemCount, recordCount);
                                    FinderLog.Log($"{Path.GetFileName ( file )}으로부터 {recordCount}개를 이미 인덱싱 했음.");
                                }
                                return;
                            }
                            else
                            {
                                cachedItemsCollection.Delete(Query.EQ("Filename", file));
                                cacheFilesCollection.Delete(Query.EQ("Filename", file));
                                FinderLog.Log($"{Path.GetFileName ( file )}의 인덱싱 데이터가 최신이 아니므로 재인덱싱 시작.");
                            }
                        }
                        else
                        {
                            FinderLog.Log($"{Path.GetFileName ( file )}은 인덱싱되지 않은 파일임.");
                        }

                        try
                        {
                            OleDbConnection connection = new OleDbConnection(
                                $"Provider=\"Microsoft.ACE.OLEDB.12.0\";Data Source=\"{file}\";Extended Properties=\"Excel 12.0;HDR=NO\";"
                                );
                            connection.Open();

                            int count = 0;
                            //Regex.Replace ( connection.GetSchema ( "Tables" ).Rows [ 1 ] [ "TABLE_NAME" ] as string, "['\"]", "" );
                            using (OleDbCommand command = new OleDbCommand(
                                       selectQuery,
                                       connection
                                       ))
                            {
                                using (var reader = command.ExecuteReader())
                                {
                                    if (!reader.Read())
                                    {
                                        state?.OpeningFailedFiles.Enqueue(file);
                                        return;
                                    }

                                    while (reader.Read())
                                    {
                                        object websiteName = reader.GetValue(8);
                                        object url         = reader.GetValue(9);
                                        object baseUrl     = reader.GetValue(31);

                                        if (websiteName == DBNull.Value || url == DBNull.Value || baseUrl == DBNull.Value)
                                        {
                                            break;
                                        }

                                        newRecord.Enqueue(new IndexedItem(websiteName as string, url as string, baseUrl as string, file));

                                        ++count;
                                    }
                                }
                            }

                            connection.Close();

                            if (state != null)
                            {
                                Interlocked.Add(ref state.totalItemCount, count);
                                Interlocked.Increment(ref state.excelFileCount);
                            }

                            newFile.Enqueue(new CacheFiles()
                            {
                                Filename = file, LastModifiedDateTime = File.GetLastWriteTime(file)
                            });

                            FinderLog.Log($"{Path.GetFileName ( file )}의 데이터 {count}개 캐시 완료.");
                        }
                        catch (Exception ex)
                        {
                            FinderLog.Log($"{Path.GetFileName ( file )} 캐시 중 오류 발생: {ex.ToString ()}");
                            state?.OpeningFailedFiles.Enqueue(file);
                        }
                    });

                    cacheFilesCollection.Insert(newFile);
                    cachedItemsCollection.Insert(newRecord);

                    db.Shrink();

                    indexedItems          = new List <IndexedItem> (cachedItemsCollection.FindAll()).ToArray();
                    List <DateTime> dates = new List <DateTime> ();
                    foreach (var f in cacheFilesCollection.FindAll())
                    {
                        string date = "20" + Regex.Match(f.Filename, $"(.*)모니터링일지-[가-힣]+-([0-9][0-9][0-1][0-9][0-3][0-9])\\\\(.*).xlsx").Groups [2].Value;
                        dates.Add(new DateTime(int.Parse(date.Substring(0, 4)), int.Parse(date.Substring(4, 2)), int.Parse(date.Substring(6, 2))));
                    }
                    indexedDates = dates.ToArray();
                }
            });

            GC.Collect();

            return(new ExcelIndexer(indexedItems, indexedDates));
        }