コード例 #1
0
ファイル: DefaultCommandBus.cs プロジェクト: jar349/AMP
 public DefaultCommandBus(IEnvelopeBus envelopeBus
     , List<IMessageProcessor> inboundChain
     , List<IMessageProcessor> outboundChain)
 {
     _commandReceiver = new DefaultCommandReceiver(envelopeBus, inboundChain);
     _commandSender = new DefaultCommandSender(envelopeBus, outboundChain);
 }
コード例 #2
0
        private DataFeed ProcessFeedItem(string groupSelector, bool infiniteLoop = false)
        {
            var config = this.configProvider.GetConfigurationSection <FeedProcessingConfig>();

            using (ICommandReceiver receiver = Factory.GetInstance <ICommandReceiver>().Open(config.InputQueueId, groupSelector))
            {
                DataFeed command;

                do
                {
                    command = receiver.GetCommand <DataFeed>();

                    if (command == null)
                    {
                        return(null);
                    }

                    if (command.IsSequenceTerminator)
                    {
                        this.ProcessTerminator(command);
                    }
                    else
                    {
                        this.ProcessFeed(command);
                    }
                }while (infiniteLoop);

                return(command);
            }
        }
コード例 #3
0
        public static ICommandReceiver <T> Trace <T>(
            this ICommandReceiver <T> receiver) =>
        receiver.UseMiddleware(
            receive: async(handle, timeout, next) =>
        {
            return(await next(async delivery =>
            {
                using (var operation = Log.Receive(delivery))
                {
                    var result = await handle(delivery);

                    Log.Completion(operation, delivery, result);

                    return result;
                }
            }, timeout));
        },
            subscribe: (onNext, next) =>
        {
            using (Log.Subscribe <T>())
            {
                return(next(async delivery =>
                {
                    using (var operation1 = Log.Receive(delivery))
                    {
                        var result1 = await onNext(delivery);

                        Log.Completion(operation1, delivery, result1);

                        return result1;
                    }
                }));
            }
        });
コード例 #4
0
ファイル: CommandRunner.cs プロジェクト: ctguxp/Waffle
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandRunner"/> class. 
        /// </summary>
        /// <param name="processor">The <see cref="IMessageProcessor"/>.</param>
        /// <param name="receiver">The <see cref="ICommandReceiver"/>.</param>
        /// <param name="degreeOfParallelism">The maximum degree of parallelism.</param>
        public CommandRunner(IMessageProcessor processor, ICommandReceiver receiver, int degreeOfParallelism)
        {
            if (processor == null)
            {
                throw new ArgumentNullException("processor");
            }

            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            if (degreeOfParallelism <= 0)
            {
                throw new ArgumentOutOfRangeException("degreeOfParallelism");
            }

            this.runners = new CommandQueueRunner[degreeOfParallelism];
            this.receiver = receiver;
            for (int i = 0; i < this.runners.Length; i++)
            {
                var runner = new CommandQueueRunner(processor, receiver);
                this.runners[i] = runner;
            }
        }
コード例 #5
0
        internal static void TrySubscribeDiscoveredHandler <T>(
            Configuration configuration,
            Type commandType,
            PocketContainer c,
            ICommandReceiver <T> receiver)
        {
            foreach (var handlerDescription in
                     configuration.CommandHandlerDescriptions
                     .Where(t => t.HandledCommandType == commandType))
            {
                var handler = c.Resolve(handlerDescription.HandlerInterface) as ICommandHandler <T>;

                if (configuration.Properties.TracingEnabled)
                {
                    handler = handler.Trace();
                }

                var subscription = receiver.Subscribe(handler);

                configuration.RegisterForDisposal(subscription);

                Logger <Configuration> .Log.Trace(
                    "Subscribing discovered command handler: {handler} to handle commands of type {commandType}",
                    handlerDescription.ConcreteHandlerType,
                    handlerDescription.HandledCommandType);
            }
        }
コード例 #6
0
ファイル: ActorBase.cs プロジェクト: mengtest/demo_tankWar3D
 protected void InitCommands()
 {
     m_CommandReceiver = new CommandReceiver();
     m_CommandReceiver.AddCommand <IdleCommand>(CommandType.Idle, CheckIdle);
     m_CommandReceiver.AddCommand <AutoMoveCommand>(CommandType.Runto, CheckRunTo);
     m_CommandReceiver.AddCommand <UseSkillCommand>(CommandType.Useskill, CheckUseSkill);
     m_CommandReceiver.AddCommand <DeadCommand>(CommandType.Dead, CheckDead);
     m_CommandReceiver.AddCommand <TurnToCommand>(CommandType.TurnTo, CheckTurnTo);
     m_CommandReceiver.AddCommand <MoveCommand>(CommandType.Moveto, CheckMoveTo);
     m_CommandReceiver.AddCommand <TalkCommand>(CommandType.Talk, CheckTalk);
     m_CommandReceiver.AddCommand <FrostCommand>(CommandType.Frost, CheckFrost);
     m_CommandReceiver.AddCommand <StunCommand>(CommandType.Stun, CheckStun);
     m_CommandReceiver.AddCommand <PalsyCommand>(CommandType.Palsy, CheckPalsy);
     m_CommandReceiver.AddCommand <SleepCommand>(CommandType.Sleep, CheckSleep);
     m_CommandReceiver.AddCommand <BlindCommand>(CommandType.Blind, CheckBlind);
     m_CommandReceiver.AddCommand <FearCommand>(CommandType.Fear, CheckFear);
     m_CommandReceiver.AddCommand <FixBodyCommand>(CommandType.Fixbody, CheckFixBody);
     m_CommandReceiver.AddCommand <WoundCommand>(CommandType.Wound, CheckWound);
     m_CommandReceiver.AddCommand <BeatDownCommand>(CommandType.Beatdown, CheckBeatDown);
     m_CommandReceiver.AddCommand <BeatBackCommand>(CommandType.Beatback, CheckBeatBack);
     m_CommandReceiver.AddCommand <BeatFlyCommand>(CommandType.Beatfly, CheckBeatFly);
     m_CommandReceiver.AddCommand <FlyCommand>(CommandType.Fly, CheckFly);
     m_CommandReceiver.AddCommand <HookCommand>(CommandType.Hook, CheckHook);
     m_CommandReceiver.AddCommand <GrabCommand>(CommandType.Grab, CheckGrab);
     m_CommandReceiver.AddCommand <VariationCommand>(CommandType.Variation, CheckVariation);
     m_CommandReceiver.AddCommand <RideCommand>(CommandType.Ride, CheckRide);
     m_CommandReceiver.AddCommand <JumpCommand>(CommandType.Jump, CheckJump);
     m_CommandReceiver.AddCommand <StealthCommand>(CommandType.Stealth, CheckStealth);
     m_CommandReceiver.AddCommand <RebornCommand>(CommandType.Reborn, CheckReborn);
     m_CommandReceiver.AddCommand <CollectMineCommand>(CommandType.Mine, CheckMine);
     m_CommandReceiver.AddCommand <InteractiveCommand>(CommandType.Interactive, CheckInteractive);
 }
コード例 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandRunner"/> class.
        /// </summary>
        /// <param name="processor">The <see cref="IMessageProcessor"/>.</param>
        /// <param name="receiver">The <see cref="ICommandReceiver"/>.</param>
        /// <param name="degreeOfParallelism">The maximum degree of parallelism.</param>
        public CommandRunner(IMessageProcessor processor, ICommandReceiver receiver, int degreeOfParallelism)
        {
            if (processor == null)
            {
                throw new ArgumentNullException("processor");
            }

            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            if (degreeOfParallelism <= 0)
            {
                throw new ArgumentOutOfRangeException("degreeOfParallelism");
            }

            this.runners  = new CommandQueueRunner[degreeOfParallelism];
            this.receiver = receiver;
            for (int i = 0; i < this.runners.Length; i++)
            {
                var runner = new CommandQueueRunner(processor, receiver);
                this.runners[i] = runner;
            }
        }
コード例 #8
0
ファイル: Floor.cs プロジェクト: NickoJ/Elevator
 public Floor(int number, ICommandReceiver receiver, bool canMoveUp, bool canMoveDown)
 {
     Number      = number;
     _receiver   = receiver;
     CanMoveUp   = canMoveUp;
     CanMoveDown = canMoveDown;
 }
コード例 #9
0
 public static async Task <ICommandDeliveryResult> Receive <T>(
     this ICommandReceiver <T> receiver,
     Func <ICommandDelivery <T>, ICommandDeliveryResult> handle,
     TimeSpan?timeout = null) =>
 await receiver.Receive(
     async delivery => await Task.Run(() => handle(delivery)),
     timeout);
コード例 #10
0
        public static IDisposable Subscribe <TReceive, THandle>(
            this ICommandReceiver <TReceive> receiver,
            ICommandHandler <THandle> handler)
            where THandle : TReceive
        {
            async Task <ICommandDeliveryResult> OnNext(ICommandDelivery <TReceive> delivery)
            {
                switch (delivery)
                {
                case ICommandDelivery <THandle> handled:
                    return(await handler.Handle(handled));

                default:
                    if (!(delivery.Command is THandle command))
                    {
                        return(null);
                    }

                    var clone = new CommandDelivery <THandle>(
                        command,
                        delivery.DueTime,
                        delivery.OriginalDueTime,
                        delivery.IdempotencyToken,
                        delivery.NumberOfPreviousAttempts);

                    return(await handler.Handle(clone));
                }
            }

            return(receiver.Subscribe(OnNext));
        }
コード例 #11
0
 public static async Task <ICommandDeliveryResult> Receive <T>(
     this ICommandReceiver <T> receiver,
     ICommandHandler <T> handler,
     TimeSpan?timeout = null) =>
 await receiver.Receive(
     async delivery => await handler.Handle(delivery),
     timeout);
コード例 #12
0
 public void AddCommandReceiver(ICommandReceiver commandReceiver, Func <Command, Task <bool> > commandFilter = null, int priority = 0)
 {
     if (commandReceiver == null)
     {
         throw new ArgumentNullException(nameof(commandReceiver));
     }
     AddEnvelopeReceiver(_commandReceivers, () => commandReceiver, commandFilter, priority);
 }
コード例 #13
0
 public static ICommandReceiver <T> UseMiddleware <T>(
     this ICommandReceiver <T> receiver,
     CommandReceivingMiddleware <T> receive,
     CommandSubscribingMiddleware <T> subscribe) =>
 Create <T>(
     receive:
     (handle, timeout) => receive(handle, timeout, receiver.Receive),
     subscribe: onNext => subscribe(onNext, receiver.Subscribe));
コード例 #14
0
ファイル: AkkaCommandBus.cs プロジェクト: jdiss/CQRS
 public AkkaCommandBus(IConfigurationManager configurationManager, ILogger logger, IActorRef actorReference, ICommandSender <TAuthenticationToken> commandSender, ICommandReceiver <TAuthenticationToken> commandReceiver)
 {
     ConfigurationManager = configurationManager;
     Logger          = logger;
     ActorReference  = actorReference;
     CommandSender   = commandSender;
     CommandReceiver = commandReceiver;
 }
コード例 #15
0
 public GameCommandInvoker()
 {
     this.commands            = new List <Command>();
     this.gameCommandReciever = new GameCommandReciever();
     this.currentComand       = 0;
     this.gameState           = new GameState();
     this.gameStates          = new List <IDictionary <string, string> >();
     this.savedState          = null;
     this.renderer            = new ConsoleRenderer();
 }
コード例 #16
0
 public AkkaCommandBus(IBusHelper busHelper, IAuthenticationTokenHelper <TAuthenticationToken> authenticationTokenHelper, ICorrelationIdHelper correlationIdHelper, IDependencyResolver dependencyResolver, ILogger logger, ICommandPublisher <TAuthenticationToken> commandPublisher, ICommandReceiver <TAuthenticationToken> commandReceiver)
 {
     Logger    = logger;
     BusHelper = busHelper;
     AuthenticationTokenHelper = authenticationTokenHelper;
     CorrelationIdHelper       = correlationIdHelper;
     DependencyResolver        = dependencyResolver;
     EventWaits       = new ConcurrentDictionary <Guid, IList <IEvent <TAuthenticationToken> > >();
     CommandPublisher = commandPublisher;
     CommandReceiver  = commandReceiver;
 }
コード例 #17
0
ファイル: CommandCenter.cs プロジェクト: yh821/Zombie
        public static void EventFunction(ICommandReceiver handler, BaseEventData eventData)
        {
            var parameterType = eventData.GetType();

            if (!map_class_methodinfo.ContainsKey(parameterType))
            {
                map_class_methodinfo[parameterType] = typeof(Actor).GetFirstMethodsBySig(parameterType);
            }

            map_class_methodinfo[parameterType].Invoke(handler, new object[] { eventData });
        }
コード例 #18
0
ファイル: CommandsManager.cs プロジェクト: Erimav/SteamArcana
    public void RegisterCommandReceiver(CommandCode code, ICommandReceiver receiver)
    {
        var typeName = code;

        if (receivers.ContainsKey(typeName))
        {
            Debug.LogError($"Attempt to register 2 receivers for {code}, aborting");
            return;
        }

        receivers[typeName] = receiver;
    }
コード例 #19
0
        public void Run()
        {
            using (ICommandReceiver receiver = Factory.GetInstance <ICommandReceiver>().Open(CONST_MembersDeltaQueueName))
            {
                while (true)
                {
                    UpdateMembersDeltaCommand command = null;

                    try
                    {
                        command = receiver.GetCommand <UpdateMembersDeltaCommand>();

                        if (command == null)
                        {
                            this.log.Debug("No export command found. Processing stopped.");
                            return;
                        }

                        using (this.unitOfWorkProvider.CreateUnitOfWork())
                        {
                            var state = this.vkGroupRepository.GetProcessingState(command.VkGroupId, DataFeedType.MembersInfo);

                            if (state == null)
                            {
                                this.log.WarnFormat("MembersInfo processing state is not found for VkGroupId = \"{0}\"", command.VkGroupId);
                                return;
                            }

                            if (command.Version < state.Version)
                            {
                                this.log.WarnFormat("Processing state of command is outdate. Command.Version = {0} and State.Version = {1}", command.Version, state.Version);
                                return;
                            }

                            this.log.DebugFormat("Processing member delta for vkgroup = \"{0}\" on \"{1}\" for version = {2}", command.VkGroupId, command.SendingDate, command.Version);
                            this.deltaUpdater.CalculateMembersDelta(command.VkGroupId, DateTime.UtcNow);
                        }
                    }
                    catch (Exception exc)
                    {
                        this.log.ErrorFormat("Exception is occured while updating members delta for the group with Id = {0}: {1}", command != null ? command.VkGroupId : 0, exc.ToString());
                    }
                    finally
                    {
                        if (command != null)
                        {
                            command.MarkAsCompleted();
                        }
                    }
                }
            }
        }
コード例 #20
0
		public static void Main(string[] args) 
		{
			switch (mode) {
			case Mode.Keyboard:
				receiver = new KeyboardCommandReceiver();
				break;
			case Mode.Socket:
				receiver = new SocketCommandReceiver();
				break;
			default:
				Console.WriteLine("Unknown mode: " + mode.ToString ());
				Environment.ExitCode = 1;
				return;
			}

			if (!test) {
				port = new SerialPort ("/dev/tty.usbmodem1421", 9600);
				port.Open ();
			}

			try {
				CancellationTokenSource cancelStop = null;
				char? lastCmd = null;
				do {
					char cmd = receiver.BlockUntilNextCmd();

					if (cancelStop != null)
						cancelStop.Cancel();

					if (lastCmd == null
						|| lastCmd.Value != cmd) {
						Send(cmd);
					} 

					lastCmd = cmd;

					cancelStop = new CancellationTokenSource();
					Task.Delay(TimeSpan.FromMilliseconds(750), cancelStop.Token)
						.ContinueWith(task => {
							if (!task.IsCanceled) {
								cancelStop = null;
								lastCmd = null;
								Send('Q');
							}
						});
				} while (receiver.AnotherCommand());

				Send('Q');
			} finally {
				port.Close();
			}
		}
コード例 #21
0
 public AkkaCommandBus(IConfigurationManager configurationManager, IBusHelper busHelper, IAuthenticationTokenHelper <TAuthenticationToken> authenticationTokenHelper, ICorrelationIdHelper correlationIdHelper, IDependencyResolver dependencyResolver, ILogger logger, IActorRef actorReference, ICommandSender <TAuthenticationToken> commandSender, ICommandReceiver <TAuthenticationToken> commandReceiver)
 {
     ConfigurationManager = configurationManager;
     Logger                    = logger;
     ActorReference            = actorReference;
     CommandSender             = commandSender;
     CommandReceiver           = commandReceiver;
     AuthenticationTokenHelper = authenticationTokenHelper;
     CorrelationIdHelper       = correlationIdHelper;
     DependencyResolver        = dependencyResolver;
     BusHelper                 = busHelper;
     EventWaits                = new ConcurrentDictionary <Guid, IList <IEvent <TAuthenticationToken> > >();
 }
コード例 #22
0
ファイル: CommandableCache.cs プロジェクト: jar349/AMP
        public CommandableCache(ICommandReceiver commandReceiver, int cacheExpiryInSeconds)
            : base(cacheExpiryInSeconds)
        {
            _commandReceiver = commandReceiver;

            try {
                // subscribe for the command to burst the routing cache.  Pass a cache
                // reference into the cache buster that handles incoming BurstRoutingCache commands
                _commandReceiver.ReceiveCommand(new RoutingCacheBuster(_routingInfoCache, _cacheLock, _cacheExpiryInSeconds));
            }
            catch (MessageException cex) {
                Log.Warn("Failed to subscribe for Routing Cache Bust commands - the cache cannot be remotely commanded.", cex);
            }
        }
コード例 #23
0
        public CommandableCache(ICommandReceiver commandReceiver, int cacheExpiryInSeconds)
            : base(cacheExpiryInSeconds)
        {
            _commandReceiver = commandReceiver;

            try {
                // subscribe for the command to burst the routing cache.  Pass a cache
                // reference into the cache buster that handles incoming BurstRoutingCache commands
                _commandReceiver.ReceiveCommand(new RoutingCacheBuster(_routingInfoCache, _cacheLock, _cacheExpiryInSeconds));
            }
            catch (MessageException cex) {
                Log.Warn("Failed to subscribe for Routing Cache Bust commands - the cache cannot be remotely commanded.", cex);
            }
        }
コード例 #24
0
ファイル: ProjectService.cs プロジェクト: Ishitori/Palantir
        private CreateProjectResultCommand DoGetCreateProjectStatus(string ticketId)
        {
            using (ICommandReceiver receiver = Factory.GetInstance <ICommandReceiver>().Open(CONST_CreateProjectResultQueueName, string.Format("TicketId = '{0}'", ticketId)))
            {
                CreateProjectResultCommand result = receiver.GetCommand <CreateProjectResultCommand>();

                if (result != null)
                {
                    result.MarkAsCompleted();
                }

                return(result);
            }
        }
コード例 #25
0
        private ExportResultCommand GetExportResult(string ticketId)
        {
            using (ICommandReceiver receiver = Factory.GetInstance <ICommandReceiver>().Open(CONST_ExportResultQueueName, string.Format("TicketId = '{0}'", ticketId)))
            {
                ExportResultCommand result = receiver.GetCommand <ExportResultCommand>();

                if (result != null)
                {
                    result.MarkAsCompleted();
                }

                return(result);
            }
        }
コード例 #26
0
ファイル: CommandQueueRunner.cs プロジェクト: ctguxp/Waffle
        public CommandQueueRunner(IMessageProcessor processor, ICommandReceiver receiver)
        {
            if (processor == null)
            {
                throw new ArgumentNullException("processor");
            }

            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            this.receiver = receiver;
            this.processor = processor;
        }
コード例 #27
0
        public CommandQueueRunner(IMessageProcessor processor, ICommandReceiver receiver)
        {
            if (processor == null)
            {
                throw new ArgumentNullException("processor");
            }

            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            this.receiver  = receiver;
            this.processor = processor;
        }
コード例 #28
0
        private static OperationExecutionReport ExecuteCommand(Command command, ICommandReceiver receiver)
        {
            OperationExecutionReport report;

            try
            {
                report = (OperationExecutionReport)((dynamic)receiver).OnReceive((dynamic)command);
            }
            catch (Exception e)
            {
                report = new OperationExecutionReport("Ошибка при обработке команды");
                report.Errors.Add(new Error(e));
            }

            return(report);
        }
コード例 #29
0
        public void Execute()
        {
            using (ICommandReceiver commandReceiver = Factory.GetInstance <ICommandReceiver>().Open("FeedJobQueue"))
            {
                while (true)
                {
                    var feedQueueItem = commandReceiver.GetCommand <FeedQueueItem>();

                    if (feedQueueItem == null)
                    {
                        break;
                    }

                    feedQueueItem.MarkAsCompleted();
                }
            }
        }
コード例 #30
0
        /// <summary>
        ///  Enables message queuing.
        /// </summary>
        /// <param name="configuration">The <see cref="ProcessorConfiguration"/>.</param>
        /// <param name="degreeOfParallelism">The maximum degree of parallelism.</param>
        /// <param name="sender">The <see cref="ICommandSender"/> used to send commands.</param>
        /// <param name="receiver">The <see cref="ICommandReceiver"/> used to receive commands.</param>
        public static void EnableMessageQueuing(this ProcessorConfiguration configuration, int degreeOfParallelism, ICommandSender sender, ICommandReceiver receiver)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            var innerWorker = configuration.Services.GetCommandWorker();
            configuration.Services.Replace(typeof(ICommandWorker), new CommandQueueWorker(innerWorker));

            configuration.Services.Replace(typeof(ICommandSender), sender);
            configuration.Services.Replace(typeof(ICommandReceiver), receiver);
            configuration.RegisterForDispose(sender as IDisposable);
            if (!object.ReferenceEquals(sender, receiver))
            {
                configuration.RegisterForDispose(receiver as IDisposable);
            }

            Action<ProcessorConfiguration> defaultInitializer = configuration.Initializer;

            configuration.Initializer = originalConfig =>
            {
                MessageProcessor processor = null;
                try
                {
                    CommandHandlerSettings settings = new CommandHandlerSettings(originalConfig);
                    settings.Services.Replace(typeof(ICommandWorker), innerWorker);
                    var config = ProcessorConfiguration.ApplyHandlerSettings(settings, originalConfig);
                    config.Initializer = defaultInitializer;
                    processor = new MessageProcessor(config);
                    var commandReceiver = originalConfig.Services.GetCommandReceiver();
                    originalConfig.CommandBroker = new CommandRunner(processor, commandReceiver, degreeOfParallelism);
                    originalConfig.RegisterForDispose(processor);
                    processor = null;
                }
                finally
                {
                    if (processor != null)
                    {
                        processor.Dispose();
                    }
                }

                defaultInitializer(originalConfig);
            };
        }
コード例 #31
0
        public AccessPointService(
            IServiceProvider ServiceProvider,
            IMediator mediator,
            IButtonService buttonService,
            ISwitchService switchService,
            IRfidReader rfidReader,
            IRelayControlService relayControlService,
            IPirSensorService pirSensorService,
            AccessPointState state,
            ICommandReceiver commandReceiver,
            IServiceEventClient serviceEventClient)
        {
            _serviceProvider     = ServiceProvider;
            _mediator            = mediator;
            _buttonService       = buttonService;
            _switchService       = switchService;
            _rfidReader          = rfidReader;
            _relayControlService = relayControlService;
            _pirSensorService    = pirSensorService;
            _state           = state;
            _commandReceiver = commandReceiver;

            WhenButtonPressedOpened = Observable.FromEventPattern(
                handler => _buttonService.Pressed += handler,
                handler => _buttonService.Pressed -= handler);

            WhenButtonReleasedClosed = Observable.FromEventPattern(
                handler => _buttonService.Released += handler,
                handler => _buttonService.Released -= handler);

            WhenSwitchOpened = Observable.FromEventPattern(
                handler => _switchService.Opened += handler,
                handler => _switchService.Opened -= handler);

            WhenSwitchClosed = Observable.FromEventPattern(
                handler => _switchService.Closed += handler,
                handler => _switchService.Closed -= handler);

            WhenMotionDetected = Observable.FromEventPattern(
                handler => _pirSensorService.MotionDetected += handler,
                handler => _pirSensorService.MotionDetected -= handler);

            WhenMotionNotDetected = Observable.FromEventPattern(
                handler => _pirSensorService.MotionNotDetected += handler,
                handler => _pirSensorService.MotionNotDetected -= handler);
        }
コード例 #32
0
        public void ProcessExportQueue()
        {
            using (ICommandReceiver receiver = Factory.GetInstance <ICommandReceiver>().Open(CONST_ExportQueueName))
            {
                while (true)
                {
                    ExportReportCommand exportCommand = null;

                    try
                    {
                        exportCommand = receiver.GetCommand <ExportReportCommand>();

                        if (exportCommand == null)
                        {
                            this.log.Debug("No export command found. Processing stopped.");
                            return;
                        }

                        string      fileName   = this.GenerateFileName(exportCommand);
                        IFileSystem fileSystem = this.fileSystemFactory.CreateFileSystem(exportCommand.InitiatorUserId);

                        byte[] exportResult    = this.dataProvider.ExportToXlsx(exportCommand.VkGroupId, exportCommand.DateRange);
                        string virtualFilePath = fileSystem.SaveToFile(fileName, exportResult);

                        this.SendExportFinished(exportCommand, true, virtualFilePath);
                    }
                    catch (Exception exc)
                    {
                        this.log.ErrorFormat("Exception is occured while processing a group Id = {0}, for userId = {1}: {2}", exportCommand != null ? exportCommand.VkGroupId : 0, exportCommand != null ? exportCommand.InitiatorUserId : 0, exc.ToString());

                        if (exportCommand != null)
                        {
                            this.SendExportFinished(exportCommand, isSuccess: false);
                        }
                    }
                    finally
                    {
                        if (exportCommand != null)
                        {
                            exportCommand.MarkAsCompleted();
                        }
                    }
                }
            }
        }
コード例 #33
0
        public void ProcessNextQueueItem()
        {
            this.log.Info("GetFeedsFromVKAction process started");

            var processingConfig = this.configProvider.GetConfigurationSection <FeedProcessingConfig>();
            var selector         = !string.IsNullOrWhiteSpace(processingConfig.FeedFilter) ? processingConfig.FeedFilter : null;

            using (ICommandReceiver commandReceiver = Factory.GetInstance <ICommandReceiver>().Open(processingConfig.InputQueueId, selector))
            {
                IVkDataProvider vkDataProvider = this.vkConnectionBuilder.GetVkDataProvider();

                for (int i = 0; i < CONST_BatchProcessingSize; i++)
                {
                    FeedQueueItem queueItem = null;

                    try
                    {
                        queueItem = commandReceiver.GetCommand <FeedQueueItem>();

                        if (queueItem == null)
                        {
                            this.log.Info("No items in queue found. Processing stopped.");
                            return;
                        }

                        this.ProcessQueueItem(queueItem, vkDataProvider, processingConfig);
                    }
                    finally
                    {
                        if (queueItem != null)
                        {
                            queueItem.MarkAsCompleted();

                            using (ICommandSender commandSender = Factory.GetInstance <ICommandSender>().Open(processingConfig.InputQueueId))
                            {
                                commandSender.SendCommand(queueItem.Copy());
                            }
                        }
                    }
                }
            }
        }
コード例 #34
0
        public void Run()
        {
            using (ICommandReceiver receiver = Factory.GetInstance <ICommandReceiver>().Open(CONST_CreateProjectQueueName))
            {
                while (true)
                {
                    CreateProjectCommand createProjectCommand = null;

                    try
                    {
                        createProjectCommand = receiver.GetCommand <CreateProjectCommand>();

                        if (createProjectCommand == null)
                        {
                            this.log.Debug("No create project command found.");
                            return;
                        }

                        var project = this.CreateProject(createProjectCommand);
                        this.SendCreateProjectFinished(createProjectCommand, project, true);
                    }
                    catch (Exception exc)
                    {
                        this.log.ErrorFormat("Exception is occured while creating a project VkUrl {0}, Title {1} for userId = {2}: {3}", createProjectCommand != null ? createProjectCommand.Url : string.Empty, createProjectCommand != null ? createProjectCommand.Title : string.Empty, createProjectCommand != null ? createProjectCommand.AccountId : 0, exc.ToString());

                        if (createProjectCommand != null)
                        {
                            this.SendCreateProjectFinished(createProjectCommand, new Project(), isSuccess: false);
                        }
                    }
                    finally
                    {
                        if (createProjectCommand != null)
                        {
                            createProjectCommand.MarkAsCompleted();
                        }
                    }
                }
            }
        }
コード例 #35
0
        private void ProcessSpecificGroupFeeds(FeedProcessingConfig processingConfig)
        {
            using (ICommandReceiver groupReceiver = Factory.GetInstance <ICommandReceiver>().Open(processingConfig.GroupQueueId))
            {
                while (true)
                {
                    GroupQueueItem commandMessage = null;

                    try
                    {
                        commandMessage = groupReceiver.GetCommand <GroupQueueItem>();

                        if (commandMessage == null)
                        {
                            this.log.Error("No groups found to process. Processing stopped.");
                            return;
                        }

                        this.ProcessGroup(commandMessage.VkGroupId);
                    }
                    catch (Exception exc)
                    {
                        this.log.ErrorFormat("Exception is occured while processing a group Id = {0}: {1}", commandMessage != null ? commandMessage.VkGroupId : 0, exc.ToString());
                        return;
                    }
                    finally
                    {
                        if (commandMessage != null)
                        {
                            commandMessage.MarkAsCompleted();

                            using (ICommandSender groupSender = Factory.GetInstance <ICommandSender>().Open(processingConfig.GroupQueueId))
                            {
                                groupSender.SendCommand(new GroupQueueItem(commandMessage.VkGroupId));
                            }
                        }
                    }
                }
            }
        }
コード例 #36
0
ファイル: CommandPipe.cs プロジェクト: furesoft/RShipCore
 public CommandPipe(ICommandReceiver receiver)
 {
     this.receiver = receiver;
 }
コード例 #37
0
ファイル: MyCommand.cs プロジェクト: sanjug01/Tests
 public MyCommand(ICommandReceiver receiver)
 {
     _receiver = receiver;
 }
コード例 #38
0
ファイル: ConsoleReceiver.cs プロジェクト: CThuleHansen/ICE
 public ConsoleReceiver(ICommandReceiver commandReceiver)
 {
     _commandReceiver = commandReceiver;
 }