public void OnPerforming(PerformingContext filterContext)
        {
            string             correlationId      = filterContext.GetJobParameter <string>(CorrelationIdKey) ?? filterContext.BackgroundJob.Id;
            IActivity          activity           = _activityFactory.CreateActivity();
            CorrelationContext correlationContext = activity.Start(correlationId);

            if (correlationContext != null)
            {
                filterContext.Items[CorrelationIdKey]     = correlationContext.CorrelationId;
                filterContext.Items[CorrelateActivityKey] = activity;
            }
        }
        public void OnPerforming(PerformingContext filterContext)
        {
            AcademyPlatform.Web.Umbraco.UmbracoConfiguration.Extensions.UmbracoContextExtensions.GetOrCreateContext();

            UmbracoContext.Current.PublishedContentRequest = new PublishedContentRequest(
                UmbracoContext.Current.HttpContext.Request.Url,
                UmbracoContext.Current.RoutingContext,
                UmbracoConfig.For.UmbracoSettings().WebRouting,
                s => Roles.Provider.GetRolesForUser(s));

            UmbracoContext.Current.PublishedContentRequest.Prepare();
        }
Пример #3
0
 public void OnPerforming(PerformingContext context)
 {
     _connection    = context.Connection;
     _currentStatus = new JobStatus
     {
         State   = "a",
         Success = false,
         Data    = null,
         Result  = null
     };
     JobId = context.BackgroundJob.Id;
 }
Пример #4
0
        public void OnPerforming(PerformingContext filterContext)
        {
            //设置新的分布式锁,分布式锁会阻止两个相同的任务并发执行,用方法名称和JobName
            var jobresource = $"{CurrentProcessId}.{filterContext.BackgroundJob.Job.Method.Name}.{filterContext.BackgroundJob.Job.Args[1]}";
            var locktimeout = TimeSpan.FromSeconds(_timeoutInSeconds);

            try
            {
                var jobItem = filterContext.BackgroundJob.Job.Args.FirstOrDefault();
                var job     = jobItem as HttpJobItem;
                if (job == null)
                {
                    return;
                }

                var jobKey = ((!string.IsNullOrEmpty(job.RecurringJobIdentifier)?job.RecurringJobIdentifier:job.JobName));
                if (!string.IsNullOrEmpty(job.JobName) && (TagsServiceStorage.Current != null))
                {
                    filterContext.BackgroundJob.Id.AddTags(job.JobName);
                }

                //设置运行时被设置的参数
                try
                {
                    var hashKey        = CodingUtil.MD5(jobKey + ".runtime");
                    var excuteDataList = filterContext.Connection.GetAllEntriesFromHash(hashKey);
                    if (excuteDataList != null && excuteDataList.Any())
                    {
                        filterContext.Items.Add("runtimeKey", hashKey);
                        //一次性的数据
                        filterContext.Items.Add("runtimeKey_dic", excuteDataList);
                        foreach (var keyvalue in excuteDataList)
                        {
                            filterContext.Items.Add(keyvalue.Key, keyvalue.Value);
                        }
                    }
                }
                catch (Exception)
                {
                    //ignore
                }

                //申请分布式锁
                var distributedLock = filterContext.Connection.AcquireDistributedLock(jobresource, locktimeout);
                filterContext.Items["DistributedLock"] = distributedLock;
            }
            catch (Exception ec)
            {
                filterContext.Canceled = true;
                logger.Info($"[OnPerforming] BackgroundJob.Job.JObName:{filterContext.BackgroundJob.Job.Args[1]} AcquireDistributedLock Timeout,BackgroundJob.Id:{filterContext.BackgroundJob.Id},Exception:{ec}");
            }
        }
Пример #5
0
        public void OnPerforming(PerformingContext filterContext)
        {
            var resource = String.Format(
                "{0}.{1}",
                filterContext.Job.Type.FullName,
                filterContext.Job.Method.Name);

            var timeout = TimeSpan.FromSeconds(_timeoutInSeconds);

            var distributedLock = filterContext.Connection.AcquireDistributedLock(resource, timeout);

            filterContext.Items["DistributedLock"] = distributedLock;
        }
Пример #6
0
        public void OnPerforming(PerformingContext filterContext)
        {
            var jobItem = filterContext.BackgroundJob.Job.Args.FirstOrDefault();
            var job     = jobItem as HttpJobItem;

            if (job == null)
            {
                return;
            }

            try
            {
                if (!string.IsNullOrEmpty(job.JobName) && (TagsServiceStorage.Current != null))
                {
                    filterContext.BackgroundJob.Id.AddTags(job.JobName);

                    if (!string.IsNullOrEmpty(job.RecurringJobIdentifier) &&
                        !job.RecurringJobIdentifier.Equals(job.JobName))
                    {
                        filterContext.BackgroundJob.Id.AddTags(job.RecurringJobIdentifier);
                    }
                }

                //设置运行时被设置的参数
                try
                {
                    var jobKey         = ((!string.IsNullOrEmpty(job.RecurringJobIdentifier) ? job.RecurringJobIdentifier : job.JobName));
                    var hashKey        = CodingUtil.MD5(jobKey + ".runtime");
                    var excuteDataList = filterContext.Connection.GetAllEntriesFromHash(hashKey);
                    if (excuteDataList != null && excuteDataList.Any())
                    {
                        filterContext.Items.Add("runtimeKey", hashKey);
                        //一次性的数据
                        filterContext.Items.Add("runtimeKey_dic", excuteDataList);
                        foreach (var keyvalue in excuteDataList)
                        {
                            filterContext.Items.Add(keyvalue.Key, keyvalue.Value);
                        }
                    }
                }
                catch (Exception)
                {
                    //ignore
                }
            }
            catch (Exception ec)
            {
                filterContext.Canceled = true;
                logger.Warn($"[OnPerforming] BackgroundJob.Job.JObName:{filterContext.BackgroundJob.Job.Args[1]} AcquireDistributedLock Timeout,BackgroundJob.Id:{filterContext.BackgroundJob.Id},Exception:{ec}");
            }
        }
        public void OnPerforming(PerformingContext filterContext)
        {
            var now  = DateTimeOffset.Now;
            var data = filterContext.BackgroundJob.Job.Args.OfType <HangfireRecurringScheduledMessageData>().Single();

            if (data.StartTime > now)
            {
                filterContext.Canceled = true;
            }
            else if (data.EndTime.HasValue && data.EndTime.Value < now)
            {
                filterContext.Canceled = true;
            }
        }
Пример #8
0
        public void OnPerforming(PerformingContext context)
        {
            if (IgnoreEvent(context))
            {
                return;
            }

            var operationName = _options.OperationNameResolver(context);

            GlobalTracer.Instance.BuildSpan(operationName)
            .WithTag(Tags.SpanKind, Tags.SpanKindServer)
            .WithTag(Tags.Component, _options.ComponentName)
            .WithTag(TracingHeaders.JobId, context.BackgroundJob.Id)
            .WithTag(TracingHeaders.CreatedAt, context.BackgroundJob.CreatedAt.ToString())
            .StartActive();
        }
Пример #9
0
        public void OnPerforming(PerformingContext filterContext)
        {
            var resource = GetResource(filterContext.BackgroundJob.Job);
            var timeout  = TimeSpan.FromSeconds(_timeoutInSeconds);

            try
            {
                var disposable = filterContext.Connection.AcquireDistributedLock(resource, timeout);
                filterContext.Items["DistributedLock"] = disposable;
            }
            catch (Exception ex)
            {
                Logger.Warn("HangFire couldn't acquire distributed lock", ex);
                filterContext.Canceled = true;
            }
        }
Пример #10
0
        private static IEnumerable <LogEventProperty> CreateProperties(PerformingContext performingContext)
        {
            var properties = new List <LogEventProperty>()
            {
                new LogEventProperty("Id", new ScalarValue(performingContext.BackgroundJob.Id)),
                new LogEventProperty("CreatedAt", new ScalarValue(performingContext.BackgroundJob.CreatedAt))
            };

            if (performingContext.BackgroundJob.Job != null)
            {
                properties.Add(new LogEventProperty("Type", new ScalarValue(performingContext.BackgroundJob.Job.Method.DeclaringType.Name)));
                properties.Add(new LogEventProperty("Method", new ScalarValue(performingContext.BackgroundJob.Job.Method.Name)));
                properties.Add(new LogEventProperty("Arguments", new SequenceValue(performingContext.BackgroundJob.Job.Args.Select(x => GetScalarValue(x)))));
            }
            return(properties);
        }
    public void OnPerforming(PerformingContext filterContext)
    {
        var resource = $"{filterContext.BackgroundJob.Job.Type.FullName}.{filterContext.BackgroundJob.Job.Method.Name}.{filterContext.BackgroundJob.Id}";
        var timeout  = TimeSpan.FromSeconds(_timeoutInSeconds);

        try
        {
            var distributedLock = filterContext.Connection.AcquireDistributedLock(resource, timeout);
            filterContext.Items["DistributedLock"] = distributedLock;
        }
        catch (Exception)
        {
            filterContext.Canceled = true;
            logger.Warn("Cancelling run for {0} job, id: {1} ", resource, filterContext.BackgroundJob.Id);
        }
    }
Пример #12
0
 /// <summary>
 /// Action: OnPerforming
 /// Description: It is the third filter to cancel any jobs if sync status is not 1 while they are performing.
 /// </summary>
 /// <param name="context"></param>
 void IServerFilter.OnPerforming(PerformingContext context)
 {
     Console.WriteLine(string.Format("Job `{0}` has been performing", context.BackgroundJob?.Id));
     if (context.Canceled == false)
     {
         var ccid        = context.BackgroundJob.Job.Args.ElementAt(2) as string;
         int connectorId = (int)context.BackgroundJob.Job.Args.ElementAt(1);
         if (!string.IsNullOrEmpty(ccid) && connectorId > 0)
         {
             //Check connector status. If it is not 1 then cancel it
             if (SyncRepository.GetSyncStatus(ccid: ccid, connectorId: connectorId) != 1)
             {
                 context.Canceled = true;
             }
         }
     }
 }
Пример #13
0
        public void OnPerforming(PerformingContext filterContext)
        {
            var cultureName   = filterContext.GetJobParameter <string>("CurrentCulture");
            var uiCultureName = filterContext.GetJobParameter <string>("CurrentUICulture");

            if (!String.IsNullOrEmpty(cultureName))
            {
                filterContext.Items["PreviousCulture"] = CultureInfo.CurrentCulture;
                Thread.CurrentThread.CurrentCulture    = new CultureInfo(cultureName);
            }

            if (!String.IsNullOrEmpty(uiCultureName))
            {
                filterContext.Items["PreviousUICulture"] = CultureInfo.CurrentUICulture;
                Thread.CurrentThread.CurrentUICulture    = new CultureInfo(uiCultureName);
            }
        }
        void IServerFilter.OnPerforming(PerformingContext filterContext)
        {
            var jobId       = this.GetJobIdentifier(filterContext.BackgroundJob.Job);
            var connection  = JobStorage.Current.GetConnection();
            var hashEntries = connection.GetAllEntriesFromHash(jobId);

            if (hashEntries is null)
            {
                return;
            }

            if (hashEntries.TryGetValue(ParameterName, out string lastSuccessUtcString) &&
                DateTime.TryParseExact(lastSuccessUtcString, "O", CultureInfo.InvariantCulture, DateTimeStyles.None, out var lastSuccess))
            {
                filterContext.SetJobParameter(ParameterName, lastSuccess);
            }
        }
Пример #15
0
        public void OnPerforming(PerformingContext filterContext)
        {
            //for recurring jobs
            var uniqueOpId = filterContext.GetJobParameter <string>("RecurringJobId");

            if (!string.IsNullOrWhiteSpace(uniqueOpId))
            {
                filterContext.Connection
                .GetAllEntriesFromHash($"{HangfireJobScheduler.RecurrentJobKeyPrefix}::{uniqueOpId}")
                .Where(_kvp => _kvp.Key == HangfireJobScheduler.CustomJobProperty_UserContext)
                .Select(_kvp => _kvp.Value)
                .FirstOrDefault()
                .Do(_v => CallContext.LogicalSetData(CallContextParameters_UserContext, JsonConvert.DeserializeObject <SerializableUserContext>(_v)));
            }

            //create a new resolution scope for use while invoking the job function
            CallContext.LogicalSetData(DependencyResolverScope, _scopeGenerator.Invoke());
        }
        public PreserveCultureAttributeFacts()
        {
            _connection = new Mock <IStorageConnection>();
            var job   = Job.FromExpression(() => Sample());
            var state = new Mock <IState>();

            var createContext = new CreateContext(
                _connection.Object, job, state.Object);

            _creatingContext = new CreatingContext(createContext);

            var workerContext = new WorkerContextMock();

            var performContext = new PerformContext(
                workerContext.Object, _connection.Object, JobId, job, DateTime.UtcNow, new Mock <IJobExecutionContext>().Object);

            _performingContext = new PerformingContext(performContext);
            _performedContext  = new PerformedContext(performContext, null, false, null);
        }
Пример #17
0
        void IServerFilter.OnPerforming(PerformingContext filterContext)
        {
            var appName     = Path.GetFileNameWithoutExtension(Globals.MainModule);
            var operationId = $"{appName}.{filterContext.BackgroundJob.Id}";

            var operationHolder = telemetryClient.StartOperation <RequestTelemetry>(GetJobName(filterContext.BackgroundJob), operationId);

            operationHolder.Telemetry.Properties.Add("arguments", GetJobArguments(filterContext.BackgroundJob));
            operationHolder.Telemetry.Properties.Add("appName", appName);

            operationHolderDict.TryAdd(filterContext.BackgroundJob.Id, operationHolder);

            var eventTelemetry = new EventTelemetry("Job Started");

            eventTelemetry.Context.Operation.Id       = operationId;
            eventTelemetry.Context.Operation.ParentId = operationId;

            telemetryClient.TrackEvent(eventTelemetry);
        }
        public void OnPerforming(PerformingContext filterContext)
        {
            if (filterContext.Connection is not JobStorageConnection connection || connection == null)
            {
                return;
            }

            string?recurringJobId = filterContext.GetJobParameter <string?>("RecurringJobId");

            if (recurringJobId == null || !recurringJobId.EndsWith("start-movie"))
            {
                return;
            }

            if (connection.GetValueFromHash($"recurring-job:{recurringJobId}", "skip") != "true")
            {
                filterContext.Canceled = true;
            }
        }
Пример #19
0
        public void OnPerforming(PerformingContext filterContext)
        {
            DeleteLogfiles();
            //设置分布式锁,分布式锁会阻止两个相同的任务并发执行,用任务名称和方法名称作为锁
            var jobresource = $"{filterContext.BackgroundJob.Job.Args[1]}.{filterContext.BackgroundJob.Job.Method.Name}";
            var locktimeout = TimeSpan.FromSeconds(_timeoutInSeconds);

            try
            {
                //申请分布式锁
                var distributedLock = filterContext.Connection.AcquireDistributedLock(jobresource, locktimeout);
                filterContext.Items["DistributedLock"] = distributedLock;
            }
            catch (Exception ec)
            {
                //获取锁超时,取消任务,任务会默认置为成功
                filterContext.Canceled = true;
                logger.Info($"任务{filterContext.BackgroundJob.Job.Args[1]}超时,任务id{filterContext.BackgroundJob.Id}");
            }
        }
        public void OnPerforming(PerformingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var argumentsArray = context.BackgroundJob.Job?.Args as object[];

            if (argumentsArray == null)
            {
                return;
            }

            var parameters = context.BackgroundJob.Job.Method.GetParameters();

            for (var index = 0; index < parameters.Length; index++)
            {
                var attribute = parameters[index].GetCustomAttribute <FromParameterAttribute>();
                if (attribute == null)
                {
                    continue;
                }

                var parameterType = parameters[index].ParameterType;
                var parameterName = attribute.ParameterName;

                if (String.IsNullOrEmpty(parameterName) || argumentsArray[index] != null)
                {
                    continue;
                }

                var serialized = context.Connection.GetJobParameter(context.BackgroundJob.Id, parameterName);
                if (serialized == null)
                {
                    continue;
                }

                argumentsArray[index] = SerializationHelper.Deserialize(serialized, parameterType, SerializationOption.User);
            }
        }
Пример #21
0
        public PreserveCultureAttributeFacts()
        {
            _connection = new Mock <IStorageConnection>();

            var storage       = new Mock <JobStorage>();
            var backgroundJob = new BackgroundJobMock {
                Id = JobId
            };
            var state = new Mock <IState>();

            var createContext = new CreateContext(
                storage.Object, _connection.Object, backgroundJob.Job, state.Object);

            _creatingContext = new CreatingContext(createContext);

            var performContext = new PerformContext(
                _connection.Object, backgroundJob.Object, new Mock <IJobCancellationToken>().Object);

            _performingContext = new PerformingContext(performContext);
            _performedContext  = new PerformedContext(performContext, null, false, null);
        }
Пример #22
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            PerformingContext context = JobContext.Current;

            if (context != null)
            {
                if (logLevel == LogLevel.Critical || logLevel == LogLevel.Error)
                {
                    context.SetTextColor(ConsoleTextColor.Red);
                }
                else if (logLevel == LogLevel.Warning)
                {
                    context.SetTextColor(ConsoleTextColor.Yellow);
                }
                else
                {
                    context.ResetTextColor();
                }
                string message = formatter(state, exception);
                context.WriteLine(message);
            }
        }
Пример #23
0
        public void OnPerformResume(PerformingContext context)
        {
            var jobArg            = context.BackgroundJob.Job.Args[0];
            var backgroundJobId   = context.BackgroundJob.Id;
            var resumptionFactory = _resumptionFactory ?? new ResumptionFactory();
            var resumption        = resumptionFactory.New();

            if (resumption.Connect())
            {
                var values = jobArg as Dictionary <string, StringBuilder>;
                LogResumption(values);
                var result = resumption.Resume(values);
                if (result.HasError)
                {
                    throw new InvalidOperationException(result.Message?.ToString(), new Exception(result.Message?.ToString()));
                }
            }
            else
            {
                _logger.Error("Failed to perform job {0}, could not establish a connection.", backgroundJobId);
            }
        }
Пример #24
0
        /// <summary>
        /// 执行开始
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnPerforming(PerformingContext filterContext)
        {
            var jobId = buildJobId(filterContext.BackgroundJob);

            if (_jobPerforming.ContainsKey(jobId))
            {
                if (_jobPerforming.TryGetValue(jobId, out DateTime startTime))
                {
                    if (startTime.AddHours(2) > DateTime.Now)
                    {
                        //存在正在执行且小于2小时则取消
                        filterContext.Canceled = true;
                        return;
                    }
                    else
                    {
                        _jobPerforming.TryRemove(jobId, out DateTime value);
                    }
                }
            }
            _jobPerforming.TryAdd(jobId, DateTime.Now);
        }
        /// <summary>
        /// Called before the performance of the job.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnPerforming(PerformingContext filterContext)
        {
            if (RecurringJobInfos == null ||
                RecurringJobInfos.Count == 0 ||
                !RecurringJobInfos.ContainsKey(filterContext.BackgroundJob.Job.ToString()))
            {
                return;
            }

            var jobInfo = RecurringJobInfos[filterContext.BackgroundJob.Job.ToString()];

            if (jobInfo == null ||
                jobInfo.ExtendedData == null ||
                jobInfo.ExtendedData.Count == 0)
            {
                return;
            }

            var jobDataKey = $"recurringjob-info-{jobInfo.ToString()}";

            filterContext.Items[jobDataKey] = jobInfo.ExtendedData;
        }
        public void OnPerforming(PerformingContext filterContext)
        {
            var state = filterContext.Connection.GetStateData(filterContext.BackgroundJob.Id);

            if (state == null)
            {
                // State for job not found?
                return;
            }

            if (!string.Equals(state.Name, ProcessingState.StateName, StringComparison.OrdinalIgnoreCase))
            {
                // Not in Processing state? Something is really off...
                return;
            }

            var startedAt = JobHelper.DeserializeDateTime(state.Data["StartedAt"]);

            filterContext.Items["ConsoleContext"] = new ConsoleContext(
                new ConsoleId(filterContext.BackgroundJob.Id, startedAt),
                new ConsoleStorage(filterContext.Connection));
        }
        public void OnPerforming(PerformingContext filterContext)
        {
            var isPauseState = filterContext.GetJobParameter <bool>("PauseState");

            if (isPauseState)
            {
                filterContext.Items["PauseState"] = isPauseState;
                filterContext.Canceled            = true;
            }
            //var uiCultureName = filterContext.GetJobParameter<string>("CurrentUICulture");

            //if (!String.IsNullOrEmpty(cultureName))
            //{
            //    filterContext.Items["PreviousCulture"] = CultureInfo.CurrentCulture;
            //    SetCurrentCulture(new CultureInfo(cultureName));
            //}

            //if (!String.IsNullOrEmpty(uiCultureName))
            //{
            //    filterContext.Items["PreviousUICulture"] = CultureInfo.CurrentUICulture;
            //    SetCurrentUICulture(new CultureInfo(uiCultureName));
            //}
        }
Пример #28
0
 public void OnPerforming(PerformingContext context)
 {
     Logger.InfoFormat("IServerFilter: Starting to perform job `{0}`", context.BackgroundJob.Id);
 }
Пример #29
0
 public void OnPerforming(PerformingContext filterContext)
 {
     UnityJobActivator.CreateChildContainer();
 }
Пример #30
0
 protected override void ApplyPaused(PerformingContext context, IServiceProvider serviceProvider)
 => ValueManagerContext.RunIsolated(() => context.ApplyPaused(GetApplication(serviceProvider)));
Пример #31
0
        public void OnPerforming(PerformingContext filterContext)
        {
            Assert.NotNull(filterContext);

            if (_cancelsTheCreation)
            {
                filterContext.Canceled = true;
            }

            _results.Add(String.Format("{0}::{1}", _name, "OnPerforming"));

            if (_setOnPreMethodParameters != null)
            {
                foreach (var parameter in _setOnPreMethodParameters)
                {
                    filterContext.SetJobParameter(parameter.Key, parameter.Value);
                }
            }

            if (_readParameters != null)
            {
                foreach (var parameter in _readParameters)
                {
                    Assert.Equal(
                        parameter.Value,
                        filterContext.GetJobParameter<string>(parameter.Key));
                }
            }
            
            if (_throwException)
            {
                throw new Exception();
            } 
        }