示例#1
0
        /// <summary>
        /// Starts a new delay execution.
        /// The previous waiting is canceled.
        /// </summary>
        /// <remarks>
        /// This method must be called on the thread that the Dispatcher is associated with.
        /// </remarks>
        /// <param name="action">The action to execute with delay.</param>
        /// <param name="delayTime">Time to wait before executing the action.</param>
        private void StartImpl(Action action, TimeSpan delayTime)
        {
            Debug.Assert(action != null);

            _dispatcherTimer.Stop();
            _dispatcherTimer.Interval = delayTime;
            _action = action;
            _dispatcherTimer.Start();
        }
示例#2
0
 public void start()
 {
     dt          = new Windows.UI.Xaml.DispatcherTimer();
     dt.Interval = DELAY_UPDATES;
     dt.Tick    += dt_ticker;
     dt.Start();
 }
示例#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;
            }
        }
 private void TimerInit()
 {
     timer          = new Windows.UI.Xaml.DispatcherTimer();
     timer.Tick    += Timer_Tick;
     timer.Interval = new TimeSpan(0, 0, 1);
     timer.Start();
 }
示例#5
0
        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);
            });
        }
示例#6
0
 public BeeStarViewModel()
 {
     _model.BeeMoved    += _model_BeeMoved;
     _model.StarChanged += _model_StarChanged;
     _timer.Interval     = TimeSpan.FromSeconds(2);
     _timer.Tick        += _timer_Tick;
     _timer.Start();
 }
 public BeeStarViewModel()
 {
     _model.BeeMoved    += BeeMovedHandler;
     _model.StarChanged += StarChangedHandler;
     _timer.Interval     = TimeSpan.FromSeconds(2);
     _timer.Tick        += timer_Tick;
     _timer.Start();//run clock
 }
        public async void Init()
        {
            await InitRGBSensor();

            timer          = new Windows.UI.Xaml.DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(3);
            timer.Tick    += Timer_Tick;
            timer.Start();
        }
示例#9
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);
            }
        }
示例#10
0
 internal void AddMouseDown(object objectUnderMouseCursor)
 {
     if (!IsRunning)
     {
         DownCount = 0;
         UpCount   = 0;
         clickTimer.Start();
         IsRunning = true;
     }
     LastDownClickPosition = this.mousePosition();
     ClickedObject         = objectUnderMouseCursor;
     DownCount++;
 }
示例#11
0
        /// <summary>
        /// Starts the <see cref="DispatcherTimer"/>.
        /// </summary>
        /// <remarks>If the timer has already started, then it is restarted.</remarks>
        public void Start()
        {
#if __ANDROID__ || __UNIFIED__ || WIN32
            if (_timer.Enabled)
            {
                _timer.Stop();
            }

            _timer.Start();
#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE
            _dispatcherTimer.Start();
#endif
        }
示例#12
0
 /// <summary>
 /// Starts game
 /// </summary>
 /// <remarks>
 /// Deletes all invaders ships and shots from sprite collection, starts timer and
 /// informs model about game start
 /// </remarks>
 private void StartGame()
 {
     Paused = false;
     foreach (var invader in _invaders.Values)
     {
         _sprites.Remove(invader);
     }
     foreach (var shot in _shots.Values)
     {
         _sprites.Remove(shot);
     }
     _model.StartGame();
     OnPropertyChanged(nameof(GameOver));
     _timer.Start();
 }
示例#13
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();
        }
示例#14
0
        private void UpdateMediaState(PlayState state)
        {
            _lastKnownState       = state;
            _timeOfLastKnownState = DateTime.Now;
            var _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                if (state.State == MediaState.Playing)
                {
                    if (!_positionTimer.IsEnabled)
                    {
                        _positionTimer.Start();
                    }
                }
                else
                {
                    _positionTimer.Stop();
                }
            });

            OnPropertyChanged(nameof(CurrentMedia), nameof(NextMedia), nameof(MediaState), nameof(Position));
        }
        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();
        }
示例#16
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);
        }
        /// <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;
        }
        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();
            
        }
示例#19
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);
        }
示例#20
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);
        }
示例#21
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; };
        }
    /// <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);
    }
    /// <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);
    }
示例#24
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));
        }
示例#25
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));
            }
        }