private void TimerInit()
 {
     timer          = new Windows.UI.Xaml.DispatcherTimer();
     timer.Tick    += Timer_Tick;
     timer.Interval = new TimeSpan(0, 0, 1);
     timer.Start();
 }
        public MainPageViewModel()
        {
            //if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            //{
            //    this._Colors = new ObservableCollection<ColorModel>();
            //    return;  // design only
            //}

            var timer = new Windows.UI.Xaml.DispatcherTimer { Interval = TimeSpan.FromSeconds(.1) };
            timer.Tick += (s, e) =>
            {
                this.SecondsAngle = ((double)DateTime.Now.Millisecond / 1000f + (double)DateTime.Now.Second) * 6d;
                this.MinutesAngle = DateTime.Now.Minute * 6;
                this.HoursAngle = DateTime.Now.Hour * 30;
                this.Day = DateTime.Now.Day.ToString();
            };
            timer.Start();
            ResetCommand.Execute(null);

            // listen for purchase
            Shared.Services.MessageBus.Instance.Register<MainPageViewModel>((m, p) =>
            {
                if (!m.Equals("PURCHASE"))
                    return;
                foreach (var item in Purchases.Where(x => x.Bitmap == null).ToArray())
                    Purchases.Remove(item);
                this.Purchases.Insert(0, p as PurchaseModel);
            });
        }
Beispiel #3
0
        /// <summary>
        /// このページがフレームに表示されるときに呼び出されます。
        /// </summary>
        /// <param name="e">このページにどのように到達したかを説明するイベント データ。Parameter 
        /// プロパティは、通常、ページを構成するために使用します。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // マリモの情報がない場合はMarimoクラスのインスタンス生成をおこなう
            if (marimo == null)
            {
                marimo = new Marimo();
            }

            // marimoEllipseとマリモの情報をデータバインディングする
            marimoEllipse.DataContext = marimo;

            // マリモを動かすためのタイマー(約30fpsで動くことを想定)
            timer = new Windows.UI.Xaml.DispatcherTimer();
            timer.Interval = System.TimeSpan.FromMilliseconds(33);
            timer.Tick += timer_Tick;
            timer.Start();

            // デフォルトの加速度センサーを取得する
            accelerometer = Windows.Devices.Sensors.Accelerometer.GetDefault();
            // デフォルトの加速度センサーが取得できなければnullを返します
            if (accelerometer != null)
            {
                // ReadingChangedイベントハンドラを設定する
                accelerometer.ReadingChanged += accelerometer_ReadingChanged;

                // 加速度センサーが搭載されているのでtrue
                marimo.IsAccelerometer = true;
            }
            else
            {
                // 加速度センサーが搭載されていないのでfalse
                marimo.IsAccelerometer = false;
            }
        }
Beispiel #4
0
 public void start()
 {
     dt          = new Windows.UI.Xaml.DispatcherTimer();
     dt.Interval = DELAY_UPDATES;
     dt.Tick    += dt_ticker;
     dt.Start();
 }
        public async void Init()
        {
            await InitRGBSensor();

            timer          = new Windows.UI.Xaml.DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(3);
            timer.Tick    += Timer_Tick;
            timer.Start();
        }
        /// <summary>
        /// Initializes a new instance of the DelayInvoker class.
        /// </summary>
        /// <param name="action">The action to execute with delay. Null is allowed.</param>
        /// <param name="delayTime">Time to wait before executing the action.</param>
        /// <param name="delegatePriority">The dispatcher priority to use for methods and properties of this class if the caller is not in the thread for dispatcher.</param>
        public DelayInvoker(Action action, TimeSpan delayTime, TheDispatcherPriority delegatePriority)
        {
            _action           = action;
            _delegatePriority = delegatePriority;

            // Creates a timer.
            _dispatcherTimer          = new TheDispatcherTimer();
            _dispatcherTimer.Interval = delayTime;
            _dispatcherTimer.Tick    += DispatcherTimer_Tick;
        }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DispatcherTimer"/> class.
        /// </summary>
        public DispatcherTimer()
        {
#if __ANDROID__ || __UNIFIED__ || WIN32
            _timer           = new Timer();
            _timer.AutoReset = true;
            _timer.Elapsed  += _timer_Elapsed;
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP
            _dispatcherTimer       = new Windows.UI.Xaml.DispatcherTimer();
            _dispatcherTimer.Tick += _dispatcherTimer_Tick;
#elif WINDOWS_PHONE
            _dispatcherTimer       = new global::System.Windows.Threading.DispatcherTimer();
            _dispatcherTimer.Tick += _dispatcherTimer_Tick;
#endif
        }
Beispiel #8
0
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (timer != null)
            {
                timer.Stop();
                timer = null;
            }

            // 画面を抜けた後なので加速度センサーのイベントを受け取らない
            if (accelerometer != null)
            {
                accelerometer.ReadingChanged -= accelerometer_ReadingChanged;
            }
        }
Beispiel #9
0
        public override void startTimer(long timeout, System.Action callback)
        {
            if (!(callback != null))
            {
                return;
            }
            var dt = new Windows.UI.Xaml.DispatcherTimer();

            dt.Interval = new System.TimeSpan(0, 0, 0, 0, (int)timeout);
            dt.Tick    += (object sender, object e) => {
                callback();
                dt.Stop();
            };
            dt.Start();
        }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the DelayInvoker class.
        /// </summary>
        /// <param name="dispatcher">The Dispatcher to execute the action.</param>
        /// <param name="action">The action to execute with delay. Null is allowed.</param>
        /// <param name="delayTime">Time to wait before executing the action.</param>
        /// <param name="dispatcherPriority">The priority at which execute the action.</param>
        /// <param name="delegatePriority">The dispatcher priority to use for methods and properties of this class if the caller is not in the thread for dispatcher.</param>
        public DelayInvoker(TheDispatcher dispatcher, Action action, TimeSpan delayTime, TheDispatcherPriority dispatcherPriority, TheDispatcherPriority delegatePriority)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException(nameof(dispatcher));
            }

            _dispatcher       = dispatcher;
            _action           = action;
            _delegatePriority = delegatePriority;

            // Creates a timer.
            _dispatcherTimer          = new TheDispatcherTimer(dispatcherPriority, dispatcher);
            _dispatcherTimer.Interval = delayTime;
            _dispatcherTimer.Tick    += DispatcherTimer_Tick;
        }
Beispiel #11
0
        /// <summary>
        /// Retrieve the current network time from ntp server  "time.windows.com".
        /// </summary>
        public async void GetNetworkTime(string ntpServer)
        {
            averageNtpRTT = 0;         //reset

            currentNtpQueryCount = 0;  //reset
            minNtpRTT            = -1; //reset

            //NTP uses UDP
            ntpSocket = new Windows.Networking.Sockets.DatagramSocket();
            ntpSocket.MessageReceived += OnNTPTimeReceived;


            if (ntpQueryTimer == null)
            {
                ntpQueryTimer          = new Windows.UI.Xaml.DispatcherTimer();
                ntpQueryTimer.Tick    += NTPQueryTimeout;
                ntpQueryTimer.Interval = new TimeSpan(0, 0, 5); //5 seconds
            }

            if (ntpRTTIntervalTimer == null)
            {
                ntpRTTIntervalTimer          = new Windows.UI.Xaml.DispatcherTimer();
                ntpRTTIntervalTimer.Tick    += SendNTPQuery;
                ntpRTTIntervalTimer.Interval = new TimeSpan(0, 0, 0, 0, 200); //200ms
            }

            ntpQueryTimer.Start();

            try
            {
                //The UDP port number assigned to NTP is 123
                await ntpSocket.ConnectAsync(new Windows.Networking.HostName(ntpServer), "123");

                ntpRTTIntervalTimer.Start();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"NtpSync: Exception when connect socket: {e.Message}");
                ntpResponseMonitor.Stop();
                ReportNtpSyncStatus(false);
            }
        }
        private void AttemptLoginCommandAction()
        {
            LoginButtonLabel     = "Logging in ...";
            IsAttemptingLogin    = true;
            LoginUserNameEnabled = false;
            LoginPasswordEnabled = false;


            Windows.UI.Xaml.DispatcherTimer dtDummyLoginAttempt = new Windows.UI.Xaml.DispatcherTimer();
            dtDummyLoginAttempt.Interval = TimeSpan.FromSeconds(3);
            dtDummyLoginAttempt.Tick    += (o, e) => {
                dtDummyLoginAttempt.Stop();
                LoginButtonLabel  = "Success";
                IsAttemptingLogin = false;

                HideLoginCommand.Execute(null);

                SendInformationNotification("Pinch/Zoom to resize desktop", 3);
            };
            dtDummyLoginAttempt.Start();
        }
Beispiel #13
0
        public static async Task <bool> setWallpaper(string filename)
        {
            StorageFolder fold = Windows.Storage.ApplicationData.Current.LocalFolder;
            var           file = await fold.GetFileAsync(filename);

            UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
            //bool success = await profileSettings.TrySetLockScreenImageAsync(file);
            bool success = await profileSettings.TrySetWallpaperImageAsync(file);

            var timer = new Windows.UI.Xaml.DispatcherTimer {
                Interval = TimeSpan.FromSeconds(0.5)
            };

            timer.Tick += (sender, args) =>
            {
                MainPage.initTitlebar();
                timer.Stop();
            };

            timer.Start();
            return(success);
        }
Beispiel #14
0
        public ItemCacheManager(fetchDataCallbackHandler callback, int batchsize = 50, string debugName = "ItemCacheManager")
        {
            cacheBlocks       = new List <CacheEntryBlock <T> >();
            requests          = new ItemIndexRangeList();
            cachedResults     = new ItemIndexRangeList();
            fetchDataCallback = callback;
            maxBatchFetchSize = batchsize;
            //set up a timer that is used to delay fetching data so that we can catch up if the list is scrolling fast
            timer       = new Windows.UI.Xaml.DispatcherTimer();
            timer.Tick += (sender, args) =>
            {
                fetchData();
            };
            timer.Interval = new TimeSpan(20 * 10000);

#if DEBUG
            this.debugName = debugName;
#endif
#if TRACE_DATASOURCE
            Debug.WriteLine(debugName + "* Cache initialized/reset");
#endif
        }
        /// <summary>
        /// https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
        /// </summary>
        /// <param name="callBackFunction"></param>
        /// <param name="delay"></param>
        /// <returns></returns>
        private int __setTimeout__(Func <Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> callBackFunction, double delay)
        {
            _timeoutID++;

            TimeOut _to = new TimeOut();

            _to.Delay    = delay;
            _to.Function = callBackFunction;
            _to.ID       = _timeoutID;

            TimeOutList.Add(_to);

            if (_dt == null)
            {
                _dt          = new Windows.UI.Xaml.DispatcherTimer();
                _dt.Interval = TimeSpan.FromMilliseconds(100);
                _dt.Tick    += _dt_Tick;
                _dt.Start();
            }

            return(_timeoutID);

            // return this._eventQueue.Enqueue(new CallBackEvent(callBackFunction, delay, CallBackType.TimeOut)).Id;
        }
 public void StartTimers()
 {
     dispatcherTimer          = new DispatcherTimer();
     dispatcherTimer.Tick    += dispatcherTimer_Tick;
     dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
 }
Beispiel #17
0
        private async Task Initialize()
        {
            // Create the scene with an imagery basemap.
            MySceneView.Scene = new Scene(Basemap.CreateImagery());

            // Add the elevation surface.
            ArcGISTiledElevationSource tiledElevationSource = new ArcGISTiledElevationSource(_elevationUri);
            Surface baseSurface = new Surface
            {
                ElevationSources = { tiledElevationSource }
            };

            MySceneView.Scene.BaseSurface = baseSurface;

            // Add buildings.
            MySceneView.Scene.OperationalLayers.Add(new ArcGISSceneLayer(_buildingsUri));

            // Configure graphics overlay for the tank and add the overlay to the SceneView.
            _tankOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative;
            MySceneView.GraphicsOverlays.Add(_tankOverlay);

            // Configure heading expression for tank; this will allow the
            //     viewshed to update automatically based on the tank's position.
            SimpleRenderer renderer3D = new SimpleRenderer();

            renderer3D.SceneProperties.HeadingExpression = "[HEADING]";
            _tankOverlay.Renderer = renderer3D;

            // Create the tank graphic - get the model path.
            string modelPath = await GetModelPath();

            // - Create the symbol and make it 10x larger (to be the right size relative to the scene).
            ModelSceneSymbol tankSymbol = await ModelSceneSymbol.CreateAsync(new Uri(modelPath), 10);

            // - Adjust the position.
            tankSymbol.Heading = 90;
            // - The tank will be positioned relative to the scene surface by its bottom.
            //       This ensures that the tank is on the ground rather than partially under it.
            tankSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom;
            // - Create the graphic.
            _tank = new Graphic(new MapPoint(-4.506390, 48.385624, SpatialReferences.Wgs84), tankSymbol);
            // - Update the heading.
            _tank.Attributes["HEADING"] = 0.0;
            // - Add the graphic to the overlay.
            _tankOverlay.Graphics.Add(_tank);

            // Create a viewshed for the tank.
            GeoElementViewshed geoViewshed = new GeoElementViewshed(
                geoElement: _tank,
                horizontalAngle: 90.0,
                verticalAngle: 40.0,
                minDistance: 0.1,
                maxDistance: 250.0,
                headingOffset: 0.0,
                pitchOffset: 0.0)
            {
                // Offset viewshed observer location to top of tank.
                OffsetZ = 3.0
            };

            // Create the analysis overlay and add to the scene.
            AnalysisOverlay overlay = new AnalysisOverlay();

            overlay.Analyses.Add(geoViewshed);
            MySceneView.AnalysisOverlays.Add(overlay);

            // Create a camera controller to orbit the tank.
            OrbitGeoElementCameraController cameraController = new OrbitGeoElementCameraController(_tank, 200.0)
            {
                CameraPitchOffset = 45.0
            };

            // - Apply the camera controller to the SceneView.
            MySceneView.CameraController = cameraController;

            // Create a timer; this will enable animating the tank.
            Windows.UI.Xaml.DispatcherTimer animationTimer = new Windows.UI.Xaml.DispatcherTimer()
            {
                Interval = new TimeSpan(0, 0, 0, 0, 60)
            };
            // - Move the tank every time the timer expires.
            animationTimer.Tick += (o, e) => { AnimateTank(); };
            // - Start the timer.
            animationTimer.Start();

            // Allow the user to click to define a new destination.
            MySceneView.GeoViewTapped += (sender, args) => { _tankEndPoint = args.Location; };
        }
        private void AttemptLoginCommandAction()
        {
            LoginButtonLabel = "Logging in ...";
            IsAttemptingLogin = true;
            LoginUserNameEnabled = false;
            LoginPasswordEnabled = false;


            Windows.UI.Xaml.DispatcherTimer dtDummyLoginAttempt = new Windows.UI.Xaml.DispatcherTimer();
            dtDummyLoginAttempt.Interval = TimeSpan.FromSeconds(3);
            dtDummyLoginAttempt.Tick += (o,e) => {

                dtDummyLoginAttempt.Stop();
                LoginButtonLabel = "Success";
                IsAttemptingLogin = false;

                HideLoginCommand.Execute(null);

                SendInformationNotification("Pinch/Zoom to resize desktop", 3);
            };
            dtDummyLoginAttempt.Start();
            
        }
    /// <summary>
    /// Handles a failed connection to a server.
    /// This method can be overrided to implement a custom failover handling
    /// </summary>
    /// <param name="server">The failed server</param>
    internal protected virtual void HandleFailover(ReplicationServer server)
    {
      BackgroundWorker worker = new BackgroundWorker();
      worker.DoWork += delegate(object sender, DoWorkEventArgs e)
      {
        bool isRunning = false;
        ReplicationServer server1 = e.Argument as ReplicationServer;
#if !RT
        System.Timers.Timer timer = new System.Timers.Timer(RetryTime * 1000.0);

        System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1)
        {
          if (isRunning) return;
          try
          {
            isRunning = true;
            using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
            {
              connectionFailed.Open();
              server1.IsAvailable = true;
              timer.Stop();
            }
          }
          catch
          {
            MySqlTrace.LogWarning(0,
              string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
          }
          finally
          {
            isRunning = false;
          }
        };
        timer.Elapsed += elapsedEvent;
        timer.Start();
        elapsedEvent(sender, null);
#else
              Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
              TimeSpan ts = new TimeSpan(RetryTime * 1000);
              System.EventHandler<object> elapsedEvent = (TickSender, TickEventArgs) =>
              {
                  if (isRunning) return;
                  try
                  {
                      isRunning = true;
                      using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                      {
                          connectionFailed.Open();
                          server1.IsAvailable = true;
                          timer.Stop();
                      }
                  }
                  catch
                  {
                      MySqlTrace.LogWarning(0,
                        string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                  }
                  finally
                  {
                      isRunning = false;
                  }
              };
              timer.Tick += elapsedEvent;
              elapsedEvent(sender, null);
              timer.Start();
#endif
      };

      worker.RunWorkerAsync(server);
    }
    /// <summary>
    /// Assigns a new server driver to the connection object
    /// </summary>
    /// <param name="groupName">Group name</param>
    /// <param name="master">True if the server connection to assign must be a master</param>
    /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
    public static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
    {
      do
      {
        if (!IsReplicationGroup(groupName)) return;

        ReplicationServerGroup group = GetGroup(groupName);
        ReplicationServer server = group.GetServer(master);

        if (server == null)
          throw new MySqlException(Properties.Resources.Replication_NoAvailableServer);

        Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
        if (connection.driver == null
          || driver.Settings.ConnectionString != connection.driver.Settings.ConnectionString)
        {
          connection.Close();
          connection.hasBeenOpen = false;
          try
          {
            connection.driver = driver;
            connection.Open();
            return;
          }
          catch (Exception)
          {
            // retry to open a failed connection and update its status
            connection.driver = null;
            server.IsAvailable = false;

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
              bool isRunning = false;
              ReplicationServer server1 = e.Argument as ReplicationServer;
              int retryTime = ReplicationManager.GetGroup(groupName).RetryTime;
#if !RT
              System.Timers.Timer timer = new System.Timers.Timer(retryTime * 1000.0);


              System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1)
              {
                if (isRunning) return;
                try
                {
                  isRunning = true;
                  using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                  {
                    connectionFailed.Open();
                    server1.IsAvailable = true;
                    timer.Stop();
                  }
                }
                catch
                {
                  MySqlTrace.LogWarning(0,
                    string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                }
                finally
                {
                  isRunning = false;
                }
              };
              timer.Elapsed += elapsedEvent;
              timer.Start();
              elapsedEvent(sender, null);
#else
              Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
              TimeSpan ts = new TimeSpan(retryTime * 1000);
              System.EventHandler<object> elapsedEvent = (TickSender, TickEventArgs) =>
              {
                  if (isRunning) return;
                  try
                  {
                      isRunning = true;
                      using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                      {
                          connectionFailed.Open();
                          server1.IsAvailable = true;
                          timer.Stop();
                      }
                  }
                  catch
                  {
                      MySqlTrace.LogWarning(0,
                        string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                  }
                  finally
                  {
                      isRunning = false;
                  }
              };
              timer.Tick += elapsedEvent;
              elapsedEvent(sender, null);
              timer.Start();
#endif
            };

            worker.RunWorkerAsync(server);
          }
        }
        else
          return;
      } while (true);
    }
Beispiel #21
0
        public MediaPlayerVM(AllPlayClient client)
        {
            _client             = client;
            _client.DeviceLost += Client_DeviceLost;
            _positionTimer      = new Windows.UI.Xaml.DispatcherTimer()
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            _positionTimer.Tick += PositionTimer_Tick;
            client.MediaPlayer.PlayStateChanged       += PlayStateChanged;
            client.MediaPlayer.PlaylistChanged        += MediaPlayer_PlaylistChanged;
            client.MediaPlayer.ShuffleModeChanged     += MediaPlayer_ShuffleModeChanged;
            client.MediaPlayer.LoopModeChanged        += MediaPlayer_LoopModeChanged;
            client.MediaPlayer.InterruptibleChanged   += MediaPlayer_InterruptibleChanged;
            client.MediaPlayer.EnabledControlsChanged += MediaPlayer_EnabledControlsChanged;
            client.MediaPlayer.EndOfPlayback          += MediaPlayer_EndOfPlayback;
            client.MediaPlayer.GetPlayerInfoAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    _playerInfo = state.Result;
                }
            });

            client.MediaPlayer.GetPlayStateAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    UpdateMediaState(state.Result);
                }
            });
            client.MediaPlayer.GetEnabledControlsAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    UpdateEnabledControls(state.Result);
                }
            });
            client.MediaPlayer.GetPlaylistAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    UpdatePlaylist(state.Result);
                }
            });
            client.MediaPlayer.GetLoopModeAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    LoopMode = state.Result;
                    OnPropertyChanged(nameof(LoopMode));
                }
                ;
            });
            client.MediaPlayer.GetShuffleModeAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    ShuffleMode = state.Result;
                    OnPropertyChanged(nameof(ShuffleMode));
                }
                ;
            });
            client.MediaPlayer.GetInterruptibleAsync().ContinueWith((state) =>
            {
                if (!state.IsFaulted && !state.IsCanceled)
                {
                    IsInterruptible = state.Result;
                    OnPropertyChanged(nameof(IsInterruptible));
                }
                ;
            });
            if (client.Volume != null)
            {
                client.Volume.VolumeChanged  += Volume_VolumeChanged;
                client.Volume.MuteChanged    += Volume_MuteChanged;
                client.Volume.EnabledChanged += Volume_EnabledChanged;
                client.Volume.GetVolumeAsync().ContinueWith((state) =>
                {
                    if (!state.IsFaulted && !state.IsCanceled)
                    {
                        Volume = state.Result;
                        OnPropertyChanged(nameof(Volume));
                    }
                    ;
                });
                client.Volume.GetVolumeEnabledAsync().ContinueWith((state) =>
                {
                    if (!state.IsFaulted && !state.IsCanceled)
                    {
                        Volume_EnabledChanged(client.Volume, state.Result);
                    }
                    ;
                });
                client.Volume.GetMuteAsync().ContinueWith((state) =>
                {
                    if (!state.IsFaulted && !state.IsCanceled)
                    {
                        Volume_MuteChanged(client.Volume, state.Result);
                    }
                    ;
                });
            }

            nextCommand     = new GenericCommand((o) => { _client.MediaPlayer.NextAsync(); }, (o) => { return(_enabledControls == null ? false : _enabledControls.Next); });
            previousCommand = new GenericCommand((o) => { _client.MediaPlayer.PreviousAsync(); }, (o) => { return(_enabledControls == null ? false : _enabledControls.Previous); });
            stopCommand     = new GenericCommand((o) => { _client.MediaPlayer.StopAsync(); });
            resumeCommand   = new GenericCommand((o) => { _client.MediaPlayer.ResumeAsync(); });

            volumeUpCommand   = new GenericCommand((o) => { _client.Volume.AdjustVolumeAsync(2); }, (o) => { return(IsVolumeEnabled); });
            volumeDownCommand = new GenericCommand((o) => { _client.Volume.AdjustVolumeAsync(-2); }, (o) => { return(IsVolumeEnabled); });
        }
Beispiel #22
0
        /// <summary>
        /// Assigns a new server driver to the connection object
        /// </summary>
        /// <param name="groupName">Group name</param>
        /// <param name="master">True if the server connection to assign must be a master</param>
        /// <param name="connection">MySqlConnection object where the new driver will be assigned</param>
        public static void GetNewConnection(string groupName, bool master, MySqlConnection connection)
        {
            do
            {
                if (!IsReplicationGroup(groupName))
                {
                    return;
                }

                ReplicationServerGroup group  = GetGroup(groupName);
                ReplicationServer      server = group.GetServer(master);

                if (server == null)
                {
                    throw new MySqlException(Properties.Resources.Replication_NoAvailableServer);
                }

                Driver driver = Driver.Create(new MySqlConnectionStringBuilder(server.ConnectionString));
                if (connection.driver == null ||
                    driver.Settings.ConnectionString != connection.driver.Settings.ConnectionString)
                {
                    connection.Close();
                    connection.hasBeenOpen = false;
                    try
                    {
                        connection.driver = driver;
                        connection.Open();
                        return;
                    }
                    catch (Exception)
                    {
                        // retry to open a failed connection and update its status
                        connection.driver  = null;
                        server.IsAvailable = false;

                        BackgroundWorker worker = new BackgroundWorker();
                        worker.DoWork += delegate(object sender, DoWorkEventArgs e)
                        {
                            bool isRunning            = false;
                            ReplicationServer server1 = e.Argument as ReplicationServer;
                            int retryTime             = ReplicationManager.GetGroup(groupName).RetryTime;
#if !RT
                            System.Timers.Timer timer = new System.Timers.Timer(retryTime * 1000.0);


                            System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1)
                            {
                                if (isRunning)
                                {
                                    return;
                                }
                                try
                                {
                                    isRunning = true;
                                    using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                                    {
                                        connectionFailed.Open();
                                        server1.IsAvailable = true;
                                        timer.Stop();
                                    }
                                }
                                catch
                                {
                                    MySqlTrace.LogWarning(0,
                                                          string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                                }
                                finally
                                {
                                    isRunning = false;
                                }
                            };
                            timer.Elapsed += elapsedEvent;
                            timer.Start();
                            elapsedEvent(sender, null);
#else
                            Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
                            TimeSpan ts = new TimeSpan(retryTime * 1000);
                            System.EventHandler <object> elapsedEvent = (TickSender, TickEventArgs) =>
                            {
                                if (isRunning)
                                {
                                    return;
                                }
                                try
                                {
                                    isRunning = true;
                                    using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                                    {
                                        connectionFailed.Open();
                                        server1.IsAvailable = true;
                                        timer.Stop();
                                    }
                                }
                                catch
                                {
                                    MySqlTrace.LogWarning(0,
                                                          string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                                }
                                finally
                                {
                                    isRunning = false;
                                }
                            };
                            timer.Tick += elapsedEvent;
                            elapsedEvent(sender, null);
                            timer.Start();
#endif
                        };

                        worker.RunWorkerAsync(server);
                    }
                }
                else
                {
                    return;
                }
            } while (true);
        }
Beispiel #23
0
        /// <summary>
        /// Handles a failed connection to a server.
        /// This method can be overrided to implement a custom failover handling
        /// </summary>
        /// <param name="server">The failed server</param>
        internal protected virtual void HandleFailover(ReplicationServer server)
        {
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                bool isRunning            = false;
                ReplicationServer server1 = e.Argument as ReplicationServer;
#if !RT
                System.Timers.Timer timer = new System.Timers.Timer(RetryTime * 1000.0);

                System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1)
                {
                    if (isRunning)
                    {
                        return;
                    }
                    try
                    {
                        isRunning = true;
                        using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                        {
                            connectionFailed.Open();
                            server1.IsAvailable = true;
                            timer.Stop();
                        }
                    }
                    catch
                    {
                        MySqlTrace.LogWarning(0,
                                              string.Format(MySqlResources.Replication_ConnectionAttemptFailed, server1.Name));
                    }
                    finally
                    {
                        isRunning = false;
                    }
                };
                timer.Elapsed += elapsedEvent;
                timer.Start();
                elapsedEvent(sender, null);
#else
                Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
                TimeSpan ts = new TimeSpan(RetryTime * 1000);
                System.EventHandler <object> elapsedEvent = (TickSender, TickEventArgs) =>
                {
                    if (isRunning)
                    {
                        return;
                    }
                    try
                    {
                        isRunning = true;
                        using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                        {
                            connectionFailed.Open();
                            server1.IsAvailable = true;
                            timer.Stop();
                        }
                    }
                    catch
                    {
                        MySqlTrace.LogWarning(0,
                                              string.Format(Properties.MySqlResources.Replication_ConnectionAttemptFailed, server1.Name));
                    }
                    finally
                    {
                        isRunning = false;
                    }
                };
                timer.Tick += elapsedEvent;
                elapsedEvent(sender, null);
                timer.Start();
#endif
            };

            worker.RunWorkerAsync(server);
        }
Beispiel #24
0
        /// <summary>
        /// Retrieve the current network time from ntp server  "time.windows.com".
        /// </summary>
        public async void GetNetworkTime(string ntpServer)
        {

            averageNtpRTT = 0; //reset

            currentNtpQueryCount = 0; //reset
            minNtpRTT = -1; //reset

            //NTP uses UDP
            ntpSocket = new Windows.Networking.Sockets.DatagramSocket();
            ntpSocket.MessageReceived += OnNTPTimeReceived;


            if (ntpQueryTimer == null)
            {
                ntpQueryTimer = new Windows.UI.Xaml.DispatcherTimer();
                ntpQueryTimer.Tick += NTPQueryTimeout;
                ntpQueryTimer.Interval = new TimeSpan(0, 0, 5); //5 seconds
            }

            if (ntpRTTIntervalTimer == null)
            {
                ntpRTTIntervalTimer = new Windows.UI.Xaml.DispatcherTimer();
                ntpRTTIntervalTimer.Tick += SendNTPQuery;
                ntpRTTIntervalTimer.Interval = new TimeSpan(0, 0, 0, 0, 200); //200ms

            }

            ntpQueryTimer.Start();

            try
            {
                //The UDP port number assigned to NTP is 123
                await ntpSocket.ConnectAsync(new Windows.Networking.HostName(ntpServer), "123");
                ntpRTTIntervalTimer.Start();

            }
            catch (Exception e)
            {
                Debug.WriteLine($"NtpSync: Exception when connect socket: {e.Message}");
                ntpResponseMonitor.Stop();
                ReportNtpSyncStatus(false);
            }

        }
Beispiel #25
0
        private async void Initialize()
        {
            // Create scene
            Scene myScene = new Scene(Basemap.CreateImageryWithLabels());
            // Create the elevation source
            ElevationSource myElevationSource = new ArcGISTiledElevationSource(_elevationUri);

            // Add the elevation source to the scene
            myScene.BaseSurface.ElevationSources.Add(myElevationSource);
            // Create the building scene layer
            ArcGISSceneLayer mySceneLayer = new ArcGISSceneLayer(_buildingsUri);

            // Add the building layer to the scene
            myScene.OperationalLayers.Add(mySceneLayer);

            // Add the observer to the scene
            // Create a graphics overlay with relative surface placement; relative surface placement allows the Z position of the observation point to be adjusted
            GraphicsOverlay overlay = new GraphicsOverlay()
            {
                SceneProperties = new LayerSceneProperties(SurfacePlacement.Relative)
            };
            // Create the symbol that will symbolize the observation point
            SimpleMarkerSceneSymbol symbol = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Sphere, Colors.Red, 10, 10, 10, SceneSymbolAnchorPosition.Bottom);

            // Create the observation point graphic from the point and symbol
            _observerGraphic = new Graphic(_observerPoint, symbol);
            // Add the observer to the overlay
            overlay.Graphics.Add(_observerGraphic);
            // Add the overlay to the scene
            MySceneView.GraphicsOverlays.Add(overlay);

            // Add the taxi to the scene
            // Create the model symbol for the taxi
            ModelSceneSymbol taxiSymbol = await ModelSceneSymbol.CreateAsync(new Uri(await GetModelUri()));

            // Set the anchor position for the mode; ensures that the model appears above the ground
            taxiSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom;
            // Create the graphic from the taxi starting point and the symbol
            _taxiGraphic = new Graphic(_points[0], taxiSymbol);
            // Add the taxi graphic to the overlay
            overlay.Graphics.Add(_taxiGraphic);

            // Create GeoElement Line of sight analysis (taxi to building)
            // Create the analysis
            _geoLine = new GeoElementLineOfSight(_observerGraphic, _taxiGraphic);
            // Apply an offset to the target. This helps avoid some false negatives
            _geoLine.TargetOffsetZ = 2;
            // Create the analysis overlay
            AnalysisOverlay myAnalysisOverlay = new AnalysisOverlay();

            // Add the analysis to the overlay
            myAnalysisOverlay.Analyses.Add(_geoLine);
            // Add the analysis overlay to the scene
            MySceneView.AnalysisOverlays.Add(myAnalysisOverlay);

            // Create a timer; this will enable animating the taxi
            Windows.UI.Xaml.DispatcherTimer animationTimer = new Windows.UI.Xaml.DispatcherTimer()
            {
                Interval = new TimeSpan(0, 0, 0, 0, 60)
            };
            // Move the taxi every time the timer expires
            animationTimer.Tick += AnimationTimer_Tick;
            // Start the timer
            animationTimer.Start();

            // Subscribe to TargetVisible events; allows for updating the UI and selecting the taxi when it is visible
            _geoLine.TargetVisibilityChanged += Geoline_TargetVisibilityChanged;

            // Add the scene to the view
            MySceneView.Scene = myScene;

            // Set the viewpoint
            MySceneView.SetViewpoint(new Viewpoint(_observerPoint, 1000));
        }
Beispiel #26
0
        public async void captureAudio(string options)
        {
            try
            {
                try
                {
                    string args = JSON.JsonHelper.Deserialize <string[]>(options)[0];
                    this.captureAudioOptions = String.IsNullOrEmpty(args) ? CaptureAudioOptions.Default : JSON.JsonHelper.Deserialize <CaptureAudioOptions>(args);
                }
                catch (Exception ex)
                {
                    this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                    return;
                }

                var mediaCaputreSettings = new MediaCaptureInitializationSettings();
                mediaCaputreSettings.StreamingCaptureMode = StreamingCaptureMode.Audio;
                audioCaptureTask = new MediaCapture();
                await audioCaptureTask.InitializeAsync(mediaCaputreSettings);

                var mediaEncodingProfile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto);
                var storageFile          = await KnownFolders.MusicLibrary.CreateFileAsync("captureAudio.mp3", CreationCollisionOption.GenerateUniqueName);

                var timer = new Windows.UI.Xaml.DispatcherTimer();
                timer.Tick += async delegate(object sender, object e)
                {
                    timer.Stop();
                    await audioCaptureTask.StopRecordAsync();

                    if (storageFile != null)
                    {
                        long   size         = 0;
                        string modifiedDate = "";
                        var    tasks        = new List <Task <BasicProperties> >();
                        tasks.Add(storageFile.GetBasicPropertiesAsync().AsTask());
                        var result = await Task.WhenAll(tasks);

                        foreach (var prop in result)
                        {
                            size         = (long)prop.Size;
                            modifiedDate = prop.DateModified.ToString();
                        }

                        string imagePathOrContent = string.Empty;
                        var    readStream         = await storageFile.OpenAsync(FileAccessMode.Read);

                        var inputStream    = readStream.GetInputStreamAt(0);
                        var dataReaderFile = new DataReader(inputStream);
                        var numByteLoaded  = await dataReaderFile.LoadAsync((uint)readStream.Size);

                        var byteString        = new byte[numByteLoaded];
                        var imageBase64String = "";
                        dataReaderFile.ReadBytes(byteString);
                        imageBase64String  = Convert.ToBase64String(byteString);
                        imagePathOrContent = "data:audio/mpeg;base64," + imageBase64String;

                        MediaFile data = new MediaFile(imagePathOrContent, storageFile.ContentType, storageFile.Name, size, modifiedDate);

                        this.files.Add(data);

                        if (files.Count < this.captureAudioOptions.Limit)
                        {
                            //dosomething here
                        }
                        else
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files));
                            files.Clear();
                        }
                    }
                };
                timer.Interval = TimeSpan.FromMilliseconds(captureAudioDuration * 1000);


                await audioCaptureTask.StartRecordToStorageFileAsync(mediaEncodingProfile, storageFile);

                timer.Start();
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message));
            }
        }