Start() публичный Метод

Starts the timing by setting to .

public Start ( ) : void
Результат void
Пример #1
0
        void OnPauseExecute()
        {
            if (RecorderState == RecorderState.Paused)
            {
                _systemTray.HideNotification();

                _recorder.Start();
                _timing?.Start();
                _timer?.Start();

                RecorderState          = RecorderState.Recording;
                Status.LocalizationKey = nameof(LanguageManager.Recording);
            }
            else
            {
                _recorder.Stop();
                _timer?.Stop();
                _timing?.Pause();

                RecorderState          = RecorderState.Paused;
                Status.LocalizationKey = nameof(LanguageManager.Paused);

                _systemTray.ShowTextNotification(Loc.Paused, null);
            }
        }
Пример #2
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.

			searchField.Text = string.Empty;

			var keyStrokeTimer = new Timer (500);
			var timeElapsedSinceChanged = true;

			keyStrokeTimer.Start ();

			keyStrokeTimer.Elapsed += (sender, e) => {
				timeElapsedSinceChanged = true;
			};

			var searchText = "";
			searchField.EditingChanged += async (sender, e) => {
				keyStrokeTimer.Stop ();

				if (timeElapsedSinceChanged) {
					// Probably should do some locking
					timeElapsedSinceChanged = false;
					keyStrokeTimer.Stop ();

					if (!string.IsNullOrEmpty (searchField.Text)) {
						if (!searchText.Equals (searchField.Text)) {
							searchText = searchField.Text;

							var results = await SearchCheeses (searchText);

							foreach (var cheeseName in results) {
											Console.WriteLine ($"Cheese name: {cheeseName}");
							}
						}
					}
				}

				keyStrokeTimer.Start();
			};


//			var editing = searchField.Events ().EditingChanged;
//
//			var searchSteam = editing
//				.Select (_ => searchField.Text)
//				.Where (t => !string.IsNullOrEmpty (t))
//				.DistinctUntilChanged ()
//				.Throttle (TimeSpan.FromSeconds (0.5))
//				.SelectMany (t =>
//					SearchCheeses (t));			                  
//
//			searchSteam.Subscribe (
//				r =>
//				r.ForEach(cheeseName =>
//					Console.WriteLine($"Cheese name: {cheeseName}"))			
//			);
		}
Пример #3
0
 public static TimerHandle SetInterval(TimeSpan delay, Action callback)
 {
   var timer = new Timer(delay.TotalMilliseconds);
   timer.Elapsed += (sender, e) =>
     {
       timer.Stop();
       callback();
       timer.Start();
     };
   timer.AutoReset = false;
   timer.Start();
   return new TimerHandle(timer, callback);
 }
Пример #4
0
        internal void AddChild(BSCarouselItem item)
        {
            Children.Add(item);
            if (Children.First() == item)
            {
                item.First();
                if (item.Interval != 0)
                {
                    InitializeTransitionTimer(item.Interval);
                    _transitionTimer?.Start();
                }
            }

            _indicatorsRef?.Refresh(Children.Count, _active);
        }
 /// <summary>
 /// Initializes a new instance of the App class.
 /// </summary>
 /// <param name="appSplashScreen">Instance of application splash screen window.</param>
 public App(DemoSplashScreen appSplashScreen)
 {
     this.appSplashScreen = appSplashScreen;
     applicationSplashScreenTimer = new ST.Timer(100);
     applicationSplashScreenTimer.Elapsed += new ST.ElapsedEventHandler(applicationSplashScreenTimer_Elapsed);
     applicationSplashScreenTimer.Start();
 }
        public DashboardView()
        {
            InitializeComponent();

            AndonManager = new AndonManager(StationList, null, Andonmanager.AndonManager.MODE.MASTER);

            AndonManager.start();
            StationList = new Queue<int>();

            Plans = new Plans();
            PlanGrid.DataContext = Plans;

            Actuals = new Models.Actuals();
            ActualGrid.DataContext = Actuals;

            AppTimer = new Timer(1000);
            AppTimer.AutoReset = false;
            AppTimer.Elapsed += AppTimer_Elapsed;

            EfficiencyWatch = new Stopwatch();

            using (PSBContext DBContext = new PSBContext())
            {

                Shifts = DBContext.Shifts.ToList();

                foreach (Shift s in Shifts)
                {
                    s.Update();
                }

            }

            AppTimer.Start();
        }
Пример #7
0
        public void Start()
        {
            Database.Initialize(ConnectionString);
            DapperConfig.Initialize();
            DefaultTraceLogInitializer.Initialize(ConnectionString, TraceLogLevel.Trace);
            MarkdownParser.RegisterJsEngineType<V8JsEngine>();

            _logger.Trace(string.Format("WEBJOB Start: Interval = {0} ミリ秒", Interval.ToString("##,###")));

            var service = new SearchService(ConnectionString);
            var status = service.GetServiceStatusAsync().Result;

            if (status == ServiceStatus.IndexNotExists)
            {
                service.RecreateEsIndexAsync().Wait();
            }

            _timer = new Timer
            {
                Interval = Interval
            };

            _timer.Elapsed += Execute;
            _timer.Start();
        }
 private void UserControl_Loaded_1(object sender, RoutedEventArgs e)
 {
     this.timer = new Timer();
     timer.Interval = 3000;
     timer.Elapsed += timer_Elapsed;
     timer.Start();
 }
Пример #9
0
 public static void InitializingTimers()
 {
     sendDataTimer = new Timer(SEND_DATA_INTERVAL);
     sendDataTimer.Elapsed += SendDataTimer_Elapsed;
     sendDataTimer.Enabled = true;
     sendDataTimer.Start();
 }
        public GameCoordinator(SteamClient steamClient, CallbackManager manager)
        {
            SessionMap = new Dictionary<uint, SessionInfo>();

            // Map gc messages to our callback functions
            MessageMap = new Dictionary<uint, Action<uint, IPacketGCMsg>>
            {
                { (uint)EGCBaseClientMsg.k_EMsgGCClientConnectionStatus, OnConnectionStatus },
                { (uint)EGCBaseClientMsg.k_EMsgGCClientWelcome, OnWelcome },
                { (uint)EGCItemMsg.k_EMsgGCUpdateItemSchema, OnItemSchemaUpdate },
                { (uint)EGCItemMsg.k_EMsgGCClientVersionUpdated, OnVersionUpdate },
                { (uint)EGCBaseMsg.k_EMsgGCSystemMessage, OnSystemMessage },

                // TF2 specific messages
                { k_EMsgGCClientGoodbye, OnConnectionStatus },
                { (uint)EGCItemMsg.k_EMsgGCGoldenWrenchBroadcast, OnWrenchBroadcast },
                { k_EMsgGCTFSpecificItemBroadcast, OnItemBroadcast },
            };

            SteamGameCoordinator = steamClient.GetHandler<SteamGameCoordinator>();

            SessionTimer = new Timer();
            SessionTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds;
            SessionTimer.Elapsed += OnSessionTick;
            SessionTimer.Start();

            manager.Subscribe<SteamGameCoordinator.MessageCallback>(OnGameCoordinatorMessage);
            manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
            manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
        }
Пример #11
0
 public void CreateTimer(double interval, ICalculatorDuplexCallback tempCallback)
 {
     callback = tempCallback;
     Timer timer = new Timer { Interval = interval };
     timer.Elapsed += Timer_Elapsed;
     timer.Start();
 }
    /// <summary>
    /// Constructor
    /// </summary>
    public CreateJoinForm(Peer peerObject, Address addressObject, ConnectWizard connectionWizard)
    {
        //
        // Required for Windows Form Designer support
        //
        InitializeComponent();
        peer = peerObject;
        this.connectionWizard = connectionWizard;
        this.Text = connectionWizard.SampleName + " - " + this.Text;
        deviceAddress = addressObject;

        //Set up the event handlers
        peer.FindHostResponse += new FindHostResponseEventHandler(FindHostResponseMessage);
        peer.ConnectComplete += new ConnectCompleteEventHandler(ConnectResult);
        peer.AsyncOperationComplete += new AsyncOperationCompleteEventHandler(CancelAsync);

        //Set up our timer
        updateListTimer = new System.Timers.Timer(300); // A 300 ms interval
        updateListTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.UpdateTimer);
        updateListTimer.SynchronizingObject = this;
        updateListTimer.Start();
        //Set up our connect timer
        connectTimer = new System.Timers.Timer(100); // A 100ms interval
        connectTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.ConnectTimer);
        connectTimer.SynchronizingObject = this;
        // Set up our connect event
        connectEvent = new ManualResetEvent(false);
    }
        public AudioPlayer()
        {
            InitializeComponent();
            timerUpdate = new Timer();

            this.timerUpdate.Interval = 50;
            this.timerUpdate.Elapsed += new ElapsedEventHandler(timerUpdate_Elapsed);
            this.pictureBoxWaveForm.MouseDown += new MouseButtonEventHandler(pictureBoxWaveForm_MouseDown);
            this.wavePosition.MouseDown += new MouseButtonEventHandler(pictureBoxWaveForm_MouseDown);
            
            
            this.wavePosition.Width = 2;
            this.wavePosition.Height = this.pictureBoxWaveForm.Height;
            this.wavePosition.Opacity = 0.5;
            this.wavePosition.Fill = Brushes.Red;

           
            _mixer = BassMix.BASS_Mixer_StreamCreate(44100, 2, BASSFlag.BASS_SAMPLE_FLOAT);
            if (_mixer == 0)
            {
                MessageBox.Show("Could not create mixer!");
                Bass.BASS_Free();
                return;
            }

            _mixerStallSync = new SYNCPROC(OnMixerStall);
            Bass.BASS_ChannelSetSync(_mixer, BASSSync.BASS_SYNC_STALL, 0L, _mixerStallSync, IntPtr.Zero);

            timerUpdate.Start();
            Bass.BASS_ChannelPlay(_mixer, false);


            newtrack(@"D:\OAIBC\2-13 California.mp3", null);

        }
Пример #14
0
 public void resetTimeout(int t)
 {
     Timer timeoutTimer = new System.Timers.Timer();
     timeoutTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
     timeoutTimer.Interval = t;
     timeoutTimer.Start();
 }
Пример #15
0
 public StressTest()
 {
     InitializeComponent();
     tmr = new Timer(500);
     tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);
     tmr.Start();
 }
Пример #16
0
 public Server()
 {
     config = new INIReader(System.IO.File.ReadAllLines("config.ini"));
     chat = new ServerChat();
     instance = this;
     vehicleController = new ServerVehicleController();
     api = new ServerApi(this);
     gamemodeManager = new GamemodeManager(api);
     gamemodeManager.loadFromFile("gamemodes/" + config.getString("gamemode"));
     server = new TcpListener(IPAddress.Any, config.getInt("game_port"));
     server.Start();
     server.BeginAcceptTcpClient(onIncomingConnection, null);
     playerpool = new List<ServerPlayer>();
     Timer timer = new Timer();
     timer.Elapsed += onBroadcastTimer;
     timer.Interval = config.getInt("broadcast_interval");
     timer.Enabled = true;
     timer.Start();
     UDPStartPort = config.getInt("udp_start_port");
     Timer timer_slow = new Timer();
     timer_slow.Elapsed += timer_slow_Elapsed;
     timer_slow.Interval = config.getInt("slow_interval");
     timer_slow.Enabled = true;
     timer_slow.Start();
     http_server = new HTTPServer();
     Console.WriteLine("Started game server on port " + config.getInt("game_port").ToString());
     Console.WriteLine("Started http server on port " + config.getInt("http_port").ToString());
 }
 public SamplingTargetPointGenerator(int samplesPerSecond)
 {
     workerTimer = new Timer(1000 / samplesPerSecond);
     workerTimer.Elapsed += this.WorkerTimerElapsed;
     workerTimer.AutoReset = false;
     workerTimer.Start();
 }
Пример #18
0
 public HomeViewModel()
 {
     timer = new Timer(1000);
     timer.Elapsed += TimerElapsed;
     timer.AutoReset = true;
     timer.Start();
 }
Пример #19
0
 protected override void InitializeImpl()
 {
     this._timers = this.TimerJobs
         .Where(j => j.Item1 > 0.0)
         .OrderBy(j => j.Item1)
         .Select(j =>
         {
             Timer timer = new Timer(j.Item1);
             timer.Elapsed += (sender, e) =>
             {
                 timer.Stop();
                 try
                 {
                     this.Host.RequestManager.Execute<Object>(Request.Parse(j.Item2));
                 }
                 finally
                 {
                     timer.Start();
                 }
             };
             return timer;
         }).ToList();
     this.RunInitializingJobs();
     base.InitializeImpl();
 }
Пример #20
0
 public void Start()
 {
     _t = new Timer();
     _t.Elapsed += Ticked;
     _t.Interval = 1000;
     _t.Start();
 }
Пример #21
0
        /// <summary>
        /// Create an new Instance of the TCP-Listener on Port 5000
        /// </summary>
        internal Server()
        {
            try
            {
                AnrlDB.AnrlDataContext db = new AnrlDB.AnrlDataContext();
                if (!db.DatabaseExists())
                {
                    db.CreateDatabase();
                }

                CalculateTabels = new System.Timers.Timer(20000);
                CalculateTabels.Elapsed += new ElapsedEventHandler(CalculateTabels_Elapsed);
                CalculateTabels.Start();

                running = true;
                this.tcpListener = new TcpListener(IPAddress.Any, 5000);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
                db.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Log("Exception in Server.Server" + ex.ToString(), 11);
            }
        }
Пример #22
0
 public bool Init()
 {
   _timer = new Timer(500) { AutoReset = true };
   _timer.Elapsed += InitAsync;
   _timer.Start();
   return true;
 }
Пример #23
0
        public Game(string mapPath)
        {
            totalPoints = 0;

            totalRounds = 9; //TU ILE MAP MA GRA TRZEBA WPISAC

            typewriter = Constants.getSoundPlayerInstance();
            typewriter.Stop();
            typewriter.SoundLocation = "step.wav";

            isNewLevel = true;

            currentPositionInPauseMenu = 0;

            timerPauseMenu = new Timer(500);
            timerPauseMenu.AutoReset = true;
            timerPauseMenu.Elapsed += (s, e) => pasueMenuTick(e);
            timerPauseMenu.Start();

            heroObject = new Hero();
            boxObject = new Box();
            pointObject = new Point();
            floorObject = new Floor();
            wallObject = new Wall();

            mapNumber = 1;
            writelock = new object();
            initMap(mapPath, true);
        }
Пример #24
0
 public VisualTimer(double time)
 {
     Interval = TimeLeft = time;
     _checker = new Timer(100);
     _checker.Elapsed += CheckerElapsed;
     _checker.Start();
 }
        /// <summary>
        /// Basic run through, timer setup for read and data save from G4
        /// </summary>
        /// <param name="options">Parsed command line parameters</param>
        private static void Run(Options options)
        {
            if (!string.IsNullOrEmpty(options.Time))
            {
                HeadingInfo.WriteMessage(string.Format("G4 will be polled every {0} milliseconds", options.Time));
            }

            if (!string.IsNullOrEmpty(options.OutputFile))
            {
                HeadingInfo.WriteMessage(string.Format("Writing G4 data to: {0}", options.OutputFile));
            }
            else
            {
                HeadingInfo.WriteMessage("G4 data could not be written.");
                Console.WriteLine("[...]");
            }

            Timer myTimer = new Timer();
            myTimer.Elapsed += new ElapsedEventHandler((sender, e) => ReadAndSaveEGV(sender, e, options));
            myTimer.Interval = Int32.Parse(options.Time);
            myTimer.Start();

            while (Console.Read() != 'q')
            {
                ;    // do nothing...
            }
        }
Пример #26
0
        public AbsoluteTimerWaitHandle(DateTimeOffset dueTime)
        {
            _dueTime = dueTime;
            _eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            SafeWaitHandle = _eventWaitHandle.SafeWaitHandle;

            var dueSpan = (_dueTime - DateTimeOffset.Now);
            var period = new TimeSpan(dueSpan.Ticks / 10);

            if (dueSpan < TimeSpan.Zero)
            {
                _eventWaitHandle.Set();
            }
            else
            {
                _timer = new Timer(period.TotalMilliseconds)
                {
                    AutoReset = false,
                };

                _timer.Elapsed += TimerOnElapsed;

                _timer.Start();
            }
        }
Пример #27
0
 public CacheUpdater()
 {
     updater = new Timer(5000);
     updater.AutoReset = true;
     updater.Elapsed += updater_Elapsed;
     updater.Start();
 }
Пример #28
0
 public static void Initialize(int seconds)
 {
     _timer = new Timer(seconds * 1000);
     _timer.Elapsed +=_timer_Elapsed;
     _timer.AutoReset = true;
     _timer.Start();
 }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // When recovery is enabled, we don't do retries on the individual lock attempts,
            // since retries are being done outside
            bool recoveryEnabled = _singletonConfig.ListenerLockRecoveryPollingInterval != Timeout.InfiniteTimeSpan;
            _lockHandle = await _singletonManager.TryLockAsync(_lockId, null, _attribute, cancellationToken, retry: !recoveryEnabled);

            if (_lockHandle == null)
            {
                // If we're unable to acquire the lock, it means another listener
                // has it so we return w/o starting our listener.
                //
                // However, we also start a periodic background "recovery" timer that will recheck
                // occasionally for the lock. This ensures that if the host that has the lock goes
                // down for whatever reason, others will have a chance to resume the work.
                if (recoveryEnabled)
                {
                    LockTimer = new System.Timers.Timer(_singletonConfig.ListenerLockRecoveryPollingInterval.TotalMilliseconds);
                    LockTimer.Elapsed += OnLockTimer;
                    LockTimer.Start();
                }
                return;
            }

            await _innerListener.StartAsync(cancellationToken);

            _isListening = true;
        }
Пример #30
0
 public void SetupTimer()
 {
     mReadyTimer = new System.Timers.Timer();
     mReadyTimer.Interval = 10000; // 10 secs
     mReadyTimer.Elapsed += new ElapsedEventHandler(ReadyTimerEvent);
     mReadyTimer.Start(); 
 }
Пример #31
0
        public async Task AddMessage(IInboundMessage message)
        {
            // TODO: Check this!
            if (_processingException != null)
            {
                throw new SilverbackException("Cannot add to the batch because the processing of the previous batch failed. See inner exception for details.", _processingException);
            }

            await _semaphore.WaitAsync();

            try
            {
                _messages.Add(message);

                _messageLogger.LogInformation(_logger, "Message added to batch.", message);

                if (_messages.Count == 1)
                {
                    CurrentBatchId = Guid.NewGuid();
                    _waitTimer?.Start();
                }
                else if (_messages.Count == _settings.Size)
                {
                    await ProcessBatch();
                }
            }
            finally
            {
                _semaphore.Release();
            }
        }
        public void Start(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            if (!GetAvailablePorts().Contains(portName))
            {
                throw new Exception(string.Format("Unknown serial port: {0}", portName));
            }

            // Start the timer to empty the receive buffer (in case data smaller than MAX_RECEIVE_BUFFER is received)
            _bufferTimer = new Timer();
            _bufferTimer.Interval = BUFFER_TIMER_INTERVAL;
            _bufferTimer.Elapsed += _bufferTimer_Elapsed;
            _bufferTimer.Start();

            // Instantiate new serial port communication
            _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

            // Open serial port communication
            _serialPort.Open();

            // Check that it is actually open
            if (!_serialPort.IsOpen)
            {
                throw new Exception(string.Format("Could not open serial port: {0}", portName));
            }

            _serialPort.ReadTimeout = 100; // Milliseconds

            _readThread = new System.Threading.Thread(ReadThread);
            _readThreadRunning = true;
            _readThread.Start();
        }
Пример #33
0
        public QueueInstance()
        {
            logger.Debug("Создание экземпляра очереди");

            ServiceLocator.Current.GetInstance<UnityContainer>()
                .BuildUp(this);

            TodayQueuePlan = new QueuePlan();
            TodayQueuePlan.Load(DateTime.Today);

            TodayQueuePlan.OnCurrentClientRequestPlanUpdated += TodayQueuePlan_CurrentClientRequestPlanUpdated;
            TodayQueuePlan.OnOperatorPlanMetricsUpdated += TodayQueuePlan_OnOperatorPlanMetricsUpdated;

            todayQueuePlanLoadTimer = new Timer();
            todayQueuePlanLoadTimer.Elapsed += todayQueuePlanLoadTimer_Elapsed;
            todayQueuePlanLoadTimer.Start();

            todayQueuePlanBuildTimer = new Timer();
            todayQueuePlanBuildTimer.Elapsed += todayQueuePlanBuildTimer_Elapsed;
            todayQueuePlanBuildTimer.Start();

            operatorHasGoneTimer = new Timer();
            operatorHasGoneTimer.Elapsed += operatorHasGoneTimer_Elapsed;
            operatorHasGoneTimer.Start();
        }
Пример #34
0
 private void Timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     _timer?.Stop();
     ExplorerMonitor.Check();
     MaximizedMonitor.Check();
     _timer?.Start();
 }
Пример #35
0
        private void ShowShadows(bool show, bool immediaty)
        {
            _restoreAnimationTimer.Enabled = false;

            if (_bordersVisible == show)
            {
                return;
            }
            if (!_shownOnce)
            {
                return;
            }

            // why this animation? Because of the restore animation in windows : the borders would be shown at the restored location
            // before the parent finishes its animation

            if (immediaty || !show)
            {
                foreach (YamuiShadowBorder sideGlow in _shadows)
                {
                    sideGlow.Show(show);
                }

                _bordersVisible = show;
            }
            else
            {
                _restoreAnimationTimer?.Start();
            }
        }
Пример #36
0
        protected override void OnResume()
        {
            base.OnResume();
            _timer?.Start();

            _secondsRemaining = 0;
            Tick();
        }
Пример #37
0
        private async void SaveTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                await SaveUpdates(analyticsStorage);

                saveTimer?.Start();
            }
            catch (Exception exc)
            {
                OnError?.Invoke(exc);
            }
        }
Пример #38
0
        public async void StartJobsAsync()
        {
            _30Timer?.Start();
            _log = "IT Inventory worker started!";
            await _log.WriteToLogAsync();

            //run tasks on startup
            await Task.Run(() => StaticData.RefreshUsers());

            await Task.Run(() => StaticData.RefreshComputers());

            await Task.Run(() => StaticData.SendUrgentItemsMail());
        }
 public void Refresh()
 {
     if (timer == null)
     {
         return;
     }
     timer?.Stop();
     if (Duration != 0)
     {
         timer?.Start();
     }
     NotifyPropertyChanged("Refresh");
 }
Пример #40
0
        private async void UpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            await syncRoot.WaitAsync();

            try
            {
                PriceHistoryManager.Update();
                await MarketTickersManager.Update();

                updateTimer?.Start();
                OnUpdate?.Invoke();
            }
            catch (Exception exc)
            {
                OnError?.Invoke(exc);
            }
            finally
            {
                syncRoot.Release();
            }
        }
Пример #41
0
        private async void RetrieveData()
        {
            try
            {
                logger.Debug("RetrieveData");
                timer?.Stop();

                logger.Debug($"Get ladder {configuration.League.Id} - {configuration.AccountName}");
                List <IEntry> entries = await httpClientService.GetEntries(configuration.League.Id, configuration.AccountName, configuration.Entry.Character.Name).ConfigureAwait(true);

                var entryRefreshed = characterService.GetEntry(entries, configuration.Entry.Character.Name);
                if (entryRefreshed != null)
                {
                    configuration.Entry = entryRefreshed;
                    RefreshDisplay(entries, entryRefreshed);
                }

                timer?.Start();
            }
            catch (OperationCanceledException e)
            {
                logger.Debug(e, "Operation cancelled");
            }
            catch (CharacterNotFoundException e)
            {
                logger.Debug(e, "Character not found");
            }
            catch (ObjectDisposedException e)
            {
                logger.Debug(e, "Object disposed after tasks cancel");
            }
            catch (InvalidOperationException e)
            {
                logger.Debug(e, "Object disposed with invalid operation");
            }
        }
        private void actualizarVentana()
        {
            try
            {
                Match matchRespuesta = Event_Data.Match(loadedData);

                if (matchRespuesta.Success)
                {
                    string device    = Tools.GetInstance().getMatchData(matchRespuesta, 1);
                    string fechaHora = Tools.GetInstance().getMatchData(matchRespuesta, 2);
                    string mainText  = Tools.GetInstance().getMatchData(matchRespuesta, 3);
                    string subText   = Tools.GetInstance().getMatchData(matchRespuesta, 4);
                    string latitud   = Tools.GetInstance().getMatchData(matchRespuesta, 5);
                    string longitud  = Tools.GetInstance().getMatchData(matchRespuesta, 6);

                    lblTitle.Text  = mainText;
                    lblDevice.Text = device;
                    if (mainText.Trim() == "MESSAGE")
                    {
                        lblInfoMessage.Text = subText;
                        Invoke(new ActualizarPanelMessage(setPanelMessageVisible));
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(subText))
                        {
                            lblInfo.Text = subText;
                            Invoke(new ActualizarPanelMessage(setPanelInfoVisible));
                        }
                        else
                        {
                            Invoke(new ActualizarPanelMessage(setMinForm));
                        }
                    }

                    lblTime.Text = fechaHora;

                    if ((!String.IsNullOrEmpty(latitud)) && (!String.IsNullOrEmpty(longitud)))
                    {
                        HTMLMapa = Tools.GetInstance().construirMapa(latitud, longitud, "16", webBrowser.Version.Major);

                        webBrowser.Visible = true;
                        pictureMap.Visible = false;
                        lblMask.Visible    = false;
                        lblStatus.Visible  = false;

                        aTimer.Enabled = true;
                        aTimer.Start();
                    }
                    else
                    {
                        lblStatus.Text = "No GPS Information";
                    }
                    stream.Close();
                }
                else
                {
                    this.Text = "Invalid Data";
                }
            }
            catch (Exception ex)
            {
                Tools.GetInstance().DoLog("Excepcion en ActualizarVentana de eventInfoTemplate: " + ex.Message);
            }
        }
Пример #43
0
 private void RestartTimer()
 {
     timer.Stop();
     timer.Start();
 }
Пример #44
0
 private void OnUpdateRulesEnded(object sender, RulesEventArgs args)
 {
     timer?.Start();
 }
Пример #45
0
        public override void FinishedLaunching(NSObject notification)
        {
            // Configure logger
            string path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "log4net.config");

            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));
            logger.Info("Ventriliquest 1.0 Starting up...");

            // Get list of available audio out devices
            xamspeech ham = new xamspeech();

            OutputDevices = ham.GetDevices();

            // Setup UI
            statusMenu = new NSMenu();
            statusItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30);

            var outputItem = new NSMenuItem("Output Device",
                                            (a, b) => {
            });

            var deviceList = new NSMenu();

            outputItem.Submenu = deviceList;

            OutputDeviceUID = "Built-in Output";

            foreach (var entry in OutputDevices)
            {
                var test = new NSMenuItem(entry.Key.ToString(),
                                          (a, b) => {
                    foreach (NSMenuItem item in deviceList.ItemArray())
                    {
                        item.State = NSCellStateValue.Off;
                    }
                    NSMenuItem theItem  = (NSMenuItem)a;
                    theItem.State       = NSCellStateValue.On;
                    config.OutputDevice = theItem.Title;
                    foreach (var e in OutputDevices)
                    {
                        if (e.Key.ToString().Equals(theItem.Title))
                        {
                            OutputDeviceUID = e.Value.ToString();
                        }
                    }
                });
                if (entry.Key.ToString().Equals(config.OutputDevice))
                {
                    test.State      = NSCellStateValue.On;
                    OutputDeviceUID = entry.Value.ToString();
                }
                deviceList.AddItem(test);
            }

            var daItem = new NSMenuItem("Local Connections Only",
                                        (a, b) => {
                NSMenuItem theItem = (NSMenuItem)a;
                if (theItem.State == NSCellStateValue.On)
                {
                    config.LocalOnly = false;
                    theItem.State    = NSCellStateValue.Off;
                }
                else
                {
                    config.LocalOnly = true;
                    theItem.State    = NSCellStateValue.On;
                }
            });

            if (config.LocalOnly)
            {
                daItem.State = NSCellStateValue.On;
            }

            var quitItem = new NSMenuItem("Quit",
                                          (a, b) => Shutdown());

            var voiceconfigItem = new NSMenuItem("Voice Configuration",
                                                 (a, b) => Process.Start("http://127.0.0.1:7888/config"));

            statusMenu.AddItem(new NSMenuItem("Version: 1.1"));
            statusMenu.AddItem(outputItem);
            statusMenu.AddItem(daItem);
            statusMenu.AddItem(voiceconfigItem);
            statusMenu.AddItem(quitItem);
            statusItem.Menu           = statusMenu;
            statusItem.Image          = NSImage.ImageNamed("tts-1.png");
            statusItem.AlternateImage = NSImage.ImageNamed("tts-2.png");
            statusItem.HighlightMode  = true;

            speechdelegate.DidComplete += delegate {
                synthesis.Set();
            };
            sounddelegate.DidComplete += delegate {
                playback.Set();
                IsSounding = false;
                IsSpeaking = false;
                sound.Dispose();
            };

            speech.Delegate = speechdelegate;

            queuetimer          = new System.Timers.Timer(250);
            queuetimer.Elapsed += (object sender, ElapsedEventArgs e) => {
                TTSRequest r;
                if (Queue.TryDequeue(out r))
                {
                    if (r.Interrupt)
                    {
                        // stop current TTS
                        NSApplication.SharedApplication.InvokeOnMainThread(delegate {
                            if (IsSpeaking)
                            {
                                speech.StopSpeaking();
                            }
                            if (IsSounding)
                            {
                                sound.Stop();
                            }
                        });
                        // clear queue
                        SpeechQueue.Clear();
                    }
                    if (!r.Reset)
                    {
                        SpeechQueue.Enqueue(r);
                    }
                    RequestCount++;
                }
                var eventdata = new Hashtable();
                eventdata.Add("ProcessedRequests", RequestCount);
                eventdata.Add("QueuedRequests", SpeechQueue.Count);
                eventdata.Add("IsSpeaking", IsSpeaking);
                InstrumentationEvent ev = new InstrumentationEvent();
                ev.EventName = "status";
                ev.Data      = eventdata;
                NotifyGui(ev.EventMessage());
            };

            // when this timer fires, it will pull off of the speech queue and speak it
            // the 1000ms delay also adds a little pause between tts requests.
            speechtimer          = new System.Timers.Timer(250);
            speechtimer.Elapsed += (object sender, ElapsedEventArgs e) => {
                if (IsSpeaking.Equals(false))
                {
                    if (SpeechQueue.Count > 0)
                    {
                        TTSRequest r = SpeechQueue.Dequeue();
                        IsSpeaking          = true;
                        speechtimer.Enabled = false;
                        var oink = Path.Combine(audiopath, "temp.aiff");
                        NSApplication.SharedApplication.InvokeOnMainThread(delegate {
                            ConfigureSpeechEngine(r);
                            speech.StartSpeakingStringtoURL(r.Text, new NSUrl(oink, false));
                        });
                        synthesis.WaitOne();
                        NSApplication.SharedApplication.InvokeOnMainThread(delegate {
                            IsSounding     = true;
                            sound          = new NSSound(Path.Combine(audiopath, "temp.aiff"), false);
                            sound.Delegate = sounddelegate;
                            //if(OutputDeviceUID != "Default") {
                            sound.PlaybackDeviceID = OutputDeviceUID;
                            //}
                            sound.Play();
                        });
                        playback.WaitOne();
                        IsSounding          = false;
                        speechtimer.Enabled = true;
                    }
                }
            };

            queuetimer.Enabled = true;
            queuetimer.Start();
            speechtimer.Enabled = true;
            speechtimer.Start();

            InitHTTPServer();
        }
Пример #46
0
        public BattleBot PromptUserForBot(int highScore)
        {
            openingSound.Play();
            Console.WriteLine("Do you want to enable the reading out of all the text?");
            if (Console.ReadLine().Trim().ToLower()[0] != 'y')
            {
                SpeakingConsole.EnableSpeaking = false;
            }
            openingSound.Stop();
            meetingOakSound.PlayLooping();
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            SpeakingConsole.WriteLine("Welcome to Rock Paper Scissors Lizard Spock");
            Console.WriteLine("\n Press Enter...");
            Console.ReadLine();

            SpeakingConsole.WriteLine("\n ...");
            Console.ReadLine();
            SpeakingConsole.WriteLine("\n  Opps, Wrong Program..");
            Console.ReadLine();
            SpeakingConsole.WriteLine("\n Welcome to Battle Bots");
            Console.ReadLine();
            SpeakingConsole.WriteLine("\n This is a Battle to the Dea... err of the Pokemon ");
            Console.ReadLine();
            SpeakingConsole.WriteLine("\n My name is Professor Oak, Welcome to the World of Pokemon");
            Console.ReadLine();
            Console.WriteLine("\n This world is inhabited by creatures called pokémon!");
            Console.WriteLine("\n For some people, pokémon are pets. Others use them for fights.");
            Console.WriteLine("\n Myself...I study pokémon as a profession.");
            Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.White;
            SpeakingConsole.WriteLine("\n Professor Oak: what is your Name?");

            string strName = SpeakingConsole.ReadLine();

            ///////////////////////////////////////////////////////////////////////
            SpeakingConsole.WriteLine("\nPlease choose a Pokemon from the following:");

            foreach (string weapon in WEAPONS)
            {
                string[] beatableWeapons   = Array.FindAll(WEAPONS, w => CanBeat(weapon, w));
                string[] unbeatableWeapons = Array.FindAll(WEAPONS, w => (!CanBeat(weapon, w)) && w != weapon);

                Console.ForegroundColor = GetColorForWeapon(weapon);
                SpeakingConsole.WriteLine("\n " + weapon + ": " + GetTypeForWeapon(weapon));
                SpeakingConsole.WriteLine("\n\tStrengths: " + string.Join(" And ", beatableWeapons));
                SpeakingConsole.WriteLine("\n\tWeekness: " + string.Join(" And ", unbeatableWeapons));
            }
            //////////////////////////////////////////////////////////////////
            Console.ForegroundColor = ConsoleColor.White;

            string strWeapon;

            while (((strWeapon = SpeakingConsole.ReadLine()) == "" || !IsValidWeapon(strWeapon)) && strName != "")
            {
                SpeakingConsole.WriteLine("Please enter a valid weapon from above");
            }
            meetingOakSound.Stop();
            timer.Start();
            intTimeSinceGameStart = 0;
            BattleBot result;

            if (IsValidWeapon(strWeapon))
            {
                if (strName != "")
                {
                    result = new BattleBot(strName, GetValidWeaponName(strWeapon));
                }
                else
                {
                    result = new BattleBot(GetValidWeaponName(strWeapon));
                }
            }
            else
            {
                result = new BattleBot();
            }
            result.UpdateHighScore(highScore);
            return(result);
        }
Пример #47
0
        private static System.Timers.Timer _filialeCacheRefresher = new System.Timers.Timer(60 * 1000);// 1分钟更新一次

        static MISService()
        {
            _filialeCacheRefresher.Elapsed += RefreshFilialeCache;
            _filialeCacheRefresher.Start();
        }
Пример #48
0
 protected override void OnResume()
 {
     base.OnResume();
     _timer?.Start();
     Tick();
 }
Пример #49
0
        private void InstallCertTimer_EventV(object sender, ElapsedEventArgs e)
        {
            InstallCertTimer.Enabled = false;
            InstallCertTimer.Stop();
            CertInstall erroItem = null;

            try
            {
                List <CertInstall> list = CertInstallBLL.SingleModel.GetListByNoInstall();
                if (list != null && list.Count > 0)
                {
                    writeLog("小程序证书安装服务进来了");
                    foreach (CertInstall item in list)
                    {
                        erroItem = item;
                        if (ZipHelper.UnZip(_folderUrl + item.Name, _installPath + item.Mc_Id))
                        {
                            //添加个人证书
                            X509Certificate2 certificate = new X509Certificate2(_installPath + item.Mc_Id + "\\apiclient_cert.p12", item.Password);
                            X509Store        store       = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                            store.Open(OpenFlags.ReadWrite);
                            store.Remove(certificate);   //可省略
                            store.Add(certificate);
                            store.Close();

                            item.State        = -1;
                            item.UpdateTime   = DateTime.Now;
                            erroItem.ErrorMsg = "";

                            //string[] files = Directory.GetFiles(_installPath + item.Mc_Id, "*.p12");
                            //if(files==null || files.Length<=0)
                            //{
                            //    item.State = -2;
                            //    item.UpdateTime = DateTime.Now;
                            //    erroItem.ErrorMsg = $"没有找到p12类型的文件";
                            //}
                            //else
                            //{
                            //    //添加个人证书
                            //    X509Certificate2 certificate = new X509Certificate2(files[0], item.Password);
                            //    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                            //    store.Open(OpenFlags.ReadWrite);
                            //    store.Remove(certificate);   //可省略
                            //    store.Add(certificate);
                            //    store.Close();

                            //    item.State = -1;
                            //    item.UpdateTime = DateTime.Now;
                            //    erroItem.ErrorMsg = "";
                            //}
                        }
                        else
                        {
                            item.State        = -2;
                            item.UpdateTime   = DateTime.Now;
                            erroItem.ErrorMsg = $"解压失败【{item.Name}】";
                        }

                        CertInstallBLL.SingleModel.Update(item, "State,UpdateTime,ErrorMsg");
                    }
                }
            }
            catch (Exception ex)
            {
                if (erroItem != null)
                {
                    erroItem.State      = -2;
                    erroItem.UpdateTime = DateTime.Now;
                    erroItem.ErrorMsg   = "小程序证书安装服务异常" + ex.Message;
                    CertInstallBLL.SingleModel.Update(erroItem, "State,UpdateTime,ErrorMsg");
                }
                log4net.LogHelper.WriteError(this.GetType(), ex);
            }
            finally
            {
                InstallCertTimer.Enabled = true;
                InstallCertTimer.Start();
            }
        }
Пример #50
0
 public ExpiringList()
 {
     timer.Elapsed += PurgeCache;
     timer.Start();
 }
Пример #51
0
        public StatusIconController()
        {
            UpdateFolders();

            SparkleShare.Controller.FolderListChanged += delegate {
                if (CurrentState != IconState.Error)
                {
                    CurrentState = IconState.Idle;

                    UpdateStateText();
                }

                UpdateFolders();

                UpdateStatusItemEvent(StateText);
                UpdateMenuEvent(CurrentState);
            };

            SparkleShare.Controller.OnIdle += delegate {
                if (CurrentState != IconState.Error)
                {
                    CurrentState = IconState.Idle;
                    UpdateStateText();
                }

                UpdateFolders();

                UpdateIconEvent(CurrentState);
                UpdateStatusItemEvent(StateText);
                UpdateQuitItemEvent(QuitItemEnabled);
                UpdateMenuEvent(CurrentState);
            };

            SparkleShare.Controller.OnSyncing += delegate {
                int repos_syncing_up   = 0;
                int repos_syncing_down = 0;

                foreach (BaseRepository repo in SparkleShare.Controller.Repositories)
                {
                    if (repo.Status == SyncStatus.SyncUp)
                    {
                        repos_syncing_up++;
                    }

                    if (repo.Status == SyncStatus.SyncDown)
                    {
                        repos_syncing_down++;
                    }
                }

                if (repos_syncing_up > 0 &&
                    repos_syncing_down > 0)
                {
                    CurrentState = IconState.Syncing;
                    StateText    = "Syncing…";
                }
                else if (repos_syncing_down == 0)
                {
                    CurrentState = IconState.SyncingUp;
                    StateText    = "Sending…";
                }
                else
                {
                    CurrentState = IconState.SyncingDown;
                    StateText    = "Receiving…";
                }

                int    progress_percentage = (int)SparkleShare.Controller.ProgressPercentage;
                string progress_speed      = "";

                if (SparkleShare.Controller.ProgressSpeedUp > 0.0 && SparkleShare.Controller.ProgressSpeedDown > 0.0)
                {
                    progress_speed = "Up: " + SparkleShare.Controller.ProgressSpeedUp.ToSize() + "/s " +
                                     "Down: " + SparkleShare.Controller.ProgressSpeedDown.ToSize() + "/s";
                }

                if (SparkleShare.Controller.ProgressSpeedUp > 0.0)
                {
                    progress_speed = SparkleShare.Controller.ProgressSpeedUp.ToSize() + "/s ";
                }

                if (SparkleShare.Controller.ProgressSpeedDown > 0.0)
                {
                    progress_speed = SparkleShare.Controller.ProgressSpeedDown.ToSize() + "/s ";
                }

                if (progress_percentage > 0)
                {
                    StateText += string.Format(" {0}% {1}", progress_percentage, progress_speed);
                }

                if (!string.IsNullOrEmpty(SparkleShare.Controller.ProgressInformation))
                {
                    StateText += " – " + SparkleShare.Controller.ProgressInformation;
                }

                UpdateIconEvent(CurrentState);
                UpdateStatusItemEvent(StateText);
                UpdateQuitItemEvent(QuitItemEnabled);
            };

            SparkleShare.Controller.OnError += delegate {
                CurrentState = IconState.Error;
                StateText    = "Not everything synced";

                UpdateFolders();

                UpdateIconEvent(CurrentState);
                UpdateStatusItemEvent(StateText);
                UpdateQuitItemEvent(QuitItemEnabled);
                UpdateMenuEvent(CurrentState);
            };


            // FIXME: Work around a race condition causing
            // the icon to not always show the right state
            var timer = new Timers.Timer {
                Interval = 30 * 1000
            };

            timer.Elapsed += delegate {
                UpdateIconEvent(CurrentState);
                UpdateStatusItemEvent(StateText);
            };

            timer.Start();
        }
Пример #52
0
        /// <summary>
        /// Handles the incoming events
        /// </summary>
        public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority priority)
        {
            ITabbedDocument document = PluginBase.MainForm.CurrentDocument;

            if (document == null || !document.IsEditable)
            {
                return;
            }
            switch (e.Type)
            {
            case EventType.Keys:
            {
                Keys keys = (e as KeyEvent).Value;
                if (this.IsSupported(document) && keys == (Keys.Control | Keys.Space))
                {
                    if (completion != null)
                    {
                        completion.OnComplete(document.SciControl, document.SciControl.CurrentPos);
                        e.Handled = true;
                    }
                }
                break;
            }

            case EventType.FileSwitch:
            case EventType.SyntaxChange:
            case EventType.ApplySettings:
            {
                if (document.IsEditable && this.IsSupported(document))
                {
                    string ext = Path.GetExtension(document.FileName).ToLower();
                    features = enabledLanguages.ContainsKey(ext) ? enabledLanguages[ext] : null;
                    if (completion == null)
                    {
                        completion = new Completion(config, settingObject);
                    }
                    completion.OnFileChanged(features);
                    if (features != null && features.Syntax != null)
                    {
                        ScintillaControl sci = document.SciControl;
                        sci.SetProperty(features.Syntax, features != null ? "1" : "0");
                        sci.Colourise(0, -1);
                    }
                }
                break;
            }

            case EventType.Completion:
            {
                if (features != null)
                {
                    e.Handled = true;
                }
                return;
            }

            case EventType.FileSave:
            {
                if (document != null && document.IsEditable && this.IsSupported(document))
                {
                    updateFile     = document.FileName;
                    updateFeatures = features;
                    updater.Start();
                }
                break;
            }
            }
        }
Пример #53
0
 /// <summary>
 /// Raised every time the slow tick timer elapses.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void SlowTickTimer_Elapsed(object sender, ElapsedEventArgs e)
 {
     OnSlowTick(EventArgs.Empty);
     _SlowTickTimer.Start();
 }
Пример #54
0
 /// <summary>
 /// Raised every time the fast tick timer elapses.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void FastTickTimer_Elapsed(object sender, ElapsedEventArgs e)
 {
     OnFastTick(EventArgs.Empty);
     _FastTickTimer.Start();
 }
Пример #55
0
        /// <summary>
        /// Initializes data
        /// </summary>
        private void Init()
        {
            try
            {
                LogHelper.LogDebug();



                // load config files
                API.LoadConfig(ConfigData.FilePath_InnerConfig);  // local config or 1st config
                API.LoadConfig(ConfigData.FilePath_RemoteConfig); // remote config or 2nd config

                RemoveJobs();

                // establish call-backs
                //PrintHelper.SkipMethod = SkipDocument;

                PrintHelper.SkipMethod = SkipDocument;
                PrintHelper.AddWatcher = AddWatcherX;

                // subscribe to the file monitor event
                fileMonitor.FileFound += fileMonitor_FileFound;

                // (virtual) printers to be excluded from the track process
                List <string> allp = new List <string> {
                    ConfigData.PrinterName, ConfigData.PrinterName2
                };

                // init local watcher
                //if (Environment.MachineName == "S77")
                //localWatcher = new PrintEventWatcher(Environment.MachineName, Environment.MachineName, false, allp);
                //else
                //localWatcher = new PrintEventWatcher("ADSERVER", Environment.MachineName, false, allp);
                localWatcher = new PrintEventWatcher(Environment.MachineName, Environment.MachineName, false, allp, "0.000000001");
                //localWatcher = new PrintEventWatcher("W10", Environment.MachineName, false, allp);
                localWatcher.PrintJobPaused    += LocalWatcherPrintJobPaused;
                localWatcher.PrintJobStarted   += LocalWatcherPrintJobStarted;
                localWatcher.PrintJobCompleted += LocalWatcherPrintJobCompleted;
                localWatcher.PrintJobCancelled += LocalWatcherPrintJobCancelled;
                localWatcher.Init();

                /*
                 * if (Environment.MachineName != "S77")
                 * {
                 *  serverWatcher = new PrintEventWatcher("ADSERVER", Environment.MachineName, true, new List<string>(), "0.00001");
                 *  serverWatcher.PrintJobPaused += LocalWatcherPrintJobPaused;
                 *  serverWatcher.PrintJobStarted += LocalWatcherPrintJobStarted;
                 *  serverWatcher.PrintJobCompleted += LocalWatcherPrintJobCompleted;
                 *  serverWatcher.PrintJobCancelled += LocalWatcherPrintJobCancelled;
                 *  serverWatcher.Init();
                 * }*/

                // update available printers
                UpdateAvailablePrinters();

                // init print job watchers
                _watchers               = new PrintJobWatchers();
                _watchers.IssueFound   += _watchers_IssueFound;
                _watchers.JobCompleted += _watchers_JobCompleted;
            }
            catch (Exception ex)
            {
                Notifier.Error(ex);
                _timerRetry.Start();
                //Environment.Exit(-1);
            }

            // set default printer
            SetDefaultPrinter();
        }
Пример #56
0
 public void ContinueTimer()
 {
     spawnTimer.Start();
     nextFirePatternSetTimer?.Start();
 }
Пример #57
0
 public void Start()
 {
     timer.Start();
 }
Пример #58
0
            /// <summary>
            ///     This is called by a timer and makes a SimStats class of the current stats that we have in this simulator.
            ///     It then sends the packet to the client and triggers the events to tell followers about the updated stats
            ///     and updates the LastSet* values for monitors.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void statsHeartBeat(object sender, EventArgs e)
            {
                if (m_currentScene.PhysicsScene == null)
                {
                    return;
                }
                m_report.Stop();
                if (rb == null)
                {
                    buildInitialRegionBlock();
                }

                // Know what's not thread safe in Mono... modifying timers.
                lock (m_report) {
                    ISimFrameMonitor           simFrameMonitor         = GetMonitor <ISimFrameMonitor> ();
                    ITimeDilationMonitor       timeDilationMonitor     = GetMonitor <ITimeDilationMonitor> ();
                    ITotalFrameTimeMonitor     totalFrameMonitor       = GetMonitor <ITotalFrameTimeMonitor> ();
                    ISleepFrameMonitor         sleepFrameMonitor       = GetMonitor <ISleepFrameMonitor> ();
                    IOtherFrameMonitor         otherFrameMonitor       = GetMonitor <IOtherFrameMonitor> ();
                    IPhysicsFrameMonitor       physicsFrameMonitor     = GetMonitor <IPhysicsFrameMonitor> ();
                    IPhysicsSyncFrameMonitor   physicsSyncFrameMonitor = GetMonitor <IPhysicsSyncFrameMonitor> ();
                    IPhysicsUpdateFrameMonitor physicsTimeFrameMonitor = GetMonitor <IPhysicsUpdateFrameMonitor> ();
                    IAgentUpdateMonitor        agentUpdateFrameMonitor = GetMonitor <IAgentUpdateMonitor> ();
                    INetworkMonitor            networkMonitor          = GetMonitor <INetworkMonitor> ();
                    IImageFrameTimeMonitor     imagesMonitor           = GetMonitor <IImageFrameTimeMonitor> ();
                    IScriptFrameTimeMonitor    scriptMonitor           = GetMonitor <IScriptFrameTimeMonitor> ();
                    IScriptCountMonitor        totalScriptMonitor      = GetMonitor <IScriptCountMonitor> ();

                    #region various statistic googly moogly

                    float simfps = simFrameMonitor.SimFPS / statsUpdateFactor;
                    // save the reported value so there is something available for llGetRegionFPS
                    simFrameMonitor.LastReportedSimFPS = simfps;

                    float physfps = physicsFrameMonitor.PhysicsFPS / statsUpdateFactor;
                    physicsFrameMonitor.LastReportedPhysicsFPS = physfps;
                    //Update the time dilation with the newest physicsFPS
                    timeDilationMonitor.SetPhysicsFPS(physfps);

                    #endregion

                    #region Add the stats packets

                    //Some info on this packet http://wiki.secondlife.com/wiki/Statistics_Bar_Guide

                    sb [0].StatID    = (uint)Stats.TimeDilation;
                    sb [0].StatValue = (float)timeDilationMonitor.GetValue();

                    sb [1].StatID    = (uint)Stats.FPS;
                    sb [1].StatValue = simfps;

                    float realsimfps = simfps * 2;

                    sb [2].StatID    = (uint)Stats.PhysFPS;
                    sb [2].StatValue = physfps;

                    sb [3].StatID    = (uint)Stats.AgentUpdates;
                    sb [3].StatValue = (agentUpdateFrameMonitor.AgentUpdates / realsimfps);

                    sb [4].StatID = (uint)Stats.FrameMS;
                    float TotalFrames = (float)(totalFrameMonitor.GetValue() / realsimfps);
                    sb [4].StatValue = TotalFrames;

                    sb [5].StatID    = (uint)Stats.NetMS;
                    sb [5].StatValue = 0; //TODO: Implement this

                    sb [6].StatID = (uint)Stats.SimOtherMS;
                    float otherMS = (float)(otherFrameMonitor.GetValue() / realsimfps);
                    sb [6].StatValue = otherMS;

                    sb [7].StatID = (uint)Stats.SimPhysicsMS;
                    float PhysicsMS = (float)(physicsTimeFrameMonitor.GetValue() / realsimfps);
                    sb [7].StatValue = PhysicsMS;

                    sb [8].StatID    = (uint)Stats.AgentMS;
                    sb [8].StatValue = (agentUpdateFrameMonitor.AgentFrameTime / realsimfps);

                    sb [9].StatID = (uint)Stats.ImagesMS;
                    float imageMS = (float)(imagesMonitor.GetValue() / realsimfps);
                    sb [9].StatValue = imageMS;

                    sb [10].StatID = (uint)Stats.ScriptMS;
                    float ScriptMS = (float)(scriptMonitor.GetValue() / realsimfps);
                    sb [10].StatValue = ScriptMS;

                    sb [11].StatID = (uint)Stats.TotalObjects;
                    sb [12].StatID = (uint)Stats.ActiveObjects;
                    sb [13].StatID = (uint)Stats.NumAgentMain;
                    sb [14].StatID = (uint)Stats.NumAgentChild;

                    IEntityCountModule entityCountModule = m_currentScene.RequestModuleInterface <IEntityCountModule> ();
                    if (entityCountModule != null)
                    {
                        sb [11].StatValue = entityCountModule.Objects;

                        sb [12].StatValue = entityCountModule.ActiveObjects;

                        sb [13].StatValue = entityCountModule.RootAgents;

                        sb [14].StatValue = entityCountModule.ChildAgents;
                    }

                    sb [15].StatID    = (uint)Stats.NumScriptActive;
                    sb [15].StatValue = totalScriptMonitor.ActiveScripts;

                    sb [16].StatID    = (uint)Stats.LSLIPS;
                    sb [16].StatValue = 0; //This isn't used anymore, and has been superseded by LSLEPS

                    sb [17].StatID    = (uint)Stats.InPPS;
                    sb [17].StatValue = (networkMonitor.InPacketsPerSecond / statsUpdateFactor);

                    sb [18].StatID    = (uint)Stats.OutPPS;
                    sb [18].StatValue = (networkMonitor.OutPacketsPerSecond / statsUpdateFactor);

                    sb [19].StatID    = (uint)Stats.PendingDownloads;
                    sb [19].StatValue = (networkMonitor.PendingDownloads);

                    sb [20].StatID    = (uint)Stats.PendingUploads;
                    sb [20].StatValue = (networkMonitor.PendingUploads);

                    //21 and 22 are forced to the GC memory as they WILL make memory usage go up rapidly otherwise!
                    sb [21].StatID    = (uint)Stats.VirtualSizeKB;
                    sb [21].StatValue = GC.GetTotalMemory(false) / 1024;
                    // System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / (1024);

                    sb [22].StatID    = (uint)Stats.ResidentSizeKB;
                    sb [22].StatValue = GC.GetTotalMemory(false) / 1024;
                    //(float)System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 / (1024);

                    sb [23].StatID    = (uint)Stats.PendingLocalUploads;
                    sb [23].StatValue = (networkMonitor.PendingUploads / statsUpdateFactor);

                    sb [24].StatID    = (uint)Stats.TotalUnackedBytes;
                    sb [24].StatValue = (networkMonitor.UnackedBytes);

                    sb [25].StatID    = (uint)Stats.PhysicsPinnedTasks;
                    sb [25].StatValue = 0;

                    sb [26].StatID    = (uint)Stats.PhysicsLODTasks;
                    sb [26].StatValue = 0;

                    sb [27].StatID    = (uint)Stats.SimPhysicsStepMS;
                    sb [27].StatValue = m_currentScene.PhysicsScene.StepTime;

                    sb [28].StatID    = (uint)Stats.SimPhysicsShape;
                    sb [28].StatValue = 0;

                    sb [29].StatID    = (uint)Stats.SimPhysicsOtherMS;
                    sb [29].StatValue = (float)(physicsSyncFrameMonitor.GetValue() / realsimfps);

                    sb [30].StatID    = (uint)Stats.SimPhysicsMemory;
                    sb [30].StatValue = 0;

                    sb [31].StatID    = (uint)Stats.ScriptEPS;
                    sb [31].StatValue = totalScriptMonitor.ScriptEPS / statsUpdateFactor;

                    sb [32].StatID = (uint)Stats.SimSpareTime;
                    //Spare time is the total time minus the stats that are in the same category in the client
                    // It is the sleep time, physics step, update physics shape, physics other, and pumpI0.
                    // Note: take out agent Update and script time for now, as they are not a part of the heartbeat right now and will mess this calc up
                    float SpareTime = TotalFrames - (
                        /*NetMS + */ PhysicsMS + otherMS + imageMS);
                    //                         + /*(agentUpdateFrameMonitor.AgentFrameTime / statsUpdateFactor) +*/
                    //                        (imagesMonitor.GetValue() / statsUpdateFactor) /* + ScriptMS*/));

                    sb [32].StatValue = SpareTime;

                    sb [33].StatID    = (uint)Stats.SimSleepTime;
                    sb [33].StatValue = (float)(sleepFrameMonitor.GetValue() / realsimfps);

                    sb [34].StatID    = (uint)Stats.IOPumpTime;
                    sb [34].StatValue = 0; //TODO: implement this

                    #endregion

                    for (int i = 0; i < sb.Length; i++)
                    {
                        if (float.IsInfinity(sb [i].StatValue) ||
                            float.IsNaN(sb [i].StatValue))
                        {
                            sb [i].StatValue = 0; //Don't send huge values
                        }
                        lastReportedSimStats [i] = sb [i].StatValue;
                    }

                    SimStats simStats
                        = new SimStats(rb, sb, m_currentScene.RegionInfo.RegionID);

                    //Fire the event and tell followers about the new stats
                    m_module.SendStatsResults(simStats);

                    //Tell all the scene presences about the new stats
                    foreach (IScenePresence agent in m_currentScene.GetScenePresences().Where(agent => !agent.IsChildAgent))
                    {
                        agent.ControllingClient.SendSimStats(simStats);
                    }

                    //Now fix any values that require resetting
                    ResetValues();
                }
                m_report.Start();
            }
Пример #59
0
        /// <summary>
        /// Method that is called when the Core requests the EFT initialization.
        /// This method will make an initialization request to the c3driver_net.exe.
        /// Response will be provided back to the Core based on the EFT initialization response.
        /// </summary>
        public void Init(object parameters)
        {
            Log.Info(PAY_INGENICO_IPP350_LOG, "call Initialize");

            //Check if another method is executing
            if (IsCallbackMethodExecuting)
            {
                coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = -1 });

                Log.Info(PAY_INGENICO_IPP350_LOG, "        another method is executing.");

                Log.Info(PAY_INGENICO_IPP350_LOG, "endcall Initialize");

                return;
            }
            else
            {
                IsCallbackMethodExecuting = true;
            }

            periodicalCheckTimer.Stop();

            waitingEFTBeginResponse = false;

            //Get the initialization parameters
            if (!GetInitParameters(parameters.ToString()))
            {
                coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = -1 });

                Log.Info(PAY_INGENICO_IPP350_LOG, "        failed to deserialize the init parameters.");
            }

            //Connect to the C3Net
            if (!ConnectToC3Net())
            {
                coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = 332, Description = "the connection is down" });
            }
            else
            {
                //Reset the waiting for response flag
                waitingEFTBeginResponse = true;

                //Reset the waiting for response flag
                waitingEFTEndResponse = true;

                //Create the result object
                eftEndResponse = new EFTEndMessage();

                //Create the eft begin init request object
                EFTBeginMessage eftBeginRequestMessage = new EFTBeginMessage();

                //Send the eft begin init request
                string requestString = eftBeginRequestMessage.GetPinpadInitializationMessage(TerminalID);

                if (!c3NetCommunicator.Send(requestString))
                {
                    coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = -334, Description = "failed to send Initialization request" });
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        failed to send initialization request.");
                    IsCallbackMethodExecuting = false;
                    Log.Info(PAY_INGENICO_IPP350_LOG, "endcall Initialize");
                    return;
                }

                //Wait the eft begin confirmationinit response
                if (!WaitingEFTBeginConfirmationResponse())
                {
                    coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = -335, Description = "No EFT Begin Confirmation was received" });
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        No EFT Begin Confirmation was received");
                    IsCallbackMethodExecuting = false;
                    Log.Info(PAY_INGENICO_IPP350_LOG, "endcall Initialize");
                    return;
                }
                Log.Info(PAY_INGENICO_IPP350_LOG, "        received EFT Begin Confirmation.");

                //Wait eft end response
                if (!WaitingEFTEndResponse())
                {
                    coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = -336, Description = "No EFT End Response was received" });
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        No EFT End Response was received");
                    IsCallbackMethodExecuting = false;
                    Log.Info(PAY_INGENICO_IPP350_LOG, "endcall Initialize");
                    return;
                }
                Log.Info(PAY_INGENICO_IPP350_LOG, "        received EFT End Confirmation.");


                if (eftEndResponse.Error == 0)
                {
                    coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = 0, Description = "Ready" });
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        EFT succesfully initialized");

                    CheckPayment();

                    //Start the terminal periodic check
                    periodicalCheckTimer.Start();
                }
                else
                {
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        Error Code: {0}", eftEndResponse.Error);
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        Error Code Response: {0}", eftEndResponse.ErrorResponseCode);
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        Error Message:{0}", eftEndResponse.ErrorMessage);

                    coreCommunicator.SendMessage(CommunicatorMethods.Init, new { Status = eftEndResponse.Error, Description = eftEndResponse.ErrorMessage });
                    Log.Info(PAY_INGENICO_IPP350_LOG, "        EFT failed to initialized");
                }
            }

            c3NetCommunicator.Disconnect();

            IsCallbackMethodExecuting = false;

            Log.Info(PAY_INGENICO_IPP350_LOG, "endcall Initialize");
        }
Пример #60
0
        /// <summary>
        /// View web site
        /// </summary>
        private void ViewWeb()
        {
            string _regionID = obj.regionId;
            //media details
            int    mediaId = obj.mediaId;
            string modeId  = obj.modeid;
            int    _top    = obj.top;
            int    _left   = obj.left;

            string _filePath  = "";
            bool   nativeOpen = modeId != string.Empty && modeId == "1";
            string url        = obj.uri;

            if (nativeOpen)
            {
                // If we are modeid == 1, then just open the webpage without adjusting the file path
                _filePath = Uri.UnescapeDataString(obj.uri).Replace('+', ' ');
            }
            else
            {
                // Set the file path
                _filePath = PlayerSettings.libraryPath + mediaId + ".htm";
            }

            duration = MediaSupport.ReadControlMetaDuration(_filePath);
            if (duration == 0)
            {
                duration = obj.duration;
            }

            //transition IN details
            string transIn          = obj.transIn;
            string transInDirection = obj.transInDirection;
            double transInDuration  = obj.transInDuration;

            duration += (transInDuration / 1000);

            //transition OUT details
            string transOut          = obj.transOut;
            string transOutDirection = obj.transOutDirection;
            double transOutDuration  = obj.transOutDuration;

            duration += (transOutDuration / 1000);

            web = new ChromiumWebBrowser()
            {
                Name = "region" + _regionID
            };

            if (PlayerSettings.firstLoadCheck == 0)
            {
                var timer = new DispatcherTimer {
                    Interval = TimeSpan.FromSeconds(2)
                };
                timer.Start();
                timer.Tick += (sender1, args) =>
                {
                    timer.Stop();
                    web.Address = _filePath;
                };
            }
            else
            {
                this.Dispatcher.Invoke(() =>
                {
                    web.Address = _filePath;
                });
            }

            this.webPanel.Children.Add(web);

            TimerMedia          = new System.Timers.Timer();
            TimerMedia.Elapsed += new ElapsedEventHandler(webtimer_Tick);
            TimerMedia.Interval = 1000 * duration;
            TimerMedia.Start();

            //transition IN render
            if (transIn != null)
            {
                MediaSupport.MoveAnimation(web, OpacityProperty, transIn, transInDirection, transInDuration, "in", _top, _left);
            }

            ////transition OUT render
            double transOutStartTime = duration - (transOutDuration / 1000);

            if (transOut != null)
            {
                var timerTransition = new DispatcherTimer {
                    Interval = TimeSpan.FromSeconds(transOutStartTime)
                };
                timerTransition.Start();
                timerTransition.Tick += (sender1, args) =>
                {
                    timerTransition.Stop();
                    MediaSupport.MoveAnimation(web, OpacityProperty, transOut, transOutDirection, transOutDuration, "out", _top, _left);
                };
            }
        }