示例#1
0
        public override void OnAddedToCommLine()
        {
            base.OnAddedToCommLine();

            bool IsWflogger = bool.Parse(CustomParams["KpWorkflowLogger"]);

            Logger.Configure(IsWflogger);
            string fnm = ReqParams.CmdLine.Trim();

            we = new WexflowEngine(AppDirs.ConfigDir + fnm);
            WriteToLog("Загружена конфигурация: " + AppDirs.ConfigDir + fnm);
            we.Run();

            wfperiods = new List <WeWatch> ();

            foreach (Workflow wf in we.Workflows)
            {
                if (wf.LaunchType == LaunchType.Periodic)
                {
                    WeWatch ww = new WeWatch(wf.Id, wf.Period);
                    wfperiods.Add(ww);
                }
            }

            WriteToLog("KpWorkflow в работе.");
        }
示例#2
0
        public static void Main(string[] args)
        {
            Config = new ConfigurationBuilder()
                     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                     .Build();

            XmlDocument log4NetConfig = new XmlDocument();

            log4NetConfig.Load(File.OpenRead("log4net.config"));
            var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

            XmlConfigurator.Configure(repo, log4NetConfig["log4net"]);

            string wexflowSettingsFile = Config["WexflowSettingsFile"];

            WexflowEngine = new WexflowEngine(wexflowSettingsFile);
            WexflowEngine.Run();
            InitializeFileSystemWatcher();

            int port = int.Parse(Config["WexflowServicePort"]);

            var host = new WebHostBuilder()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseKestrel((context, options) =>
            {
                options.ListenAnyIP(port);
            })
                       .UseStartup <Startup>()
                       .Build();

            host.Run();

            Console.WriteLine("Press any key to stop Wexflow server...");
            Console.ReadKey();
        }
示例#3
0
        public static void Main(string[] args)
        {
            Config = new ConfigurationBuilder()
                     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                     .Build();

            var log4NetConfig = new XmlDocument();

            log4NetConfig.Load(File.OpenRead("log4net.config"));
            var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

            XmlConfigurator.Configure(repo, log4NetConfig["log4net"]);

            var wexflowSettingsFile = Config["WexflowSettingsFile"];

            superAdminUsername = Config["SuperAdminUsername"];
            var enableWorkflowsHotFolder = bool.Parse(Config["EnableWorkflowsHotFolder"]);

            WexflowEngine = new WexflowEngine(wexflowSettingsFile, enableWorkflowsHotFolder);

            if (enableWorkflowsHotFolder)
            {
                InitializePollingFileSystemWatcher();
            }
            else
            {
                Logger.Info("Workflows hot folder is disabled.");
            }

            WexflowEngine.Run();

            var port = int.Parse(Config["WexflowServicePort"]);

            var host = new WebHostBuilder()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseKestrel((context, options) =>
            {
                options.ListenAnyIP(port);
            })
                       .UseStartup <Startup>()
                       .Build();

            host.Run();

            Console.Write("Press any key to stop Wexflow server...");
            Console.ReadKey();
            WexflowEngine.Stop(true, true);
        }
示例#4
0
        public bool SaveWorkflow(Stream streamdata)
        {
            try
            {
                StreamReader reader = new StreamReader(streamdata);
                string       json   = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                JObject o  = JObject.Parse(json);
                var     wi = o.SelectToken("WorkflowInfo");

                var isNew = (bool)wi.SelectToken("IsNew");
                if (isNew)
                {
                    XNamespace xn   = "urn:wexflow-schema";
                    var        xdoc = new XDocument();

                    int        workflowId         = (int)wi.SelectToken("Id");
                    string     workflowName       = (string)wi.SelectToken("Name");
                    LaunchType workflowLaunchType = (LaunchType)((int)wi.SelectToken("LaunchType"));
                    string     p = (string)wi.SelectToken("Period");
                    TimeSpan   workflowPeriod = TimeSpan.Parse(string.IsNullOrEmpty(p) ? "00.00:00:00" : p);
                    string     cronExpression = (string)wi.SelectToken("CronExpression");

                    if (workflowLaunchType == LaunchType.Cron && !WexflowEngine.IsCronExpressionValid(cronExpression))
                    {
                        throw new Exception("The cron expression '" + cronExpression + "' is not valid.");
                    }

                    bool   isWorkflowEnabled = (bool)wi.SelectToken("IsEnabled");
                    string workflowDesc      = (string)wi.SelectToken("Description");

                    // tasks
                    var xtasks = new XElement(xn + "Tasks");
                    var tasks  = o.SelectToken("Tasks");
                    foreach (var task in tasks)
                    {
                        int    taskId        = (int)task.SelectToken("Id");
                        string taskName      = (string)task.SelectToken("Name");
                        string taskDesc      = (string)task.SelectToken("Description");
                        bool   isTaskEnabled = (bool)task.SelectToken("IsEnabled");

                        var xtask = new XElement(xn + "Task"
                                                 , new XAttribute("id", taskId)
                                                 , new XAttribute("name", taskName)
                                                 , new XAttribute("description", taskDesc)
                                                 , new XAttribute("enabled", isTaskEnabled.ToString().ToLower())
                                                 );

                        var settings = task.SelectToken("Settings");
                        foreach (var setting in settings)
                        {
                            string settingName  = (string)setting.SelectToken("Name");
                            string settingValue = (string)setting.SelectToken("Value");

                            var xsetting = new XElement(xn + "Setting"
                                                        , new XAttribute("name", settingName)
                                                        );

                            if (!string.IsNullOrEmpty(settingValue))
                            {
                                xsetting.SetAttributeValue("value", settingValue);
                            }

                            if (settingName == "selectFiles" || settingName == "selectAttachments")
                            {
                                if (!string.IsNullOrEmpty(settingValue))
                                {
                                    xsetting.SetAttributeValue("value", settingValue);
                                }
                            }
                            else
                            {
                                xsetting.SetAttributeValue("value", settingValue);
                            }

                            var attributes = setting.SelectToken("Attributes");
                            foreach (var attribute in attributes)
                            {
                                string attributeName  = (string)attribute.SelectToken("Name");
                                string attributeValue = (string)attribute.SelectToken("Value");
                                xsetting.SetAttributeValue(attributeName, attributeValue);
                            }

                            xtask.Add(xsetting);
                        }

                        xtasks.Add(xtask);
                    }

                    // root
                    var xwf = new XElement(xn + "Workflow"
                                           , new XAttribute("id", workflowId)
                                           , new XAttribute("name", workflowName)
                                           , new XAttribute("description", workflowDesc)
                                           , new XElement(xn + "Settings"
                                                          , new XElement(xn + "Setting"
                                                                         , new XAttribute("name", "launchType")
                                                                         , new XAttribute("value", workflowLaunchType.ToString().ToLower()))
                                                          , new XElement(xn + "Setting"
                                                                         , new XAttribute("name", "enabled")
                                                                         , new XAttribute("value", isWorkflowEnabled.ToString().ToLower()))
                                                          , new XElement(xn + "Setting"
                                                                         , new XAttribute("name", "period")
                                                                         , new XAttribute("value", workflowPeriod.ToString(@"dd\.hh\:mm\:ss")))
                                                          , new XElement(xn + "Setting"
                                                                         , new XAttribute("name", "cronExpression")
                                                                         , new XAttribute("value", cronExpression))
                                                          )
                                           , xtasks
                                           );

                    xdoc.Add(xwf);

                    var path = (string)wi.SelectToken("Path");
                    xdoc.Save(path);
                }
                else
                {
                    int id = int.Parse((string)o.SelectToken("Id"));
                    var wf = WexflowWindowsService.WexflowEngine.GetWorkflow(id);
                    if (wf != null)
                    {
                        var xdoc = wf.XDoc;

                        int        workflowId         = (int)wi.SelectToken("Id");
                        string     workflowName       = (string)wi.SelectToken("Name");
                        LaunchType workflowLaunchType = (LaunchType)((int)wi.SelectToken("LaunchType"));
                        string     p = (string)wi.SelectToken("Period");
                        TimeSpan   workflowPeriod = TimeSpan.Parse(string.IsNullOrEmpty(p) ? "00.00:00:00" : p);
                        string     cronExpression = (string)wi.SelectToken("CronExpression");

                        if (workflowLaunchType == LaunchType.Cron &&
                            !WexflowEngine.IsCronExpressionValid(cronExpression))
                        {
                            throw new Exception("The cron expression '" + cronExpression + "' is not valid.");
                        }

                        bool   isWorkflowEnabled = (bool)wi.SelectToken("IsEnabled");
                        string workflowDesc      = (string)wi.SelectToken("Description");

                        //if(xdoc.Root == null) throw new Exception("Root is null");
                        xdoc.Root.Attribute("id").Value          = workflowId.ToString();
                        xdoc.Root.Attribute("name").Value        = workflowName;
                        xdoc.Root.Attribute("description").Value = workflowDesc;

                        var xwfEnabled = xdoc.Root.XPathSelectElement("wf:Settings/wf:Setting[@name='enabled']",
                                                                      wf.XmlNamespaceManager);
                        xwfEnabled.Attribute("value").Value = isWorkflowEnabled.ToString().ToLower();
                        var xwfLaunchType = xdoc.Root.XPathSelectElement("wf:Settings/wf:Setting[@name='launchType']",
                                                                         wf.XmlNamespaceManager);
                        xwfLaunchType.Attribute("value").Value = workflowLaunchType.ToString().ToLower();

                        var xwfPeriod = xdoc.Root.XPathSelectElement("wf:Settings/wf:Setting[@name='period']",
                                                                     wf.XmlNamespaceManager);
                        //if (workflowLaunchType == LaunchType.Periodic)
                        //{
                        if (xwfPeriod != null)
                        {
                            xwfPeriod.Attribute("value").Value = workflowPeriod.ToString(@"dd\.hh\:mm\:ss");
                        }
                        else
                        {
                            xdoc.Root.XPathSelectElement("wf:Settings", wf.XmlNamespaceManager)
                            .Add(new XElement(wf.XNamespaceWf + "Setting", new XAttribute("name", "period"),
                                              new XAttribute("value", workflowPeriod.ToString())));
                        }
                        //}

                        var xwfCronExpression = xdoc.Root.XPathSelectElement(
                            "wf:Settings/wf:Setting[@name='cronExpression']",
                            wf.XmlNamespaceManager);

                        if (xwfCronExpression != null)
                        {
                            xwfCronExpression.Attribute("value").Value = cronExpression ?? string.Empty;
                        }
                        else if (!string.IsNullOrEmpty(cronExpression))
                        {
                            xdoc.Root.XPathSelectElement("wf:Settings", wf.XmlNamespaceManager)
                            .Add(new XElement(wf.XNamespaceWf + "Setting", new XAttribute("name", "cronExpression"),
                                              new XAttribute("value", cronExpression)));
                        }

                        var xtasks   = xdoc.Root.Element(wf.XNamespaceWf + "Tasks");
                        var alltasks = xtasks.Elements(wf.XNamespaceWf + "Task");
                        alltasks.Remove();

                        var tasks = o.SelectToken("Tasks");
                        foreach (var task in tasks)
                        {
                            int    taskId        = (int)task.SelectToken("Id");
                            string taskName      = (string)task.SelectToken("Name");
                            string taskDesc      = (string)task.SelectToken("Description");
                            bool   isTaskEnabled = (bool)task.SelectToken("IsEnabled");

                            var xtask = new XElement(wf.XNamespaceWf + "Task"
                                                     , new XAttribute("id", taskId)
                                                     , new XAttribute("name", taskName)
                                                     , new XAttribute("description", taskDesc)
                                                     , new XAttribute("enabled", isTaskEnabled.ToString().ToLower())
                                                     );

                            var settings = task.SelectToken("Settings");
                            foreach (var setting in settings)
                            {
                                string settingName  = (string)setting.SelectToken("Name");
                                string settingValue = (string)setting.SelectToken("Value");

                                var xsetting = new XElement(wf.XNamespaceWf + "Setting"
                                                            , new XAttribute("name", settingName)
                                                            );

                                if (settingName == "selectFiles" || settingName == "selectAttachments")
                                {
                                    if (!string.IsNullOrEmpty(settingValue))
                                    {
                                        xsetting.SetAttributeValue("value", settingValue);
                                    }
                                }
                                else
                                {
                                    xsetting.SetAttributeValue("value", settingValue);
                                }

                                var attributes = setting.SelectToken("Attributes");
                                foreach (var attribute in attributes)
                                {
                                    string attributeName  = (string)attribute.SelectToken("Name");
                                    string attributeValue = (string)attribute.SelectToken("Value");
                                    xsetting.SetAttributeValue(attributeName, attributeValue);
                                }

                                xtask.Add(xsetting);
                            }

                            xtasks.Add(xtask);
                        }

                        xdoc.Save(wf.WorkflowFilePath);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
示例#5
0
        public static void Main(string[] args)
        {
            Config = new ConfigurationBuilder()
                     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                     .Build();

            var log4NetConfig = new XmlDocument();

            log4NetConfig.Load(File.OpenRead("log4net.config"));
            var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

            XmlConfigurator.Configure(repo, log4NetConfig["log4net"]);

            var settingsFile = Config["WexflowSettingsFile"];

            superAdminUsername = Config["SuperAdminUsername"];
            var enableWorkflowsHotFolder = bool.Parse(Config["EnableWorkflowsHotFolder"]);
            var enableRecordsHotFolder   = bool.Parse(Config["EnableRecordsHotFolder"]);
            var enableEmailNotifications = bool.Parse(Config["EnableEmailNotifications"]);
            var smtpHost      = Config["Smtp.Host"];
            var smtpPort      = int.Parse(Config["Smtp.Port"]);
            var smtpEnableSsl = bool.Parse(Config["Smtp.EnableSsl"]);
            var smtpUser      = Config["Smtp.User"];
            var smtpPassword  = Config["Smtp.Password"];
            var smtpFrom      = Config["Smtp.From"];

            WexflowEngine = new WexflowEngine(settingsFile
                                              , enableWorkflowsHotFolder
                                              , superAdminUsername
                                              , enableEmailNotifications
                                              , smtpHost
                                              , smtpPort
                                              , smtpEnableSsl
                                              , smtpUser
                                              , smtpPassword
                                              , smtpFrom
                                              );

            if (enableWorkflowsHotFolder)
            {
                InitializeWorkflowsFileSystemWatcher();
            }
            else
            {
                Logger.Info("Workflows hot folder is disabled.");
            }

            if (enableRecordsHotFolder)
            {
                // On file found.
                foreach (var file in Directory.GetFiles(WexflowEngine.RecordsHotFolder))
                {
                    var recordId = WexflowEngine.SaveRecordFromFile(file, superAdminUsername);

                    if (recordId != "-1")
                    {
                        Logger.Info($"Record inserted from file {file}. RecordId: {recordId}");
                    }
                    else
                    {
                        Logger.Error($"An error occured while inserting a record from the file {file}.");
                    }
                }

                // On file created.
                InitializeRecordsFileSystemWatcher();
            }
            else
            {
                Logger.Info("Records hot folder is disabled.");
            }

            WexflowEngine.Run();

            var port = int.Parse(Config["WexflowServicePort"]);

            var host = new WebHostBuilder()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseKestrel((context, options) =>
            {
                options.ListenAnyIP(port);
            })
                       .UseStartup <Startup>()
                       .Build();

            host.Run();

            Console.Write("Press any key to stop Wexflow server...");
            Console.ReadKey();
            WexflowEngine.Stop(true, true);
        }
示例#6
0
        public bool IsCronExpressionValid(string expression)
        {
            var res = WexflowEngine.IsCronExpressionValid(expression);

            return(res);
        }
示例#7
0
        public static void Main(string[] args)
        {
            try
            {
                Config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .Build();

                int port = int.Parse(Config["WexflowServicePort"]);

                XmlDocument log4NetConfig = new XmlDocument();
                log4NetConfig.Load(File.OpenRead("log4net.config"));
                var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
                XmlConfigurator.Configure(repo, log4NetConfig["log4net"]);

                string wexflowSettingsFile = Config["WexflowSettingsFile"];
                WexflowEngine = new WexflowEngine(wexflowSettingsFile
                                                  , Config["WorkiomAuthUrl"]
                                                  , Config["CreateRecordUrl"]
                                                  , Config["UpdateRecordUrl"]
                                                  , Config["NotifyUserUrl"]);

                WexflowEngine.Run();

                var uri       = Config["CloudAmpqUrl"];
                var queueName = Config["QueueName"];
                var factory   = new ConnectionFactory()
                {
                    Uri = new Uri(uri)
                };
                //var factory = new ConnectionFactory() { HostName = "localhost" };
                //var wexflowWebServiceUri = string.Format("http://localhost:{0}/wexflow/", port);
                var wexflowWebServiceUri = Config["WexflowWebServiceUri"];
                var client   = new WexflowServiceClient(wexflowWebServiceUri);
                var username = Config["Username"];
                var password = Config["Password"];
                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: queueName,
                                             durable: true,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);

                        var consumer = new EventingBasicConsumer(channel);
                        consumer.Received += (model, ea) =>
                        {
                            try
                            {
                                var body    = ea.Body;
                                var message = Encoding.UTF8.GetString(body);
                                Logger.InfoFormat("Received: {0}", message);

                                var o          = JObject.Parse(message);
                                var workflowId = o.Value <int>("workflowId");
                                var payload    = o.Value <JObject>("payload");

                                var parameters =
                                    "[" +
                                    "{\"ParamName\":\"Payload\",\"ParamValue\":" + (payload == null ? "\"\"" : payload.ToString()) + "}" +
                                    "]";

                                var started = client.StartWorkflow(workflowId, username, password, parameters);

                                if (started)
                                {
                                    Logger.InfoFormat("Workflow {0} started.", workflowId);
                                }
                                else
                                {
                                    Logger.ErrorFormat("Workflow {0} not started. Error: Unauthorized.", workflowId);
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Error("An error occured while consuming queue message.", e);
                            }
                        };
                        channel.BasicConsume(queue: queueName,
                                             autoAck: true,
                                             consumer: consumer);

                        var host = new WebHostBuilder()
                                   .UseContentRoot(Directory.GetCurrentDirectory())
                                   .UseKestrel((context, options) =>
                        {
                            options.ListenAnyIP(port);
                        })
                                   .UseStartup <Startup>()
                                   .Build();

                        host.Run();
                    }
            }
            catch (Exception e)
            {
                Logger.Error("An error occured while starting Wexflow server.", e);
            }

            Console.WriteLine();
            Console.Write("Press any key to stop Wexflow server...");
            Console.ReadKey();
        }
示例#8
0
        public override TaskStatus Run()
        {
            InfoFormat("Watching the folder {0} ...", FolderToWatch);

            try
            {
                if (!Directory.Exists(FolderToWatch))
                {
                    ErrorFormat("The folder {0} does not exist.", FolderToWatch);
                    return(new TaskStatus(Status.Error));
                }

                Info("Checking existing files...");
                var files = GetFiles();

                foreach (var file in files)
                {
                    InfoFormat("FileSystemWatcher.OnFound started for {0}", file);
                    try
                    {
                        if (SafeMode && WexflowEngine.IsFileLocked(file))
                        {
                            Info($"File lock detected on file {file}");
                            while (WexflowEngine.IsFileLocked(file))
                            {
                                Thread.Sleep(1000);
                            }
                        }
                        ClearFiles();
                        Files.Add(new FileInf(file, Id));
                        var tasks = GetTasks(OnFileFound);
                        foreach (var task in tasks)
                        {
                            task.Logs.Clear();
                            task.Run();
                            CurrentLogs.AddRange(task.Logs);
                        }
                        Files.RemoveAll(f => f.Path == file);
                    }
                    catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
                    {
                        Logger.InfoFormat("There is a sharing violation for the file {0}.", file);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while triggering FileSystemWatcher.OnFound on the file {0}. Message: {1}", file, ex.Message);
                    }
                    finally
                    {
                        Info("FileSystemWatcher.OnFound finished.");
                    }
                    try
                    {
                        var entry = Workflow.Database.GetEntry(Workflow.Id, Workflow.InstanceId);
                        entry.Logs = string.Join("\r\n", CurrentLogs);
                        Workflow.Database.UpdateEntry(entry.GetDbId(), entry);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while updating FileSystemWatcher.OnFound database entry.", ex);
                    }
                }
                Info("Checking existing files finished.");


                Info("Initializing PollingFileSystemWatcher...");
                Watcher = new PollingFileSystemWatcher(FolderToWatch, Filter, new EnumerationOptions {
                    RecurseSubdirectories = IncludeSubFolders
                });

                // Add event handlers.
                Watcher.ChangedDetailed += OnChanged;

                // Begin watching.
                Watcher.Start();
                InfoFormat("PollingFileSystemWatcher.Path={0}", Watcher.Path);
                InfoFormat("PollingFileSystemWatcher.Filter={0}", Watcher.Filter);
                Info("PollingFileSystemWatcher Initialized.");

                Info("Begin watching ...");
                CurrentLogs.AddRange(Logs);
                while (!IsStopped)
                {
                    Thread.Sleep(1);
                }
                Watcher.Dispose();
            }
            catch (Exception e)
            {
                if (Watcher != null)
                {
                    Watcher.Dispose();
                }
                ErrorFormat("An error occured while watching the folder {0}. Error: {1}", FolderToWatch, e.Message);
                return(new TaskStatus(Status.Error, false));
            }

            Info("Task finished");
            return(new TaskStatus(Status.Success));
        }
示例#9
0
        private void OnChanged(object source, PollingFileSystemEventArgs e)
        {
            foreach (var change in e.Changes)
            {
                var path = Path.Combine(change.Directory, change.Name);
                switch (change.ChangeType)
                {
                case WatcherChangeTypes.Created:
                    Info("PollingFileSystemWatcher.OnCreated started.");
                    try
                    {
                        if (SafeMode && WexflowEngine.IsFileLocked(path))
                        {
                            Info($"File lock detected on file {path}");
                            while (WexflowEngine.IsFileLocked(path))
                            {
                                Thread.Sleep(1000);
                            }
                        }
                        ClearFiles();
                        Files.Add(new FileInf(path, Id));
                        var tasks = GetTasks(OnFileCreated);
                        foreach (var task in tasks)
                        {
                            task.Logs.Clear();
                            task.Run();
                            CurrentLogs.AddRange(task.Logs);
                        }
                        Files.RemoveAll(f => f.Path == path);
                    }
                    catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
                    {
                        Logger.InfoFormat("There is a sharing violation for the file {0}.", path);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while triggering PollingFileSystemWatcher.OnCreated on the file {0}. Message: {1}", path, ex.Message);
                    }
                    Info("PollingFileSystemWatcher.OnCreated finished.");

                    try
                    {
                        var entry = Workflow.Database.GetEntry(Workflow.Id, Workflow.InstanceId);
                        entry.Logs = string.Join("\r\n", CurrentLogs);
                        Workflow.Database.UpdateEntry(entry.GetDbId(), entry);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while updating PollingFileSystemWatcher.OnCreated database entry.", ex);
                    }
                    break;

                case WatcherChangeTypes.Changed:
                    Info("PollingFileSystemWatcher.OnChanged started.");
                    try
                    {
                        if (SafeMode && WexflowEngine.IsFileLocked(path))
                        {
                            Info($"File lock detected on file {path}");
                            while (WexflowEngine.IsFileLocked(path))
                            {
                                Thread.Sleep(1000);
                            }
                        }
                        ClearFiles();
                        Files.Add(new FileInf(path, Id));
                        var tasks = GetTasks(OnFileChanged);
                        foreach (var task in tasks)
                        {
                            task.Logs.Clear();
                            task.Run();
                            CurrentLogs.AddRange(task.Logs);
                        }
                        Files.RemoveAll(f => f.Path == path);
                    }
                    catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
                    {
                        Logger.InfoFormat("There is a sharing violation for the file {0}.", path);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while triggering PollingFileSystemWatcher.OnChanged on the file {0}. Message: {1}", path, ex.Message);
                    }
                    Info("PollingFileSystemWatcher.OnChanged finished.");

                    try
                    {
                        var entry = Workflow.Database.GetEntry(Workflow.Id, Workflow.InstanceId);
                        entry.Logs = string.Join("\r\n", CurrentLogs);
                        Workflow.Database.UpdateEntry(entry.GetDbId(), entry);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while updating PollingFileSystemWatcher.OnChanged database entry.", ex);
                    }
                    break;

                case WatcherChangeTypes.Deleted:
                    Info("PollingFileSystemWatcher.OnDeleted started.");
                    try
                    {
                        ClearFiles();
                        Files.Add(new FileInf(path, Id));
                        var tasks = GetTasks(OnFileDeleted);
                        foreach (var task in tasks)
                        {
                            task.Logs.Clear();
                            task.Run();
                            CurrentLogs.AddRange(task.Logs);
                        }
                        Files.RemoveAll(f => f.Path == path);
                    }
                    catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
                    {
                        Logger.InfoFormat("There is a sharing violation for the file {0}.", path);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while triggering PollingFileSystemWatcher.OnDeleted on the file {0}. Message: {1}", path, ex.Message);
                    }
                    Info("PollingFileSystemWatcher.OnDeleted finished.");

                    try
                    {
                        var entry = Workflow.Database.GetEntry(Workflow.Id, Workflow.InstanceId);
                        entry.Logs = string.Join("\r\n", CurrentLogs);
                        Workflow.Database.UpdateEntry(entry.GetDbId(), entry);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while updating PollingFileSystemWatcher.OnDeleted database entry.", ex);
                    }
                    break;
                }
            }
        }
示例#10
0
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            try
            {
                Thread.Sleep(500);

                if (File.Exists(e.FullPath) && !IsDirectory(e.FullPath))
                {
                    Info("FileSystemWatcher.OnChanged started.");
                    if (SafeMode && WexflowEngine.IsFileLocked(e.FullPath))
                    {
                        Info($"File lock detected on file {e.FullPath}");

                        while (WexflowEngine.IsFileLocked(e.FullPath))
                        {
                            Thread.Sleep(1000);
                        }
                    }
                    try
                    {
                        ClearFiles();
                        Files.Add(new FileInf(e.FullPath, Id));
                        var tasks = GetTasks(OnFileChanged);
                        foreach (var task in tasks)
                        {
                            task.Logs.Clear();
                            task.Run();
                            CurrentLogs.AddRange(task.Logs);
                        }
                        Files.RemoveAll(f => f.Path == e.FullPath);
                    }
                    catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
                    {
                        Logger.InfoFormat("There is a sharing violation for the file {0}.", e.FullPath);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while triggering FileSystemWatcher.OnChanged on the file {0}. Message: {1}", e.FullPath, ex.Message);
                    }
                    Info("FileSystemWatcher.OnChanged finished.");

                    try
                    {
                        var entry = Workflow.Database.GetEntry(Workflow.Id, Workflow.InstanceId);
                        entry.Logs = string.Join("\r\n", CurrentLogs);
                        Workflow.Database.UpdateEntry(entry.GetDbId(), entry);
                    }
                    catch (Exception ex)
                    {
                        ErrorFormat("An error while updating FileSystemWatcher.OnChanged database entry.", ex);
                    }
                }
            }
            catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
            {
                Logger.InfoFormat("There is a sharing violation for the file {0}.", e.FullPath);
            }
            catch (Exception ex)
            {
                ErrorFormat("An error while triggering FileSystemWatcher.OnChanged on the file {0}. Message: {1}", e.FullPath, ex.Message);
            }
        }
示例#11
0
        private void InitFileSystemWatcher()
        {
            Info("Checking existing files...");
            var files = GetFiles();

            foreach (var file in files)
            {
                InfoFormat("FileSystemWatcher.OnFound started for {0}", file);
                try
                {
                    if (SafeMode && WexflowEngine.IsFileLocked(file))
                    {
                        Info($"File lock detected on file {file}");
                        while (WexflowEngine.IsFileLocked(file))
                        {
                            Thread.Sleep(1000);
                        }
                    }
                    ClearFiles();
                    Files.Add(new FileInf(file, Id));
                    var tasks = GetTasks(OnFileFound);
                    foreach (var task in tasks)
                    {
                        task.Logs.Clear();
                        task.Run();
                        CurrentLogs.AddRange(task.Logs);
                    }
                    Files.RemoveAll(f => f.Path == file);
                }
                catch (IOException ex) when((ex.HResult & 0x0000FFFF) == 32)
                {
                    Logger.InfoFormat("There is a sharing violation for the file {0}.", file);
                }
                catch (Exception ex)
                {
                    ErrorFormat("An error while triggering FileSystemWatcher.OnFound on the file {0}. Message: {1}", file, ex.Message);
                }
                Info("FileSystemWatcher.OnFound finished.");
            }

            try
            {
                var entry = Workflow.Database.GetEntry(Workflow.Id, Workflow.InstanceId);
                entry.Logs = string.Join("\r\n", CurrentLogs);
                Workflow.Database.UpdateEntry(entry.GetDbId(), entry);
            }
            catch (Exception ex)
            {
                ErrorFormat("An error while updating FileSystemWatcher.OnFound database entry.", ex);
            }
            Info("Checking existing files finished.");

            Info("Initializing FileSystemWatcher...");
            Watcher = new IO.FileSystemWatcher
            {
                Path   = FolderToWatch,
                Filter = Filter,
                IncludeSubdirectories = IncludeSubFolders
            };

            // Add event handlers.
            Watcher.Created += OnCreated;
            Watcher.Changed += OnChanged;
            Watcher.Deleted += OnDeleted;

            // Begin watching.
            Watcher.EnableRaisingEvents = true;
            InfoFormat("FileSystemWatcher.Path={0}", Watcher.Path);
            InfoFormat("FileSystemWatcher.Filter={0}", Watcher.Filter);
            InfoFormat("FileSystemWatcher.EnableRaisingEvents={0}", Watcher.EnableRaisingEvents);
            Info("FileSystemWatcher Initialized.");

            Info("Begin watching ...");
            CurrentLogs.AddRange(Logs);
            while (true)
            {
                Thread.Sleep(1);
            }
        }