Exemple #1
0
        public Task Handle(UpdateUserEvent @event)
        {
            _logger.LogInformation("Handling 'UpdateUserEvent' event", @event.Id, AppDomain.CurrentDomain.FriendlyName,
                                   @event);
            TimeSpan timeSpan = TimeSpan.FromMinutes(_cacheKeyManager.CacheTime);

            _locker.PerformActionWithLock(_cacheKeyManager.BuilerRedisEventLockKey(@event),
                                          timeSpan, () =>
            {
                var command = new UpdateUserEventCommand(

                    @event.OtherId,
                    @event.UserName,
                    @event.ContactNumber
                    );

                _bus.SendCommand(command).Wait();
                if (_notifications.HasNotifications())
                {
                    var(errorCode, errorMessage) = _notifications.GetNotificationMessage();
                    _logger.LogError(
                        $"Handling 'UpdateUserEvent' event Error Code:{errorCode},Message:{errorMessage}",
                        @event);
                }
            });
            return(Task.CompletedTask);
        }
Exemple #2
0
        public Task Handle(CreateUserEvent @event, [FromCap] CapHeader header, CancellationToken cancellationToken)
        {
            //需要重新设置身份认证头
            EngineContext.Current.ClaimManager.CapEventBusReSetClaim(header);

            _logger.LogInformation($"Handling 'CreateUserEvent' eventId:{@event.Id}");

            var cacheConfig = EngineContext.Current.GetAppModuleConfig <CacheConfig>();
            var timeSpan    = TimeSpan.FromSeconds(cacheConfig.CacheBaseConfig.DefaultCacheTime);

            _locker.PerformActionWithLock(@event.Id.ToString(),
                                          timeSpan, () =>
            {
                var command = new EventCreateUserCommand(
                    @event.UserAccount,
                    @event.UserPassword.ToMd5(),
                    @event.UserName,
                    @event.ContactNumber,
                    DataState.Enable,
                    UserType.TenantAdminUser,     //此处创建的为租户管理员
                    @event.TenantId
                    );
                _bus.SendCommand(command, cancellationToken).Wait(cancellationToken);
                if (_notifications.HasNotifications())
                {
                    var errorMessage = _notifications.GetNotificationMessage();
                    _logger.LogError(
                        $"Handling 'CreateUserEvent' event Error Code:{400},Message:{errorMessage}",
                        @event);
                }
            });
            return(Task.CompletedTask);
        }
Exemple #3
0
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <param name="scheduleTask">Schedule task</param>
        /// <param name="forceRun">Force run</param>
        /// <param name="throwException">A value indicating whether exception should be thrown if some error happens</param>
        /// <param name="ensureRunOncePerPeriod">A value indicating whether we should ensure this task is run once per run period</param>
        public async Task ExecuteAsync(ScheduleTask scheduleTask, bool forceRun = false, bool throwException = false, bool ensureRunOncePerPeriod = true)
        {
            var enabled = forceRun || (scheduleTask?.Enabled ?? false);

            if (scheduleTask == null || !enabled)
            {
                return;
            }

            if (ensureRunOncePerPeriod)
            {
                //task already running
                if (IsTaskAlreadyRunning(scheduleTask))
                {
                    return;
                }

                //validation (so nobody else can invoke this method when he wants)
                if (scheduleTask.LastStartUtc.HasValue && (DateTime.UtcNow - scheduleTask.LastStartUtc).Value.TotalSeconds < scheduleTask.Seconds)
                {
                    //too early
                    return;
                }
            }

            try
            {
                //get expiration time
                var expirationInSeconds = Math.Min(scheduleTask.Seconds, 300) - 1;
                var expiration          = TimeSpan.FromSeconds(expirationInSeconds);

                //execute task with lock
                _locker.PerformActionWithLock(scheduleTask.Type, expiration, () => ExecuteTask(scheduleTask));
            }
            catch (Exception exc)
            {
                var store = await _storeContext.GetCurrentStoreAsync();

                var scheduleTaskUrl = $"{store.Url}{NopTaskDefaults.ScheduleTaskPath}";

                scheduleTask.Enabled    = !scheduleTask.StopOnError;
                scheduleTask.LastEndUtc = DateTime.UtcNow;
                await _scheduleTaskService.UpdateTaskAsync(scheduleTask);

                var message = string.Format(await _localizationService.GetResourceAsync("ScheduleTasks.Error"), scheduleTask.Name,
                                            exc.Message, scheduleTask.Type, store.Name, scheduleTaskUrl);

                //log error
                await _logger.ErrorAsync(message, exc);

                if (throwException)
                {
                    throw;
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <param name="throwException">A value indicating whether exception should be thrown if some error happens</param>
        /// <param name="ensureRunOncePerPeriod">A value indicating whether we should ensure this task is run once per run period</param>
        public void Execute(bool throwException = false, bool ensureRunOncePerPeriod = true)
        {
            if (ScheduleTask == null || !Enabled)
            {
                return;
            }

            if (ensureRunOncePerPeriod)
            {
                //task already running
                if (IsTaskAlreadyRunning(ScheduleTask))
                {
                    return;
                }

                //validation (so nobody else can invoke this method when he wants)
                if (ScheduleTask.LastStartUtc.HasValue && (DateTime.UtcNow - ScheduleTask.LastStartUtc).Value.TotalSeconds < ScheduleTask.Seconds)
                {
                    //too early
                    return;
                }
            }

            try
            {
                //get expiration time
                int      expirationInSeconds = Math.Min(ScheduleTask.Seconds, 300) - 1;
                TimeSpan expiration          = TimeSpan.FromSeconds(expirationInSeconds);

                //execute task with lock
                ILocker locker = ServiceProviderFactory.ServiceProvider.GetService <ILocker>();
                locker.PerformActionWithLock(ScheduleTask.Type, expiration, ExecuteTask);
            }
            catch (Exception exc)
            {
                IScheduleTaskService scheduleTaskService = ServiceProviderFactory.ServiceProvider.GetService <IScheduleTaskService>();

                ScheduleTask.Enabled    = !ScheduleTask.StopOnError;
                ScheduleTask.LastEndUtc = DateTime.UtcNow;
                scheduleTaskService.UpdateTask(ScheduleTask);

                //log error
                ILogger logger = ServiceProviderFactory.ServiceProvider.GetService <ILogger>();
                logger.Error($"Error while running the '{ScheduleTask.Name}' schedule task. {exc.Message}", exc);
                if (throwException)
                {
                    throw;
                }
            }
        }
 public Task Handle(RemoveAuthorizeCacheEvent @event, [FromCap] CapHeader header,
                    CancellationToken cancellationToken)
 {
     EngineContext.Current.ClaimManager.CapEventBusReSetClaim(header);
     _locker.PerformActionWithLock(@event.Id.ToString(),
                                   TimeSpan.FromMinutes(30),
                                   () =>
     {
         try
         {
             _staticCacheManager.RemoveByPrefix(GirvsAuthorizePermissionCacheKeyManager
                                                .CurrentUserAuthorizeCacheKeyPrefix);
         }
         catch (Exception e)
         {
             _logger.LogError(e.Message, e);
         }
     });
     return(Task.CompletedTask);
 }
Exemple #6
0
        public Task Handle(AuthorizeEvent @event, [FromCap] CapHeader header, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Handling 'AuthorizeEvent' eventId:{@event.Id}");
            //需要重新设置身份认证头
            EngineContext.Current.ClaimManager.CapEventBusReSetClaim(header);

            var cacheConfig = EngineContext.Current.GetAppModuleConfig <CacheConfig>();

            var timeSpan = TimeSpan.FromSeconds(cacheConfig.CacheBaseConfig.DefaultCacheTime);

            var isLock = _locker.PerformActionWithLock(@event.Id.ToString(),
                                                       timeSpan, () =>
            {
                var servicePermissionCommandModels = new List <ServicePermissionCommandModel>();
                foreach (var permissionAuthoriz in @event.AuthorizePermissions)
                {
                    servicePermissionCommandModels.Add(new ServicePermissionCommandModel()
                    {
                        ServiceName = permissionAuthoriz.ServiceName,
                        ServiceId   = permissionAuthoriz.ServiceId,
                        Permissions = permissionAuthoriz.Permissions,
                        OperationPermissionModels = permissionAuthoriz.OperationPermissionModels
                    });
                }

                var serviceDataRuleCommandModels = new List <ServiceDataRuleCommandModel>();

                foreach (var authorizeDataRule in @event.AuthorizeDataRules)
                {
                    foreach (var dataRuleFieldModel in authorizeDataRule.AuthorizeDataRuleFieldModels)
                    {
                        serviceDataRuleCommandModels.Add(new ServiceDataRuleCommandModel()
                        {
                            EntityTypeName = authorizeDataRule.EntityTypeName,
                            EntityDesc     = authorizeDataRule.EntityDesc,
                            FieldName      = dataRuleFieldModel.FieldName,
                            FieldType      = dataRuleFieldModel.FieldType,
                            FieldValue     = dataRuleFieldModel.FieldValue,
                            ExpressionType = dataRuleFieldModel.ExpressionType,
                            FieldDesc      = dataRuleFieldModel.FieldDesc,
                            UserType       = dataRuleFieldModel.UserType
                        });
                    }
                }

                var command =
                    new NeedAuthorizeListCommand(servicePermissionCommandModels, serviceDataRuleCommandModels);

                _bus.SendCommand(command).Wait(cancellationToken);

                if (_notifications.HasNotifications())
                {
                    var errorMessage = _notifications.GetNotificationMessage();
                    _logger.LogError(
                        $"Handling 'AuthorizeEvent' event Error Code:{400},Message:{errorMessage}",
                        @event);
                }
            });

            _logger.LogInformation($"本次事件处理过程中,Reids锁的情况为:{isLock} 事件ID为:{@event.Id}");


            return(Task.CompletedTask);
        }