Example #1
1
        private static void RegisterCommands(Container container)
        {
            var eventDelegator = new EventBus();
            var eventStore = new EventStore(eventDelegator);
            var aggregateFactory = new AggregateFactory();
            var commandProcessor = new CommandProcessor(aggregateFactory, eventStore);

            container.RegisterSingleton<IProcessCommands>(() => commandProcessor);
        }
        public void CancelCommandGroup_CancelAGroup_AllCommandsInGroupAreCancelled()
        {
            int[] commandsCanceled = {0};
            var fakeFilterManager = A.Fake<IFilterManager>();
            A.CallTo(() => fakeFilterManager.Process(A<CommandBase>.Ignored)).Returns(false);

            var processor = new CommandProcessor(null, fakeFilterManager);
            var commands = new[]
                           {
                               new TestCommand(CommandState.New, groupId: "GroupA"),
                               new TestCommand(CommandState.New, groupId: "GroupB"),
                               new TestCommand(CommandState.New, groupId: "GroupA"),
                               new TestCommand(CommandState.New, groupId: "GroupA"),
                               new TestCommand(CommandState.New, groupId: "GroupB"),
                               new TestCommand(CommandState.New, groupId: "GroupA"),
                               new TestCommand(CommandState.New, groupId: "GroupC"),

                           };
            foreach (var command in commands)
            {
                command.RegisterForStateChange(Observer.Create<CommandState>(b =>
                {
                    if (b == CommandState.Canceled)
                    {
                        commandsCanceled[0]++;
                    }
                }));

                processor.PublishCommand(command);
            }

            processor.CancelCommandGroup("GroupA");

            Assert.AreEqual(4, commandsCanceled[0]);
        }
Example #3
0
 public start_the_application(IBackgroundThread thread, ILoadPresentationModulesCommand command,
                              CommandProcessor processor)
 {
     this.thread = thread;
     this.command = command;
     this.processor = processor;
 }
Example #4
0
        public void SetUp()
        {
            repository = new Mock<Repository>();
              next = new Mock<Processor<Event>>();

              sut = new CommandProcessor(repository.Object, next.Object);
        }
Example #5
0
 private static void ExecuteQuery(CommandProcessor commandProcessor)
 {
     Console.WriteLine("Executing query");
     var query = new SayHelloQuery("Dan");
     commandProcessor.Execute(query).Wait();
     Console.WriteLine(query.Result);
 }
Example #6
0
        public static IRunner BuildRunner(Action<IConfigurationHelper> configurator)
        {
            var configPlan = new ConfigurationPlan();

            if (configurator != null)
            {
                configurator(configPlan);
            }

            configPlan.Validate();

            var routingInfo = GetRoutingInfo(configPlan);

            routingInfo.Validate();

            var router = new CommandRouter(routingInfo);

            var argsHelper = new ArgsHelper(configPlan.SwitchDelimiter);
            var argsHelpProvider = new ArgsParameterHelpProvider(argsHelper);
            var argsParameterBinder = new ArgsParameterBinder(argsHelper);

            var helpProvider = new HelpProvider(router, argsHelpProvider);
            var cmdProcessor = new CommandProcessor(router, configPlan.TypeInstantiationStrategy, argsParameterBinder);

            return new RunnerInternal(helpProvider, cmdProcessor);
        }
Example #7
0
        public static void Main()
        {
            // we can create a singleton instance of the command processor. each execution can occur concurrently
            // and has it's own state.
            var processorSingleton = new CommandProcessor(DemoAPICommandProcessorConfiguration.Instance);

            // command with return value - 1 transaction per command
            int id = processorSingleton.Execute(new AddProductModel()
            {
                // ... properties ...
            });

            // command with no return value - 1 transaction per command
            processorSingleton.Execute(new SetProductModelName()
            {
                // ... properties ...
            });

            processorSingleton.Execute(new AddProductReview()
            {
                ProductId = 316,

                ReviewerName = "Joseph Daigle",
                EmailAddress = "*****@*****.**",
                Rating = 4,
                Comments = "Meh",
            });
        }
		public SesService(CommandProcessor processor)
		{
			if (processor == null)
			{
				throw new ArgumentNullException("processor");
			}
			_processor = processor;
		}
 public void SupportsQueryCommand()
 {
     HomeState state = new HomeState();
     state.CreateFurniture("sofa","room",new DateTime(2015,12,01));
     Mock<TextWriter> writerMock = new Mock<TextWriter>();
     CommandProcessor processor = new CommandProcessor(state, writerMock.Object);
     string command = "query -date 01.12.2015";
     processor.Process(command);
     writerMock.Verify(w=>w.WriteLine(It.IsAny<string>()));
 }
Example #10
0
        static void TestProcessCommand()
        {
            SubscriptionClient subscriptionClient = SubscriptionClient.CreateFromConnectionString( serviceBusConnectionString, commandTopicPath, commandHandlerSubscription );
            SubscriptionReceiver receiver = new SubscriptionReceiver( subscriptionClient );
            ITextSerializer serializer = new JsonTextSerializer();

            CommandProcessor orderCommandProcessor = new CommandProcessor( receiver, serializer );
            orderCommandProcessor.Register( new OrderCommandHandler() );

            orderCommandProcessor.Start();
        }
        public void ExecuteWithNullCommandThrowsArgumentNullException()
        {
            var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);

            var sut = new CommandProcessor(serviceProviderMock.Object);

            TestCommand command = null;

            var ex = Assert.Throws<ArgumentNullException>(() => sut.Execute(command));

            Assert.Equal("command", ex.ParamName);
        }
Example #12
0
 public static void Main()
 {
     // TODO: Add instance of the GameRenderingEngine and call that instance when creating the game engine
     var brightSkin = new BrightSkin();
     IOInterface userInterractor = new ConsoleInterface(brightSkin);
     Scoreboard scoreboard = Scoreboard.GetInstance;
     scoreboard.SetIOInterface(userInterractor);
     GameBoard gameBoard = GameBoard.GetInstance;
     CommandProcessor commandProcessor = new CommandProcessor(gameBoard, scoreboard, userInterractor, new CommandParser());
     GameEngine engine = new GameEngine(commandProcessor, userInterractor, gameBoard);
     engine.Play();
 }
        public static void SetUp()
        {
            container = new TinyInversionOfControlContainer(new TinyIoCContainer());

            commandProcessor = new CommandProcessor(container);
            container.Register<IAmAUnitOfWorkFactory, UnitOfWorkFactory>().AsSingleton();
            container.Register<IRepository<Meeting, MeetingDocument>, Repository<Meeting, MeetingDocument>>().AsMultiInstance();
            container.Register<IIssueTickets, TicketIssuer>().AsMultiInstance();
            container.Register<IScheduler, Scheduler>();
            container.Register<IAmAnOverbookingPolicy, FiftyPercentOverbookingPolicy>();
            container.Register<IIssueTickets, TicketIssuer>();
            container.Register<IHandleRequests<ScheduleMeetingCommand>, ScheduleMeetingCommandHandler>("ScheduleMeetingCommandHandler");
        }
		public void VerifyTest()
		{
			var cmd = new VerifyEmailAddressCommand
			          	{
			          		EmailAddress = Helper.GetSenderEmailAddress()
			          	};


			var cp = new CommandProcessor(_builder);

			var resp = cp.Process(cmd, _parser);


			Console.WriteLine(resp.Command + " : ID " +  resp.RequestID);
		}
        public void SupprotsCreateFurnitureCommand()
        {
            Mock<IHomeState> stateMock = new Mock<IHomeState>();
            CommandProcessor processor = new CommandProcessor(stateMock.Object, Console.Out);
            string command = "create-furniture -date 12.01.2015 -room Bedroom -type sofa";
            processor.Process(command);
            stateMock.Verify(a => a.CreateFurniture("sofa", "Bedroom", new DateTime(2015, 01, 12)));

            command = "create-furniture -room Bedroom -date 12.01.2015 -type sofa";
            processor.Process(command);
            stateMock.Verify(a => a.CreateFurniture("sofa", "Bedroom", new DateTime(2015, 01, 12)));

            command = "create-furniture -room Bedroom -type sofa";
            processor.Process(command);
            stateMock.Verify(a => a.CreateFurniture("sofa", "Bedroom", It.IsAny<DateTime>()));
        }
Example #16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Waiting for command.");
            Console.WriteLine("Run crawler: run --host=http://www.example.com --deep=3 --path=D:\\Folder\\ --allOrigins");
            Console.WriteLine("Exit: exit");
            var commandProcessor = new CommandProcessor();

            while (commandProcessor.Run)
            {
                string command = Console.ReadLine();
                commandProcessor.ProcessCommand(command);
            }

            Console.WriteLine("End of execution.");
            Console.ReadKey();
        }
Example #17
0
 public void Create(params string[] lines)
 {
     _view = Utils.EditorUtil.CreateView(lines);
     _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, 0));
     _map = new RegisterMap();
     _host = new FakeVimHost();
     _editOpts = new Mock<IEditorOperations>(MockBehavior.Strict);
     _operations = new Mock<IOperations>(MockBehavior.Strict);
     _bufferData = MockObjectFactory.CreateVimBuffer(
         _view,
         "test",
         MockObjectFactory.CreateVim(_map, host: _host).Object,
         _editOpts.Object);
     _processorRaw = new Vim.Modes.Command.CommandProcessor(_bufferData.Object, _operations.Object);
     _processor = _processorRaw;
 }
        public void SupportsRemoveRoomCommand()
        {
            Mock<IHomeState> stateMock = new Mock<IHomeState>();
            CommandProcessor processor = new CommandProcessor(stateMock.Object, Console.Out);
            string command = "remove-room -date 12.01.2015 -room Bedroom -transfer dining";
            processor.Process(command);
            stateMock.Verify(a => a.RemoveRoom("Bedroom", "dining", new DateTime(2015, 01, 12)));

            command = "remove-room -room Bedroom -date 12.01.2015";
            processor.Process(command);
            stateMock.Verify(a => a.RemoveRoom("Bedroom","dining",new DateTime(2015, 01, 12)));

            command = "remove-room -room Bedroom -transfer dining";
            processor.Process(command);
            stateMock.Verify(a => a.RemoveRoom("Bedroom", "dining", It.IsAny<DateTime>()));
        }
 public void Create(params string[] lines)
 {
     _view = Utils.EditorUtil.CreateView(lines);
     _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, 0));
     _map = new RegisterMap();
     _editOpts = new Mock<IEditorOperations>(MockBehavior.Strict);
     _operations = new Mock<IOperations>(MockBehavior.Strict);
     _operations.SetupGet(x => x.EditorOperations).Returns(_editOpts.Object);
     _statusUtil = new Mock<IStatusUtil>();
     _fileSystem = new Mock<IFileSystem>(MockBehavior.Strict);
     _bufferData = MockObjectFactory.CreateVimBuffer(
         _view,
         "test",
         MockObjectFactory.CreateVim(_map).Object);
     _processorRaw = new Vim.Modes.Command.CommandProcessor(_bufferData.Object, _operations.Object, _statusUtil.Object, _fileSystem.Object);
     _processor = _processorRaw;
 }
		public void Run()
		{
			var cmd = new DeleteVerifiedEmailAddressCommand
			          	{
			          		EmailAddress = _email
			          	};


			

			var cp = new CommandProcessor(_builder);

			var resp = cp.Process(cmd, new DeleteVerifiedEmailAddressResponseParser());

			Console.WriteLine(resp.Command + " : ID " + resp.RequestID);

		}
Example #21
0
 private static void Main(string[] args)
 {
     var maxConcurrentJobs = GetMaxConcurrentJobs();
     var allTaskList = new BlockingCollection<Job>();
     var socketServer = new SocketServer(IPAddress.Loopback, 6666);
     var jobQueue = new JobQueue();
     var scheduler = new Scheduler(jobQueue);
     using (var queueProcessor = new QueueProcessor(maxConcurrentJobs, jobQueue))
     {
         var commandProcessor = new CommandProcessor(allTaskList, scheduler, jobQueue, queueProcessor);
         using (var dispatcher = new CommandDispatcherService(socketServer, commandProcessor))
         using (var display = new DisplayService(allTaskList, jobQueue))
         {
             Console.ReadLine();
         }
     }
 }
		public void T1()
		{
			var cmd = new SendRawEmailCommand
			{
				Source = Helper.GetSenderEmailAddress(),

				RawData = Convert.ToBase64String(RawEmailGenerator.SendRawEmail(Encoding.ASCII, Helper.GetSenderEmailAddress(), Helper.GetRecipientEmailAddress(), "test email subject", "this is some text",
			             "<p>this is some html</p><p>asdasd asdasd</p>"))
			};


			cmd.Destination.ToAddresses.Add(Helper.GetRecipientEmailAddress());
//            cmd.RawData =
//                @"From: [email protected]
//To: [email protected]
//Subject: testing SES
//MIME-Version: 1.0
//Content-Type: multipart/alternative; 
//	boundary=""----=_Part_286008_14012783.1304034624483""
//Date: Thu, 28 Apr 2011 23:50:24 +0000
//Message-ID: <*****@*****.**>
//
//------=_Part_286008_14012783.1304034624483
//Content-Type: text/plain; charset=UTF-8
//Content-Transfer-Encoding: 7bit
//
//this is not bold text
//------=_Part_286008_14012783.1304034624483
//Content-Type: text/html; charset=UTF-8
//Content-Transfer-Encoding: 7bit
//
//<b>this is bold text</b>
//------=_Part_286008_14012783.1304034624483--
//";

			Console.WriteLine(cmd.RawData);

			var cp = new CommandProcessor(_builder);

			var resp = cp.Process(cmd, new SendRawEmailCommandResponseParser());


			Console.WriteLine(resp.Command + " : ID " + resp.RequestID);
		}
Example #23
0
        static void Main(string[] args)
        {
            ICommandRegistry commandRegistry = new CommandRegistry();
            commandRegistry.Register<SayHelloQuery, SayHelloQueryHandler>();
            commandRegistry.Register<SayHelloCommand, SayHelloCommandHandler>();

            ContainerBuilder container = new ContainerBuilder();
            RegisterHandlers(container);

            AutofacCommandHandlerFactory autofacCommandHandlerFactory = new AutofacCommandHandlerFactory(container.Build());

            _commandProcessor = new CommandProcessor(commandRegistry, autofacCommandHandlerFactory);

            ExecuteCommand(_commandProcessor);
            ExecuteCommand(_commandProcessor);
            ExecuteQuery(_commandProcessor);

            Console.ReadLine();
        }
        public void ExecuteWithValidCommandExecutesCommand()
        {
            var serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
            var commandHandlerMock = new Mock<ICommandHandler<TestCommand>>(MockBehavior.Strict);

            var sut = new CommandProcessor(serviceProviderMock.Object);

            var command = new TestCommand();

            serviceProviderMock
                .Setup(sp => sp.GetService(typeof(ICommandHandler<TestCommand>)))
                .Returns(commandHandlerMock.Object);

            commandHandlerMock.Setup(ch => ch.Handle(command));

            sut.Execute(command);

            serviceProviderMock.VerifyAll();
            commandHandlerMock.VerifyAll();
        }
        public async Task ExecuteDeviceCommandAsyncInvalidIdTest()
        {
            //Arrange 
            var dbConnection = new UnitTestDbConnection();
            Database.SetInitializer(new CreateFreshDbInitializer());

            var adapterManager = new StubIAdapterManager();
            var ranstoredCommands = new List<int>();
            var log = new StubIFeedback<LogEntry>();
            var cts = new CancellationTokenSource();
            var commmandProcessor = new CommandProcessor(adapterManager, dbConnection, log);

            //Act
            var result = await commmandProcessor.ExecuteDeviceCommandAsync(new DeviceCommand(), "", "", cts.Token);
            Console.WriteLine(result.Message);

            //Assert
            Assert.IsTrue(result.HasError);
            Assert.IsTrue(ranstoredCommands.Count == 0, "Process did not run the correct amount of commands.");
            Assert.IsTrue(result.Message.Contains("Cannot locate"), "Expect error message to contain 'Cannot locate'");
        }
        public void CancelCommand_CommandIsBlockedAndShouldFailIfBlocked_CommandFails()
        {
            var resetEvent = new ManualResetEventSlim(false);

            var fakeFilterManager = A.Fake<IFilterManager>();
            A.CallTo(() => fakeFilterManager.Process(A<CommandBase>.Ignored)).Returns(true);
            var processor = new CommandProcessor(null, fakeFilterManager);
            var command = new TestCommand(CommandState.New, blockCanExecute: true, shouldFailIfBlocked:true);

            command.RegisterForStateChange(Observer.Create<CommandState>(b =>
            {
                if (b == CommandState.Failed)
                {
                    resetEvent.Set();
                }
            }));
            processor.PublishCommand(command);
            resetEvent.Wait();

            Assert.AreEqual(CommandState.Failed, command.CurrentState);
        }
Example #27
0
        static void Main(string[] args)
        {
            try {
                System.Console.WriteLine(WELCOME_MESSAGE);
                System.Console.WriteLine(COMMAND_INIT_MESSAGE);

                IRobot robot = new Robot();
                ICommandProcessor commandProcessor = new CommandProcessor(robot);

                while (true)
                {
                    string output = commandProcessor.Process(System.Console.ReadLine());
                    if (output != "") {
                        System.Console.WriteLine(output);
                    }
                }
            }catch (Exception ex)
            {
                //TODO : Exception to be logged
                System.Console.WriteLine(UNKNOWN_ERROR);
            }
        }
		public void SendStatistics()
		{
			var cmd = new GetSendStatisticsCommand();


			HttpWebRequest request = _builder.Build(cmd);

			Helper.ProcessRequest(request);

			var cp = new CommandProcessor(_builder);

			var stats = cp.Process(cmd, new GetSendStatisticsResponseParser());

			foreach(var stat in stats.SendStatistics)
			{
				Console.WriteLine("DeliveryAttempts : " + stat.DeliveryAttempts);
				Console.WriteLine("Timestamp : " + stat.Timestamp);
				Console.WriteLine("Bounces : " + stat.Bounces);
				Console.WriteLine("Rejects : " + stat.Rejects);
				Console.WriteLine("Complaints : " + stat.Complaints);
			}
			
		}
        partial void OnCreateContainer(IServiceCollection services, ITextSerializer serializer, IMetadataProvider metadata, ILoggerFactory loggerFactory)
        {
            var azureSettings = InfrastructureSettings.Read("Application\\Settings.xml");

            var busConfig = new ServiceBusConfig(azureSettings.ServiceBus, loggerFactory);

            busConfig.Initialize();

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString);

            services.AddSingleton <IBlobStorage>(new CloudBlobStorage(blobStorageAccount, azureSettings.BlobStorage.RootContainerName, loggerFactory.CreateLogger <CloudBlobStorage>()));
            var topicLogger       = loggerFactory.CreateLogger <TopicSender>();
            var commandBus        = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path, topicLogger), metadata, serializer);
            var eventsTopicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path, topicLogger);

            services.AddSingleton <IMessageSender>(eventsTopicSender);
            services.AddSingleton <IMessageSender>(/*"orders", */ new TopicSender(azureSettings.ServiceBus, Topics.EventsOrders.Path, topicLogger));
            services.AddSingleton <IMessageSender>(/*"seatsavailability",*/ new TopicSender(azureSettings.ServiceBus, Topics.EventsAvailability.Path, topicLogger));
            var eventBus = new EventBus(eventsTopicSender, metadata, serializer);

            var subscriptionLogger          = loggerFactory.CreateLogger <SubscriptionReceiver>();
            var sessionSubscriptionLogger   = loggerFactory.CreateLogger <SessionSubscriptionReceiver>();
            var sessionlessCommandProcessor =
                new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Sessionless, false, subscriptionLogger), serializer, loggerFactory.CreateLogger <CommandProcessor>());
            var anchorsAvailabilityCommandProcessor =
                new CommandProcessor(new SessionSubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Anchorsavailability, false, sessionSubscriptionLogger), serializer, loggerFactory.CreateLogger <CommandProcessor>());

            var synchronousCommandBus = new SynchronousCommandBusDecorator(commandBus, loggerFactory.CreateLogger <SynchronousCommandBusDecorator>());

            services.AddSingleton <ICommandBus>(synchronousCommandBus);

            services.AddSingleton <IEventBus>(eventBus);
            services.AddSingleton <IProcessor>(/*"SessionlessCommandProcessor", */ sessionlessCommandProcessor);
            services.AddSingleton <IProcessor>(/*"AnchorsAvailabilityCommandProcessor", */ anchorsAvailabilityCommandProcessor);

            RegisterRepositories(services, azureSettings, loggerFactory);

            var serviceProvider = services.BuildServiceProvider();

            RegisterEventProcessors(services, serviceProvider, busConfig, serializer, loggerFactory);

            var commandHandlers = serviceProvider.GetServices <ICommandHandler>().ToList();

            RegisterCommandHandlers(services, commandHandlers, sessionlessCommandProcessor, anchorsAvailabilityCommandProcessor);

            // handle order commands inline, as they do not have competition.
            // TODO: Get exactly OrderCommandHandler
            synchronousCommandBus.Register(commandHandlers.First(s => s.GetType() == typeof(OrderCommandHandler)));

            // message log
            var messageLogAccount = CloudStorageAccount.Parse(azureSettings.MessageLog.ConnectionString);

            services.AddSingleton <IProcessor>(/*"EventLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Events.Path, Topics.Events.Subscriptions.Log, true, subscriptionLogger)));

            services.AddSingleton <IProcessor>(/*"OrderEventLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.EventsOrders.Path, Topics.EventsOrders.Subscriptions.LogOrders, true, subscriptionLogger)));

            services.AddSingleton <IProcessor>(/*"SeatsAvailabilityEventLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.EventsAvailability.Path, Topics.EventsAvailability.Subscriptions.LogAvail, true, subscriptionLogger)));

            services.AddSingleton <IProcessor>(/*"CommandLogger", */ new AzureMessageLogListener(
                                                   new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName),
                                                   new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Log, true, subscriptionLogger)));
        }
        private bool HandleQuoteTyped(ITypingContext typingContext)
        {
            ITextControl textControl = typingContext.TextControl;

            if (typingContext.EnsureWritable() != EnsureWritableResult.SUCCESS)
            {
                return(false);
            }

            using (CommandProcessor.UsingCommand("Smart quote"))
            {
                TextControlUtil.DeleteSelection(textControl);
                textControl.FillVirtualSpaceUntilCaret();

                CachingLexer  lexer   = GetCachingLexer(textControl);
                IBuffer       buffer  = lexer.Buffer;
                int           charPos = TextControlToLexer(textControl, textControl.Caret.Offset());
                TokenNodeType correspondingTokenType = PsiTokenType.STRING_LITERAL;

                if (charPos < 0 || !lexer.FindTokenAt(charPos))
                {
                    return(false);
                }

                TokenNodeType tokenType = lexer.TokenType;


                // check if we should skip the typed char
                if (charPos < buffer.Length && buffer[charPos] == typingContext.Char && tokenType == correspondingTokenType &&
                    lexer.TokenStart != charPos && buffer[lexer.TokenStart] != '@')
                {
                    int position = charPos;
                    if (position >= 0)
                    {
                        textControl.Caret.MoveTo(position + 1, CaretVisualPlacement.DontScrollIfVisible);
                    }
                    return(true);
                }

                // check that next token is a good one
                if (tokenType != null && !IsStopperTokenForStringLiteral(tokenType))
                {
                    return(false);
                }


                // find next not whitespace token
                while (lexer.TokenType == PsiTokenType.WHITE_SPACE)
                {
                    lexer.Advance();
                }

                bool doInsertPairQuote = (lexer.TokenType == correspondingTokenType) &&
                                         ((lexer.TokenEnd > lexer.TokenStart + 1) && (lexer.Buffer[lexer.TokenStart] == typingContext.Char) && (lexer.Buffer[lexer.TokenEnd - 1] == typingContext.Char));

                // do inserting of the requested char and updating of the lexer
                typingContext.CallNext();
                lexer = GetCachingLexer(textControl);
                //        charPos = TextControlToLexer(textControl, textControl.CaretModel.Offset - 1);

                if (!doInsertPairQuote)
                {
                    // check if the typed char is the beginning of the corresponding token
                    if (!lexer.FindTokenAt(charPos))
                    {
                        return(true);
                    }

                    bool isStringWithAt = lexer.TokenType == PsiTokenType.STRING_LITERAL && lexer.TokenStart == charPos - 1 &&
                                          lexer.Buffer[lexer.TokenStart] == '@';
                    if ((lexer.TokenStart != charPos) && !isStringWithAt)
                    {
                        return(true);
                    }

                    // check if there is unclosed token of the corresponding type up to the end of the source line
                    int newPos = charPos;
                    if (newPos < 0)
                    {
                        return(true);
                    }

                    DocumentCoords documentCoords = textControl.Document.GetCoordsByOffset(newPos);
                    int            offset         = textControl.Document.GetLineEndOffsetNoLineBreak(documentCoords.Line) - 1;

                    int lexerOffset = TextControlToLexer(textControl, offset);
                    if (lexerOffset >= 0)
                    {
                        lexer.FindTokenAt(lexerOffset);
                    }
                    if (lexerOffset < 0 || lexer.TokenType == null)
                    {
                        charPos = TextControlToLexer(textControl, textControl.Caret.Offset() - 1);
                        if (charPos >= 0)
                        {
                            lexer.FindTokenAt(charPos);
                        }
                        else
                        {
                            return(true);
                        }
                    }

                    doInsertPairQuote = (lexer.TokenType == correspondingTokenType) &&
                                        ((lexer.TokenEnd == lexer.TokenStart + 1) || (lexer.Buffer[lexer.TokenEnd - 1] != typingContext.Char) ||
                                         (isStringWithAt && (lexer.TokenStart == charPos - 1) && (lexer.TokenEnd != charPos + 1)));
                }

                // insert paired quote
                if (doInsertPairQuote)
                {
                    charPos++;
                    int documentPos = charPos;
                    if (documentPos >= 0)
                    {
                        textControl.Document.InsertText(documentPos, typingContext.Char == '\'' ? "'" : "\"");
                        textControl.Caret.MoveTo(documentPos, CaretVisualPlacement.DontScrollIfVisible);
                    }
                }
            }

            return(true);
        }
Example #31
0
        /// <summary>
        /// Default constructor for the Router class
        /// </summary>
        public Router()
        {
            CounterCreationDataCollection CCDC;

            categoryName = "WspEventRouter";
            communicationCategoryName = "WspEventRouterCommunication";
            categoryHelp = "WspEventRouter counters showing internal performance of the router.";
            communicationCategoryHelp = "WspEventRouter counters showing communication queues to other servers";
            subscriptionQueueSizeName = "SubscriptionQueueSize";
            rePublisherQueueSizeName  = "RePublisherQueueSize";
            persisterQueueSizeName    = "PersisterQueueSize";
            forwarderQueueSizeName    = "ForwarderQueueSize";
            mgmtQueueSizeName         = "MgmtQueueSize";
            cmdQueueSizeName          = "CmdQueueSize";
            subscriptionEntriesName   = "SubscriptionEntries";
            eventsProcessedName       = "EventsProcessed";
            eventsProcessedBytesName  = "EventsProcessedBytes";
            baseInstance = "BaseInstance";

            subscriptionQueueSize = new PerformanceCounter(categoryName, subscriptionQueueSizeName, string.Empty, false);
            rePublisherQueueSize  = new PerformanceCounter(categoryName, rePublisherQueueSizeName, string.Empty, false);
            persisterQueueSize    = new PerformanceCounter(categoryName, persisterQueueSizeName, string.Empty, false);
            mgmtQueueSize         = new PerformanceCounter(categoryName, mgmtQueueSizeName, string.Empty, false);
            cmdQueueSize          = new PerformanceCounter(categoryName, cmdQueueSizeName, string.Empty, false);
            subscriptionEntries   = new PerformanceCounter(categoryName, subscriptionEntriesName, string.Empty, false);
            eventsProcessed       = new PerformanceCounter(categoryName, eventsProcessedName, string.Empty, false);
            eventsProcessedBytes  = new PerformanceCounter(categoryName, eventsProcessedBytesName, string.Empty, false);

            if (PerformanceCounterCategory.Exists(communicationCategoryName) == false)
            {
                CCDC = new CounterCreationDataCollection();

                CounterCreationData forwarderQueueCounter = new CounterCreationData();
                forwarderQueueCounter.CounterType = PerformanceCounterType.NumberOfItems32;
                forwarderQueueCounter.CounterName = forwarderQueueSizeName;
                CCDC.Add(forwarderQueueCounter);

                PerformanceCounterCategory.Create(communicationCategoryName, communicationCategoryHelp,
                                                  PerformanceCounterCategoryType.MultiInstance, CCDC);
            }

            forwarderQueueSize = new PerformanceCounter(communicationCategoryName, forwarderQueueSizeName, baseInstance, false);

            subscriptionQueueSize.RawValue = 0;
            rePublisherQueueSize.RawValue  = 0;
            persisterQueueSize.RawValue    = 0;
            forwarderQueueSize.RawValue    = 0;
            mgmtQueueSize.RawValue         = 0;
            cmdQueueSize.RawValue          = 0;
            subscriptionEntries.RawValue   = 0;
            eventsProcessed.RawValue       = 0;
            eventsProcessedBytes.RawValue  = 0;
            //eventQueueSize = 10240;
            //averageEventSize = 10240;

            //eventQueueName = @"WspEventQueue";

            //thisBufferSize = 1024000;
            //thisTimeout = 10000;

            listener         = new Listener();
            rePublisher      = new RePublisher();
            subscriptionMgr  = new SubscriptionMgr();
            persister        = new Persister();
            communicator     = new Communicator();
            configurator     = new Configurator();
            commandProcessor = new CommandProcessor();
            manager          = new Manager();

            subscriptionMgrQueue = new SynchronizationQueue <QueueElement>(2000, subscriptionQueueSize);
            rePublisherQueue     = new SynchronizationQueue <QueueElement>(2000, rePublisherQueueSize);
            persisterQueue       = new SynchronizationQueue <QueueElement>(2000, persisterQueueSize);
            forwarderQueue       = new SynchronizationQueue <QueueElement>(2000, forwarderQueueSize);
            mgmtQueue            = new SynchronizationQueue <QueueElement>(100, mgmtQueueSize);
            cmdQueue             = new SynchronizationQueue <QueueElement>(100, cmdQueueSize);

            workerThreads = new Dictionary <Type, Thread>();

            workerThreads.Add(listener.GetType(), null);
            workerThreads.Add(rePublisher.GetType(), null);
            workerThreads.Add(subscriptionMgr.GetType(), null);
            workerThreads.Add(persister.GetType(), null);
            workerThreads.Add(communicator.GetType(), null);
            workerThreads.Add(configurator.GetType(), null);
            workerThreads.Add(commandProcessor.GetType(), null);
            workerThreads.Add(manager.GetType(), null);

            try
            {
                Configurator.LoadConfiguration();
            }
            catch
            {
                // We'll load the config later
            }

            this.ServiceName = "WspEventRouter";
        }
 private static async void PlayerCommandInvoked(IClientPlayer clientObj, string[] tokens)
 {
     await ChatWriter.WriteChatTo(clientObj, "(requiem)",
                                  new[] { CreateHelp(CommandProcessor.GetGameCommands().ToArray()) });
 }
 public void Dispose()
 {
     CommandProcessor.ClearExtServiceBus();
 }
Example #34
0
        public bool SendAndReceive(string command, ref IList <string> data, CommandProcessor processor = null,
                                   Encoding encoding = null, bool pushResultToDatadespiteProcessor = false)
        {
#if !NETFX_CORE
            if (_idleState == IdleState.On)
            {
                PauseIdling();
            }
#endif
            lock (_lock)
            {
                if (_client == null || !_client.Connected)
                {
                    throw new SocketException((int)SocketError.NotConnected);
                }

                const string tmpl = "IMAPX{0} {1}";
                _counter++;

                StreamReader reader = encoding == null || Equals(encoding, Encoding.UTF8)
                    ? _streamReader
                    : new StreamReader(_ioStream, encoding);

                var parts = new Queue <string>(NewLineRex.Split(command));

                string text  = string.Format(tmpl, _counter, parts.Dequeue().Trim()) + "\r\n";
                byte[] bytes = Encoding.UTF8.GetBytes(text.ToCharArray());

                if (IsDebug)
                {
                    Debug.WriteLine(text);
                }

                _ioStream.Write(bytes, 0, bytes.Length);

                _lastActivity = DateTime.Now;

                while (true)
                {
                    string tmp = reader.ReadLine();

                    if (tmp == null)
                    {
#if !NETFX_CORE
                        if (_idleState == IdleState.Paused)
                        {
                            StartIdling();
                        }
#endif
                        return(false);
                    }

                    if (IsDebug)
                    {
                        Debug.WriteLine(tmp);
                    }

                    if (processor == null || pushResultToDatadespiteProcessor)
                    {
                        data.Add(tmp);
                    }

                    if (processor != null)
                    {
                        processor.ProcessCommandResult(tmp);
                    }

                    if (tmp.StartsWith("+ ") && (parts.Count > 0 || (processor != null && processor.TwoWayProcessing)))
                    {
                        if (parts.Count > 0)
                        {
                            text = parts.Dequeue().Trim() + "\r\n";

                            if (IsDebug)
                            {
                                Debug.WriteLine(text);
                            }

                            bytes = Encoding.UTF8.GetBytes(text.ToCharArray());
                        }
                        else if (processor != null)
                        {
                            bytes = processor.AppendCommandData(tmp);
                        }

                        _ioStream.Write(bytes, 0, bytes.Length);
                        continue;
                    }

                    if (tmp.StartsWith(string.Format(tmpl, _counter, ResponseType.Ok)))
                    {
#if !NETFX_CORE
                        if (_idleState == IdleState.Paused)
                        {
                            StartIdling();
                        }
#endif
                        return(true);
                    }

                    if (tmp.StartsWith(string.Format(tmpl, _counter, ResponseType.PreAuth)))
                    {
#if !NETFX_CORE
                        if (_idleState == IdleState.Paused)
                        {
                            StartIdling();
                        }
#endif
                        return(true);
                    }

                    if (tmp.StartsWith(string.Format(tmpl, _counter, ResponseType.No)) ||
                        tmp.StartsWith(string.Format(tmpl, _counter, ResponseType.Bad)))
                    {
#if !NETFX_CORE
                        if (_idleState == IdleState.Paused)
                        {
                            StartIdling();
                        }
#endif
                        Match serverAlertMatch = Expressions.ServerAlertRex.Match(tmp);
                        if (serverAlertMatch.Success && tmp.Contains("IMAP") && tmp.Contains("abled"))
                        {
                            throw new ServerAlertException(serverAlertMatch.Groups[1].Value);
                        }
                        return(false);
                    }
                }
            }
        }
Example #35
0
        public RunCommandDialog(CommandLineArgs args, MainWindow mainWindow, bool isCollect = false, Action continuation = null) : base(mainWindow)
        {
            //Owner = mainWindow;
            if (mainWindow.CollectWindow != null)
            {
                throw new ApplicationException("Collection Dialog already open.");
            }

            m_continuation = continuation;
            Closing       += delegate(object sender, CancelEventArgs e)
            {
                mainWindow.CollectWindow = null;
            };

            App.CommandProcessor.LaunchPerfViewElevatedIfNeeded(isCollect ? "GuiCollect" : "GuiRun", args);

            InitializeComponent();

            var osVersion = Environment.OSVersion.Version.Major + Environment.OSVersion.Version.Minor / 10.0;

            if (osVersion < 6.2)        // CPU Counters only supported on Windows 8 and above
            {
                CpuCountersListButton.IsEnabled = false;
                CpuCountersTextBox.IsEnabled    = false;
            }

            if (args.DataFile == null)
            {
                args.DataFile = "PerfViewData.etl";
            }
            else if (!args.DataFile.EndsWith(".etl", StringComparison.OrdinalIgnoreCase))
            {
                if (args.DataFile.EndsWith(".etl.zip", StringComparison.OrdinalIgnoreCase))
                {
                    args.DataFile = args.DataFile.Substring(0, args.DataFile.Length - 4);       // Strip off the .zip.
                }
                else
                {
                    args.DataFile = "PerfViewData.etl";
                }
            }
            mainWindow.StatusBar.Log("Collection Dialog open.");

            m_args       = args;
            m_isCollect  = isCollect;
            m_mainWindow = mainWindow;

            CurrentDirTextBox.Text = Environment.CurrentDirectory;

            // Initialize the CommandToRun history if available.
            var commandToRunHistory = App.UserConfigData["CommandToRunHistory"];

            if (commandToRunHistory != null)
            {
                CommandToRunTextBox.SetHistory(commandToRunHistory.Split(';'));
            }

            if (args.CommandLine != null)
            {
                CommandToRunTextBox.Text = args.CommandLine;
            }

            if (args.FocusProcess != null)
            {
                FocusProcessTextBox.Text = args.FocusProcess;
            }

            var dataFile = args.DataFile;

            if (Path.Combine(CurrentDirTextBox.Text, Path.GetFileName(dataFile)) == dataFile)
            {
                dataFile = Path.GetFileName(dataFile);
            }

            DataFileNameTextBox.Text   = dataFile;
            RundownTimeoutTextBox.Text = args.RundownTimeout.ToString();
            SampleIntervalTextBox.Text = args.CpuSampleMSec.ToString();
            MaxCollectTextBox.Text     = args.MaxCollectSec == 0 ? "" : args.MaxCollectSec.ToString();
            StopTriggerTextBox.Text    = args.StopOnPerfCounter == null ? "" : string.Join(",", args.StopOnPerfCounter);
            CircularTextBox.Text       = args.CircularMB.ToString();

            ZipCheckBox.IsChecked   = args.Zip;
            MergeCheckBox.IsChecked = args.Merge;

            // We are not running from the command line
            if (CommandProcessor.IsGuiCollection(args))
            {
                // Then get the values from previous runs if present.
                if (!ZipCheckBox.IsChecked.HasValue)
                {
                    string configZip;
                    if (App.UserConfigData.TryGetValue("Zip", out configZip))
                    {
                        ZipCheckBox.IsChecked = string.Compare(configZip, "true", true) == 0;
                    }
                }
                if (!MergeCheckBox.IsChecked.HasValue)
                {
                    string configMerge;
                    if (App.UserConfigData.TryGetValue("Merge", out configMerge))
                    {
                        MergeCheckBox.IsChecked = string.Compare(configMerge, "true", true) == 0;
                    }
                }
            }

            NoNGenRundownCheckBox.IsChecked = args.NoNGenRundown;

            if (args.CpuCounters != null)
            {
                CpuCountersTextBox.Text = string.Join(" ", args.CpuCounters);
            }

            // TODO give better feedback about what happens when conflicts happen.
            if (args.ClrEvents != ClrTraceEventParser.Keywords.None)
            {
                ClrCheckBox.IsChecked = true;
            }

            if (args.TplEvents != TplEtwProviderTraceEventParser.Keywords.None)
            {
                TplCaptureCheckBox.IsChecked = true;
            }

            var kernelBase = (KernelTraceEventParser.Keywords)(KernelTraceEventParser.Keywords.Default - KernelTraceEventParser.Keywords.Profile);

            if ((args.KernelEvents & kernelBase) == kernelBase)
            {
                KernelBaseCheckBox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.Profile) != 0)
            {
                CpuSamplesCheckBox.IsChecked = true;
            }

            if (args.GCOnly)
            {
                GCOnlyCheckBox.IsChecked = true;
            }

            if (args.GCCollectOnly)
            {
                GCCollectOnlyCheckBox.IsChecked = true;
            }

            if (args.DotNetAlloc)
            {
                DotNetAllocCheckBox.IsChecked = true;
            }

            if (args.DotNetAllocSampled)
            {
                DotNetAllocSampledCheckBox.IsChecked = true;
            }

            if (args.DotNetCalls)
            {
                DotNetCallsCheckBox.IsChecked = true;
            }

            if (args.JITInlining)
            {
                JITInliningCheckBox.IsChecked = true;
            }

            if ((args.ClrEvents & ClrTraceEventParser.Keywords.GCSampledObjectAllocationHigh) != 0)
            {
                ETWDotNetAllocSampledCheckBox.IsChecked = true;
            }

            if (args.NetworkCapture)
            {
                NetCaptureCheckBox.IsChecked = true;
            }

            if (args.NetMonCapture)
            {
                NetMonCheckBox.IsChecked = true;
            }

            if (args.CCWRefCount)
            {
                CCWRefCountCheckBox.IsChecked = true;
            }

            if (args.RuntimeLoading)
            {
                RuntimeLoadingCheckBox.IsChecked = true;
            }

            if (args.DumpHeap)
            {
                HeapSnapshotCheckBox.IsChecked = true;
            }

            if (args.OSHeapExe != null)
            {
                OSHeapExeTextBox.Text = args.OSHeapExe;
            }

            if (args.OSHeapProcess != 0)
            {
                OSHeapProcessTextBox.Text = args.OSHeapProcess.ToString();
            }

            if ((args.KernelEvents & (KernelTraceEventParser.Keywords.ContextSwitch | KernelTraceEventParser.Keywords.Dispatcher)) != 0)
            {
                ThreadTimeCheckbox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.Memory) != 0)
            {
                MemoryCheckBox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.Registry) != 0)
            {
                RegistryCheckBox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.FileIOInit) != 0)
            {
                FileIOCheckBox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.VirtualAlloc) != 0)
            {
                VirtualAllocCheckBox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.ReferenceSet) != 0)
            {
                RefSetCheckBox.IsChecked = true;
            }

            if ((args.KernelEvents & KernelTraceEventParser.Keywords.Handle) != 0)
            {
                HandleCheckBox.IsChecked = true;
            }

            // Initialize history of additional providers
            var additionalProvidersHistory = App.UserConfigData["AdditionalProvidersHistory"];

            if (additionalProvidersHistory != null)
            {
                AdditionalProvidersTextBox.SetHistory(additionalProvidersHistory.Split(';'));
            }

            if (args.Providers != null)
            {
                var str = "";
                foreach (var provider in args.Providers)
                {
                    if (string.Compare(provider, "Microsoft-Windows-IIS", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        IISCheckBox.IsChecked = true;
                    }

                    if (string.Compare(provider, "ClrStress", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        StressCheckBox.IsChecked = true;
                    }
                    else if (string.Compare(provider, "Microsoft-Windows-Kernel-Memory") == 0)
                    {
                        MemInfoCheckBox.IsChecked = true;
                    }
                    else
                    {
                        if (str.Length != 0)
                        {
                            str += ",";
                        }

                        str += provider;
                    }
                }
                AdditionalProvidersTextBox.Text = str;
            }

            if (args.Message != null)
            {
                MarkTextBox.Text = args.Message;
            }
            else
            {
                MarkTextBox.Text = "Mark 1";
            }

            // TODO the defaults are wrong if you switch from run to collect and back
            if (isCollect)
            {
                Title = "Collecting data over a user specified interval";
                CommandToRunTextBox.IsEnabled   = false;
                CommandToRunTextBox.Visibility  = Visibility.Hidden;
                CommandToRunLabel.Visibility    = Visibility.Hidden;
                FocusProcessCheckBox.Visibility = Visibility.Visible;
                FocusProcessTextBox.Visibility  = Visibility.Visible;
                FocusProcessLabel.Visibility    = Visibility.Visible;
                if (!string.IsNullOrEmpty(FocusProcessTextBox.Text))
                {
                    FocusProcessCheckBox.IsChecked = true;
                    FocusProcessTextBox.IsEnabled  = true;
                }
                else
                {
                    FocusProcessCheckBox.IsChecked = false;
                    FocusProcessTextBox.IsEnabled  = false;
                    FocusProcessTextBox.Text       = "** Machine Wide **";
                }


                RundownCheckBox.IsChecked       = !args.NoRundown;
                RundownTimeoutTextBox.IsEnabled = !args.NoRundown;
                if (args.CircularMB == 0)
                {
                    CircularTextBox.Text = "500";
                }

                OKButton.Content   = "Start Collection";
                StatusTextBox.Text = "Press Start Collection to Start.";
                DataFileNameTextBox.Focus();
            }
            else
            {
                CommandToRunTextBox.Visibility  = Visibility.Visible;
                CommandToRunLabel.Visibility    = Visibility.Visible;
                FocusProcessCheckBox.Visibility = Visibility.Hidden;
                FocusProcessTextBox.Visibility  = Visibility.Hidden;
                FocusProcessLabel.Visibility    = Visibility.Hidden;

                CommandToRunTextBox.Focus();
            }
        }
Example #36
0
        public void Invoke()
        {
            Debug.Assert(_association != null, "The Association reference is null");

            // if the association was deleted in this transaction, just return since we won't need to process it
            if (_association == null ||
                _association.XObject == null)
            {
                return;
            }

            // if foreign keys are supported in this EF version, then we skip all processing here.
            if (EdmFeatureManager.GetForeignKeysInModelFeatureState(_association.Artifact.SchemaVersion).IsEnabled())
            {
                return;
            }

            Debug.Assert(_association.EntityModel.IsCSDL, "Inferring ref constraints isn't valid for SSDL associations");
            Debug.Assert(
                _association.AssociationEnds().Count == 2,
                "The association to be processed does not have 2 ends while trying to infer ref constraints");
            Debug.Assert(
                _association.AssociationSet != null,
                "The association being processed does not have a valid AssociationSet while trying to infer ref constraints");

            // some local aliases for readability
            var end1 = _association.AssociationEnds()[0];
            var end2 = _association.AssociationEnds()[1];

            Debug.Assert(end1 != null && end2 != null, "Null end found while trying to infer ref constraints");
            if (end1 == null ||
                end2 == null)
            {
                return;
            }

            // regardless, we will remove the constraint
            if (_association.ReferentialConstraint != null)
            {
                DeleteEFElementCommand.DeleteInTransaction(_context, _association.ReferentialConstraint);
            }

            // we will never create a constraint against a self-association
            if (end1.Type.Target == end2.Type.Target)
            {
                return;
            }

            AssociationEnd principal = null;
            AssociationEnd dependent = null;

            ModelHelper.DeterminePrincipalDependentAssociationEnds(
                _association, out principal, out dependent,
                ModelHelper.DeterminePrincipalDependentAssociationEndsScenario.InferReferentialConstraint);

            // We found our principal and dependent ends but we still need to confirm that
            // the AssociationSetMapping contains key properties that are mapped to the same column
            if (principal != null &&
                principal.Type.Target != null &&
                dependent != null &&
                dependent.Type.Target != null)
            {
                var associationSet = _association.AssociationSet;
                if (associationSet != null)
                {
                    var asm = associationSet.AssociationSetMapping;
                    if (asm != null &&
                        asm.EndProperties().Count == 2)
                    {
                        // any commonly mapped properties will be loaded into these HashSets
                        var principalPropertyRefs = new HashSet <Property>();
                        var dependentPropertyRefs = new HashSet <Property>();

                        EndProperty dependentEndProperty = null;
                        EndProperty principalEndProperty = null;
                        var         endProp1             = asm.EndProperties()[0];
                        var         endProp2             = asm.EndProperties()[1];
                        if (endProp1.Name.Target != null)
                        {
                            if (endProp1.Name.Target.Role.Target == dependent)
                            {
                                dependentEndProperty = endProp1;
                                principalEndProperty = endProp2;
                            }
                            else
                            {
                                dependentEndProperty = endProp2;
                                principalEndProperty = endProp1;
                            }
                        }

                        Debug.Assert(
                            dependentEndProperty != null && principalEndProperty != null,
                            "Either dependent or principal EndProperty is null");
                        if (dependentEndProperty != null &&
                            principalEndProperty != null)
                        {
                            // for each column that is mapped to a key property on the dependent end, determine if there is a
                            // key property on the principal end that it is also mapped to. If there is, then we need a
                            // ReferentialConstraint
                            foreach (var dependentScalarProp in dependentEndProperty.ScalarProperties())
                            {
                                var principalScalarProp =
                                    principalEndProperty.ScalarProperties()
                                    .FirstOrDefault(psp => psp.ColumnName.Target == dependentScalarProp.ColumnName.Target);
                                if (principalScalarProp != null)
                                {
                                    principalPropertyRefs.Add(principalScalarProp.Name.Target);
                                    dependentPropertyRefs.Add(dependentScalarProp.Name.Target);
                                }
                            }

                            Debug.Assert(
                                principalPropertyRefs.Count == dependentPropertyRefs.Count,
                                "List of keys are mismatched while trying to create a Ref Constraint");
                            if (principalPropertyRefs.Count > 0 &&
                                dependentPropertyRefs.Count > 0 &&
                                principalPropertyRefs.Count == dependentPropertyRefs.Count)
                            {
                                // if the propertyRefs sets have any data in them, add the constraint
                                var cmd = new CreateReferentialConstraintCommand(
                                    principal, dependent, principalPropertyRefs, dependentPropertyRefs);
                                CommandProcessor.InvokeSingleCommand(_context, cmd);
                            }
                        }
                    }
                }
            }
        }
Example #37
0
        private void OpenRastaRegistrar(CommandProcessor commandProcessor)
        {
            _internalDependencyResolver = new InternalDependencyResolver();

            _internalDependencyResolver.AddDependencyInstance<IAmACommandProcessor>(commandProcessor, DependencyLifetime.Singleton);
            _internalDependencyResolver.AddDependency<ITaskRetriever, TaskRetriever>(DependencyLifetime.Singleton);
            _internalDependencyResolver.AddDependency<ITaskListRetriever, TaskListRetriever>(DependencyLifetime.Singleton);
            _internalDependencyResolver.AddDependency<ITasksDAO, TasksDAO>(DependencyLifetime.Singleton);
        }
 public TasksController(CommandProcessor commandProcessor, IMapper mapper)
 {
     _commandProcessor = commandProcessor ?? throw new ArgumentNullException(nameof(commandProcessor));
     _mapper           = mapper ?? throw new ArgumentNullException(nameof(mapper));
 }
Example #39
0
 /// <summary>
 /// The command processor used to send and publish messages to handlers by the service activator.
 /// </summary>
 /// <param name="theCommandProcessor">The command processor.</param>
 /// <returns>INeedAMessageMapper.</returns>
 public INeedAMessageMapper CommandProcessor(CommandProcessor theCommandProcessor)
 {
     _commandProcessor = theCommandProcessor;
     return(this);
 }
        /// <summary>
        /// Load content for the screen.
        /// </summary>
        /// <param name="GraphicInfo"></param>
        /// <param name="factory"></param>
        /// <param name="contentManager"></param>
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            RegisterDebugDrawCommand rc = new RegisterDebugDrawCommand(ddrawer);

            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(rc);

            path.AddCircularObstacle(Vector3.Zero, 10);

            path.AddCircularObstacle(new Vector3(0, 20, 0), 15);

            path.AddCircularObstacle(new Vector3(200), 10);

            foreach (var item in path.Obstacles)
            {
                SphericalObstacle SphericalObstacle = item as SphericalObstacle;
                DebugSphere       s = new DebugSphere(SphericalObstacle.Center, SphericalObstacle.Radius, Color.Blue);
                ddrawer.AddShape(s);
            }
            //DebugSphere.WireFrameEnabled = true;

            DebugLines dls = new DebugLines();

            ddrawer.AddShape(dls);
            for (int i = 0; i < path.PolyPath.pointCount - 1; i++)
            {
                dls.AddLine(path.PolyPath.points[i], path.PolyPath.points[i] + Vector3.Up * 200, Color.Brown);
                dls.AddLine(path.PolyPath.points[i], path.PolyPath.points[i + 1], Color.Red);
            }
            dls.AddLine(path.PolyPath.points[path.PolyPath.pointCount - 1], path.PolyPath.points[path.PolyPath.pointCount - 1] + Vector3.Up * 200, Color.Brown);

            PlugIn = new PedestrianPlugIn(this.World, path,
                                          (pd) =>
            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Green), TextureType.DIFFUSE);
                ///Physic info (position, rotation and scale are set here)
                GhostObject tmesh = new GhostObject();
                ///Forward Shader (look at this shader construction for more info)
                ForwardXNABasicShader shader = new ForwardXNABasicShader();
                ///Deferred material
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                ///The object itself
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                obj.IObjectAttachment.Add(new SteerAtachment(pd));
                return(obj);
            });

            PlugIn.Init();

            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
                ///Physic info (position, rotation and scale are set here)
                BoxObject tmesh = new BoxObject(Vector3.Zero, 1, 1, 1, 10, new Vector3(1000, 1, 1000), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());
                tmesh.isMotionLess = true;
                ///Forward Shader (look at this shader construction for more info)
                ForwardXNABasicShader shader = new ForwardXNABasicShader();
                ///Deferred material
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                ///The object itself
                this.World.AddObject(new IObject(fmaterial, simpleModel, tmesh));
            }

            ///add a camera
            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Example #41
0
        internal CommandProcessorBase CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, bool addToHistory, CommandOrigin origin)
        {
            CommandProcessorBase base2;
            string       str2;
            HelpCategory category;

            if (!this.IsScript)
            {
                if (this._useLocalScope.HasValue && !this._useLocalScope.Value)
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        throw new RuntimeException(StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed, new object[] { "UseLocalScope", PSLanguageMode.RestrictedLanguage.ToString(), PSLanguageMode.NoLanguage.ToString() }));
                    }
                }
                base2 = commandFactory.CreateCommand(this.CommandText, origin, this._useLocalScope);
            }
            else
            {
                if (executionContext.LanguageMode == PSLanguageMode.NoLanguage)
                {
                    throw InterpreterError.NewInterpreterException(this.CommandText, typeof(ParseException), null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed, new object[0]);
                }
                ScriptBlock function = executionContext.Engine.ParseScriptBlock(this.CommandText, addToHistory);
                switch (executionContext.LanguageMode)
                {
                case PSLanguageMode.FullLanguage:
                case PSLanguageMode.ConstrainedLanguage:
                    break;

                case PSLanguageMode.RestrictedLanguage:
                    function.CheckRestrictedLanguage(null, null, false);
                    break;

                default:
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }
                if (function.UsesCmdletBinding)
                {
                    FunctionInfo scriptCommandInfo = new FunctionInfo("", function, executionContext);
                    bool?        nullable          = this._useLocalScope;
                    base2 = new CommandProcessor(scriptCommandInfo, executionContext, nullable.HasValue ? nullable.GetValueOrDefault() : false, false, executionContext.EngineSessionState);
                }
                else
                {
                    bool?nullable2 = this._useLocalScope;
                    base2 = new DlrScriptCommandProcessor(function, executionContext, nullable2.HasValue ? nullable2.GetValueOrDefault() : false, CommandOrigin.Runspace, executionContext.EngineSessionState);
                }
            }
            CommandParameterCollection parameters = this.Parameters;

            if (parameters != null)
            {
                bool forNativeCommand = base2 is NativeCommandProcessor;
                foreach (CommandParameter parameter in parameters)
                {
                    CommandParameterInternal internal2 = CommandParameter.ToCommandParameterInternal(parameter, forNativeCommand);
                    base2.AddParameter(internal2);
                }
            }
            if (base2.IsHelpRequested(out str2, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(executionContext, str2, category);
            }
            this.SetMergeSettingsOnCommandProcessor(base2);
            return(base2);
        }
Example #42
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);
            {
                SimpleModel          simpleModel = new SimpleModel(factory, "Model//cenario");
                TriangleMeshObject   tmesh       = new TriangleMeshObject(simpleModel, Vector3.Zero, Matrix.Identity, Vector3.One, MaterialDescription.DefaultBepuMaterial());
                DeferredNormalShader shader      = new DeferredNormalShader();
                DeferredMaterial     fmaterial   = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                this.World.AddObject(obj);
            }

            {
                SimpleModel sm = new SimpleModel(factory, "..\\Content\\Model\\block");
                sm.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
                BoxObject            pi     = new BoxObject(new Vector3(100, 40, 0), 1, 1, 1, 25, new Vector3(100, 10, 100), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());
                DeferredNormalShader shader = new DeferredNormalShader();
                IMaterial            mat    = new DeferredMaterial(shader);
                IObject obj3 = new IObject(mat, sm, pi);
                this.World.AddObject(obj3);
            }

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            CameraFirstPerson cam = new CameraFirstPerson(GraphicInfo);
            //cam.FarPlane = 100;
            this.World.CameraManager.AddCamera(cam);

            Texture2D texture = factory.GetTexture2D("Textures//goo");

            LightThrowBepu lt = new LightThrowBepu(this.World, factory);

            var projection = Matrix.CreatePerspectiveFieldOfView(cam.FieldOfView / 20, cam.AspectRatio, 1, 1000);

            var view = Matrix.CreateLookAt(
                new Vector3(1500, 200, 200),
                new Vector3(0, 0, 0),
                Vector3.Up
                );

            Decal decal = new Decal(texture, view, projection);

            DecalComponent.Decals.Add(decal);

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//grasscube");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
Example #43
0
 public Analyzer()
 {
     _serviceProvider  = new ServiceProvider();
     _consoleProvider  = new ConsoleProvider();
     _commandProcessor = new CommandProcessor(_serviceProvider, _consoleProvider, new Assembly[] { typeof(Analyzer).Assembly });
 }
 public void CleanUp()
 {
     mm0.BindAction = BindAction.REMOVE;
     CommandProcessor.getCommandProcessor().SendCommandAssyncronous(mm0);
 }
Example #45
0
        private void OnTick(object sender, EventArgs e)
        {
            var status = CommandProcessor.GetStatusLine(m_args, m_startTime, ref m_startedDropping);

            StatusTextBox.Text = status + "  Click Stop button to stop.";
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            SimpleModel simpleModel = new SimpleModel(factory, "Model//block");

            simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
            BoxObject tmesh = new BoxObject(new Vector3(0, 10, 0), 1, 1, 1, 50, new Vector3(5000, 1, 5000), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());

            tmesh.isMotionLess = true;
            DeferredNormalShader shader    = new DeferredNormalShader();
            DeferredMaterial     fmaterial = new DeferredMaterial(shader);
            IObject obj = new IObject(fmaterial, simpleModel, tmesh);

            this.World.AddObject(obj);

            {
                List <Vector3> poss = new List <Vector3>();
                for (int i = 0; i < 10; i++)
                {
                    for (int j = 0; j < 10; j++)
                    {
                        float x, y;
                        x = i * 100;
                        y = j * 100;
                        poss.Add(new Vector3(x, 5, y));
                    }
                }
                ///Bilboard Model
                StaticBilboardModel bm = new StaticBilboardModel(factory, "Bilbs", "..\\Content\\Textures\\tree", poss);
                ///Bilboard Shader, this one is otimized for Cilindrical Bilboard only
                DeferredCilindricGPUBilboardShader cb = new DeferredCilindricGPUBilboardShader();
                cb.Atenuation = new Vector4(0.8f, 0.8f, 0.8f, 1);
                DeferredMaterial matfor = new DeferredMaterial(cb);
                ///You can Change Parameters (position, scale ...) of ALL bilboards changing the World Matrix of the physical Object
                ///for Ghost Object we can use go.setInternalWorldMatrix.
                GhostObject go = new GhostObject();
                go.Position = new Vector3(200, -10f, 0);
                IObject obj2 = new IObject(matfor, bm, go);
                this.World.AddObject(obj2);
            }


            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            CameraFirstPerson cam = new CameraFirstPerson(MathHelper.ToRadians(-60), MathHelper.ToRadians(-10), new Vector3(-200, 150, 250), GraphicInfo);
            this.World.CameraManager.AddCamera(cam);

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//grassCube");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <param name="hostName">Name of the host.</param>
        /// <returns>Dispatcher.</returns>
        public Dispatcher Build(string hostName)
        {
            // We want to register policies, messages and handlers for receiving built in commands. It's simple enough to do this for
            // the registries, but we cannot know your HandlerFactory implementation in order to insert. So we have to rely on
            // an internal HandlerFactory to build these for you.
            // We also need to  pass the supervised dispatcher as a dependency to our command handlers, so this allows us to manage
            // the injection of the dependency as part of our handler factory

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICY, retryPolicy }
            };

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <ConfigurationCommand, ConfigurationCommandHandler>();
            subscriberRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandHandler>();

            var incomingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            incomingMessageMapperRegistry.Register <ConfigurationCommand, ConfigurationCommandMessageMapper>();
            incomingMessageMapperRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandMessageMapper>();

            var outgoingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            outgoingMessageMapperRegistry.Register <HeartbeatReply, HeartbeatReplyCommandMessageMapper>();

            //TODO: It doesn't feel quite right that we have to pass this in for both dispatcher channel factory and task queue configuration
            //as we should be over same broker. But, so far, refactoring either ends up exposing properties of the channel factory, which we don't want
            //or stalling on the need for channel factory to be broker defined. It is possible the fix is to drop channel factory in favour of passing
            //in producer and sender. But that's a breaking change to the builder, so contemplating for now.

            var producer = _producerFactory.Create();

            var outbox = new SinkOutbox();

            CommandProcessor commandProcessor = null;

            commandProcessor = CommandProcessorBuilder.With()
                               .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactory(_dispatcher, () => commandProcessor)))
                               .Policies(policyRegistry)
                               .TaskQueues(new MessagingConfiguration(outbox, producer, outgoingMessageMapperRegistry))
                               .RequestContextFactory(new InMemoryRequestContextFactory())
                               .Build();

            // These are the control bus channels, we hardcode them because we want to know they exist, but we use
            // a base naming scheme to allow centralized management.
            var connectionsConfiguration = new Subscription[]
            {
                new Subscription <ConfigurationCommand>(
                    new SubscriptionName($"{hostName}.{CONFIGURATION}"),
                    new ChannelName($"{hostName}.{CONFIGURATION}"),
                    new RoutingKey($"{hostName}.{CONFIGURATION}")),
                new Subscription <HeartbeatRequest>(
                    new SubscriptionName($"{hostName}.{HEARTBEAT}"),
                    new ChannelName($"{hostName}.{HEARTBEAT}"),
                    new RoutingKey($"{hostName}.{HEARTBEAT}"))
            };

            return(DispatchBuilder.With()
                   .CommandProcessor(commandProcessor)
                   .MessageMappers(incomingMessageMapperRegistry)
                   .DefaultChannelFactory(_channelFactory)
                   .Connections(connectionsConfiguration)
                   .Build());
        }
        internal override void CreateModelItem(CommandProcessorContext cpc, EditingContext context, EFElement underlyingModelItem)
        {
            Debug.Assert(context != null, "null context");

            Debug.Assert(Function == null, "Don't call this method if we already have a ModelItem");
            Debug.Assert(MappingFunctionEntityType.EntityType != null, "The parent item isn't set up correctly");

            Debug.Assert(underlyingModelItem != null, "null underlyingModelItem");

            var function = underlyingModelItem as Function;

            Debug.Assert(
                function != null, "underlyingModelItem must be of type Function, actual type = " + underlyingModelItem.GetType().FullName);
            Debug.Assert(!function.EntityModel.IsCSDL, "The function must be in the SSDL");

            Context = context;

            // create a context if we weren't passed one
            if (cpc == null)
            {
                cpc = new CommandProcessorContext(
                    Context, EfiTransactionOriginator.MappingDetailsOriginatorId, Resources.Tx_CreateFunctionMapping);
            }

            // create the commands
            var cmd = new CreateFunctionMappingCommand(MappingFunctionEntityType.EntityType, function, null, _functionType);

            // set up our post event to fix up the view model
            cmd.PostInvokeEvent += (o, eventsArgs) =>
            {
                var mf = cmd.ModificationFunction;
                Debug.Assert(mf != null, "null ModificationFunction");

                // fix up our view model
                ModelItem = mf;
                // The parent item for the function mapping view model always has 3 children; insert, update and delete items.  If there isn’t
                // a function mapped for any of these, then there is still a view model item since we want to display the ‘creator node’ text.
                // Calling this.Parent.AddChild(this) here would make the parent think it had a new child instead of updating the existing one -
                // so it is correct to _not_ call it here.
            };

            var cmd2 = new DelegateCommand(
                () =>
            {
                var mf = ModificationFunction;
                Debug.Assert(
                    mf != null,
                    "Null ModificationFunction when trying to create view-model dummy nodes in MappingModificationFunctionMapping.CreateModelItem()");

                if (mf != null)
                {
                    //set up _properties and _resultBindings here as they are dummy ViewModel nodes
                    // (i.e. don't correspond to any underlying ModelItem)
                    _properties     = new MappingFunctionScalarProperties(context, mf, this);
                    _resultBindings = new MappingResultBindings(context, mf, this);
                    _properties.Parent.AddChild(_properties);
                    _resultBindings.Parent.AddChild(_resultBindings);

                    // now ensure _properties scalar properties children have been calculated
                    // (this creates scalar properties with just the column info
                    // since this ModificationFunction has not yet been mapped)
                    _properties.LoadScalarProperties();

                    // now try and do some match ups between the function and the entity
                    var mappedEntityType = MappingFunctionEntityType.EntityType as ConceptualEntityType;

                    Debug.Assert(
                        MappingFunctionEntityType.EntityType == null || mappedEntityType != null,
                        "EntityType is not ConceptualEntityType");

                    if (mappedEntityType != null)
                    {
                        foreach (var mfsp in _properties.ScalarProperties)
                        {
                            // Try to do some auto-matching of the sproc's parameters to the EntityType's properties.
                            // Search for a property in the mapped EntityType's inheritance hierarchy that matches the
                            // parameter's name. First search this EntityType (both its scalar and complex properties),
                            // then search its parents scalar and complex properties and so on up the hierarchy
                            var propNameToSearchFor = mfsp.StoreParameter.LocalName.Value;
                            var propList            = new List <Property>();
                            var entityTypeToSearch  = mappedEntityType;
                            // reset this back to the mapped EntityType each time through the loop
                            while (entityTypeToSearch != null &&
                                   false
                                   == ModelHelper.FindScalarPropertyPathByLocalName(
                                       entityTypeToSearch, propNameToSearchFor, out propList))
                            {
                                if (entityTypeToSearch.BaseType == null)
                                {
                                    // safety code - this should not happen but will prevent an infinite loop if it does
                                    entityTypeToSearch = null;
                                }
                                else
                                {
                                    entityTypeToSearch = entityTypeToSearch.BaseType.Target;
                                }
                            }

                            // if propList is still empty that means we did not find a match - so leave the parameter unmapped
                            if (propList.Count > 0)
                            {
                                mfsp.CreateModelItem(cpc, _context, propList);
                            }
                        }
                    }
                }
            });

            try
            {
                // now make the change
                var cp = new CommandProcessor(cpc);
                cp.EnqueueCommand(cmd);
                cp.EnqueueCommand(cmd2);
                cp.Invoke();
            }
            catch
            {
                ModelItem = null;
                ClearChildren();

                throw;
            }
        }
Example #49
0
 public AniDBHttpConnectionHandler(ILogger <AniDBHttpConnectionHandler> logger, CommandProcessor queue, HttpRateLimiter rateLimiter) : base(logger, queue, rateLimiter)
 {
 }
Example #50
0
        private void DumpHeap(bool closeOnComplete)
        {
            // Are we collecting from a live process?
            m_args.Process = null;
            if (m_processList != null)
            {
                // Set the process ID
                var selectedProcess = Processes.SelectedItem as ProcessInfo;
                if (selectedProcess != null)
                {
                    m_args.Process = selectedProcess.ProcessID.ToString();
                }
                else
                {
                    StatusBar.Log("No selection made");
                    return;
                }
                m_args.DoCommand = App.CommandProcessor.HeapSnapshot;
            }
            else
            {
                m_args.ProcessDumpFile = ProcessDumpTextBox.Text;
                m_args.DoCommand       = App.CommandProcessor.HeapSnapshotFromProcessDump;
            }

            var dataFile = DataFileNameTextBox.Text;

            if (dataFile.Length == 0)
            {
                StatusBar.Log("Error: Output data file not specififed.");
                return;
            }
            m_args.DataFile = dataFile;
            m_args.Freeze   = FreezeCheckBox.IsChecked ?? false;
            m_args.SaveETL  = SaveETLCheckBox.IsChecked ?? false;
            m_args.DumpData = false;  // TODO FIX NOW acutlaly use
            if (!int.TryParse(MaxDumpTextBox.Text, out m_args.MaxDumpCountK))
            {
                StatusBar.LogError("Could not parse MaxDump " + MaxDumpTextBox.Text);
                return;
            }

            if (m_args.MaxDumpCountK >= 10000)
            {
                var response = MessageBox.Show("WARNING: you have selected a Max Dump Count larger than 10M objects.\r\n" +
                                               "You should only need 100K to do a good job, even at 10M the GUI will be very sluggish.\r\n" +
                                               "Consider canceling and picking a smaller value.", "Max Dump Size Too Big",
                                               MessageBoxButton.OKCancel);
                if (response != MessageBoxResult.OK)
                {
                    StatusBar.Log("Memory collection canceled.");
                    Close();
                    GuiApp.MainWindow.Focus();
                    return;
                }
            }

            m_args.NoView   = true;
            m_tookASnapshot = true;
            m_mainWindow.ExecuteCommand("Dumping GC Heap to " + System.IO.Path.GetFullPath(App.CommandLineArgs.DataFile),
                                        m_args.DoCommand, StatusBar, closeOnComplete ? m_continuation : null,
                                        delegate
            {
                m_mainWindow.StatusBar.Status = StatusBar.Status;
                if (closeOnComplete)
                {
                    Close();
                }
                else
                {
                    StatusBar.Status = "Data in: " + DataFileNameTextBox.Text + ".  Press 'Close' or 'Dump GC Heap' to continue.";
                    StatusBar.Beep();
                    DataFileNameTextBox.Text = CommandProcessor.GetNewFile(DataFileNameTextBox.Text);
                }
            });
        }
Example #51
0
        internal void ChangeFunctionScalarProperty(EditingContext context, List <Property> newPropertiesChain)
        {
            if (ScalarProperty == null)
            {
                // if we don't have a scalar property, there is nothing to set this into;
                // create the scalar property first
                throw new InvalidOperationException();
            }
            else
            {
                // is the propertiesChain different from what we have already?
                var propertiesChain = ScalarProperty.GetMappedPropertiesList();
                var changeNeeded    = false;
                if (propertiesChain.Count != newPropertiesChain.Count)
                {
                    changeNeeded = true;
                }
                else
                {
                    for (var i = 0; i < propertiesChain.Count; i++)
                    {
                        if (propertiesChain[i] != newPropertiesChain[i])
                        {
                            changeNeeded = true;
                            break;
                        }
                    }

                    // if no change needed yet, check NavProp as well
                    if (changeNeeded == false)
                    {
                        // if this property is pointed to by a navigation property, then check if the
                        // new navigation property is different from the old one
                        if (ScalarProperty.AssociationEnd != null)
                        {
                            var currentNavProp = ModelHelper.FindNavigationPropertyForFunctionScalarProperty(ScalarProperty);
                            // currentNavProp can be null if the NavProp has been deleted
                            changeNeeded = (currentNavProp == null ? true : (currentNavProp != _pointingNavProperty));
                        }
                        else
                        {
                            // the previous property was not pointed to by a navigation property but the new one is
                            if (_pointingNavProperty != null)
                            {
                                changeNeeded = true;
                            }
                        }
                    }
                }

                if (changeNeeded)
                {
                    // delete old and create new FunctionScalarProperty in one transaction - this takes care of
                    // removing any old ComplexProperty or AssociationEnd parent nodes as necessary
                    var cpc = new CommandProcessorContext(
                        context, EfiTransactionOriginator.MappingDetailsOriginatorId, Resources.Tx_ChangeScalarProperty);
                    var version = (ScalarProperty.Version == null ? null : ScalarProperty.Version.Value);
                    // Version is used only for Update ModificationFunctions
                    var cmd = new ChangeFunctionScalarPropertyCommand(
                        ScalarProperty, newPropertiesChain, _pointingNavProperty, StoreParameter, version);
                    cmd.PostInvokeEvent += (o, eventsArgs) =>
                    {
                        var fsp = cmd.FunctionScalarProperty;
                        Debug.Assert(fsp != null, "ChangeFunctionScalarPropertyCommand failed to create a FunctionScalarProperty");
                        ModelItem = fsp;
                    };

                    var cp = new CommandProcessor(cpc, cmd);
                    try
                    {
                        cp.Invoke();
                    }
                    catch
                    {
                        ModelItem = null;

                        throw;
                    }
                }
            }
        }
Example #52
0
        internal void ChangeScalarProperty(EditingContext context, List <Property> newPropertiesChain)
        {
            if (ModelItem != null)
            {
                var propertiesChain = ScalarProperty.GetMappedPropertiesList();
                var changeNeeded    = false;
                // is it different than what we have already?
                if (propertiesChain.Count != newPropertiesChain.Count)
                {
                    changeNeeded = true;
                }
                else
                {
                    for (var i = 0; i < propertiesChain.Count; i++)
                    {
                        if (propertiesChain[i] != newPropertiesChain[i])
                        {
                            changeNeeded = true;
                            break;
                        }
                    }
                }

                if (changeNeeded)
                {
                    Debug.Assert(ScalarProperty.ColumnName.Status == BindingStatus.Known, "Table column not found");
                    if (ScalarProperty.ColumnName.Status == BindingStatus.Known)
                    {
                        // delete old and create new ScalarProperty in one transaction
                        var cpc = new CommandProcessorContext(
                            context, EfiTransactionOriginator.MappingDetailsOriginatorId, Resources.Tx_ChangeScalarProperty);
                        var cmd1 = ScalarProperty.GetDeleteCommand();
                        var cmd2 = new CreateFragmentScalarPropertyTreeCommand(
                            MappingConceptualEntityType.ConceptualEntityType, newPropertiesChain, ScalarProperty.ColumnName.Target);
                        cmd2.PostInvokeEvent += (o, eventsArgs) =>
                        {
                            var sp = cmd2.ScalarProperty;
                            Debug.Assert(sp != null, "CreateFragmentScalarPropertyTreeCommand falied to create a ScalarProperty");
                            ModelItem = sp;
                        };

                        var cp = new CommandProcessor(cpc, cmd1, cmd2);
                        try
                        {
                            cp.Invoke();
                        }
                        catch
                        {
                            ModelItem = null;

                            throw;
                        }
                    }
                }
            }
            else
            {
                // if we don't have a scalar property, there is nothing to set this into;
                // create the scalar property first
                throw new InvalidOperationException();
            }
        }
 public PlannerController(string username)
 {
     _processor  = new CommandProcessor();
     CurrentUser = new User(0, username);
 }
        protected void AddSkyBox(String skyboxtextureName)
        {
            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube(skyboxtextureName);

            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
        /// <summary>
        /// Apply the rules.
        /// </summary>
        /// <remarks>
        /// When rules are applied, we are simply adding new <see cref="ServerDatabaseCommand"/> instances
        /// for the rules to the currently executing <see cref="ServerCommandProcessor"/>.  They will be
        /// executed after all other rules have been executed.
        /// </remarks>
        protected override void OnExecute(CommandProcessor theProcessor)
        {
            string   studyXmlFile = Path.Combine(_directory, String.Format("{0}.xml", _studyInstanceUid));
            StudyXml theXml       = new StudyXml(_studyInstanceUid);

            if (File.Exists(studyXmlFile))
            {
                using (Stream fileStream = FileStreamOpener.OpenForRead(studyXmlFile, FileMode.Open))
                {
                    XmlDocument theDoc = new XmlDocument();

                    StudyXmlIo.Read(theDoc, fileStream);

                    theXml.SetMemento(theDoc);

                    fileStream.Close();
                }
            }
            else
            {
                string errorMsg = String.Format("Unable to load study XML file of restored study: {0}", studyXmlFile);

                Platform.Log(LogLevel.Error, errorMsg);
                throw new ApplicationException(errorMsg);
            }

            DicomFile defaultFile   = null;
            bool      rulesExecuted = false;

            foreach (SeriesXml seriesXml in theXml)
            {
                foreach (InstanceXml instanceXml in seriesXml)
                {
                    // Skip non-image objects
                    if (instanceXml.SopClass.Equals(SopClass.KeyObjectSelectionDocumentStorage) ||
                        instanceXml.SopClass.Equals(SopClass.GrayscaleSoftcopyPresentationStateStorageSopClass) ||
                        instanceXml.SopClass.Equals(SopClass.BlendingSoftcopyPresentationStateStorageSopClass) ||
                        instanceXml.SopClass.Equals(SopClass.ColorSoftcopyPresentationStateStorageSopClass))
                    {
                        // Save the first one encountered, just in case the whole study is non-image objects.
                        if (defaultFile == null)
                        {
                            defaultFile = new DicomFile("test", new DicomAttributeCollection(), instanceXml.Collection);
                        }
                        continue;
                    }

                    DicomFile file = new DicomFile("test", new DicomAttributeCollection(), instanceXml.Collection);
                    _context.Message = file;
                    _engine.Execute(_context);
                    rulesExecuted = true;
                    break;
                }
                if (rulesExecuted)
                {
                    break;
                }
            }

            if (!rulesExecuted && defaultFile != null)
            {
                _context.Message = defaultFile;
                _engine.Execute(_context);
            }
        }
        public void ApplyTeleportEffects(Player Ply, List <string> Effects)
        {
            if (Ply == null)
            {
                return;
            }
            if (Effects.Count == 0)
            {
                return;
            }

            foreach (string effect in Effects)
            {
                string[] args = effect.Split((":").ToCharArray());
                switch (args.First().ToLower())
                {
                case "addahp":
                    if (Ply.Role == RoleType.Scp096)
                    {
                        continue;
                    }
                    try
                    {
                        Ply.AdrenalineHealth += Convert.ToInt32(args.ElementAt(1));
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "applyeffect":
                    try
                    {
                        Ply.ReferenceHub.playerEffectsController.EnableByString(args.ElementAt(1), Convert.ToInt32(args.ElementAt(2)));
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "broadcast":
                    try
                    {
                        int    type = Convert.ToInt32(args.ElementAt(1));
                        int    dur  = Convert.ToInt32(args.ElementAt(2));
                        string msg  = string.Join(" ", args.Skip(3));
                        IEnumerable <Player> Plrs = new List <Player> {
                        };
                        switch (type)
                        {
                        case 0:
                            Plrs = new List <Player> {
                                Ply
                            };
                            break;

                        case 1:
                            Plrs = Player.List;
                            break;

                        case 2:
                            Plrs = Player.List.Where(p => p.Team == Team.SCP);
                            break;

                        case 3:
                            Plrs = Player.List.Where(p => CommandProcessor.CheckPermissions(p.Sender, "AdminChat", PlayerPermissions.AdminChat));
                            break;

                        default:
                            Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" first argument (type) is invalid.");
                            break;
                        }
                        foreach (Player ToSend in Plrs)
                        {
                            ToSend.ClearBroadcasts();
                            ToSend.Broadcast((ushort)dur, msg.Replace("{Name}", Ply.Nickname).Replace("{Room}", GetRoomName(Ply.CurrentRoom)).Replace("{Class}", $"<color={Ply.Role.GetColor().ToHex()}>{Constants.ClassStrings[Ply.Role.ToString()]}</color>") + "\n");
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "damage":
                    try
                    {
                        int amt = Convert.ToInt32(args.ElementAt(1));
                        if (Ply.IsGodModeEnabled == false)
                        {
                            Ply.Hurt(amt, DamageTypes.Wall, "SCP-914 Teleportation");
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "dropitems":
                    try
                    {
                        if (args.ElementAt(1) == "all" || args.ElementAt(1) == "*")
                        {
                            Ply.Inventory.ServerDropAll();
                        }
                        else
                        {
                            int amount = Convert.ToInt32(args.ElementAt(1));
                            for (int i = 0; i < amount; i++)
                            {
                                int pos = rnd.Next(0, Ply.Inventory.items.Count() - 1);
                                Ply.DropItem(Ply.Inventory.items.ElementAt(pos));
                            }
                            ;
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "god":
                    try
                    {
                        if (!Ply.IsGodModeEnabled)     // do not toggle godmode if they already had it on - that defeats the point
                        {
                            Ply.IsGodModeEnabled = true;
                            Timing.CallDelayed((float)Convert.ToInt32(args.ElementAt(1)), () =>
                            {
                                Ply.IsGodModeEnabled = false;
                            });
                        }
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                case "stamina":
                    if (Ply.Team == Team.SCP)
                    {
                        break;
                    }
                    try
                    {
                        int amt = Convert.ToInt32(args.ElementAt(1)) / 100;
                        Ply.Stamina.RemainingStamina = amt;
                    }
                    catch
                    {
                        Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. \"{effect}\" arguments are not valid.");
                    }
                    break;

                default:
                    Log.Warn($"WARNING: SCP-914 Teleportation effects configured incorrectly. Invalid effect type: {effect}.");
                    break;
                }
            }
        }
 public bool RegisterCommand(string label, CommandProcessor callback)
 {
     if (_commands.ContainsKey(label)) return false;
     _commands[label] = callback;
     return true;
 }
        protected override void OnExecute(CommandProcessor theProcessor, IUpdateContext updateContext)
        {
            var delete = updateContext.GetBroker <IWorkQueueUidEntityBroker>();

            delete.Delete(_uid.GetKey());
        }
Example #59
0
 /// <summary>
 /// Execute the ServerDatabaseCommand with the specified <see cref="IUpdateContext"/>.
 /// </summary>
 protected abstract void OnExecute(CommandProcessor theProcessor, IUpdateContext updateContext);
Example #60
0
 public CommandProcessorPublishMissingHandlerFactoryAsyncTests()
 {
     _commandProcessor = new CommandProcessor(new SubscriberRegistry(), null, new InMemoryRequestContextFactory(), new PolicyRegistry());
     PipelineBuilder <MyEvent> .ClearPipelineCache();
 }