Ejemplo n.º 1
0
 protected void Application_End(object sender, EventArgs e)
 {
     using (ILoggingOperation log = _logger.CriticalOperation())
     {
         log.Wrap(() => Scheduler.Shutdown(true));
     }
 }
        public void ResumeJobs(IEnumerable <string> jobIdList)
        {
            using (ILoggingOperation log = _logger.NormalOperation())
            {
                log.Wrap(() =>
                {
                    List <JobDetail> result = new List <JobDetail>();

                    foreach (JobKey item in Global.Scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(ServiceConstants.JobGroupName))
                             .Where(p => jobIdList.Contains(p.Name))
                             )
                    {
                        using (ILoggingOperation tmpLog = log.NormalOperation()
                                                          .AddProperty("jobId", item.Name))
                        {
                            tmpLog.SinkWrap(() =>
                            {
                                ITrigger trigger = Global.Scheduler.GetTriggersOfJob(item).First(p => p.Key.Group == ServiceConstants.TriggerGroupName && Global.Scheduler.GetTriggerState(p.Key) == TriggerState.Paused);

                                Global.Scheduler.RescheduleJob(trigger.Key, (ITrigger)trigger.Clone());
                                //Global.Scheduler.ResumeJob(item);
                            });
                        }
                    }
                });
            }
        }
        protected override void RemoteCall(IJobExecutionContext context)
        {
            using (ILoggingOperation log = _logger.NormalOperation())
            {
                log.Wrap(() =>
                {
                    RabbitMQChannelsFactory factory = new RabbitMQChannelsFactory();

                    IChannelWriter <object> ch = null;
                    if (Broadcast)
                    {
                        ch = factory.GetSubscribableChannel <object>(ChannelName);
                    }
                    else
                    {
                        ch = factory.GetChannel <object>(ChannelName);
                    }

                    using (ch)
                    {
                        ch.Write(Message);
                    }
                });
            }
        }
Ejemplo n.º 4
0
        public string PeriodicHttpRequestMessage(string method, Uri destination, Dictionary <string, string> headers, Dictionary <string, string> parameters, TimeSpan delay, TimeSpan period, TimeSpan timeLimit, bool fireAndForget)
        {
            if (delay == null)
            {
                throw new ArgumentNullException("delay");
            }
            if (delay < TimeSpan.Parse("00:00:00"))
            {
                throw new ArithmeticException("delay must be positive");
            }

            if (period == null)
            {
                throw new ArgumentNullException("period");
            }
            if (period < TimeSpan.Parse("00:00:00"))
            {
                throw new ArithmeticException("period must be positive");
            }

            string jobId = _idProducer.GetId();

            using (ILoggingOperation log = _logger.NormalOperation().AddProperty("jobId", jobId))
            {
                log.Wrap(() =>
                {
                    log.Info($"scheduling request {jobId} HttpRequestJob with parameters method={method}, destination={destination}, headaers={headers}, parameters={parameters}, delay={delay}, period={period}, timeLimit={timeLimit}, fireAndForget={fireAndForget}");

                    IJobDetail job = JobBuilder.Create <HttpRequestJob>()
                                     .WithIdentity(jobId, ServiceConstants.JobGroupName)
                                     .StoreDurably(false)
                                     .UsingJobData("Method", method)
                                     .UsingJobData("Destination", destination.ToString())
                                     .UsingJobData("HeadersJSON", JsonConvert.SerializeObject(headers))
                                     .UsingJobData("ParametersJSON", JsonConvert.SerializeObject(parameters))
                                     .UsingJobData("RetryCount", "0")
                                     .UsingJobData("FireAndForget", fireAndForget.ToString())
                                     .Build();
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(Guid.NewGuid().ToString(), Service.ServiceConstants.TriggerGroupName)
                                       .StartAt(DateBuilder.FutureDate((int)delay.TotalMilliseconds, IntervalUnit.Millisecond))
                                       .WithSimpleSchedule(p => p
                                                           .WithMisfireHandlingInstructionFireNow()
                                                           .WithInterval(period)
                                                           .RepeatForever()
                                                           )
                                       .EndAt(DateBuilder.FutureDate((int)(timeLimit == null ? TimeSpan.MaxValue : timeLimit).TotalMilliseconds, IntervalUnit.Millisecond))
                                       .Build();

                    DateTimeOffset t = Global.Scheduler.ScheduleJob(job, trigger);

                    log.Info($"scheduled request {jobId} HttpRequestJob in {t.ToString("HH:mm:ss.fff")}");
                });

                return(jobId);
            }
        }
Ejemplo n.º 5
0
        public string PeriodicSOAPRequestMessage(string hostname, int port, byte[] payload, TimeSpan delay, TimeSpan period, TimeSpan timeLimit, bool fireAndForget)
        {
            if (delay == null)
            {
                throw new ArgumentNullException("delay");
            }
            if (delay < TimeSpan.Parse("00:00:00"))
            {
                throw new ArithmeticException("delay must be positive");
            }

            if (period == null)
            {
                throw new ArgumentNullException("period");
            }
            if (period < TimeSpan.Parse("00:00:00"))
            {
                throw new ArithmeticException("period must be positive");
            }

            string jobId = _idProducer.GetId();

            using (ILoggingOperation log = _logger.NormalOperation().AddProperty("jobId", jobId))
            {
                log.Wrap(() =>
                {
                    log.Info($"scheduling request {jobId} TCPRequestJob with parameters hostname={hostname}, port={port}, payload={Convert.ToBase64String(payload)}, delay={delay}, period={period}, timeLimit={timeLimit}, fireAndForget={fireAndForget}");

                    IJobDetail job = JobBuilder.Create <SOAPRequestJob>()
                                     .WithIdentity(jobId, ServiceConstants.JobGroupName)
                                     .StoreDurably(false)
                                     .UsingJobData("Hostname", hostname)
                                     .UsingJobData("Port", port.ToString())
                                     .UsingJobData("PayloadBase64", Convert.ToBase64String(payload))
                                     .UsingJobData("RetryCount", "0")
                                     .UsingJobData("FireAndForget", fireAndForget.ToString())
                                     .Build();
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(Guid.NewGuid().ToString(), Service.ServiceConstants.TriggerGroupName)
                                       .StartAt(DateBuilder.FutureDate((int)delay.TotalMilliseconds, IntervalUnit.Millisecond))
                                       .WithSimpleSchedule(p => p
                                                           .WithMisfireHandlingInstructionFireNow()
                                                           .WithInterval(period)
                                                           .RepeatForever()
                                                           )
                                       .EndAt(DateBuilder.FutureDate((int)(timeLimit == null ? TimeSpan.MaxValue : timeLimit).TotalMilliseconds, IntervalUnit.Millisecond))
                                       .Build();

                    DateTimeOffset t = Global.Scheduler.ScheduleJob(job, trigger);

                    log.Info($"scheduled request {jobId} TCPRequestJob in {t.ToString("HH:mm:ss.fff")}");
                });

                return(jobId);
            }
        }
Ejemplo n.º 6
0
 public void TestMethod2()
 {
     using (ILoggingOperation op = LogManager.GetLogger("Test2").NormalOperation())
     {
         op.Wrap(() =>
         {
             Assert.IsTrue(true);
             throw new Exception("xy");
         });
     }
     Assert.IsTrue(true);
 }
Ejemplo n.º 7
0
 public void TestMethod1()
 {
     using (ILoggingOperation op = LogManager.GetLogger("Test1").NormalOperation())
     {
         op.Wrap(() =>
         {
             Assert.IsTrue(true);
             op.InfoFormat("Prova di log format {0}", DateTime.Now);
         });
     }
     Assert.IsTrue(true);
 }
Ejemplo n.º 8
0
        protected void Application_Start(object sender, EventArgs e)
        {
            _logger = LogManager.GetLogger(GetType());

            using (ILoggingOperation log = _logger.CriticalOperation())
            {
                log.Wrap(() =>
                {
                    ProbeManager.Init();
                    HealthCheckManager.Init();
                    ReportingManager.Init();
                    RemoteReportingManager.Init();
                });

                log.Wrap(() => ChannelsRabbitMQManager.Init());

                log.Wrap(() => Factory   = new StdSchedulerFactory());
                log.Wrap(() => Scheduler = Factory.GetScheduler());

                log.Wrap(() => Scheduler.Start());
            }
        }
 public void AbortJob(string jobId)
 {
     using (ILoggingOperation log = _logger.NormalOperation()
                                    .AddProperty("jobId", jobId))
     {
         log.Wrap(() =>
         {
             if (!Global.Scheduler.DeleteJob(JobKey.Create(jobId, ServiceConstants.JobGroupName)))
             {
                 throw new Exception("Error executing job deletion.");
             }
         });
     }
 }
        public List <JobDetail> ListJobs(string jobIdFilter)
        {
            if (string.IsNullOrEmpty(jobIdFilter))
            {
                jobIdFilter = ".*";
            }

            using (ILoggingOperation log = _logger.NormalOperation())
            {
                return(log.Wrap <List <JobDetail> >(() =>
                {
                    List <JobDetail> result = new List <JobDetail>();

                    foreach (JobKey item in Global.Scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(ServiceConstants.JobGroupName))
                             .Where(p => Regex.IsMatch(p.Name, jobIdFilter))
                             )
                    {
                        IJobDetail detail = Global.Scheduler.GetJobDetail(item);
                        IEnumerable <ITrigger> triggers = Global.Scheduler.GetTriggersOfJob(item);

                        JobDetail jdet = new JobDetail()
                        {
                            JobId = item.Name,
                            JobDataMap = detail.JobDataMap.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()),
                            Triggers = new List <TriggerDetail>(),
                            Paused = triggers.Any(p => p.Key.Group == ServiceConstants.TriggerGroupName && Global.Scheduler.GetTriggerState(p.Key) == TriggerState.Paused)
                        };

                        foreach (ITrigger trigger in triggers)
                        {
                            DateTimeOffset?nf = trigger.GetNextFireTimeUtc();
                            jdet.Triggers.Add(new TriggerDetail()
                            {
                                TriggerId = trigger.Key.ToString(),
                                JobDataMap = trigger.JobDataMap.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()),
                                StartTime = trigger.StartTimeUtc.UtcDateTime,
                                NextFireTime = nf.HasValue ? nf.Value.UtcDateTime : (DateTime?)null
                            });
                        }

                        result.Add(jdet);
                    }

                    return result;
                }));
            }
        }
Ejemplo n.º 11
0
        public string CRONHttpRequestMessage(string method, Uri destination, Dictionary <string, string> headers, Dictionary <string, string> parameters, string CRONString, TimeSpan timeLimit, bool fireAndForget)
        {
            if (CRONString == null)
            {
                throw new ArgumentNullException("CRONString");
            }
            if (!CronExpression.IsValidExpression(CRONString))
            {
                throw new ArgumentException("CRONString is not a valid cron string");
            }

            string jobId = _idProducer.GetId();

            using (ILoggingOperation log = _logger.NormalOperation().AddProperty("jobId", jobId))
            {
                log.Wrap(() =>
                {
                    log.Info($"scheduling request {jobId} HttpRequestJob with parameters method={method}, destination={destination}, headaers={headers}, parameters={parameters}, CRONString={CRONString}, timeLimit={timeLimit}, fireAndForget={fireAndForget}");

                    IJobDetail job = JobBuilder.Create <HttpRequestJob>()
                                     .WithIdentity(jobId, ServiceConstants.JobGroupName)
                                     .StoreDurably(false)
                                     .UsingJobData("Method", method)
                                     .UsingJobData("Destination", destination.ToString())
                                     .UsingJobData("HeadersJSON", JsonConvert.SerializeObject(headers))
                                     .UsingJobData("ParametersJSON", JsonConvert.SerializeObject(parameters))
                                     .UsingJobData("RetryCount", "0")
                                     .UsingJobData("FireAndForget", fireAndForget.ToString())
                                     .Build();
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(Guid.NewGuid().ToString(), Service.ServiceConstants.TriggerGroupName)
                                       .StartAt(DateBuilder.FutureDate(0, IntervalUnit.Millisecond))
                                       .WithCronSchedule(CRONString, p => p
                                                         .WithMisfireHandlingInstructionFireAndProceed()
                                                         )
                                       .EndAt(DateBuilder.FutureDate((int)(timeLimit == null ? TimeSpan.MaxValue : timeLimit).TotalMilliseconds, IntervalUnit.Millisecond))
                                       .Build();

                    DateTimeOffset t = Global.Scheduler.ScheduleJob(job, trigger);

                    log.Info($"scheduled request {jobId} HttpRequestJob in {t.ToString("HH:mm:ss.fff")}");
                });

                return(jobId);
            }
        }
Ejemplo n.º 12
0
        public string CRONSOAPRequestMessage(string hostname, int port, byte[] payload, string CRONString, TimeSpan timeLimit, bool fireAndForget)
        {
            if (CRONString == null)
            {
                throw new ArgumentNullException("CRONString");
            }
            if (!CronExpression.IsValidExpression(CRONString))
            {
                throw new ArgumentException("CRONString is not a valid cron string");
            }

            string jobId = _idProducer.GetId();

            using (ILoggingOperation log = _logger.NormalOperation().AddProperty("jobId", jobId))
            {
                log.Wrap(() =>
                {
                    log.Info($"scheduling request {jobId} TCPRequestJob with parameters hostname={hostname}, port={port}, payload={Convert.ToBase64String(payload)}, CRONString={CRONString}, timeLimit={timeLimit}, fireAndForget={fireAndForget}");

                    IJobDetail job = JobBuilder.Create <SOAPRequestJob>()
                                     .WithIdentity(jobId, ServiceConstants.JobGroupName)
                                     .StoreDurably(false)
                                     .UsingJobData("Hostname", hostname)
                                     .UsingJobData("Port", port.ToString())
                                     .UsingJobData("PayloadBase64", Convert.ToBase64String(payload))
                                     .UsingJobData("RetryCount", "0")
                                     .UsingJobData("FireAndForget", fireAndForget.ToString())
                                     .Build();
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(Guid.NewGuid().ToString(), Service.ServiceConstants.TriggerGroupName)
                                       .StartAt(DateBuilder.FutureDate(0, IntervalUnit.Millisecond))
                                       .WithCronSchedule(CRONString, p => p
                                                         .WithMisfireHandlingInstructionFireAndProceed()
                                                         )
                                       .EndAt(DateBuilder.FutureDate((int)(timeLimit == null ? TimeSpan.MaxValue : timeLimit).TotalMilliseconds, IntervalUnit.Millisecond))
                                       .Build();

                    DateTimeOffset t = Global.Scheduler.ScheduleJob(job, trigger);

                    log.Info($"scheduled request {jobId} TCPRequestJob in {t.ToString("HH:mm:ss.fff")}");
                });

                return(jobId);
            }
        }
Ejemplo n.º 13
0
        public string DelayedChannelMessage(string channelName, bool broadcast, string message, TimeSpan delay, int retryCount, bool fireAndForget)
        {
            if (delay == null)
            {
                throw new ArgumentNullException("delay");
            }
            if (delay < TimeSpan.Parse("00:00:00"))
            {
                throw new ArithmeticException("delay must be positive");
            }

            string jobId = _idProducer.GetId();

            using (ILoggingOperation log = _logger.NormalOperation().AddProperty("jobId", jobId))
            {
                log.Wrap(() =>
                {
                    log.Info($"scheduling request {jobId} ChannelsMessageJob with parameters channelName={channelName}, broadcast={broadcast}, message={message}, delay={delay}, retryCount={retryCount}, fireAndForget={fireAndForget}");

                    IJobDetail job = JobBuilder.Create <ChannelsMessageJob>()
                                     .WithIdentity(jobId, ServiceConstants.JobGroupName)
                                     .StoreDurably(false)
                                     .UsingJobData("ChannelName", channelName)
                                     .UsingJobData("Broadcast", broadcast)
                                     .UsingJobData("Message", message)
                                     .UsingJobData("RetryCount", retryCount.ToString())
                                     .UsingJobData("FireAndForget", fireAndForget.ToString())
                                     .Build();
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(Guid.NewGuid().ToString(), Service.ServiceConstants.TriggerGroupName)
                                       .StartAt(DateBuilder.FutureDate((int)delay.TotalMilliseconds, IntervalUnit.Millisecond))
                                       .WithSimpleSchedule(p => p.WithMisfireHandlingInstructionFireNow())
                                       .Build();

                    DateTimeOffset t = Global.Scheduler.ScheduleJob(job, trigger);

                    log.Info($"scheduled request {jobId} ChannelsMessageJob in {t.ToString("HH:mm:ss.fff")}");
                });

                return(jobId);
            }
        }
Ejemplo n.º 14
0
        protected virtual void StopJob(bool success)
        {
            using (ILoggingOperation log = _logger.NormalOperation())
                using (ChannelFactory <ISchedulerService> ch = new ChannelFactory <ISchedulerService>(ClientUtilManager.Ask().EndpointConfigurationName))
                {
                    log.Wrap(() =>
                    {
                        ISchedulerService svc = ch.CreateChannel();

                        JobContextData data = GetContextData();
                        if (data == null)
                        {
                            log.Debug("No JobContextData found.");
                        }
                        else
                        {
                            svc.StopJob(data.JobId, success);
                        }
                    });
                }
        }
Ejemplo n.º 15
0
 public void StopJob(string jobId, bool success)
 {
     using (ILoggingOperation log = _logger.NormalOperation()
                                    .AddProperty("jobId", jobId))
     {
         log.Wrap(() =>
         {
             if (!Global.Scheduler.DeleteJob(JobKey.Create(jobId, ServiceConstants.JobGroupName)))
             {
                 throw new Exception("Error executing job deletion.");
             }
             if (success)
             {
                 log.Info($"job stopped with success");
             }
             else
             {
                 log.Info($"job stopped with failure");
             }
         });
     }
 }
Ejemplo n.º 16
0
        protected override void RemoteCall(IJobExecutionContext context)
        {
            using (ILoggingOperation log = _logger.NormalOperation())
                using (TcpClient client = new TcpClient(Hostname, Convert.ToInt32(Port)))
                    using (NetworkStream stream = client.GetStream())
                    {
                        log.Wrap(() =>
                        {
                            stream.ReadTimeout  = _readTimeoutMillis;
                            stream.WriteTimeout = _writeTimeoutMillis;

                            byte[] tmp = Convert.FromBase64String(PayloadBase64);

                            StringBuilder result = new StringBuilder(tmp.Length + 200);
                            using (MemoryStream ms = new MemoryStream(tmp))
                                using (StreamReader sr = new StreamReader(ms))
                                {
                                    string line = null;
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        if (Regex.IsMatch(line, "Content-Length", RegexOptions.IgnoreCase))
                                        {
                                            result.AppendLine($"{JobContextData.JobDataHeaderName}:{JsonConvert.SerializeObject(new JobContextData() { JobGroup = context.JobDetail.Key.Group, JobId = context.JobDetail.Key.Name })}");
                                            log.Debug("added jobContextData");
                                        }
                                        result.AppendLine(line);
                                    }
                                    tmp = sr.CurrentEncoding.GetBytes(result.ToString());
                                }

                            log.Debug("calling service");
                            stream.Write(tmp, 0, tmp.Length);
                            log.Debug("request sent");

                            if (Convert.ToBoolean(FireAndForget) == false)
                            {
                                using (StreamReader sr = new StreamReader(stream))
                                {
                                    log.Debug("waiting response");

                                    StringBuilder b = new StringBuilder();
                                    string x        = null;
                                    int cntLength   = 0;
                                    while (x != "")
                                    {
                                        x       = sr.ReadLine();
                                        Match m = Regex.Match(x, "Content-Length:\\s*(\\d+)");
                                        if (m.Success)
                                        {
                                            cntLength = Convert.ToInt32(m.Groups[1].ToString());
                                        }
                                        b.AppendLine(x);
                                    }

                                    byte[] msg = new byte[cntLength];
                                    for (int i = 0; i < cntLength; i++)
                                    {
                                        msg[i] = (byte)sr.Read();
                                    }
                                    string res = b.ToString();

                                    log.Debug("response received");

                                    if (!Regex.IsMatch(res.Split('\n')[0], "20\\d"))
                                    {
                                        throw new Exception($"Error invoking service. {res}");
                                    }
                                }
                            }
                            else
                            {
                                log.Debug("FireAndForget set.");
                            }
                        });
                    }
        }
Ejemplo n.º 17
0
        protected override void RemoteCall(IJobExecutionContext context)
        {
            using (ILoggingOperation log = _logger.NormalOperation())
                using (HttpClient client = new HttpClient())
                {
                    log.Wrap(() =>
                    {
                        Dictionary <string, string> content = JsonConvert.DeserializeObject <Dictionary <string, string> >(ParametersJSON);
                        Dictionary <string, string> headers = JsonConvert.DeserializeObject <Dictionary <string, string> >(HeadersJSON);

                        headers.Add(JobContextData.JobDataHeaderName, JsonConvert.SerializeObject(new JobContextData()
                        {
                            JobGroup = context.JobDetail.Key.Group, JobId = context.JobDetail.Key.Name
                        }));
                        log.Debug("added jobContextData");

                        client.Timeout = TimeSpan.FromMilliseconds((int)_readTimeoutMillis + (int)_writeTimeoutMillis);

                        foreach (string hd in headers.Keys)
                        {
                            if (client.DefaultRequestHeaders.Contains(hd))
                            {
                                client.DefaultRequestHeaders.Remove(hd);
                            }
                            client.DefaultRequestHeaders.Add(hd, headers[hd]);
                        }

                        log.Debug("calling service");

                        Task <HttpResponseMessage> resp;
                        switch (Method.ToUpper())
                        {
                        case "GET":
                            resp = client.GetAsync(Destination);
                            break;

                        case "POST":
                            resp = client.PostAsync(Destination, new FormUrlEncodedContent(content));
                            break;

                        case "PUT":
                            resp = client.PutAsync(Destination, new FormUrlEncodedContent(content));
                            break;

                        default:
                            throw new ArgumentException($"Method {Method} not allowed");
                        }

                        log.Debug("request sent");

                        if (Convert.ToBoolean(FireAndForget) == false)
                        {
                            log.Debug("waiting response");
                            resp.Wait();
                            log.Debug("response received");
                            resp.Result.EnsureSuccessStatusCode();
                        }
                        else
                        {
                            log.Debug("FireAndForget set.");
                        }
                    });
                }
        }