Beispiel #1
0
        public static IEnumerable <SorterService.ClassLibrary.FileListener> InitializeFileSystemSorters()
        {
            var fileSystemProvider = new FileSystemWorker();

            foreach (ListenDirectoryElement directory in Config.Configuration.ListenDirectories)
            {
                var directoryWatcher = new DirectoryWorker(directory.Path)
                {
                    IncludeSubdirectories = true
                };

                var fileSystemSorter = new SorterService.ClassLibrary.FileListener(directoryWatcher,
                                                                                   Config.Configuration.DefaultDirectory.Path, fileSystemProvider)
                {
                    Rules = Config.Configuration.patternPathDictionary,
                    GenerateNewFileName = NameWorker.GenerateNewFileName
                };


                fileSystemSorter.directoryWorker.Created += OnCreated;
                fileSystemSorter.directoryWorker.Changed += OnChanged;
                fileSystemSorter.directoryWorker.Deleted += OnDeleted;

                fileSystemSorter.RuleFound += (s, e) =>
                                              Console.WriteLine(ResourceManagment.GetString("FileFoundMessage"), e.Rule, e.FileName, e.PathToMove);
                fileSystemSorter.RuleNotFound += (s, e) =>
                                                 Console.WriteLine(ResourceManagment.GetString("FileNotFoundMessage"), e.FileName, e.DefaultPath);

                yield return(fileSystemSorter);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Метод инициализирует запуск работы всех модулей программы.
        /// </summary>
        private void DoInitialisingOfAllComponents()
        {
            // Создание объекта, следящим за указанной директорией и управляющим буфером файлов; загружает файлы в буффер.
            DirectoryWorker.Start();

            // Вывод служебной информации
            ConsoleColorPrinter.WriteLineWithTime($"Server on [{Dns.GetHostName()}] Started!", ConsoleColor.Green, ConsoleColor.Yellow);

            // Настройка слушателя http запросов и его запуск.
            httpListener = this.GetConfiguredListener();
            httpListener.Start();
            ConsoleColorPrinter.WriteLineWithTime("Start listening requests...\n", ConsoleColor.Green, ConsoleColor.Yellow);
        }
        private static void DirectoryExamples()
        {
            var directoryWorker = new DirectoryWorker();

            directoryWorker.DirectoryListAndDetails();

            directoryWorker.ListDirectories();

            directoryWorker.GetCurrentDirectory();

            directoryWorker.DirectoryOperations();

            Console.ReadKey();
        }
        public IActionResult Get(String requestPath)
        {
            String reqPath  = requestPath.Replace('/', Path.DirectorySeparatorChar);
            String realPath = Path.Combine(Configuration.Get.GalleryPath, reqPath);

            // The requested path must be a subdir of our configured gallery path, and it must exist
            if (realPath.Contains(Configuration.Get.GalleryPath) && Directory.Exists(realPath))
            {
                DirectoryWorker worker = new DirectoryWorker(new DirectoryInfo(realPath));
                return(Ok(worker.Process(Configuration.Get.RegenerateThumbnails)));
            }

            return(NotFound());
        }
Beispiel #5
0
        private void AddWorker()
        {
            if (IsValidateAdd())
            {
                DirectoryWorker worker = new DirectoryWorker();
                worker.LastName  = textBoxLastName.Text;
                worker.FirstName = textBoxFirstName.Text;

                if (!string.IsNullOrWhiteSpace(textBoxMidName.Text))
                {
                    worker.MidName = textBoxMidName.Text;
                }

                worker.Gender = radioButtonMale.Checked ? Gender.Male : Gender.Female;

                worker.BirthDay  = dateTimePickerBirthDay.Value;
                worker.Address   = textBoxAddress.Text;
                worker.CellPhone = textBoxCellPhone.Text;

                if (!string.IsNullOrWhiteSpace(textBoxHomePhone.Text))
                {
                    worker.HomePhone = textBoxHomePhone.Text;
                }

                worker.StartDate = dateTimePickerDateOfStart.Value;


                for (int i = 0; i < dataGridViewCompanyAndPost.RowCount; i++)
                {
                    var currentPost = new CurrentPost
                    {
                        ChangeDate      = DateTime.Parse(dataGridViewCompanyAndPost[5, i].Value.ToString()),
                        DirectoryPostId = int.Parse(dataGridViewCompanyAndPost[0, i].Value.ToString())
                    };

                    worker.Posts.Add(currentPost);
                }

                _qt.AddDirectoryWorker(worker);
                _qt.Save();
                ClearForm();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Обработчик события NotifyAboutDelete от DirectoryAnalyser.
        /// Если файл является HTML, то удаляет его директорию в список префиксов
        /// </summary>
        /// <param name="file"></param>
        public void OnDeleteFile(FileInfo file)
        {
            if (file.Extension.EndsWith(".html"))
            {
                string localDirectory = DirectoryWorker.GetLocalPath(file.DirectoryName);
                //ConsoleColorPrinter.WriteLineWithTime($"HTML file deleted in=[{localDirectory}/]. Deleting it from .Prefixes",
                //                                ConsoleColor.Green, ConsoleColor.Yellow);
                logger.Debug($"HTML file deleted in=[{localDirectory}/]. Deleting it from .Prefixes");

                foreach (string path in uriHelper.ConnectBeginigsWithPath(localDirectory))
                {
                    this.httpListener.Prefixes.Remove(path);
                }

                //ConsoleColorPrinter.WriteLine($"Prefix deleted!", ConsoleColor.DarkGreen);
                logger.Debug($"Deleting finished");
                //this.PrintPrefixes(httpListener);
            }
        }
Beispiel #7
0
 /// <summary>
 /// Очистка ресурсов, которые использует объект. Прерываются асинхронные операции, которые делаются на фоне.
 /// </summary>
 public void Shutdown()
 {
     try
     {
         if (httpListener.IsListening)
         {
             httpListener.Stop();
             //logger.Debug("Listener stopped");
             ConsoleColorPrinter.WriteLineWithTime("Listener stopped", ConsoleColor.DarkGreen, ConsoleColor.Yellow);
         }
         DirectoryWorker.Shutdown();
         //logger.Debug("File system wathcer stopped");
         ConsoleColorPrinter.WriteLineWithTime("File system watcher stopped", ConsoleColor.DarkGreen, ConsoleColor.Yellow);
         NLog.LogManager.Shutdown();
         //logger.Debug("Logger stopped");
         ConsoleColorPrinter.WriteLineWithTime("Logger stopped", ConsoleColor.DarkGreen, ConsoleColor.Yellow);
     }
     catch (Exception) { }
 }
Beispiel #8
0
        /// <summary>
        /// Обработчик события NotifyAboutCreate от DirectoryAnalyser.
        /// Если файл является HTML, то добавляет его директорию в список префиксов.
        /// </summary>
        /// <param name="file"></param>
        public void OnNewFile(FileInfo file)
        {
            if (file.Extension.EndsWith(".html"))
            {
                string localDirectory = DirectoryWorker.GetLocalPath(file.DirectoryName);
                //ConsoleColorPrinter.WriteLineWithTime($"Find new HTML file in=[{localDirectory}/]. Adding it to .Prefixes",
                //                                ConsoleColor.Green, ConsoleColor.Yellow);
                logger.Debug($"Find new HTML file in=[{localDirectory}/]. Adding it to .Prefixes");

                foreach (string path in uriHelper.ConnectBeginigsWithPath(localDirectory))
                {
                    try { this.httpListener.Prefixes.Add(path); }
                    catch (Exception ex)
                    {
                        logger.Warn($"Trouble with adding prefix!\nMessage: {ex.Message}\nStackTrace:\n{ex.StackTrace}");
                    }
                }
                //ConsoleColorPrinter.WriteLine($"New prefix created!", ConsoleColor.DarkGreen);
                logger.Debug("Prefix adding procedure finished\n");
                //this.PrintPrefixes(httpListener);
            }
        }
Beispiel #9
0
        public DirectoryEditWorkerViewModel(int workerId)
            : base()
        {
            _selectedDirectoryWorker = BC.GetDirectoryWorker(workerId);

            IsFireWorkerEnable = Privileges.HasAccess(UserPrivileges.Workers_FireWorkers);

            if (!IsNotFireDate)
            {
                VisibilityBringAlive = Visibility.Visible;
                IsFireWorkerEnable   = false;
            }
            else
            {
                VisibilityBringAlive = Visibility.Collapsed;
            }

            EditWorkerCommand = new RelayCommand(EditWorker, CanEditingWorker);
            FireWorkerCommand = new RelayCommand(FireWorker, CanEditingWorker);
            BringAliveCommand = new RelayCommand(BringAlive);

            FillInputData();
        }
Beispiel #10
0
 public void AddDirectoryWorker(DirectoryWorker worker)
 {
     _db.DirectoryWorkers.Add(worker);
 }
Beispiel #11
0
        /// <summary>
        ///  Prepare the Host management settings json.
        ///  Returns:
        ///    An System.Boolean that contains true or false.
        ///  Exceptions:
        ///   System.IO.FileNotFoundException:
        ///     No settings file found.
        /// </summary>
        public static bool Initialize(bool isHostApplication = false, bool _throw = false)
        {
            if (_IS_CATCH)
            {
                return(true);
            }
            if (isHostApplication)
            {
                var _assembly = System.Reflection.Assembly.GetEntryAssembly().Location;
                Global.APP_DIR = System.IO.Path.GetDirectoryName(_assembly);
            }
            var    _AppSettings = new SettingsJson();
            string settingsDir  = string.Format(@"{0}/settings/", Global.APP_DIR);

            DirectoryWorker.CreateDirectory(settingsDir);
            string logDir = string.Format(@"{0}/", Global.APP_DIR);

            Log.LOG_DIR = logDir;
            DirectoryWorker.CreateDirectory(logDir);
            string filePath = string.Format(@"{0}settings.json", settingsDir);
            string msg      = "";

            if (!File.Exists(filePath))
            {
                msg = string.Format("No Setting(s) file found in following path {0};", filePath);
                Log.WriteAsync(msg, true);

                if (_throw)
                {
                    throw new Exception("Invalid settings. Contact with web administrator... :(");
                }
                return(false);
            }
            string infoJson = FileWorker.Read(filePath);

            if (string.IsNullOrEmpty(infoJson))
            {
                msg = string.Format("No Setting(s) Data found in following path {0};", filePath);
                Log.WriteAsync(msg, true);
                if (_throw)
                {
                    throw new Exception("Invalid settings. Contact with web administrator... :(");
                }
                return(false);
            }
            _AppSettings = new JavaScriptSerializer().Deserialize <SettingsJson>(infoJson); infoJson = null;
            if (string.IsNullOrEmpty(_AppSettings.DB_CONNECTION))
            {
                msg = string.Format("No Database Connection found in following path {0};", filePath);
                Log.WriteAsync(msg, true);
                if (_throw)
                {
                    throw new Exception("Invalid settings. Contact with web administrator... :(");
                }
                return(false);
            }
            if (_AppSettings.DB_IS_ENCRYPT)
            {
                _AppSettings.DB_CONNECTION = Decrypt.Token(_AppSettings.DB_CONNECTION);
            }
            Connection.Set(_AppSettings.DB_CONNECTION);
            _IS_CATCH = true; _AppSettings.SIGNALR_IS_HOST_APPLICATION = isHostApplication;
            if (_AppSettings.EMAIL_INFO_IS_ENCRYPT)
            {
                _AppSettings.EMAIL_FROM     = Decrypt.Token(_AppSettings.EMAIL_FROM);
                _AppSettings.EMAIL_PASSWORD = Decrypt.Token(_AppSettings.EMAIL_PASSWORD);
                _AppSettings.SMTP_LOGIN_ID  = Decrypt.Token(_AppSettings.SMTP_LOGIN_ID);
                _AppSettings.SMTP_SERVER    = Decrypt.Token(_AppSettings.SMTP_SERVER);
            }
            if (_AppSettings.IS_WEB)
            {
                if (string.IsNullOrEmpty(_AppSettings.HOST_NAME))
                {
                    _AppSettings.HOST_NAME = Helper.HostName;
                }
            }
            Global.SetSettings(_AppSettings); _AppSettings = null;

            return(true);
        }