Beispiel #1
0
        public ConnctionService(OmvServiceProvider omvServiceProvider, SshServiceProvider sshServiceProvider,
                                SynoServiceProvider synoServiceProvider, WebminServiceProvider webminServiceProvider,
                                IMessageBoxService messageBoxService, IDataProvider dataProvider, IMessagingCenter messagingCenter, IPreferences preferences)
        {
            _omvServiceProvider    = omvServiceProvider;
            _sshServiceProvider    = sshServiceProvider;
            _synoServiceProvider   = synoServiceProvider;
            _webminServiceProvider = webminServiceProvider;
            _messageBoxService     = messageBoxService;
            _dataProvider          = dataProvider;
            _messagingCenter       = messagingCenter;
            _preferences           = preferences;


            _messagingCenter.Subscribe <string, string>(
                this, MessengerKeys.SessionExpired, async(sender, arg) =>
            {
                await Init();
            });
            _messagingCenter.Subscribe <DataProvider, TableBase>(
                this, MessengerKeys.ItemChanged, async(sender, arg) =>
            {
                if (arg is Host)
                {
                    await Init();
                }
            });
        }
Beispiel #2
0
        public SuperheroesViewModel(INavigationService navigation, IMessagingCenter messaging, IRestClient client)
        {
            _navigation = navigation;
            _messaging  = messaging;
            _client     = client;

            Title = "Browse";

            LoadCommand = new Command(async() => await ExecuteLoadCommand(), () => !IsBusy);
            NewCommand  = new Command(async() => await ExecuteNewCommand(), () => !IsBusy);
            ViewCommand = new Command(async() => await ExecuteViewCommand(), () => !IsBusy);

            _messaging.Subscribe <SuperheroCreateViewModel, SuperheroListDTO>(this, AddSuperhero, (obj, superhero) =>
            {
                Items.Add(superhero);
            });
            _messaging.Subscribe <SuperheroUpdateViewModel, SuperheroListDTO>(this, Message, (obj, superhero) =>
            {
                var existing = Items.FirstOrDefault(h => h.Id == superhero.Id);
                if (existing != null)
                {
                    Items.Remove(existing);
                }
                Items.Add(superhero);
            });
            _messaging.Subscribe <SuperheroDetailsViewModel, int>(this, DeleteSuperhero, (obj, superheroId) =>
            {
                var existing = Items.FirstOrDefault(h => h.Id == superheroId);
                if (existing != null)
                {
                    Items.Remove(existing);
                }
            });
        }
        /// <inheritdoc />
        public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
        {
            var result = base.FinishedLaunching(uiApplication, launchOptions);

            _messagingCenter = MessagingCenter.Instance;
            _messagingCenter.Subscribe <object>(this, ToBackgroundMessages.StartBackgroundService, OnStartBackgroundServiceMessage);
            _messagingCenter.Subscribe <object>(this, ToBackgroundMessages.StopBackgroundService, OnStopBackgroundServiceMessage);
            _messagingCenter.Subscribe <object>(this, ToBackgroundMessages.GetBackgroundServiceState, OnGetBackgroundServiceState);

            BackgroundService = new NativeBackgroundServiceHost();

            return(result);
        }
        private async void Startup()
        {
            _starting = true;
            try
            {
                BuildForegroundService();

                using (var mre = new ManualResetEventSlim())
                {
                    await Task.Run(async() =>
                    {
                        await StartInBackground();
                        mre.Set();
                    });

                    if (!mre.Wait(_startupTimeout))
                    {
                        Log.Error(_builder.ServiceName, "Background service did not cleanup within timeout time");
                        return;
                    }
                }
                IsStarted = true;
                _messagingCenter.Send <object, BackgroundServiceState>(this,
                                                                       FromBackgroundMessages.BackgroundServiceState, new BackgroundServiceState(true));
                _messagingCenter.Subscribe <object, UpdateNotificationMessage>(this,
                                                                               ToBackgroundMessages.UpdateBackgroundServiceNotificationMessage,
                                                                               OnNotificationMessageUpdate);
            }
            finally
            {
                _starting = false;
            }
        }
Beispiel #5
0
        /// <inheritdoc />
        /// Note that the system calls this on your service's main thread.
        /// A service's main thread is the same thread where UI operations take place for Activities running in the same process.
        /// You should always avoid stalling the main thread's event loop.
        /// When doing long-running operations, network calls, or heavy disk I/O, you should kick off a new thread, or use AsyncTask`3.
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            var stopRequest = intent.GetBooleanExtra(StopServiceExtra, false);

            if (!stopRequest && (IsStarted || _starting)) // Not a stop request, already started or starting
            {
                return(StartCommandResult.Sticky);
            }

            Task.Factory.StartNew(async() =>
            {
                if (!stopRequest) // Start request
                {
                    _starting = true;
                    BuildForegroundService();
                    await StartInBackground();
                    _starting = false;
                    IsStarted = true;
                    _messagingCenter.Send <object, BackgroundServiceState>(this,
                                                                           FromBackgroundMessages.BackgroundServiceState, new BackgroundServiceState(true));
                    _messagingCenter.Subscribe <object, UpdateNotificationMessage>(this,
                                                                                   ToBackgroundMessages.UpdateBackgroundServiceNotificationMessage,
                                                                                   OnNotificationMessageUpdate);
                }
                else // Stop request
                {
                    await Cleanup();
                }
            });

            return(StartCommandResult.Sticky);
        }
Beispiel #6
0
        public void Subscribe <T>(Action <T> action)
        {
            Action <EventAggregator, T> actionX = (_, t) =>
            {
                action(t);
            };

            messagingCenter.Subscribe(this, nameof(T), actionX);
        }
Beispiel #7
0
        public BaseViewModel(IMessagingCenter messagingCenter,
                             IGameService gameService,
                             IGameHubService gameHubService,
                             ILocalStorageService localStorageService)
        {
            MessagingCenter     = messagingCenter;
            GameService         = gameService;
            GameHubService      = gameHubService;
            LocalStorageService = localStorageService;

            TryReconnectCommand = new Command(async() => await OnTryReconnectAsync(), CanTryReconnect);

            messagingCenter.Subscribe <GameHubService, ConnectionStateChangedMessage>(this, nameof(ConnectionStateChangedMessage), HandleConnectionStateChanged);
        }
        public SuperheroDetailsViewModel(INavigationService navigation, IMessagingCenter messaging, IRestClient client)
        {
            _navigation = navigation;
            _messaging  = messaging;
            _client     = client;

            LoadCommand   = new Command(async o => await ExecuteLoadCommand(o as SuperheroListDTO), _ => !IsBusy);
            EditCommand   = new Command(async _ => await ExecuteEditCommand(), _ => !IsBusy);
            DeleteCommand = new Command(async _ => await ExecuteDeleteCommand(), _ => !IsBusy);

            _messaging.Subscribe <SuperheroUpdateViewModel, SuperheroDetailsDTO>(this, UpdateSuperhero, (obj, superhero) =>
            {
                SetSuperhero(superhero);
            });
        }
Beispiel #9
0
        //XFMA - Dependency injection at work
        public ItemsViewModel(INavigationService navigationService, IDataStore <Item> dataStore, IMessagingCenter messagingCenter)
        {
            this.navigationService = navigationService;
            this.dataStore         = dataStore;

            Title = "List";
            Items = new ObservableRangeCollection <Item>();

            //XFMA - With different design we can avoid having to use
            //MessagingCenter but this was a nice demonstration of
            //how you can use Interfaces and DI to make code testable
            messagingCenter.Subscribe <NewItemViewModel, Item>(this, "AddItem", async(obj, item) =>
            {
                await dataStore.AddItemAsync(item);
            });
        }
        public MainPageViewModel(INavigationService navigationService, IUserDialogs userDialogs, IMessagingCenter messagingCenter, IRandomUploadService randomUploadService)
            : base(navigationService)
        {
            Title = "Main Page";

            UserDialogs         = userDialogs;
            MessagingCenter     = messagingCenter;
            RandomUploadService = randomUploadService;
            PushRandomCommand   = new Command(() => Push());


            // TODO: It is obvious that I only need one of these. Please fixe, I started out with only 2
            MessagingCenter.Subscribe <IUploadStateMessenger, string>(this, Constants.Running, async(sender, id) =>
            {
                await UserDialogs.AlertAsync($"Message received {id}", Constants.Running, "OK");
            });

            MessagingCenter.Subscribe <IUploadStateMessenger, string>(this, Constants.Blocked, async(sender, id) =>
            {
                await UserDialogs.AlertAsync($"Message received {id}", Constants.Blocked, "OK");
            });

            MessagingCenter.Subscribe <IUploadStateMessenger, string>(this, Constants.Enqueued, async(sender, id) =>
            {
                await UserDialogs.AlertAsync($"Message received {id}", Constants.Enqueued, "OK");
            });

            MessagingCenter.Subscribe <IUploadStateMessenger, string>(this, Constants.Cancelled, async(sender, id) =>
            {
                await UserDialogs.AlertAsync($"Message received {id}", Constants.Cancelled, "OK");
            });

            MessagingCenter.Subscribe <IUploadStateMessenger, string>(this, Constants.Failed, async(sender, id) =>
            {
                await UserDialogs.AlertAsync($"Message received {id}", Constants.Failed, "OK");
            });

            MessagingCenter.Subscribe <IUploadStateMessenger, string>(this, Constants.Succeeded, async(sender, id) =>
            {
                var imageUpload = ImageUploads.SingleOrDefault(x => x.TaskId == id);
                if (imageUpload != null)
                {
                    await UserDialogs.AlertAsync($"Message received {id}", Constants.Succeeded, "OK");
                }
            });
        }
        public void Init()
        {
            //_aimTimerNotificationService.Stop();
            AimTimerListItemViewModels.CollectionChanged -= AimTimerItemViewModels_CollectionChanged;
            //_aimTimerNotificationService.OnStatusChanged -= AimTimerNotificationService_OnStatusChanged;
            _messagingCenter.Unsubscribe <IAimTimerItem>(this, MessagingCenterMessages.AimTimerUpdated);

            AimTimerListItemViewModels.Clear();
            foreach (var aimTimerItem in _aimTimerService.GetActiveAimTimers())
            {
                AimTimerListItemViewModels.Add(_aimTimerItemViewModelFactory.Create(aimTimerItem));
            }

            //_aimTimerNotificationService.SetItemsToFollow(AimTimerListItemViewModels.Select(i => i.GetAimTimerItem()).ToList());
            AimTimerListItemViewModels.CollectionChanged += AimTimerItemViewModels_CollectionChanged;
            //_aimTimerNotificationService.OnStatusChanged += AimTimerNotificationService_OnStatusChanged;
            //_aimTimerNotificationService.Start();
            _messagingCenter.Subscribe <IAimTimerItem>(this, MessagingCenterMessages.AimTimerUpdated, OnItemUpdated);

            InitTimer();

            OnPropertyChanged(nameof(Title));
        }
 public ComponentWithMessagingDependency(IMessagingCenter messagingCenter)
 {
     _messagingCenter = messagingCenter;
     _messagingCenter.Subscribe <ComponentWithMessagingDependency>(this, "test", dependency => Console.WriteLine("test"));
 }
        public MyOrdersViewModel(IOrderService orderSvc,
                                 ICache <Models.Order> orderCache,
                                 ICache <PropertyModel> propertyCache,
                                 ICache <ImageModel> imageCache,
                                 ILogger <MyOrdersViewModel> logger,
                                 ICacheRefresher cacheRefresher,
                                 IOrderValidationService validator,
                                 IPageFactory pageFactory,
                                 ICurrentUserService userService,
                                 LaunchedFromPushModel pushModel,
                                 MainThreadNavigator nav,
                                 IMessagingCenter messagingCenter,
                                 Action <Action> uiInvoke,
                                 Action <BaseNavPageType> baseNavAction)
        {
            _orderService      = orderSvc;
            _orderCache        = orderCache;
            _propertyCache     = propertyCache;
            _imageCache        = imageCache;
            _logger            = logger;
            _uiInvoke          = uiInvoke;
            _cacheRefresher    = cacheRefresher;
            _validationService = validator;
            _pageFactory       = pageFactory;
            _userService       = userService;
            _messagingCenter   = messagingCenter;
            _nav                 = nav;
            _baseNavAction       = baseNavAction;
            ExampleReportCommand = new Command(() =>
            {
                try
                {
                    var order = JsonConvert.DeserializeObject <Models.Order>(Examples.ExampleOrder);
                    _imageCache.Put(order.OrderId, new ImageModel()
                    {
                        OrderId = order.OrderId,
                        Image   = Convert.FromBase64String(Examples.ExampleImage)
                    });
                    _propertyCache.Put(order.OrderId, JsonConvert.DeserializeObject <PropertyModel>(Examples.ExampleProperty));
                    _nav.Push(_pageFactory.GetPage(PageType.OrderDetail, order));
                }
                catch (Exception ex)
                {
                    _logger.LogError($"An error occurred while trying to open example order.", ex);
                }
            });
            Action refreshAction = async() =>
            {
                try
                {
                    OrderListRefreshing = true;
                    var fresh = await _orderService.GetMemberOrders(_userService.GetLoggedInAccount()?.UserId);

                    _orderCache.Put(fresh.ToDictionary(x => x.OrderId, x => x));
                    SetListViewSource(fresh.ToList());
                    OrderListRefreshing = false;
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Failed to refresh order list.", ex);
                }
            };

            OrderListRefreshCommand = new Command(refreshAction);
            _messagingCenter.Subscribe <App>(this, "CacheInvalidated", async x =>
            {
                await this.SetViewState();
            });
            OnAppearingBehavior = new Command(async() =>
            {
                if (!_pmEventSubscribed)
                {
                    _pmEventSubscribed         = true;
                    pushModel.PropertyChanged += async(s, e) =>
                    {
                        if (!string.IsNullOrWhiteSpace(pushModel.OrderId))
                        {
                            var order = await _orderService.GetOrder(pushModel.OrderId);
                            _orderCache.Put(order.OrderId, order);
                            _nav.Push(_pageFactory.GetPage(PageType.OrderDetail, order));
                        }
                    };
                }
                await SetViewState();
            });
        }
Beispiel #14
0
 public MainPage()
 {
     InitializeComponent();
     _messagingCenter = (BindingContext as MainViewModel)?.MessagingCenter;
     _messagingCenter.Subscribe <MainViewModel>(this, nameof(FileSetActiveMessage), FileSetActive);
 }
 public void Subscribe <T>(Action <T> handler)
 {
     _messagingCenter.Subscribe <IMessageBus, T>(this, typeof(T).Name, (_, args) => handler(args));
 }