Esempio n. 1
0
    public virtual void UpdateStats(BaseCaracterStats statData, IEventAggregator messenger)
    {
        MaxLife += statData.MaxLife;
        Life += statData.Life;
        if (MaxLife < Life) Life = MaxLife;
        if (Life <= 0)
        {
            Life = 0;
            messenger.Publish(new StopMessage());
            messenger.Publish(new PlayerDeathMessage());
        }
        RedHearts += statData.RedHearts;
        BlueHearts += statData.BlueHearts;
        YellowHearts += statData.YellowHearts;

        Attack += statData.Attack;
        BaseSpeed += statData.BaseSpeed;
        CurrentSpeed = BaseSpeed;
        AttackCadence += statData.AttackCadence;
        if (statData.OldTools)
        {
            OldTools = statData.OldTools;
        }
        messenger.Publish(new UpdateGuiMessage(this));
    }
        public OkCancelPanelViewModel(IEventAggregator eventAggregator)
        {
            this.OkCommand = new DelegateCommand<object>(
                o => eventAggregator.Publish(new CleanUpFilesMessage()));

            this.CancelCommand = new DelegateCommand<object>(o =>
                eventAggregator.Publish(new ClearFileSelectionMessage()));
        }
Esempio n. 3
0
        //, Func<ProjectExplorerViewModel> projectExplorerViewModelBuilder, Func<EventAggregatorDebugViewModel> eventsDebugBuilder,)
        public MenuViewModel(IEventAggregator eventAggregator, Func<TeapotViewModel> teapotBuilder, IScriptRunner script, ProjectManager manager)
        {
            _eventAggregator = eventAggregator;
            Items = new BindableCollection<MenuItemViewModel> {
                new MenuItemViewModel {
                    Header = "_FILE",
                    Items = new BindableCollection<MenuItemViewModel> {
                        new MenuItemViewModel {
                            Header = "_Open",
                            Items = new BindableCollection<MenuItemViewModel> {
                                new MenuItemViewModel {
                                    Header = "_Project",
                                    Action = () => _eventAggregator.Publish(new OpenProjectDialog())
                                },
                                new MenuItemViewModel {
                                    Header = "Teapot",
                                    Action = () => _eventAggregator.Publish(new AddTabViewCommand {Model = teapotBuilder()})
                                },

                            }
                        },
                        new MenuItemViewModel {
                            Header = "Close",
                            Action = () => _eventAggregator.Publish(new DebugCommand("close"))
                        }
                    }
                },
                new MenuItemViewModel {
                    Header = "_EDIT"
                },
                new MenuItemViewModel {
                    Header = "_VIEW"
                },
                new MenuItemViewModel {
                    Header = "_BUILD",
                    Items = new BindableCollection<MenuItemViewModel> {
                        new MenuItemViewModel {
                            Header = "_Build Project",
                            Action = () => script.Execute(manager.Project)
                        },
                        new MenuItemViewModel {
                            Header = "Teapot",
                            Action = () => _eventAggregator.Publish(new AddTabViewCommand {Model = teapotBuilder()})
                        },

                    }
                },
                new MenuItemViewModel {
                    Header = "_WINDOW"
                },
                new MenuItemViewModel {
                    Header = "_HELP"
                }
            };
        }
Esempio n. 4
0
        private void UpdateMessageList(MessageInfo[] updatedMessageList)
        {
            var existingIds = Messages.Select(m => m.Id).ToArray();
            var updatedIds  = updatedMessageList.Select(m => m.Id).ToArray();

            var removedMessagesIds = existingIds.Union(updatedIds).Except(updatedIds).ToArray();
            var newMessagesIds     = updatedIds.Except(existingIds).ToArray();

            try
            {
                IsNotifying = false;
                foreach (var removedMessageId in removedMessagesIds)
                {
                    var message = Messages.SingleOrDefault(m => m.Id == removedMessageId);
                    if (message != null)
                    {
                        Messages.Remove(message);
                    }
                }
                foreach (var newMessagesId in newMessagesIds)
                {
                    var message = updatedMessageList.SingleOrDefault(m => m.Id == newMessagesId);
                    Messages.Add(new MessageGridRowViewModel(message));
                }
            }
            finally
            {
                IsNotifying = true;
            }
            if (removedMessagesIds.Any() || newMessagesIds.Any())
            {
                _eventAggregator.Publish(new QueueMessageCountChangedEvent(_messageQueue));
            }
        }
Esempio n. 5
0
 public void AddToPlaylist()
 {
     _eventAggregator.Publish(new PlaylistMessage {
         Queue = SelectedSubsonicItems.ToList()
     });
     SelectedItems.Clear();
 }
Esempio n. 6
0
 public MenuViewModel(IEventAggregator eventAggregator,
                      Func<ProjectExplorerViewModel> projectExplorerViewModelBuilder,
                      Func<EventAggregatorDebugViewModel> eventsDebugBuilder,
                      Func<TeapotViewModel> teapotBuilder)
 {
     _eventAggregator = eventAggregator;
     Items = new BindableCollection<MenuItemViewModel> {
         new MenuItemViewModel {
             Header = "_FILE",
             Items = new BindableCollection<MenuItemViewModel> {
                 new MenuItemViewModel {
                     Header = "Open Teapot",
                     Action = () =>
                              _eventAggregator.Publish(new AddTabViewCommand {Model = teapotBuilder()})
                 },
                 new MenuItemViewModel {
                     Header = "Open Events Tool",
                     Action = () =>
                              _eventAggregator.Publish(new AddToolViewCommand {Model = eventsDebugBuilder()})
                 },
                 new MenuItemViewModel {
                     Header = "Open Project Explorer",
                     Action = () =>
                              _eventAggregator.Publish(new AddToolViewCommand {Model = projectExplorerViewModelBuilder()})
                 },
                 new MenuItemViewModel {
                     Header = "Add part",
                     Action = () => _eventAggregator.Publish(new AddPartCommand {Part = new JsonPartMeta {FilePath = @"C:\temp\OpenCad\temp.cadpart"}})
                 },
                 new MenuItemViewModel {
                     Header = "Open Part",
                     Action = () =>
                              _eventAggregator.Publish(new AddTabViewCommand {Model = new PartViewModel()})
                 }
             }
         },
         new MenuItemViewModel {
             Header = "_EDIT"
         },
         new MenuItemViewModel {
             Header = "_VIEW"
         },
         new MenuItemViewModel {
             Header = "_WINDOW"
         },
         new MenuItemViewModel {
             Header = "_HELP"
         }
     };
 }
Esempio n. 7
0
        public ShellViewModel(
            IServer server,
            ServerUriProvider uriProvider,
            NavigationViewModel navigation,
            NotificationsViewModel notifications,
            BusyStatusViewModel busyStatus,
            SelectDatabaseViewModel startScreen,
            DatabaseExplorer databaseScreen,
            IKeyboardShortcutBinder binder,
            IEventAggregator events)
        {
            this.databaseScreen = databaseScreen;
            this.navigation     = navigation;
            this.notifications  = notifications;
            this.busyStatus     = busyStatus;
            this.startScreen    = startScreen;
            navigation.SetGoHome(() => this.TrackNavigationTo(startScreen, events));
            this.binder = binder;
            this.events = events;
            this.server = server;
            events.Subscribe(this);


            Items.Add(startScreen);
            Items.Add(databaseScreen);

            serverUri = new Uri(uriProvider.GetServerUri());

            events.Publish(new WorkStarted("Connecting to server"));
            server.Connect(serverUri,
                           () =>
            {
                events.Publish(new WorkCompleted("Connecting to server"));

                switch (server.Databases.Count())
                {
                case 0:
                    //NOTE: perhaps we should display a retry button?
                    break;

                case 1:
                    ActivateItem(databaseScreen);
                    break;

                default:
                    ActivateItem(startScreen);
                    break;
                }
            });
        }
Esempio n. 8
0
        public void SelectionChanged(SelectionChangedEventArgs args)
        {
            SelectedItems.AddRange(args.AddedItems.Cast <PresetItemViewModel>());
            SelectedItems.RemoveRange(args.RemovedItems.Cast <PresetItemViewModel>());

            if (args.AddedItems.Count == 0 && !SelectedItems.Any())
            {
                eventAggregator.Publish(new Events.PresetItemsSelectionChanged(false));
            }

            if (args.RemovedItems.Count == 0 && SelectedItems.Count == 1)
            {
                eventAggregator.Publish(new Events.PresetItemsSelectionChanged(true));
            }
        }
Esempio n. 9
0
        public void Update(GameTime gameTime)
        {
            var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            Velocity *= _velocityDamping;
            Position += Velocity * elapsed;

            if (Math.Abs(Velocity.X) > _movementTolerance)
            {
                _eventAggregator.Publish(new PaddleMoved
                {
                    Paddle = this
                });
            }
        }
        private void TriggerErrorEventNotOnPythonThread(Exception e)
        {
            if (e.InnerException != null)
            {
                TriggerErrorEventNotOnPythonThread(e.InnerException);
                return;
            }

            var stack      = PythonOps.GetDynamicStackFrames(e);
            var lineNumber = stack
                             .Select(s => (int?)s.GetFileLineNumber())
                             .FirstOrDefault();

            if (!lineNumber.HasValue && e is SyntaxErrorException)
            {
                lineNumber = (e as SyntaxErrorException).Line;
            }

            lineNumber -= startingLine;
            ThreadPool.QueueUserWorkItem(obj =>
            {
                try
                {
                    Stop();
                }
                finally
                {
                    eventAggregator.Publish(new ScriptErrorEvent(ErrorLevel.Exception, e.Message, lineNumber));
                }
            });
        }
Esempio n. 11
0
 void DoShowParent()
 {
     if (!IsDeleted)
     {
         _eventPublisher.Publish(new EditActivityMessage(ModelItem, EnvironmentID, null));
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Runs the all specified package migration plans and publishes a <see cref="MigrationPlansExecutedNotification"/>
        /// if all are successful.
        /// </summary>
        /// <param name="plansToRun"></param>
        /// <returns></returns>
        /// <exception cref="Exception">If any plan fails it will throw an exception.</exception>
        public IEnumerable <ExecutedMigrationPlan> RunPackagePlans(IEnumerable <string> plansToRun)
        {
            var results = new List <ExecutedMigrationPlan>();

            // Create an explicit scope around all package migrations so they are
            // all executed in a single transaction. If one package migration fails,
            // none of them will be committed. This is intended behavior so we can
            // ensure when we publish the success notification that is is done when they all succeed.
            using (ICoreScope scope = _scopeProvider.CreateCoreScope(autoComplete: true))
            {
                foreach (var migrationName in plansToRun)
                {
                    if (!_packageMigrationPlans.TryGetValue(migrationName, out PackageMigrationPlan? plan))
                    {
                        throw new InvalidOperationException("Cannot find package migration plan " + migrationName);
                    }

                    using (_profilingLogger.TraceDuration <PackageMigrationRunner>(
                               "Starting unattended package migration for " + migrationName,
                               "Unattended upgrade completed for " + migrationName))
                    {
                        var upgrader = new Upgrader(plan);
                        // This may throw, if so the transaction will be rolled back
                        results.Add(upgrader.Execute(_migrationPlanExecutor, _scopeProvider, _keyValueService));
                    }
                }
            }

            var executedPlansNotification = new MigrationPlansExecutedNotification(results);

            _eventAggregator.Publish(executedPlansNotification);

            return(results);
        }
Esempio n. 13
0
 public void ButtonClickCommandExecute()
 {
     events.Publish(new SomeMessage {
         SomeNumber = 5,
         SomeString = "Blah..."
     });
 }
Esempio n. 14
0
        public void basic_thread_safty()
        {
            var threadTestClass = new ThreadingTestHelper(_eventAggregator, NameToSend);

            for (int i = 0; i < ThreadingTestHelper.ListenerThreadsNumber; i++)
            {
                threadTestClass.CreateListenerThread(i);
            }

            threadTestClass.CreatePublisherThread();

            threadTestClass.StartAllThreadsAndWaitForTheEndOfThem();

            //wait for the end of all listeners, one second for each. Otherwise break the test
            for (int i = 0; i < ThreadingTestHelper.ListenerThreadsNumber; i++)
            {
                Assert.IsTrue(threadTestClass.EndSynchronization[i].WaitOne(1000),
                              "All listeners did not finish in specified amount of time");
                threadTestClass.Invoked[i] = false;
            }
            if (threadTestClass.Exception != null)
            {
                throw threadTestClass.Exception;
            }

            //verify, if all listeners subscribed successfuly
            //invoke
            _eventAggregator.Publish(new MessageType(NameToSend));
            //verify response
            for (int i = 0; i < 100; i++)
            {
                Assert.IsTrue(threadTestClass.Invoked[i],
                              string.Format("Subscribed event {0} was not invoked", i));
            }
        }
Esempio n. 15
0
        public void Ok()
        {
            if (_patient == null)
            {
                _patient = new Patient();
            }
            _patient.Name     = Name;
            _patient.Sex      = Sex;
            _patient.Birthday = BirthDay;
            _patient.Address  = Address;
            _patient.Phone    = Phone;

            App.Current.EsClinicContext.Entry(_patient).State = _patient.PatientId == 0
                ? EntityState.Added
                : EntityState.Modified;
            App.Current.EsClinicContext.SaveChanges();

            if (_isNewMode)
            {
                var visitor = new Visitor()
                {
                    PatientId = _patient.PatientId
                };
                App.Current.EsClinicContext.Visitors.Add(visitor);
                App.Current.EsClinicContext.SaveChanges();
                _events.Publish(_patient, action => { Task.Factory.StartNew(action); });
            }
            TryClose();
        }
        void ChooseAttachments()
        {
            const string separator = @";";
            var          message   = new FileChooserMessage {
                SelectedFiles = Attachments.Split(separator.ToCharArray())
            };

            message.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == @"SelectedFiles")
                {
                    if (message.SelectedFiles == null || !message.SelectedFiles.Any())
                    {
                        Attachments = "";
                    }
                    else
                    {
                        if (message.SelectedFiles != null)
                        {
                            Attachments = string.Join(separator, message.SelectedFiles);
                        }
                    }
                }
            };
            _eventPublisher.Publish(message);
        }
Esempio n. 17
0
 protected void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
 {
     if (ShouldRequestSyncOnPropertyChange(e.PropertyName))
     {
         _eventAggregator.Publish(new SyncRequestMessage(_target));
     }
 }
 void huePicker1_ValuesChanged(object sender, EventArgs e)
 {
     eventAggregator.Publish(new HuePickerMessage(type, huePicker1.Min, huePicker1.Max), action =>
     {
         Task.Factory.StartNew(action);
     });
 }
Esempio n. 19
0
        public ExpensesFilterVM(IEventAggregator eventAggregator)
        {
            //CashFlows = new BindableCollectionExt<ExpensesFilterEntityVM>();
            //CashFlowGroups = new BindableCollectionExt<ExpensesFilterEntityVM>();

            PropertyChanged += (s, e) => { eventAggregator.Publish(this); };
        }
    // And the navigate method goes:
    public void Navigate(Type viewModelType, object modelParams)
    {
        // Resolve the viewmodel type from the container
        var viewModel = IoC.GetInstance(viewModelType, null);

        // Inject any props by passing through IoC buildup
        IoC.BuildUp(viewModel);
        // Check if the viewmodel implements IViewModelParams and call accordingly
        var interfaces = viewModel.GetType().GetInterfaces()
                         .Where(x => typeof(IViewModelParams).IsAssignableFrom(x) && x.IsGenericType);

        // Loop through interfaces and find one that matches the generic signature based on modelParams...
        foreach (var @interface in interfaces)
        {
            var type   = @interface.GetGenericArguments()[0];
            var method = @interface.GetMethod("ProcessParameters");
            if (type.IsAssignableFrom(modelParams.GetType()))
            {
                // If we found one, invoke the method to run ProcessParameters(modelParams)
                method.Invoke(viewModel, new object[] { modelParams });
            }
        }
        // Publish an aggregator event to let the shell/other VMs know to change their active view
        _aggregator.Publish(new NavigationEventMessage(viewModel));
    }
Esempio n. 21
0
        private void TriggerErrorEventNotOnPythonThread(Exception e)
        {
            if (e.InnerException != null)
            {
                TriggerErrorEventNotOnPythonThread(e.InnerException);
                return;
            }

            var stack      = PythonOps.GetDynamicStackFrames(e);
            var lineNumber = stack
                             .Select(s => (int?)s.GetFileLineNumber())
                             .FirstOrDefault();

            ThreadPool.QueueUserWorkItem(obj =>
            {
                try
                {
                    Stop();
                }
                finally
                {
                    eventAggregator.Publish(new ScriptErrorEvent(e, lineNumber));
                }
            });
        }
        public void OpenStream()
        {
            // Get the currently selected provider.
            var selectedProvider = _selectedProvider;

            if (selectedProvider != null)
            {
                // Find the view model.
                var type = selectedProvider.Type;

                if (IsValidConfiguration(type))
                {
                    var listener = _providerService.CreateListener(type);
                    var context  = CreateContext(type);

                    if (listener != null && context != null)
                    {
                        // Send a request to start listening.
                        _eventAggregator.Publish(new StartListeningEvent(listener, context));

                        // Close the window.
                        TryClose(true);
                    }
                }
            }
        }
        public async Task <ProofRecord> ProcessProposalAsync(IAgentContext agentContext, ProposePresentationMessage proposePresentationMessage, ConnectionRecord connection)
        {
            // save in wallet

            var proofProposal = new ProofProposal
            {
                Comment            = proposePresentationMessage.Comment,
                ProposedAttributes = proposePresentationMessage.PresentationPreviewMessage.ProposedAttributes.ToList <ProposedAttribute>(),
                ProposedPredicates = proposePresentationMessage.PresentationPreviewMessage.ProposedPredicates.ToList <ProposedPredicate>()
            };

            var proofRecord = new ProofRecord
            {
                Id           = Guid.NewGuid().ToString(),
                ProposalJson = proofProposal.ToJson(),
                ConnectionId = connection?.Id,
                State        = ProofState.Proposed
            };

            proofRecord.SetTag(TagConstants.LastThreadId, proposePresentationMessage.GetThreadId());
            proofRecord.SetTag(TagConstants.Role, TagConstants.Requestor);
            await RecordService.AddAsync(agentContext.Wallet, proofRecord);

            EventAggregator.Publish(new ServiceMessageProcessingEvent
            {
                RecordId    = proofRecord.Id,
                MessageType = proposePresentationMessage.Type,
                ThreadId    = proposePresentationMessage.GetThreadId()
            });

            return(proofRecord);
        }
Esempio n. 24
0
        public void NotifySelfShouldNotThrowExceptionTest()
        {
            var listener          = new GenericHandler <object>();
            var containerListener = new GenericHandler <object>();
            var observable        = new TestObservable();

            observable.Subscribe(containerListener);

            IEventAggregator eventAggregator = CreateEventAggregator();

            eventAggregator.Subscribe(listener);
            eventAggregator.Subscribe(observable);
            observable.Subscribe(new TestObservable {
                Listeners = eventAggregator
            });

            eventAggregator.Publish(this, eventAggregator);
            listener.Count.ShouldEqual(1);
            listener.Sender.ShouldEqual(this);
            listener.Message.ShouldEqual(eventAggregator);

            containerListener.Count.ShouldEqual(0);
            containerListener.Sender.ShouldBeNull();
            containerListener.Message.ShouldBeNull();
        }
        public void NavigateTo(string url)
        {
            var viewModel = ViewModelFromUrl(url);
            var message   = new NavigationOccurred(url, viewModel);

            eventAggregator.Publish(message);
        }
        /// <summary>
        /// Publishes a message on the UI thread asynchrone.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        /// <param name="message">The message instance.</param>
        public static Task PublishOnUIThreadAsync(this IEventAggregator eventAggregator, object message)
        {
            Task task = null;

            eventAggregator.Publish(message, action => task = Application.Current.Dispatcher.InvokeAsync(action).Task);
            return(task);
        }
Esempio n. 27
0
 protected virtual void PublishActiveItemChangedMessage(IScreen newItem)
 {
     if (IsActive)
     {
         EventAggregator.Publish(new ActiveItemChangedMessage(this, newItem));
     }
 }
Esempio n. 28
0
 void ExecuteDeletion(EditIndexViewModel index)
 {
     events.Publish(new WorkCompleted("removing index " + index.Name));
     using (var session = server.OpenSession())
     {
         session.Advanced.AsyncDatabaseCommands
         .DeleteIndexAsync(index.Name)
         .ContinueOnSuccess(task =>
         {
             events.Publish(new WorkCompleted("removing index " + index.Name));
             events.Publish(new IndexUpdated {
                 Index = index, IsRemoved = true
             });
         });
     }
 }
Esempio n. 29
0
        private T Notify <T>(BackOfficeIdentityUser currentUser, Func <BackOfficeIdentityUser, T> createNotification) where T : INotification
        {
            var notification = createNotification(currentUser);

            _eventAggregator.Publish(notification);
            return(notification);
        }
Esempio n. 30
0
 protected virtual void PublishInternal(object sender, object message)
 {
     if (InitializeEventAggregator(false))
     {
         _localEventAggregator.Publish(sender, message);
     }
 }
 public void ShowResourceChanged(IContextualResourceModel resource, IList <string> numberOfDependants, IResourceChangedDialog resourceChangedDialog)
 {
     if (resource == null)
     {
         throw new ArgumentNullException("resource");
     }
     if (numberOfDependants == null)
     {
         throw new ArgumentNullException("numberOfDependants");
     }
     if (resourceChangedDialog == null)
     {
         resourceChangedDialog = new ResourceChangedDialog(resource, numberOfDependants.Count);
     }
     resourceChangedDialog.ShowDialog();
     if (resourceChangedDialog.OpenDependencyGraph)
     {
         if (numberOfDependants.Count == 1)
         {
             var shellViewModel = CustomContainer.Get <IShellViewModel>();
             shellViewModel.OpenResourceAsync(Guid.Parse(numberOfDependants[0]), shellViewModel.ActiveServer);
         }
         else
         {
             Dev2Logger.Info("Publish message of type - " + typeof(ShowReverseDependencyVisualizer), "Warewolf Info");
             _eventPublisher.Publish(new ShowReverseDependencyVisualizer(resource));
         }
     }
 }
Esempio n. 32
0
        public override void CanClose(Action <bool> callback)
        {
            eventAggregator.Publish(new ExitingEvent());

            persistanceManager.Save();
            base.CanClose(callback);
        }
Esempio n. 33
0
        public void SaveEvents(Guid aggregateId, IEnumerable <Event> events, int expectedVersion)
        {
            List <EventDescriptor> eventDescriptors;

            if (!current.TryGetValue(aggregateId, out eventDescriptors))
            {
                eventDescriptors = new List <EventDescriptor>();
                current.Add(aggregateId, eventDescriptors);
            }
            else if (eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion && expectedVersion != -1)
            {
                throw new ConcurrencyException();
            }

            var i = expectedVersion;

            foreach (var evt in events)
            {
                i++;
                evt.Version = i;
                eventDescriptors.Add(new EventDescriptor(aggregateId, evt, i));

                publisher.Publish <Event>(evt);
            }
        }
Esempio n. 34
0
        private void AddAdvertisementCompleted(Task completedTask)
        {
            if (completedTask.Exception == null)
            {
                var specialEvent = new NotificationEvent("Saved", NotificationType.Success);
                _eventAggregator.Publish(specialEvent);
            }
            else
            {
                var specialEvent = new NotificationEvent(ErrorMessages.ServerError, NotificationType.Error);
                _eventAggregator.Publish(specialEvent);
            }

            ResetValues();
            IsBusy = false;
        }
        /// <summary>
        /// Processes the agent message
        /// </summary>
        /// <param name="agentContext">The agent context.</param>
        /// <param name="messageContext">The agent message context.</param>
        public async Task <AgentMessage> ProcessAsync(IAgentContext agentContext, UnpackedMessageContext messageContext)
        {
            await Task.Yield();

            switch (messageContext.GetMessageType())
            {
            case CustomMessageTypes.TrustPingMessageType:
            {
                var pingMessage = messageContext.GetMessage <TrustPingMessage>();

                if (pingMessage.ResponseRequested)
                {
                    return(pingMessage.CreateThreadedReply <TrustPingResponseMessage>());
                }
                break;
            }

            case CustomMessageTypes.TrustPingResponseMessageType:
            {
                _eventAggregator.Publish(new ServiceMessageProcessingEvent
                    {
                        MessageType = CustomMessageTypes.TrustPingResponseMessageType
                    });
                break;
            }
            }
            return(null);
        }
Esempio n. 36
0
 private static void PublishChange(IEventAggregator aggregator)
 {
     Task.Factory.StartNew(() =>
     {
         var message = new NetworkStatusChanged();
         aggregator.Publish(message);
     });
 }
Esempio n. 37
0
 public SpeakerViewModel(IEventAggregator eventAggregator, IWindowManager windowManager, ILoggingService loggingService)
 {
     EventAggregator = eventAggregator;
     _windowManager = windowManager;
     _loggingService = loggingService;
     EventAggregator.Publish(this);
     GetEventPresentationsForSpeaker(Int32.Parse(App.EventId), Int32.Parse(App.PersonId));
 }
        public MessageListViewModel(IEventAggregator eventAggregator)
        {
            ServiceControl.Instance.Messages()
                .SubscribeOnBackground()
                .Subscribe(ms => Messages = ms.DeserializeCollection<Message>());

            this.ChangedProperty<Message>(nameof(SelectedMessage))
                .Subscribe(m => eventAggregator.Publish(new MessageSelected() { Id = m.After?.Id }));
        }
Esempio n. 39
0
        public CardReader(ILog log, IEventAggregator eventAggregator)
        {
            Log = log;
            EventAggregator = eventAggregator;

            Log.Debug("CardReader constructed");

            Connect();

            KeepAliveTimer = new Timer(s => EventAggregator.Publish(new KeepAlive()), null, KeepAliveInterval, KeepAliveInterval);
        }
Esempio n. 40
0
 public TopNavigationViewModel(ImageGetter getter, IEventAggregator events)
 {
     _Events = events;
     Commands = new List<CommandItem>
     {
         new CommandItem { Image = getter.Home, DoCommand = () => {_Events.Publish(new NavigationMessage { Action = NavigationCommand.Home });} },
         new CommandItem { Image = getter.ArrowLeft, DoCommand = () => {throw new NotImplementedException("Left command is not implemented yet");} },
         new CommandItem { Image = getter.ArrowRight, DoCommand = () => {throw new NotImplementedException("Right command is not implemented yet");} },
         new CommandItem { Image = getter.Settings, DoCommand = () => {throw new NotImplementedException("Settings command is not implemented yet");} },
         new CommandItem { Image = getter.Help, DoCommand = () => {throw new NotImplementedException("Help command is not implemented yet");} }
     };
 }
 public CarsRemoverCommand( IMouseInformation mouseInformation, Factories.Factories factories, IEventAggregator eventAggregator )
 {
     Contract.Requires( mouseInformation != null );
     Contract.Requires( factories != null );
     Contract.Requires( eventAggregator != null );
     this._mouseInformation = mouseInformation;
     this._mouseInformation.LeftButtonPressed.Subscribe( s =>
                         {
                             var carInserter = new CarsRemover( factories, s.Location );
                             eventAggregator.Publish( new AddControlToRoadLayer( carInserter ) );
                         } );
 }
Esempio n. 42
0
        public static void EditResource(IResourceModel resource, IEventAggregator eventAggregator)
        {
            if(eventAggregator == null)
            {
                throw new ArgumentNullException("eventAggregator");
            }
            if(resource != null)
            {
                switch(resource.ResourceType)
                {
                    case ResourceType.WorkflowService:
                        eventAggregator.Publish(new AddWorkSurfaceMessage(resource));
                        break;

                    case ResourceType.Service:
                        eventAggregator.Publish(new ShowEditResourceWizardMessage(resource));
                        break;
                    case ResourceType.Source:
                        eventAggregator.Publish(new ShowEditResourceWizardMessage(resource));
                        break;
                }
            }
        }
Esempio n. 43
0
        public AlbumViewModel(Album album)
        {
            _events = IoC.Get<IEventAggregator>();
            _windowManager = IoC.Get<IWindowManager>();
            Model = album;
            Tracks = new ReactiveList<TrackViewModel>();
            Tracks.AddRange(album.Tracks.Select(x => new TrackViewModel(x)));

            AddAlbumToPlaylistCommand = new ReactiveCommand();
            AddAlbumToPlaylistCommand.Subscribe(param => _events.Publish(Tracks.Select(x => x.Track).ToList()));

            EditorEditAlbumsCommand = new ReactiveCommand();
            EditorEditAlbumsCommand.Subscribe(
                param => _windowManager.ShowDialog(new AlbumTagEditorViewModel(Tracks.Select(x => x.Track.Model).ToList())));
        }
Esempio n. 44
0
        public ArtistViewModel(Artist artist)
        {
            Model = artist;
            Albums = artist.Albums;
            _events = IoC.Get<IEventAggregator>();
            _windowManager = IoC.Get<IWindowManager>();

            AddArtistToPlaylistCommand = new ReactiveCommand();
            AddArtistToPlaylistCommand.Subscribe(
                param => _events.Publish(Albums.SelectMany(x => x.Tracks).Select(x => x).ToList()));

            EditorEditArtistsCommand = new ReactiveCommand();
            EditorEditArtistsCommand.Subscribe(param => _windowManager.ShowDialog(
                new ArtistTagEditorViewModel(Albums.SelectMany(x => x.Tracks).Select(x => x.Model).ToList())));
        }
Esempio n. 45
0
        /// <summary>
        /// Loads the given URI by using an asynchronous request.
        /// </summary>
        /// <param name="requesters">The requesters to try.</param>
        /// <param name="request">The data of the request to send.</param>
        /// <param name="events">The event aggregator.</param>
        /// <param name="cancel">
        /// The token which can be used to cancel the request.
        /// </param>
        /// <returns>
        /// The task which will eventually return the response.
        /// </returns>
        public static async Task<IResponse> LoadAsync(this IEnumerable<IRequester> requesters, IRequest request, IEventAggregator events, CancellationToken cancel)
        {
            foreach (var requester in requesters)
            {
                if (requester.SupportsProtocol(request.Address.Scheme))
                {
                    using (var evt = new RequestStartEvent(requester, request))
                    {
                        if (events != null)
                            events.Publish(evt);

                        return await requester.RequestAsync(request, cancel).ConfigureAwait(false);
                    }
                }
            }

            return default(IResponse);
        }
Esempio n. 46
0
        public void Start(EmulationContext context, IEventAggregator eventAggregator, EmulationMode mode)
        {
            _emulator = _emulatorRegistry.GetEmulator(context.EmulatedSystem, _handle);

            IRomSource loader = null;

            if (context.Game.RomPath.ToLower().EndsWith(".zip"))
            {
                loader = new ZipRomSource(context.Game.RomPath);
            }
            else
            {
                loader = new FileRomSource(context.Game.RomPath);
            }

            using (var romData = loader.GetRomData())
            {
                if (!_emulator.IsRomValid(romData))
                    return;

                romData.Seek(0, System.IO.SeekOrigin.Begin);

                _emulator.LoadRom(romData, null);
            }

            eventAggregator.Publish(new EmulatorStartingEvent(InstanceId, this, context.Game, mode));

            while (_bus.HasMessages)
            {
                _bus.GetCommand().Execute(_emulator);
            }

            _emulator.Initialize(eventAggregator);

            int pixelWidth, pixelHeight;
            Wren.Core.PixelFormats requestedPixelFormat;
            Int32 framePerSecond;

            // assemble rendering pipeline
            _emulator.GetSpecifications(out pixelWidth, out pixelHeight, out framePerSecond, out requestedPixelFormat);

            var rSource = _renderingSourceFactory.Create(pixelWidth, pixelHeight, requestedPixelFormat);
            eventAggregator.Publish(new RenderingSurfaceCreatedEvent(this.InstanceId, rSource.MemorySection, rSource.RenderingSurface, rSource.SurfaceInformation));

            _emulator.SetRenderingSurface(rSource.RenderingSurface);
            var input = _inputPipeline.BuildInputSource(context);

            eventAggregator.Publish(new EmulatorStartedEvent(this.InstanceId));

            FrameRateTimer fp = _frameRateTimerFactory.GetFrameRateTimer(framePerSecond);
            fp.ScheduleAction(() =>
            {
                while (_bus.HasMessages)
                {
                    _bus.GetCommand().Execute(_emulator);
                }

                _emulator.SetInput(input.GetCurrentInputState());

                Boolean isRunning;
                try
                {
                    isRunning = _emulator.Run();
                }
                catch
                {
                    isRunning = false;
                }

                eventAggregator.Publish(new FrameRenderedEvent(this.InstanceId));

                if (!isRunning)
                {
                    eventAggregator.Publish(new EmulatorQuitEvent(this.InstanceId));
                    input.Close();
                }

                return isRunning;
            });

            if (!fp.IsRunning)
            {
                fp.Start();
            }
        }
Esempio n. 47
0
        private CoAppService(IEventAggregator events)
        {
            CurrentTask.Events += new PackageInstallProgress((name, progress, overall) =>
            {
                events.Publish(new InstallEvent(name, progress));
            });

            CurrentTask.Events += new PackageInstalled(name =>
            {
                events.Publish(new InstallEvent(name, 100));
            });

            CurrentTask.Events += new PackageRemoveProgress((name, progress) =>
            {
                events.Publish(new RemoveEvent(name, progress));
            });

            CurrentTask.Events += new PackageRemoved(name =>
            {
                events.Publish(new RemoveEvent(name, 100));
            });

            CurrentTask.Events += new DownloadProgress((remoteLocation, location, progress) =>
            {
                var decodedUrl = remoteLocation.UrlDecode();

                try
                {
                    CanonicalName result = new CanonicalName(decodedUrl);
                    events.Publish(new DownloadEvent(result, progress));
                }
                catch
                {
                    if (!downloads.Contains(decodedUrl))
                    {
                        downloads.Add(decodedUrl);
                    }
                }
            });
            
            CurrentTask.Events += new DownloadCompleted((remoteLocation, locallocation) =>
            {
                var decodedUrl = remoteLocation.UrlDecode();

                try
                {
                    CanonicalName result = new CanonicalName(decodedUrl);
                    events.Publish(new DownloadEvent(result, 100));

                    if (currentDownload.PackageName == result.PackageName)
                        waitDownload.Set();
                }
                catch
                {
                    if (downloads.Contains(decodedUrl))
                    {
                        downloads.Remove(decodedUrl);
                    }
                }
            });
        }
        public ProjectTeamViewModel(
            [Import]IEventAggregator eventAggregator,
            [Import]IProjectsService projectsServices,
            [Import]ITeamService teamServices,
            [Import]ITasksService taskServices,
            [Import]IBackgroundExecutor backgroundExecutor,
            [Import] IDialogService dialogs,
            [Import]IAuthorizationService authorizationService)
        {
            this.taskServices = taskServices;
            this.aggregator = eventAggregator;
            this.projectsServices = projectsServices;
            this.teamServices = teamServices;
            this.executor = backgroundExecutor;
            this.authorizator = authorizationService;
            this.dialogs = dialogs;

            ShowRolesListCommand = new DelegateCommand(CanShowRoleList, ShowRolesList);
            AddNewMemberCommand = new DelegateCommand(CanAddNewMember, AddNewMember);

            RemoveMemberCommand = new DelegateCommand<ProjectMembershipViewModel>(CanRemoveMember, RemoveMember);

            ShowJoinDialogCommand = new DelegateCommand(CanJoinProject, ShowJoinDialog);

            ShowContactListCommand = new DelegateCommand(ShowContactList);

            SelectNewRoleCommand = new DelegateCommand<Role>(SelectNewRole);

            membershipViewSource = new System.Windows.Data.CollectionViewSource();
            membershipViewSource.SortDescriptions.Add(new SortDescription("SortPriority", ListSortDirection.Ascending));
            membershipViewSource.SortDescriptions.Add(new SortDescription("ProjectMembership.Role.RoleName", ListSortDirection.Ascending));
            membershipViewSource.SortDescriptions.Add(new SortDescription("Member.FullName", ListSortDirection.Ascending));

            membershipViewSource.Filter += new System.Windows.Data.FilterEventHandler(membershipViewSource_Filter);

            aggregator.Subscribe<Project>(ScrumFactoryEvent.ViewProjectDetails, OnViewProjectDetails);

            aggregator.Subscribe<ICollection<Role>>(ScrumFactoryEvent.ProjectRolesChanged, roles => { OnPropertyChanged("Roles"); });
            aggregator.Subscribe<Role>(ScrumFactoryEvent.ProjectRoleChanged, role => { membershipViewSource.View.Refresh(); });

            aggregator.Subscribe(ScrumFactoryEvent.ShowProjectTeam, () => { aggregator.Publish<IProjectTabViewModel>(ScrumFactoryEvent.ShowProjectTab, this); });

            // need thi when membership is removed from the project module
            aggregator.Subscribe<ProjectMembership>(ScrumFactoryEvent.ProjectMembershipRemoved, AfterRemoveMember);

            MemberCustomFilter = MemberFilter;

            RefreshMemberFilter = LoadMembers;
        }
        public ProjectsListViewModel(
            [Import] IEventAggregator aggregator,
            [Import] IProjectsService projectsService,
            [Import] IBackgroundExecutor executor,
            [Import] IDialogService dialogs,
            [Import] IAuthorizationService authorizator)
        {
            this.aggregator = aggregator;
            this.projectsService = projectsService;
            this.executor = executor;
            this.dialogs = dialogs;
            this.authorizator = authorizator;

            projectsViewSource = new System.Windows.Data.CollectionViewSource();
            projectsViewSource.SortDescriptions.Add(new SortDescription("Status", ListSortDirection.Ascending));
            projectsViewSource.SortDescriptions.Add(new SortDescription("TotalDayAllocation", ListSortDirection.Descending));
            projectsViewSource.SortDescriptions.Add(new SortDescription("ProjectNumber", ListSortDirection.Descending));

            projectsViewSource.Filter += new System.Windows.Data.FilterEventHandler(FilteredProjects_Filter);
            delayFilter = new DelayAction(500, new DelayAction.ActionDelegate(() => {
                if (allDataLoaded && FilteredProjects != null) {
                    FilteredProjects.Refresh();
                    SetGroupCount();
                } else {
                    LoadProjectList();
                }
            }));

            aggregator.Subscribe<Project>(ScrumFactoryEvent.ProjectStatusChanged, OnProjectStatusChanged);

            aggregator.Subscribe<Project>(ScrumFactoryEvent.ProjectCreated, OnProjectCreated);

            aggregator.Subscribe<MemberProfile>(ScrumFactoryEvent.SignedMemberChanged,
                m => {
                    ((DelegateCommand)CreateProjectCommand).NotifyCanExecuteChanged();
                    if (m == null) {
                        OnProjectListLoaded(new List<Project>());
                        SelectedProject = null;
                        aggregator.Publish<Project>(ScrumFactoryEvent.ViewProjectDetails, SelectedProject);
                        return;
                    }
                    LoadProjectList();
                    ShowDetailOnInit();
                });

            aggregator.Subscribe<Project>(ScrumFactoryEvent.ViewProjectDetails, p => {
                if (SelectedProject != p)
                    SelectedProject = p;
            });

            aggregator.Subscribe(ScrumFactoryEvent.CreateNewProject, () => {
                dialogs.SelectTopMenu(this);
                OpenCreateProjectWindow();
            });

            aggregator.Subscribe<int>(ScrumFactoryEvent.ProjectArgOnInit, OnProjectArgOnInit);

            OnLoadCommand = new DelegateCommand(() => { if (NeedRefresh) LoadProjectList(); });

            RefreshProjectListCommand = new DelegateCommand(() => { LoadProjectList(); });
            ShowDetailWindowCommand = new DelegateCommand<Project>(p => { ShowDetailWindow(p.ProjectUId); });
            CreateProjectCommand = new DelegateCommand(CanCreateProject, OpenCreateProjectWindow);

            CopyToClipboardCommand = new DelegateCommand(CopyToClipboard);

            LoadMoreCommand = new DelegateCommand(() => { LoadProjectList(false); });

            NeedRefresh = true;
        }
Esempio n. 50
0
 /// <summary>
 /// Reload the page by navigating and setting the tournée label
 /// </summary>
 /// <param name="synchronizationService"></param>
 /// <param name="eventAggregator"></param>
 /// <param name="navigationService"></param>
 private static void RefreshContext(SynchronizationService synchronizationService, IEventAggregator eventAggregator, NavigationService navigationService)
 {
     eventAggregator.Publish("FilAriane".AsViewNavigationArgs().AddNamedParameter("Title", synchronizationService.LibelleTournee));
     Refresh(navigationService);
 }
Esempio n. 51
0
        public void Initialize(IEventAggregator eventAggregator)
        {
            _isRunning = true;
            _eventAggregator = eventAggregator;

            if (_systemBus is IDebuggingSystemBus)
            {
                ((IDebuggingSystemBus)_systemBus).ValueChanged += new System.EventHandler<ValueChangedEventArgs>(
                    (sender, e) => eventAggregator.Publish(new MemoryValueChangedEvent(e.Address, e.Value)));
            }

            _breakpointHandler.BreakpointHit +=new System.EventHandler<BreakpointHitEventArgs>(
                (sender, e) => eventAggregator.Publish(new BreakpointHitEvent(e.Address)));           
           
            _componentManager.AttachComponent(_cpu);
            _componentManager.AttachComponent(_ram);
            _componentManager.AttachComponent(_vdp);
            _componentManager.AttachComponent(new UnknownPorts());
            _componentManager.AttachComponent(_gamepads);
            _componentManager.AttachComponent(new SN76489());
            _componentManager.AttachComponent(_cart);
            _componentManager.AttachComponent(_breakpointHandler);
            _componentManager.AttachComponent(new YM2413());
            _componentManager.InitializeComponents(_systemBus);
        }
Esempio n. 52
0
 public StatusBarMessage(string message)
 {
     _eventAggregator = IoC.Get<IEventAggregator>();
     _eventAggregator.Publish(new StatusBarMessageEvent(message));
 }
Esempio n. 53
0
            public Label(IEventAggregator eventAggregator)
            {
                PropertyChanged += (sender, args) =>
                {
                    if (!IsNotifying)
                        return;

                    if (args.PropertyName != "Selected") 
                        return;

                    if (Selected)
                        eventAggregator.Publish(new CardLabelAdded {CardId = CardId, Color = Color, Name = Name});
                    else
                        eventAggregator.Publish(new CardLabelRemoved {CardId = CardId, Color = Color, Name = Name});
                };
            }