private void WaitForSignal()
 {
     _autoEvent?.Reset();
     _autoEvent = new AutoResetEvent(false);
     _autoEvent.WaitOne();
     _autoEvent = null;
 }
示例#2
0
 public void SetReset()
 {
     using (AutoResetEvent are = new AutoResetEvent(false))
     {
         Assert.False(are.WaitOne(0));
         are.Set();
         Assert.True(are.WaitOne(0));
         Assert.False(are.WaitOne(0));
         are.Set();
         are.Reset();
         Assert.False(are.WaitOne(0));
     }
 }
示例#3
0
    public bool PosTest1()
    {
        bool           retVal = true;
        AutoResetEvent are;
	long           ticksBefore;
	long           ticksAfter;

        TestLibrary.TestFramework.BeginScenario("PosTest1: AutoResetEvent.Reset()");

        try
        {
            // true means that the initial state should be signaled
            are = new AutoResetEvent(true);
 
            if (!are.Reset())
            {
                TestLibrary.TestFramework.LogError("001", "AutoResetEvent.Reset() failed");
                retVal = false;
            }

            ticksBefore = DateTime.Now.Ticks;

            // verify that the autoreset event is signaled
            // if it is not signaled the following call will block for ever
            TestLibrary.TestFramework.LogInformation("Calling AutoResetEvent.WaitOne()... if the event is signaled it will not wait long enough");
            are.WaitOne(c_MILLISECONDS_TOWAIT);

            ticksAfter = DateTime.Now.Ticks;

            if (c_DELTA < Math.Abs((ticksAfter - ticksBefore) - (c_MILLISECONDS_TOWAIT*10000)))
            {
                TestLibrary.TestFramework.LogError("002", "AutoResetEvent did not wait long enough... this implies that the parameter was not respected.");
                TestLibrary.TestFramework.LogError("002", " WaitTime=" + (ticksAfter-ticksBefore) + " (ticks)");
                TestLibrary.TestFramework.LogError("002", " Execpted=" + (c_MILLISECONDS_TOWAIT*10000) + " (ticks)");
                TestLibrary.TestFramework.LogError("002", " Acceptable Delta=" + c_DELTA + " (ticks)");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
        public void ProcessBody(Body body, HttpListenerContext ctx)
        {
            try
            {
                IdleWatcher.UpdateTimeout(Id, TimeSpan.MaxValue);

                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (ctx == null)
                {
                    throw new ArgumentNullException("httpContext");
                }

                log.DebugFormat("Start process body connection {0}\r\n{1}\r\n", Id, body);

                if (!ValidateBody(body))
                {
                    BoshXmppHelper.TerminateBoshSession(ctx, "bad-request");
                    return;
                }
                if (body.Type == BoshType.terminate)
                {
                    Close();
                    ctx.Response.Close();
                    return;
                }

                waitDrop.Set();
                waitDrop.Reset();

                ReadBodyHeaders(body);

                if (string.IsNullOrEmpty(body.Sid) || body.XmppRestart)
                {
                    InvokeStreamStart(body);
                }
                foreach (var node in body.ChildNodes)
                {
                    if (node is Element)
                    {
                        InvokeStreamElement((Element)node);
                    }
                }

                WriteBodyHeaders(body);

                log.DebugFormat("Connection {0} WAIT ...", Id);
                var waitResult = WaitAnswerOrDrop();

                if (waitResult == WaitResult.Success)
                {
                    log.DebugFormat("Connection {0} send answer", Id);
                    SendAnswer(body, ctx);
                }
                else if (waitResult == WaitResult.Timeout)
                {
                    log.DebugFormat("Connection {0} drop by timeout", Id);
                    BoshXmppHelper.SendAndCloseResponse(ctx, new Body().ToString());
                }
                else
                {
                    log.DebugFormat("Connection {0} terminate", Id);
                    BoshXmppHelper.TerminateBoshSession(ctx, body);
                }
            }
            finally
            {
                IdleWatcher.UpdateTimeout(Id, inactivityPeriod);
            }
        }
        public static void InterruptTest()
        {
            // Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets
            // interrupted
            var threadReady = new AutoResetEvent(false);
            var continueThread = new AutoResetEvent(false);
            bool continueThreadBool = false;
            Action waitForThread;
            var t =
                ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                {
                    threadReady.Set();
                    ThreadTestHelpers.WaitForConditionWithoutBlocking(() => Volatile.Read(ref continueThreadBool));
                    threadReady.Set();
                    Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait());
                });
            t.IsBackground = true;
            t.Start();
            threadReady.CheckedWait();
            t.Interrupt();
            Assert.False(threadReady.WaitOne(ExpectedTimeoutMilliseconds));
            Volatile.Write(ref continueThreadBool, true);
            waitForThread();

            // Interrupting a dead thread does nothing
            t.Interrupt();

            // Interrupting an unstarted thread causes the thread to be interrupted after it is started and starts blocking
            t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                    Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
            t.IsBackground = true;
            t.Interrupt();
            t.Start();
            waitForThread();

            // A thread that is already blocked on a synchronization primitive unblocks immediately
            continueThread.Reset();
            t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
                    Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()));
            t.IsBackground = true;
            t.Start();
            ThreadTestHelpers.WaitForCondition(() => (t.ThreadState & ThreadState.WaitSleepJoin) != 0);
            t.Interrupt();
            waitForThread();
        }
 private void PauseIfNeeded_()
 {
     innerDebugLock_?.WaitOne();
     outerDebugLock_?.Reset();
 }
示例#7
0
 //pausar letras
 private void pausarB_Click(object sender, EventArgs e)
 {
     pausar = true;
     _pauseEvent.Reset();
 }
示例#8
0
 /// <summary>
 /// Loads a PDF from disk given the requested filename.
 /// </summary>
 /// <param name="filename">The filename of the PDF.</param>
 public void LoadPDF(string filename)
 {
     pdfLoadEvent.Reset();
     LoadPDFAsync(filename);
     pdfLoadEvent.WaitOne();
 }
        /// <summary> Starts capturing and processing video frames. </summary>
        /// <param name="frameGrabDelay"> The frame grab delay. </param>
        /// <param name="timestampFn">    Function to generate the timestamp for each frame. This
        ///     function will get called once per frame. </param>
        protected void StartProcessing(TimeSpan frameGrabDelay, Func <DateTime> timestampFn)
        {
            OnProcessingStarting();

            _resetTrigger = true;
            _frameGrabTimer.Reset();
            _analysisTaskQueue = new BlockingCollection <Task <NewResultEventArgs> >();

            var timerIterations = 0;

            // Create a background thread that will grab frames in a loop.
            _producerTask = Task.Factory.StartNew(() =>
            {
                var frameCount = 0;
                while (!_stopping)
                {
                    LogMessage("Producer: waiting for timer to trigger frame-grab");

                    // Wait to get released by the timer.
                    _frameGrabTimer.WaitOne();
                    LogMessage("Producer: grabbing frame...");

                    var startTime = DateTime.Now;

                    // Grab single frame.
                    var timestamp = timestampFn();
                    Mat image     = new Mat();
                    bool success  = _reader.Read(image);

                    LogMessage("Producer: frame-grab took {0} ms", (DateTime.Now - startTime).Milliseconds);

                    if (!success)
                    {
                        // If we've reached the end of the video, stop here.
                        if (_reader.CaptureType == CaptureType.File)
                        {
                            LogMessage("Producer: null frame from video file, stop!");
                            // This will call StopProcessing on a new thread.
                            var stopTask = StopProcessingAsync();
                            // Break out of the loop to make sure we don't try grabbing more
                            // frames.
                            break;
                        }
                        else
                        {
                            // If failed on live camera, try again.
                            LogMessage("Producer: null frame from live camera, continue!");
                            continue;
                        }
                    }

                    // Package the image for submission.
                    VideoFrameMetadata meta;
                    meta.Index        = frameCount;
                    meta.Timestamp    = timestamp;
                    VideoFrame vframe = new VideoFrame(image, meta);

                    // Raise the new frame event
                    LogMessage("Producer: new frame provided, should analyze? Frame num: {0}", meta.Index);
                    OnNewFrameProvided(vframe);

                    if (_analysisPredicate(vframe))
                    {
                        LogMessage("Producer: analyzing frame");

                        // Call the analysis function on a threadpool thread
                        var analysisTask = DoAnalyzeFrame(vframe);

                        LogMessage("Producer: adding analysis task to queue {0}", analysisTask.Id);

                        // Push the frame onto the queue
                        _analysisTaskQueue.Add(analysisTask);
                    }
                    else
                    {
                        LogMessage("Producer: not analyzing frame");
                    }

                    LogMessage("Producer: iteration took {0} ms", (DateTime.Now - startTime).Milliseconds);

                    ++frameCount;
                }

                LogMessage("Producer: stopping, destroy reader and timer");
                _analysisTaskQueue.CompleteAdding();

                // We reach this point by breaking out of the while loop. So we must be stopping.
                _reader.Dispose();
                _reader = null;

                // Make sure the timer stops, then get rid of it.
                var h = new ManualResetEvent(false);
                _timer.Dispose(h);
                h.WaitOne();
                _timer = null;

                LogMessage("Producer: stopped");
            }, TaskCreationOptions.LongRunning);

            _consumerTask = Task.Factory.StartNew(async() =>
            {
                while (!_analysisTaskQueue.IsCompleted)
                {
                    LogMessage("Consumer: waiting for task to get added");

                    // Get the next processing task.
                    Task <NewResultEventArgs> nextTask = null;

                    // Blocks if m_analysisTaskQueue.Count == 0
                    // IOE means that Take() was called on a completed collection.
                    // Some other thread can call CompleteAdding after we pass the
                    // IsCompleted check but before we call Take.
                    // In this example, we can simply catch the exception since the
                    // loop will break on the next iteration.
                    // See https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx
                    try
                    {
                        nextTask = _analysisTaskQueue.Take();
                    }
                    catch (InvalidOperationException) { }

                    if (nextTask != null)
                    {
                        // Block until the result becomes available.
                        LogMessage("Consumer: waiting for next result to arrive for task {0}", nextTask.Id);
                        var result = await nextTask;

                        // Raise the new result event.
                        LogMessage("Consumer: got result for frame {0}. {1} tasks in queue", result.Frame.Metadata.Index, _analysisTaskQueue.Count);
                        OnNewResultAvailable(result);
                    }
                }

                LogMessage("Consumer: stopped");
            }, TaskCreationOptions.LongRunning);

            // Set up a timer object that will trigger the frame-grab at a regular interval.
            _timer = new Timer(async s /* state */ =>
            {
                await _timerMutex.WaitAsync();
                try
                {
                    // If the handle was not reset by the producer, then the frame-grab was missed.
                    bool missed = _frameGrabTimer.WaitOne(0);

                    _frameGrabTimer.Set();

                    if (missed)
                    {
                        LogMessage("Timer: missed frame-grab {0}", timerIterations - 1);
                    }
                    LogMessage("Timer: grab frame num {0}", timerIterations);
                    ++timerIterations;
                }
                finally
                {
                    _timerMutex.Release();
                }
            }, null, TimeSpan.Zero, frameGrabDelay);

            OnProcessingStarted();
        }
示例#10
0
        private void ProcessReceivedData()
        {
            byte command          = 0;
            byte multiByteChannel = 0;
            int  dataNeeded       = 0;
            byte multiByteCommand = 0;
            bool parsingSysex     = false;

            while (true)
            {
                try
                {
                    if (_input.Size == 0)
                    {
                        _haveDataEvent.WaitOne();
                    }

                    command = 0;
                    byte b = _input.Get();
                    if (parsingSysex)
                    {
                        if (b == (byte)CommandCode.END_SYSEX)
                        {
                            parsingSysex = false;
                            ProcessSysexMessage();
                        }
                        else
                        {
                            if (_cbInputMessage < _inputMessage.Length)
                            {
                                _inputMessage[_cbInputMessage++] = b;
                            }
                        }
                    }
                    else if (dataNeeded > 0 && b < 128)
                    {
                        _inputMessage[--dataNeeded] = b;
                        if (dataNeeded == 0 && multiByteCommand != 0)
                        {
                            switch (multiByteCommand)
                            {
                            case (byte)CommandCode.ANALOG_MESSAGE:
                                _board.ProcessAnalogMessage(multiByteChannel, _inputMessage[0] << 7 | _inputMessage[1]);
                                break;

                            case (byte)CommandCode.DIGITAL_MESSAGE:
                                _board.ProcessDigitalMessage(multiByteChannel, _inputMessage[0] << 7 | _inputMessage[1]);
                                break;

                            case (byte)CommandCode.SET_PIN_MODE:
                                _board.SetPinMode(_inputMessage[1], _inputMessage[0] << 7 | _inputMessage[1]);
                                break;

                            case (byte)CommandCode.REPORT_ANALOG:
                                _board.ReportAnalog(multiByteChannel, _inputMessage[0] << 7 | _inputMessage[1]);
                                break;

                            case (byte)CommandCode.REPORT_DIGITAL:
                                _board.ReportDigital(multiByteChannel, _inputMessage[0] << 7 | _inputMessage[1]);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (b < 0xf0)
                        {
                            command          = (byte)(b & 0xf0);
                            multiByteChannel = (byte)(b & 0x0F);
                        }
                        else
                        {
                            command = b;
                        }
                    }

                    switch (command)
                    {
                    case (byte)CommandCode.ANALOG_MESSAGE:
                    case (byte)CommandCode.DIGITAL_MESSAGE:
                    case (byte)CommandCode.SET_PIN_MODE:
                    case (byte)CommandCode.REPORT_ANALOG:
                    case (byte)CommandCode.REPORT_DIGITAL:
                        dataNeeded       = 2;
                        multiByteCommand = command;
                        break;

                    case (byte)CommandCode.START_SYSEX:
                        parsingSysex    = true;
                        _cbInputMessage = 0;
                        break;

                    case (byte)CommandCode.SYSTEM_RESET:
                        // reset the input parsing state machine
                        multiByteChannel = 0;
                        dataNeeded       = 0;
                        multiByteCommand = 0;
                        parsingSysex     = false;
                        _cbInputMessage  = 0;
                        Array.Clear(_inputMessage, 0, _inputMessage.Length);
                        _board.Reset();
                        break;

                    case (byte)CommandCode.REPORT_VERSION:
                        SendVersion();
                        break;

                    default:
                        break;
                    }

                    _haveDataEvent.Reset();
                }
                catch
                {
                }
            }
        }
示例#11
0
文件: BatchTask.cs 项目: zgren/dp2
        // 工作线程
        public virtual void ThreadMain()
        {
            try
            {
                WaitHandle[] events = new WaitHandle[2];

                events[0] = eventClose;
                events[1] = eventActive;

                while (true)
                {
                    int index = 0;
                    try
                    {
                        index = WaitHandle.WaitAny(events, PerTime, false);
                    }
                    catch (System.Threading.ThreadAbortException /*ex*/)
                    {
                        /*
                         * // 调试用
                         * LibraryApplication.WriteWindowsLog("BatchTask俘获了ThreadAbortException异常", EventLogEntryType.Information);
                         * */
                        this.App.Save(null, false);    // 触发保存
                        this.App.WriteErrorLog("刚才是ThreadAbortException触发了配置文件保存");
                        break;
                    }

                    if (index == WaitHandle.WaitTimeout)
                    {
                        // 超时
                        eventActive.Reset();
                        Worker();
                        eventActive.Reset();    // 2013/11/23 只让堵住的时候发挥作用
                    }
                    else if (index == 0)
                    {
                        break;
                    }
                    else
                    {
                        // 得到激活信号
                        eventActive.Reset();
                        Worker();
                        eventActive.Reset();    // 2013/11/23 只让堵住的时候发挥作用
                    }

                    // 是否循环?
                    if (this.Loop == false)
                    {
                        break;
                    }
                }
                this.ManualStart = false;   // 这个变量只在一轮处理中管用
            }
            catch (Exception ex)
            {
                string strErrorText = "BatchTask工作线程出现异常: " + ExceptionUtil.GetDebugText(ex);
                try
                {
                    this.App.WriteErrorLog(strErrorText);
                    this.AppendResultText(strErrorText + "\r\n");
                }
                catch
                {
                    LibraryApplication.WriteWindowsLog(strErrorText);
                }
            }
            finally
            {
                // 2009/7/16 移动到这里
                try
                {
                    eventFinished.Set();
                    eventStarted.Set();         // 2017/8/23
                }
                catch (ObjectDisposedException) // 2016/4/19
                {
                }

                // 2009/7/16 新增
                // this.m_bClosed = true;
                this.Stopped = true;
            }
        }
示例#12
0
        private void FilenameSuggestionWorker()
        {
            var numericPatternPartParser = new Regex(@"%(?<n>n+)(?<d>\d*)%");

            do
            {
                string originalFilename  = null;
                string suggestionPattern = null;
                int    startNumber       = 1;
                bool   hasNumericPart    = false;

                // Wait to be signalled that the suggestion pattern has changed
                mFilenameSuggestionTrigger.WaitOne();
                Dispatcher.Invoke(DispatcherPriority.Send, new ThreadStart(delegate
                {
                    // Get the current path pattern and reset the trigger. If it changes again, the trigger will be set again so a new suggestion is generated.
                    // As this takes place in a single dispatched block, the pattern can't change between being read and the trigger being reset (as pattern changing is also dispatched).
                    originalFilename  = Filename;
                    suggestionPattern = mSuggestedFilenamePattern.PathPattern;
                    mFilenameSuggestionTrigger.Reset();
                }));

                suggestionPattern = Common.MakeSafeForPath(suggestionPattern);

                // Substitute the %filename% and %extension% parameters with {0} and {2} for string format.
                suggestionPattern = suggestionPattern.Replace("%filename%", "{0}").Replace("%extension%", "{2}");

                // Parse the numeric part of the suggestion, and replace with string formatters
                suggestionPattern = numericPatternPartParser.Replace(suggestionPattern, new MatchEvaluator(delegate(Match match)
                {
                    hasNumericPart = true;

                    if (match.Groups["d"].Length > 0)
                    {
                        Int32.TryParse(match.Groups["d"].Value, out startNumber);
                    }
                    return("{1:" + new String('0', match.Groups["n"].Length) + "}");
                }));

                string extension = Path.GetExtension(originalFilename);
                string originalFilenameNoExtension = originalFilename.Substring(0, originalFilename.Length - extension.Length);
                if (extension.Length > 1)
                {
                    extension = extension.Substring(1);                     // Remove the .
                }

                // Find the next filename that can match
                int    i = startNumber;
                string suggestedFilename;
                do
                {
                    suggestedFilename = String.Format(System.Globalization.CultureInfo.CurrentUICulture, suggestionPattern, originalFilenameNoExtension, i++, extension);
                } while (hasNumericPart && File.Exists(suggestedFilename));                 //If there's no numeric part, we can't vary to suggest other filenames anyway, so don't look further.

                // Found a filename, so present it
                Dispatcher.Invoke(DispatcherPriority.DataBind, new ThreadStart(delegate
                {
                    SuggestedFilename = suggestedFilename;
                    NotifyPropertyChanged("SuggestedFilename");
                }));
            } while (true);
        }
示例#13
0
        private static bool ReloadAppDomain()
        {
            if (!GameThreadHelper.IsInGameThread())
            {
                bool result = false;
                GameThreadHelper.Run(delegate { result = ReloadAppDomain(); });
                return(result);
            }

            if (!File.Exists(assemblyPath))
            {
                hotreloadData = null;
                return(false);
            }

            if (appDomain != null)
            {
                UnloadAppDomain();
            }

            if (LoadAssemblyWithoutAppDomain)
            {
                try
                {
                    AssemblyLoader loader = new AssemblyLoader(assemblyPath, entryPointType, entryPointMethod, entryPointArg, hotreloadData, false);
                    loader.Load();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Failed to load assembly \"" + assemblyPath + "\" " +
                                    Environment.NewLine + Environment.NewLine + e, errorMsgBoxTitle);
                    hotreloadData = null;
                    return(false);
                }
            }
            else
            {
                string entryPointArgEx = entryPointArg;
                bool   firstLoad       = preloadAppDomainWaitHandle == null;
                if (firstLoad)
                {
                    PreloadNextAppDomain(true);
                }
                else
                {
                    entryPointArgEx += "|Reloading=true";
                }

                preloadAppDomainWaitHandle.WaitOne(Timeout.Infinite);
                preloadAppDomainWaitHandle.Reset();

                if (!preloadFailed)
                {
                    appDomain        = preloadAppDomain;
                    preloadAppDomain = null;

                    try
                    {
                        AssemblyLoader loader = new AssemblyLoader(assemblyPath, entryPointType, entryPointMethod, entryPointArgEx, hotreloadData, false);
                        appDomain.DoCallBack(loader.Load);
                        UpdateAssemblyWatchers(appDomain.GetData(hotReloadAssemblyPathsName) as string[]);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Failed to create AppDomain for \"" + assemblyPath + "\" " +
                                        Environment.NewLine + Environment.NewLine + e, errorMsgBoxTitle);
                    }
                }
            }

            if (!LoadAssemblyWithoutAppDomain)
            {
                PreloadNextAppDomain(false);
            }
            hotreloadData = null;
            return(true);
        }
示例#14
0
        /// <summary>
        /// Called for each time the timer ticks.
        /// </summary>
        /// <param name="State"></param>
        public void Run(object State)
        {
            try
            {
                if (_disabled)
                {
                    return;
                }

                if (_timerRunning)
                {
                    _timerLagging = true;
                    log.Warn("<Player " + _player.Id + "> Server can't keep up, Player timer is lagging behind.");
                    return;
                }

                _resetEvent.Reset();

                // BEGIN CODE

                #region Muted Checks
                if (_player.TimeMuted > 0)
                {
                    _player.TimeMuted -= 60;
                }
                #endregion

                #region Console Checks
                if (_player.MessengerSpamTime > 0)
                {
                    _player.MessengerSpamTime -= 60;
                }
                if (_player.MessengerSpamTime <= 0)
                {
                    _player.MessengerSpamCount = 0;
                }
                #endregion

                _player.TimeAFK += 1;

                #region Respect checking
                if (_player.GetStats().RespectsTimestamp != DateTime.Today.ToString("MM/dd"))
                {
                    _player.GetStats().RespectsTimestamp = DateTime.Today.ToString("MM/dd");
                    using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                    {
                        dbClient.RunQuery("UPDATE `user_stats` SET `dailyRespectPoints` = '" + (_player.Rank == 1 && _player.VIPRank == 0 ? 10 : _player.VIPRank == 1 ? 15 : 20) + "', `dailyPetRespectPoints` = '" + (_player.Rank == 1 && _player.VIPRank == 0 ? 10 : _player.VIPRank == 1 ? 15 : 20) + "', `respectsTimestamp` = '" + DateTime.Today.ToString("MM/dd") + "' WHERE `id` = '" + _player.Id + "' LIMIT 1");
                    }

                    _player.GetStats().DailyRespectPoints    = (_player.Rank == 1 && _player.VIPRank == 0 ? 10 : _player.VIPRank == 1 ? 15 : 20);
                    _player.GetStats().DailyPetRespectPoints = (_player.Rank == 1 && _player.VIPRank == 0 ? 10 : _player.VIPRank == 1 ? 15 : 20);

                    if (_player.GetClient() != null)
                    {
                        _player.GetClient().SendPacket(new UserObjectComposer(_player));
                    }
                }
                #endregion

                #region Reset Scripting Warnings
                if (_player.GiftPurchasingWarnings < 15)
                {
                    _player.GiftPurchasingWarnings = 0;
                }

                if (_player.MottoUpdateWarnings < 15)
                {
                    _player.MottoUpdateWarnings = 0;
                }

                if (_player.ClothingUpdateWarnings < 15)
                {
                    _player.ClothingUpdateWarnings = 0;
                }
                #endregion


                if (_player.GetClient() != null)
                {
                    PlusEnvironment.GetGame().GetAchievementManager().ProgressAchievement(_player.GetClient(), "ACH_AllTimeHotelPresence", 1);
                }

                _player.CheckCreditsTimer();
                _player.Effects().CheckEffectExpiry(_player);

                // END CODE

                // Reset the values
                _timerRunning = false;
                _timerLagging = false;

                _resetEvent.Set();
            }
            catch { }
        }
示例#15
0
 private void Start()
 {
     wait.Reset();
 }
示例#16
0
        private static void SyncThread()
        {
            running = 1;
            //mainForm.LogLine("Starting EDDN sync thread");

            while (hlscanunsyncedlist.Count != 0)
            {
                HistoryEntry he = null;

                int eventcount = 0;

                while (hlscanunsyncedlist.TryDequeue(out he))
                {
                    try
                    {
                        hlscanevent.Reset();

                        TimeSpan age = he.AgeOfEntry();

                        if (age.Days >= 1 && he.EntryType != EliteDangerousCore.JournalTypeEnum.Scan)
                        {
                            System.Diagnostics.Debug.WriteLine("EDDN: Ignoring entry due to age");
                        }
                        else
                        {
                            bool?res = EDDNSync.SendToEDDN(he);

                            if (res != null)    // if attempted to send
                            {
                                if (res.Value == true)
                                {
                                    logger?.Invoke($"Sent {he.EntryType.ToString()} event to EDDN ({he.EventSummary})");
                                    eventcount++;
                                }
                                else
                                {
                                    logger?.Invoke($"Failed sending {he.EntryType.ToString()} event to EDDN ({he.EventSummary})");
                                }
                            }
                            else
                            {
                                continue; // skip the 1 second delay if nothing was sent
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                        System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.StackTrace);
                        logger?.Invoke("EDDN sync Exception " + ex.Message + Environment.NewLine + ex.StackTrace);
                    }

                    if (Exit)
                    {
                        running = 0;
                        return;
                    }

                    Thread.Sleep(1000);   // Throttling to 1 per second to not kill EDDN network
                }

                SentEvents?.Invoke(eventcount);     // tell the system..

                if (hlscanunsyncedlist.IsEmpty)     // if nothing there..
                {
                    hlscanevent.WaitOne(60000);     // Wait up to 60 seconds for another EDDN event to come in
                }
                if (Exit)
                {
                    break;
                }
            }

            running = 0;
        }
        /* this function translates a target IP address into a destination physical address
         * NOTE: if the address could not be translated, the function returns zero. */
        internal UInt64 TranslateIPAddressToPhysicalAddress(UInt32 ipAddress, Int64 timeoutInMachineTicks)
        {
            // if the ipAdderss is the broadcast address, return a broadcast MAC address
            if (ipAddress == 0xFFFFFFFF)
            {
                return(ETHERNET_BROADCAST_ADDRESS);
            }

            ArpCacheEntry arpEntry = null;

            // retrieve our existing ARP entry, if it exists
            lock (_arpCacheLock)
            {
                arpEntry = (ArpCacheEntry)_arpCache[ipAddress];

                // if we retrieved an entry, make sure it has not timed out.
                if (arpEntry != null)
                {
                    Int64 nowTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks;
                    if (arpEntry.TimeoutTicks < nowTicks)
                    {
                        // if the entry has timed out, dispose of it; we will re-query the target
                        _arpCache.Remove(ipAddress);
                        arpEntry = null;
                    }
                }
            }

            // if we were caching a valid ARP entry, return its PhysicalAddress now.
            if (arpEntry != null)
            {
                return(arpEntry.PhysicalAddress);
            }

            // if we did not obtain a valid ARP entry, query for one now.
            lock (_simultaneousArpRequestLock) /* lock our current ARP request...we can only have one request at a time. */
            {
                Int32 waitTimeout;
                for (int iAttempt = 0; iAttempt < MAX_ARP_TRANSLATE_ATTEMPTS; iAttempt++)
                {
                    // set the IP Address of our current ARP request
                    _currentArpRequestProtocolAddress = ipAddress;
                    _currentArpRequestPhysicalAddress = 0; // this will be set to a non-zero value if we get a response
                    _currentArpRequestAnsweredEvent.Reset();
                    // send the ARP request
                    SendArpRequest(ipAddress, timeoutInMachineTicks);
                    // wait on a reply (for up to our timeout time or 1 second...whichever is less)
                    waitTimeout = System.Math.Min((Int32)((timeoutInMachineTicks != Int64.MaxValue) ? Math.Max((timeoutInMachineTicks - Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks) / System.TimeSpan.TicksPerMillisecond, 0) : 1000), 1000);
                    _currentArpRequestAnsweredEvent.WaitOne(waitTimeout, false);

                    // if we received an ARP reply, add it to our cache table
                    try
                    {
                        if (_currentArpRequestPhysicalAddress != 0)
                        {
                            lock (_arpCacheLock)
                            {
                                // first make sure that our cache table is not full; if it is full then remove the oldest entry (based on LastUsedTime)
                                if (_arpCache.Count >= ARP_CACHE_MAXIMUM_ENTRIES)
                                {
                                    Int64  oldestLastUsedTicks = Int64.MaxValue;
                                    UInt32 oldestKey           = 0;
                                    foreach (UInt32 key in _arpCache.Keys)
                                    {
                                        if (((ArpCacheEntry)_arpCache[key]).LastUsedTicks < oldestLastUsedTicks)
                                        {
                                            oldestKey           = key;
                                            oldestLastUsedTicks = ((ArpCacheEntry)_arpCache[key]).LastUsedTicks;
                                        }
                                    }
                                    _arpCache.Remove(oldestKey);
                                }

                                // then add our new cache entry and return the ARP reply's address.
                                Int64 nowTicks = Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks;
                                arpEntry = new ArpCacheEntry(_currentArpRequestPhysicalAddress, nowTicks + (TimeSpan.TicksPerSecond * DEFAULT_ARP_CACHE_TIMEOUT_IN_SECONDS), nowTicks);
                                _arpCache.Add(_currentArpRequestProtocolAddress, arpEntry);
                            }
                            return(_currentArpRequestPhysicalAddress);
                        }

                        // if we're out of (user-specified) time without a reply, return zero (no address).
                        if (Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks > timeoutInMachineTicks)
                        {
                            return(0);
                        }
                    }
                    finally
                    {
                        _currentArpRequestProtocolAddress = 0; // no ARP request is in process now.
                    }
                }
            }

            // if we could not get the address of the target, return zero.
            return(0);
        }
示例#18
0
 private void button44_Click(object sender, EventArgs e)
 {
     if (tbIncrement.Text.Length != 0)
     {
         Int16 value = Convert.ToInt16(tbIncrement.Text);
         z3coor += value;
         DynamixelCom.sendPositionToMoveTo((Int16)z3coor);
         wait.Reset();
         wait.WaitOne();
         updatePositions();
         //move("Z3", z3coor);
     }
 }
示例#19
0
        private void m_buttonFile_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog fileDialog = new OpenFileDialog
                {
                    Multiselect     = false,
                    CheckFileExists = true,
                    DefaultExt      = ".txt",
                    Filter          = ResString.GetEnumDisplayName(typeof(FileFilter), FileFilter.Txt)
                };
                if (fileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    string path = fileDialog.FileName;

                    if (!File.Exists(path) ||
                        numHBIndexW.SelectedIndex < 0 ||
                        headList.All(head => { return(!head.Checked); }) ||
                        abList.All(cbk => { return(!cbk.Checked); }))
                    {
                        MessageBox.Show(@"Input is wrong.");
                        return;
                    }
                    groupBox4.Enabled = false;
                    int             hbindex       = numHBIndexW.SelectedIndex;
                    string          info          = "";
                    HEAD_BOARD_TYPE headBoardType = (HEAD_BOARD_TYPE)CoreInterface.get_HeadBoardType(true);
                    byte[]          wfdata;
                    if (m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4A_RH06 || m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4B_YH06_5pl)
                    {
                        wfdata = PubFunc.GetAllDataFromFileKyocera_KJ4A_RH06_Des(path, ref info);
                        //wfdata = PubFunc.GetAllDataFromFileKyocera_KJ4A_RH06(m_UpdaterFileName);
                    }
                    else
                    {
                        wfdata = PubFunc.GetAllDataFromFileKyocera_Des(path, ref info);
                        //wfdata = PubFunc.GetAllDataFromFileKyocera(m_UpdaterFileName);
                    }
                    if (null == wfdata)
                    {
                        if (info == "")
                        {
                            MessageBox.Show("wavefrom file error!");
                            return;
                        }
                        else
                        {
                            MessageBox.Show(info);
                            return;
                        }
                    }
                    Task.Factory.StartNew(new Action(() =>
                    {
                        downloadEvent.Reset();
                        for (int i = 0; i < headList.Count; i++)
                        {
                            for (int j = 0; j < abList.Count; j++)
                            {
                                if (headList[i].Checked && abList[j].Checked)
                                {
                                    ColorEnum type = ColorEnum.Cyan;//(ColorEnum)(Enum.Parse(typeof(ColorEnum), m_Ctrls.InkGroupers[i].Text));
                                    Decimal saveID = hbindex * 8 + i * 2 + j;
                                    if (m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4A_TA06_6pl ||
                                        m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4A_RH06 ||
                                        m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4B_YH06_5pl ||
                                        m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4B_QA06_5pl ||
                                        m_printerProperty.ePrinterHead == PrinterHeadEnum.Kyocera_KJ4A_AA06_3pl)
                                    {
                                        saveID = hbindex * 4 + i;
                                    }
                                    //m_nHeadId = (int)saveID;
                                    {
                                        UpdateCoreBoard(wfdata, type, (byte)saveID);
                                        //progressBarStatu.Maximum = ++nCount;
                                    }
                                    downloadEvent.WaitOne();
                                    downloadEvent.Reset();
                                }
                            }
                        }
                        MessageBox.Show(@"Download complete");
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#20
0
 private void ParkingAdapter_ParkApaterReconnected(object sender, EventArgs e)
 {
     _ConnectFailEvent.Reset();
     _ConnectedOKEvent.Set();
     Ralid.GeneralLibrary.LOG.FileLog.Log("系统", "与服务器连接成功");
 }
示例#21
0
        //[Fact]
        // This test works locally, but fails in AppVeyor some of the time
        // TODO:  Work to identify why this happens...
        public void TestCallbacksOrder()
        {
            bool firstDisconnect = true;

            long orig = DateTime.Now.Ticks;

            long dtime1 = orig;
            long dtime2 = orig;
            long rtime  = orig;
            long atime1 = orig;
            long atime2 = orig;
            long ctime  = orig;

            AutoResetEvent reconnected = new AutoResetEvent(false);
            AutoResetEvent closed      = new AutoResetEvent(false);
            AutoResetEvent asyncErr1   = new AutoResetEvent(false);
            AutoResetEvent asyncErr2   = new AutoResetEvent(false);
            AutoResetEvent recvCh      = new AutoResetEvent(false);
            AutoResetEvent recvCh1     = new AutoResetEvent(false);
            AutoResetEvent recvCh2     = new AutoResetEvent(false);

            using (NATSServer s = utils.CreateServerWithConfig("auth_1222.conf"),
                   def = new NATSServer())
            {
                Options o = utils.DefaultTestOptions;

                o.DisconnectedEventHandler += (sender, args) =>
                {
                    Thread.Sleep(100);
                    if (firstDisconnect)
                    {
                        firstDisconnect = false;
                        dtime1          = DateTime.Now.Ticks;
                    }
                    else
                    {
                        dtime2 = DateTime.Now.Ticks;
                    }
                };

                o.ReconnectedEventHandler += (sender, args) =>
                {
                    Thread.Sleep(100);
                    rtime = DateTime.Now.Ticks;
                    reconnected.Set();
                };

                o.AsyncErrorEventHandler += (sender, args) =>
                {
                    Thread.Sleep(100);
                    if (args.Subscription.Subject.Equals("foo"))
                    {
                        atime1 = DateTime.Now.Ticks;
                        asyncErr1.Set();
                    }
                    else
                    {
                        atime2 = DateTime.Now.Ticks;
                        asyncErr2.Set();
                    }
                };

                o.ClosedEventHandler += (sender, args) =>
                {
                    ctime = DateTime.Now.Ticks;
                    closed.Set();
                };

                o.ReconnectWait    = 500;
                o.NoRandomize      = true;
                o.Servers          = new string[] { "nats://localhost:4222", "nats://localhost:1222" };
                o.SubChannelLength = 1;

                using (IConnection nc = new ConnectionFactory().CreateConnection(o),
                       ncp = utils.DefaultTestConnection)
                {
                    // On hosted environments, some threads/tasks can start before others
                    // due to resource constraints.  Allow time to start.
                    Thread.Sleep(1000);

                    def.Bounce(1000);

                    Thread.Sleep(1000);

                    Assert.True(reconnected.WaitOne(3000));

                    object asyncLock = new object();
                    EventHandler <MsgHandlerEventArgs> eh = (sender, args) =>
                    {
                        lock (asyncLock)
                        {
                            recvCh.Set();
                            if (args.Message.Subject.Equals("foo"))
                            {
                                recvCh1.Set();
                            }
                            else
                            {
                                recvCh2.Set();
                            }
                        }
                    };

                    IAsyncSubscription sub1 = nc.SubscribeAsync("foo", eh);
                    IAsyncSubscription sub2 = nc.SubscribeAsync("bar", eh);
                    nc.Flush();

                    ncp.Publish("foo", System.Text.Encoding.UTF8.GetBytes("hello"));
                    ncp.Publish("bar", System.Text.Encoding.UTF8.GetBytes("hello"));
                    ncp.Flush();

                    recvCh.WaitOne(3000);

                    for (int i = 0; i < 3; i++)
                    {
                        ncp.Publish("foo", System.Text.Encoding.UTF8.GetBytes("hello"));
                        ncp.Publish("bar", System.Text.Encoding.UTF8.GetBytes("hello"));
                    }

                    ncp.Flush();

                    Assert.True(asyncErr1.WaitOne(3000));
                    Assert.True(asyncErr2.WaitOne(3000));

                    def.Shutdown();

                    Thread.Sleep(1000);
                    closed.Reset();
                    nc.Close();

                    Assert.True(closed.WaitOne(3000));
                }


                if (dtime1 == orig || dtime2 == orig || rtime == orig ||
                    atime1 == orig || atime2 == orig || ctime == orig)
                {
                    Console.WriteLine("Error = callback didn't fire: {0}\n{1}\n{2}\n{3}\n{4}\n{5}\n",
                                      dtime1, dtime2, rtime, atime1, atime2, ctime);
                    throw new Exception("Callback didn't fire.");
                }

                if (rtime < dtime1 || dtime2 < rtime || ctime < atime2)
                {
                    Console.WriteLine("Wrong callback order:\n" +
                                      "dtime1: {0}\n" +
                                      "rtime:  {1}\n" +
                                      "atime1: {2}\n" +
                                      "atime2: {3}\n" +
                                      "dtime2: {4}\n" +
                                      "ctime:  {5}\n",
                                      dtime1, rtime, atime1, atime2, dtime2, ctime);
                    throw new Exception("Invalid callback order.");
                }
            }
        }
示例#22
0
        public Recorder(string fileName,
                        FourCC codec, int quality,
                        int audioSourceIndex, SupportedWaveFormat audioWaveFormat, bool encodeAudio, int audioBitRate)
        {
            System.Windows.Media.Matrix toDevice;
            using (var source = new HwndSource(new HwndSourceParameters()))
            {
                toDevice = source.CompositionTarget.TransformToDevice;
            }

            screenWidth  = (int)Math.Round(SystemParameters.PrimaryScreenWidth * toDevice.M11);
            screenHeight = (int)Math.Round(SystemParameters.PrimaryScreenHeight * toDevice.M22);

            try
            {
                // Create AVI writer and specify FPS
                writer = new AviWriter(fileName)
                {
                    FramesPerSecond = 10,
                    EmitIndex1      = true,
                };
            }
            catch (Exception)
            {
                try
                {
                    writer.Close();
                }
                catch (Exception)
                {
                }
                throw;
            }
            // Create video stream
            videoStream = CreateVideoStream(codec, quality);
            // Set only name. Other properties were when creating stream,
            // either explicitly by arguments or implicitly by the encoder used
            videoStream.Name = "Screencast";

            if (audioSourceIndex >= 0)
            {
                var waveFormat = ToWaveFormat(audioWaveFormat);

                audioStream = CreateAudioStream(waveFormat, encodeAudio, audioBitRate);
                // Set only name. Other properties were when creating stream,
                // either explicitly by arguments or implicitly by the encoder used
                audioStream.Name = "Voice";

                audioSource = new WaveInEvent
                {
                    DeviceNumber = audioSourceIndex,
                    WaveFormat   = waveFormat,
                    // Buffer size to store duration of 1 frame
                    BufferMilliseconds = (int)Math.Ceiling(1000 / writer.FramesPerSecond),
                    NumberOfBuffers    = 3,
                };
                audioSource.DataAvailable += audioSource_DataAvailable;
            }
            screenThread = new Thread(RecordScreen)
            {
                Name         = typeof(Recorder).Name + ".RecordScreen",
                IsBackground = true
            };

            if (audioSource != null)
            {
                videoFrameWritten.Set();
                audioBlockWritten.Reset();
                audioSource.StartRecording();
            }
            screenThread.Start();
        }
示例#23
0
 private void Wait(TimeSpan timeout)
 {
     notifyEvent.WaitOne(timeout);
     notifyEvent.Reset();
 }
示例#24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="position">Position to read from</param>
        /// <param name="count">Count of bytes, unlimited</param>
        /// <param name="dst">Destination buffer</param>
        /// <param name="dstOffset">Offset in destination buffer to write from</param>
        /// <returns>Count of bytes readed to dst</returns>
        public int getDataAt(long position, int count, byte[] dst, int dstOffset = 0)
        {
            int received = 0;

            bool isEOF     = false;
            int  hitLength = this.getDataFromBuffer(position, count, dst, dstOffset, ref isEOF);

            if (hitLength > 0)
            {
#if DEBUG
                Console.WriteLine($@"Readbuffer hit {hitLength}");
#endif
                received  += hitLength;
                count     -= hitLength;
                position  += hitLength;
                dstOffset += hitLength;
                if (isEOF || count == 0)                //nothing remains
                {
                    _position += received;
                    return(received);
                }
            }

            //small request, we want to load more data than requested and store them in buffer:
            if (count < this.optimalReadRequestSize)
            {
                this.ReadDataToBufferSync(position);
                hitLength = this.getDataFromBuffer(position, count, dst, dstOffset, ref isEOF);

                _position = position + received + hitLength;
                return(received + hitLength);
            }

            //request with big buffers remains:
            var waits = new List <EventWaitHandle>();

            int readCount     = count;
            int winOffset     = 0;
            int receivedTotal = 0;
#if DEBUG
            DateTime startTime = DateTime.Now;
#endif
            while (readCount > 0)
            {
                int winSize = readCount > this.optimalReadRequestSize ? this.optimalReadRequestSize : readCount;

                EventWaitHandle wait = new AutoResetEvent(false);
                wait.Reset();
                waits.Add(wait);

                this.ReadAsync(position + winOffset, winSize, dst, dstOffset + winOffset,
                               receivedStatus =>
                {
                    Interlocked.Add(ref receivedTotal, receivedStatus);
                    wait.Set();
                }
                               );

                winOffset += winSize;
                readCount -= winSize;
            }

            if (!WaitHandle.WaitAll(waits.ToArray(), 20000))
            {
                throw new SshOperationTimeoutException("Timeout on wait");
            }
#if DEBUG
            int rrTime = (DateTime.Now - startTime).Milliseconds;
            Console.WriteLine(rrTime + " with " + waits.Count);
#endif
            _position = _position + received + receivedTotal;
            return(received + receivedTotal);
        }
        public void ChangeOffsetsWithAdditionalVelocityAndAttachedScrollControllers()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone2))
            {
                Log.Comment("Skipping failing test on RS1.");
                return;
            }

            Scroller  scroller = null;
            Rectangle rectangleScrollerContent = null;
            CompositionScrollController horizontalScrollController = null;
            CompositionScrollController verticalScrollController   = null;
            AutoResetEvent loadedEvent          = new AutoResetEvent(false);
            AutoResetEvent scrollCompletedEvent = new AutoResetEvent(false);
            int            hOffsetChangeId      = -1;
            int            vOffsetChangeId      = -1;

            RunOnUIThread.Execute(() =>
            {
                rectangleScrollerContent = new Rectangle();
                scroller = new Scroller();
                horizontalScrollController = new CompositionScrollController();
                verticalScrollController   = new CompositionScrollController();

                horizontalScrollController.Orientation = Orientation.Horizontal;

                horizontalScrollController.LogMessage += (CompositionScrollController sender, string args) =>
                {
                    Log.Comment(args);
                };

                verticalScrollController.LogMessage += (CompositionScrollController sender, string args) =>
                {
                    Log.Comment(args);
                };

                scroller.HorizontalScrollController = horizontalScrollController;
                scroller.VerticalScrollController   = verticalScrollController;

                SetupUIWithScrollControllers(
                    scroller,
                    rectangleScrollerContent,
                    horizontalScrollController,
                    verticalScrollController,
                    loadedEvent);

                horizontalScrollController.OffsetChangeCompleted += (CompositionScrollController sender, CompositionScrollControllerOffsetChangeCompletedEventArgs args) =>
                {
                    Log.Comment("ChangeOffset completed. OffsetChangeId=" + args.OffsetChangeId);

                    Log.Comment("Setting completion event");
                    scrollCompletedEvent.Set();
                };
            });

            WaitForEvent("Waiting for Loaded event", loadedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("HorizontalScrollController size={0}, {1}", horizontalScrollController.ActualWidth, horizontalScrollController.ActualHeight);
                Log.Comment("VerticalScrollController size={0}, {1}", verticalScrollController.ActualWidth, verticalScrollController.ActualHeight);
            });

            Log.Comment("Jump to zoomFactor 0.75");
            ZoomTo(
                scroller,
                0.75f,
                0.0f,
                0.0f,
                AnimationMode.Disabled,
                SnapPointsMode.Ignore);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Adding velocity to horizontal offset, with default inertia decay rate");
                hOffsetChangeId = horizontalScrollController.ScrollFrom(
                    100.0f /*offsetVelocity*/, null /*inertiaDecayRate*/);

                Log.Comment("Adding velocity to vertical offset, with default inertia decay rate");
                vOffsetChangeId = verticalScrollController.ScrollFrom(
                    100.0f /*offsetVelocity*/, null /*inertiaDecayRate*/);

                Verify.AreEqual(hOffsetChangeId, vOffsetChangeId);
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("scroller.HorizontalOffset={0}", scroller.HorizontalOffset);
                Log.Comment("scroller.VerticalOffset={0}", scroller.VerticalOffset);

                Verify.IsTrue(scroller.HorizontalOffset > 20.0);
                Verify.IsTrue(scroller.VerticalOffset > 20.0);

                Log.Comment("Adding negative velocity to horizontal offset, with custom inertia decay rate");
                hOffsetChangeId = horizontalScrollController.ScrollFrom(
                    -50.0f /*offsetVelocity*/, 0.9f /*inertiaDecayRate*/);

                Log.Comment("Adding negative velocity to vertical offset, with custom inertia decay rate");
                vOffsetChangeId = verticalScrollController.ScrollFrom(
                    -50.0f /*offsetVelocity*/, 0.9f /*inertiaDecayRate*/);

                Verify.AreEqual(hOffsetChangeId, vOffsetChangeId);

                scrollCompletedEvent.Reset();
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("scroller.HorizontalOffset={0}", scroller.HorizontalOffset);
                Log.Comment("scroller.VerticalOffset={0}", scroller.VerticalOffset);

                Verify.IsTrue(scroller.HorizontalOffset < 20.0);
                Verify.IsTrue(scroller.VerticalOffset < 20.0);

                Log.Comment("Adding velocity to horizontal offset, with no inertia decay rate");
                hOffsetChangeId = horizontalScrollController.ScrollFrom(
                    200.0f /*offsetVelocity*/, 0.0f /*inertiaDecayRate*/);

                Log.Comment("Adding velocity to vertical offset, with no inertia decay rate");
                vOffsetChangeId = verticalScrollController.ScrollFrom(
                    200.0f /*offsetVelocity*/, 0.0f /*inertiaDecayRate*/);

                Verify.AreEqual(hOffsetChangeId, vOffsetChangeId);

                scrollCompletedEvent.Reset();
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("scroller.HorizontalOffset={0}", scroller.HorizontalOffset);
                Log.Comment("scroller.VerticalOffset={0}", scroller.VerticalOffset);

                Verify.AreEqual(600.0, scroller.HorizontalOffset);
                Verify.AreEqual(250.0, scroller.VerticalOffset);
            });
        }
示例#26
0
 //pausar
 private void pausar_letra_Click(object sender, EventArgs e)
 {
     pausar_char = true;
     _pauseSecondEvent.Reset();
 }
        public void ChangeOffsetsWithAttachedBiDirectionalScrollController()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone2))
            {
                Log.Comment("Skipping failing test on RS1.");
                return;
            }

            Scroller  scroller = null;
            Rectangle rectangleScrollerContent = null;
            BiDirectionalScrollController biDirectionalScrollController = null;
            AutoResetEvent loadedEvent          = new AutoResetEvent(false);
            AutoResetEvent scrollCompletedEvent = new AutoResetEvent(false);

            RunOnUIThread.Execute(() =>
            {
                rectangleScrollerContent = new Rectangle();
                scroller = new Scroller();
                biDirectionalScrollController = new BiDirectionalScrollController();

                biDirectionalScrollController.LogMessage += (BiDirectionalScrollController sender, string args) =>
                {
                    Log.Comment(args);
                };

                scroller.HorizontalScrollController = biDirectionalScrollController.HorizontalScrollController;
                scroller.VerticalScrollController   = biDirectionalScrollController.VerticalScrollController;

                SetupUIWithBiDirectionalScrollController(
                    scroller,
                    rectangleScrollerContent,
                    biDirectionalScrollController,
                    loadedEvent);

                biDirectionalScrollController.ScrollCompleted += (BiDirectionalScrollController sender, BiDirectionalScrollControllerScrollCompletedEventArgs args) =>
                {
                    Log.Comment("ChangeOffset completed. OffsetsChangeId=" + args.OffsetsChangeId);

                    Log.Comment("Setting completion event");
                    scrollCompletedEvent.Set();
                };
            });

            WaitForEvent("Waiting for Loaded event", loadedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("BiDirectionalScrollController size={0}, {1}", biDirectionalScrollController.ActualWidth, biDirectionalScrollController.ActualHeight);
            });

            Log.Comment("Jump to zoomFactor 0.75");
            ZoomTo(
                scroller,
                0.75f,
                0.0f,
                0.0f,
                AnimationMode.Disabled,
                SnapPointsMode.Ignore);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Jumping to offsets");
                biDirectionalScrollController.ScrollTo(
                    (c_defaultUIScrollerContentWidth * 0.75 - c_defaultUIScrollerWidth) / 4.0,
                    (c_defaultUIScrollerContentHeight * 0.75 - c_defaultUIScrollerHeight) / 4.0,
                    AnimationMode.Disabled);
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Verify.AreEqual((c_defaultUIScrollerContentWidth * 0.75 - c_defaultUIScrollerWidth) / 4.0, scroller.HorizontalOffset);
                Verify.AreEqual((c_defaultUIScrollerContentHeight * 0.75 - c_defaultUIScrollerHeight) / 4.0, scroller.VerticalOffset);

                Log.Comment("Animating to offsets");
                biDirectionalScrollController.ScrollTo(
                    (c_defaultUIScrollerContentWidth * 0.75 - c_defaultUIScrollerWidth) / 2.0,
                    (c_defaultUIScrollerContentHeight * 0.75 - c_defaultUIScrollerHeight) / 2.0,
                    AnimationMode.Enabled);

                scrollCompletedEvent.Reset();
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Verify.AreEqual((c_defaultUIScrollerContentWidth * 0.75 - c_defaultUIScrollerWidth) / 2.0, scroller.HorizontalOffset);
                Verify.AreEqual((c_defaultUIScrollerContentHeight * 0.75 - c_defaultUIScrollerHeight) / 2.0, scroller.VerticalOffset);
            });
        }
        /// <summary>
        ///     After the event is reset, test to make sure WaitOne timeout in the same thread
        /// </summary>
        private static void TestTrivialReset()
        {
            Console.Write("    test trivial reset ");

            //
            // reset by constructor
            //
            evt = new AutoResetEvent(false);
            Console.Write('.');
            bool ret = evt.WaitOne(trivialTestWaitTime);

            if (ret)
            {
                Expect.Fail("wait should timeout");
                return;
            }
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout again");
                return;
            }
            evt.Close();

            //
            // reset by constructor and Reset()
            //
            evt = new AutoResetEvent(false);
            evt.Reset();
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout");
                return;
            }
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout again");
                return;
            }
            evt.Close();

            //
            // set by constructor and then explicitly Reset()
            //
            evt = new AutoResetEvent(true);
            evt.Reset();
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout");
                return;
            }
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout again");
                return;
            }
            evt.Close();

            //
            // Set() and Reset() several times
            //
            evt = new AutoResetEvent(true);
            evt.Set();
            evt.Reset();
            evt.Set();
            evt.Reset();
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout");
                return;
            }
            Console.Write('.');
            ret = evt.WaitOne(trivialTestWaitTime);
            if (ret)
            {
                Expect.Fail("wait should timeout again");
                return;
            }
            evt.Close();

            evt = null;
            Console.WriteLine("OK");
        }
    bool Inventory_OnObjectOffered(InstantMessage offerDetails, AssetType type, UUID objectID, bool fromTask)
    {
        AutoResetEvent ObjectOfferEvent = new AutoResetEvent(false);
            ResponseType object_offer_result=ResponseType.Yes;

            string msg = "";
            ResponseType result;
            if (!fromTask)
                msg = "The user "+offerDetails.FromAgentName + " has offered you\n" + offerDetails.Message + "\n Which is a " + type.ToString() + "\nPress Yes to accept or no to decline";
            else
                msg = "The object "+offerDetails.FromAgentName + " has offered you\n" + offerDetails.Message + "\n Which is a " + type.ToString() + "\nPress Yes to accept or no to decline";

            Application.Invoke(delegate {
                    ObjectOfferEvent.Reset();

                    Gtk.MessageDialog md = new MessageDialog(MainClass.win, DialogFlags.Modal, MessageType.Other, ButtonsType.YesNo, false, msg);

                    result = (ResponseType)md.Run();
                    object_offer_result=result;
                    md.Destroy();
                    ObjectOfferEvent.Set();
            });

            ObjectOfferEvent.WaitOne(1000*3600,false);

           if (object_offer_result == ResponseType.Yes)
           {
               if(OnInventoryAccepted!=null)
               {
                  OnInventoryAccepted(type,objectID);
               }
                return true;
           }
           else
        {
                return false;
            }
    }
 internal void DebugPauseService()
 {
     innerDebugLock_?.Reset();
 }
示例#31
0
        private void Run(string[] args)
        {
            AssemblyInformationalVersionAttribute versionAttribute
                = Attribute.GetCustomAttribute(typeof(Program).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;

            Console.WriteLine("Wyam version {0}", versionAttribute == null ? "unknown" : versionAttribute.InformationalVersion);

            // Parse the command line
            if (!ParseArgs(args))
            {
                return;
            }

            // It's not a serious console app unless there's some ASCII art
            OutputLogo();

            // Fix the root folder and other files
            _rootFolder = _rootFolder == null ? Environment.CurrentDirectory : Path.Combine(Environment.CurrentDirectory, _rootFolder);
            _logFile    = _logFile == null ? null : Path.Combine(_rootFolder, _logFile);
            _configFile = string.IsNullOrWhiteSpace(_configFile)
                ? Path.Combine(_rootFolder, "config.wyam") : Path.Combine(_rootFolder, _configFile);

            // Get the engine
            Engine engine = GetEngine();

            if (engine == null)
            {
                return;
            }

            // Pause
            if (_pause)
            {
                engine.Trace.Information("Pause requested, hit any key to continue");
                Console.ReadKey();
            }

            // Configure and execute
            if (!Configure(engine))
            {
                return;
            }
            if (!Execute(engine))
            {
                return;
            }

            bool messagePump = false;

            // Start the preview server
            IDisposable previewServer = null;

            if (_preview)
            {
                messagePump = true;
                try
                {
                    engine.Trace.Information("Preview server listening on port {0} and serving from {1}", _previewPort, engine.OutputFolder);
                    previewServer = Preview(engine);
                }
                catch (Exception ex)
                {
                    engine.Trace.Critical("Error while running preview server: {0}", ex.Message);
                }
            }

            // Start the watchers
            IDisposable inputFolderWatcher = null;
            IDisposable configFileWatcher  = null;

            if (_watch)
            {
                messagePump = true;

                engine.Trace.Information("Watching folder {0}", engine.InputFolder);
                inputFolderWatcher = new ActionFileSystemWatcher(engine.InputFolder, true, "*.*", path =>
                {
                    _changedFiles.Enqueue(path);
                    _messageEvent.Set();
                });

                if (_configFile != null)
                {
                    engine.Trace.Information("Watching configuration file {0}", _configFile);
                    configFileWatcher = new ActionFileSystemWatcher(Path.GetDirectoryName(_configFile), false, Path.GetFileName(_configFile), path =>
                    {
                        if (path == _configFile)
                        {
                            _newEngine.Set();
                            _messageEvent.Set();
                        }
                    });
                }
            }

            // Start the message pump if an async process is running
            if (messagePump)
            {
                // Start the key listening thread
                engine.Trace.Information("Hit any key to exit");
                var thread = new Thread(() =>
                {
                    Console.ReadKey();
                    _exit.Set();
                    _messageEvent.Set();
                })
                {
                    IsBackground = true
                };
                thread.Start();

                // Wait for activity
                while (true)
                {
                    _messageEvent.WaitOne();  // Blocks the current thread until a signal
                    if (_exit)
                    {
                        break;
                    }

                    // See if we need a new engine
                    if (_newEngine)
                    {
                        // Get a new engine
                        engine.Trace.Information("Configuration file {0} has changed, re-running", _configFile);
                        engine.Dispose();
                        engine = GetEngine();

                        // Configure and execute
                        if (!Configure(engine))
                        {
                            break;
                        }
                        if (!Execute(engine))
                        {
                            break;
                        }

                        // Clear the changed files since we just re-ran
                        string changedFile;
                        while (_changedFiles.TryDequeue(out changedFile))
                        {
                        }

                        _newEngine.Unset();
                    }
                    else
                    {
                        // Execute if files have changed
                        HashSet <string> changedFiles = new HashSet <string>();
                        string           changedFile;
                        while (_changedFiles.TryDequeue(out changedFile))
                        {
                            if (changedFiles.Add(changedFile))
                            {
                                engine.Trace.Verbose("{0} has changed", changedFile);
                            }
                        }
                        if (changedFiles.Count > 0)
                        {
                            engine.Trace.Information("{0} files have changed, re-executing", changedFiles.Count);
                            if (!Execute(engine))
                            {
                                break;
                            }
                        }
                    }

                    // Check one more time for exit
                    if (_exit)
                    {
                        break;
                    }
                    engine.Trace.Information("Hit any key to exit");
                    _messageEvent.Reset();
                }

                // Shutdown
                engine.Trace.Information("Shutting down");
                engine.Dispose();
                if (inputFolderWatcher != null)
                {
                    inputFolderWatcher.Dispose();
                }
                if (configFileWatcher != null)
                {
                    configFileWatcher.Dispose();
                }
                if (previewServer != null)
                {
                    previewServer.Dispose();
                }
            }
        }
示例#32
0
	public static int Main (string[] args)
	{ 
		Console.WriteLine ("Touch.Unit Simple Server");
		Console.WriteLine ("Copyright 2011, Xamarin Inc. All rights reserved.");
		
		bool help = false;
		bool verbose = false;
		string address = null;
		string port = null;
		string log_path = ".";
		string log_file = null;
		string launchdev = null;
		string launchsim = null;
		bool autoexit = false;
		string device_name = String.Empty;
		string device_type = String.Empty;
		TimeSpan? timeout = null;
		TimeSpan? startup_timeout = null;
		var mtouch_arguments = new List<string> ();

		var os = new OptionSet () {
			{ "h|?|help", "Display help", v => help = true },
			{ "verbose", "Display verbose output", v => verbose = true },
			{ "ip", "IP address to listen (default: Any)", v => address = v },
			{ "port", "TCP port to listen (default: Any)", v => port = v },
			{ "logpath", "Path to save the log files (default: .)", v => log_path = v },
			{ "logfile=", "Filename to save the log to (default: automatically generated)", v => log_file = v },
			{ "launchdev=", "Run the specified app on a device (specify using bundle identifier)", v => launchdev = v },
			{ "launchsim=", "Run the specified app on the simulator (specify using path to *.app directory)", v => launchsim = v },
			{ "autoexit", "Exit the server once a test run has completed (default: false)", v => autoexit = true },
			{ "devname=", "Specify the device to connect to", v => device_name = v},
			{ "device=", "Specifies the device type to launch the simulator", v => device_type = v },
			{ "timeout=", "Specifies a timeout (in minutes), after which the simulator app will be killed (ignored for device runs)", v => timeout = TimeSpan.FromMinutes (double.Parse (v)) },
			{ "startup-timeout=", "Specifies a timeout (in seconds) for the simulator app to connect to Touch.Server (ignored for device runs)", v => startup_timeout = TimeSpan.FromSeconds (double.Parse (v)) },
			{ "mtouch-argument=", "Specifies an extra mtouch argument when launching the application", v => mtouch_arguments.Add (v) },
		};
		
		try {
			os.Parse (args);
			if (help)
				ShowHelp (os);
			
			var listener = new SimpleListener ();
			
			IPAddress ip;
			if (String.IsNullOrEmpty (address) || !IPAddress.TryParse (address, out ip))
				listener.Address = IPAddress.Any;
			
			ushort p;
			if (UInt16.TryParse (port, out p))
				listener.Port = p;
			
			listener.LogPath = log_path ?? ".";
			listener.LogFile = log_file;
			listener.AutoExit = autoexit;
			listener.Initialize ();
			
			string mt_root = Environment.GetEnvironmentVariable ("MONOTOUCH_ROOT");
			if (String.IsNullOrEmpty (mt_root))
				mt_root = "/Developer/MonoTouch";

			string mtouch = Path.Combine (mt_root, "bin", "mtouch");
			if (!File.Exists (mtouch))
				mtouch = Path.Combine (mt_root, "usr", "bin", "mtouch");

			Process proc = null;
			if (launchdev != null) {
				ThreadPool.QueueUserWorkItem ((v) => {
					{
						proc = new Process ();
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
							procArgs.Append ("--sdkroot ").Append (sdk_root);
						procArgs.Append (" --launchdev ");
						procArgs.Append (Quote (launchdev));
						if (!String.IsNullOrEmpty (device_name))
							procArgs.Append (" --devname=").Append (Quote (device_name));
						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						procArgs.Append (" -argument=-app-arg:-hostname:");
						foreach (var arg in mtouch_arguments)
							procArgs.Append (" ").Append (arg);
						var ipAddresses = System.Net.Dns.GetHostEntry (System.Net.Dns.GetHostName ()).AddressList;
						for (int i = 0; i < ipAddresses.Length; i++) {
							if (i > 0)
								procArgs.Append (',');
							procArgs.Append (ipAddresses [i].ToString ());
						}
						proc.StartInfo.FileName = mtouch;
						proc.StartInfo.Arguments = procArgs.ToString ();
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardError = true;
						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							lock (output) {
								output.Append ("[mtouch stderr] ");
								output.AppendLine (e.Data);
							}
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							lock (output) {
								output.Append ("[mtouch stdout] ");
								output.AppendLine (e.Data);
							}
						};
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						proc.WaitForExit ();
						if (proc.ExitCode != 0)
							listener.Cancel ();
						Console.WriteLine (output.ToString ());
					}
				});
			}

			var lastErrorDataReceived = new AutoResetEvent (true);
			var lastOutDataReceived = new AutoResetEvent (true);
			if (launchsim != null) {
				lastErrorDataReceived.Reset ();
				lastOutDataReceived.Reset ();

				ThreadPool.QueueUserWorkItem ((v) => {
					{
						proc = new Process ();
						int pid = 0;
						StringBuilder output = new StringBuilder ();
						StringBuilder procArgs = new StringBuilder ();
						string sdk_root = Environment.GetEnvironmentVariable ("XCODE_DEVELOPER_ROOT");
						if (!String.IsNullOrEmpty (sdk_root))
							procArgs.Append ("--sdkroot ").Append (sdk_root);
						procArgs.Append (" --launchsim ");
						procArgs.Append (Quote (launchsim));
						if (!string.IsNullOrEmpty (device_type))
							procArgs.Append (" --device ").Append (device_type);
						procArgs.Append (" -argument=-connection-mode -argument=none");
						procArgs.Append (" -argument=-app-arg:-autostart");
						procArgs.Append (" -argument=-app-arg:-autoexit");
						procArgs.Append (" -argument=-app-arg:-enablenetwork");
						procArgs.Append (" -argument=-app-arg:-hostname:127.0.0.1");
						procArgs.AppendFormat (" -argument=-app-arg:-hostport:{0}", listener.Port);
						foreach (var arg in mtouch_arguments)
							procArgs.Append (" ").Append (arg);
						proc.StartInfo.FileName = mtouch;
						proc.StartInfo.Arguments = procArgs.ToString ();
						proc.StartInfo.UseShellExecute = false;
						proc.StartInfo.RedirectStandardError = true;
						proc.StartInfo.RedirectStandardOutput = true;
						proc.StartInfo.RedirectStandardInput = true;

						proc.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							if (e.Data == null) {
								Console.WriteLine ("[mtouch stderr EOS]");
								lastErrorDataReceived.Set ();
								return;
							}
							Console.WriteLine ("[mtouch stderr {0}] {1}", DateTime.Now.ToLongTimeString (), e.Data);
						};
						proc.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
							if (e.Data == null){
								Console.WriteLine ("[mtouch stdout EOS]");
								lastOutDataReceived.Set ();
								return;
							}
							Console.WriteLine ("[mtouch stdout {0}] {1}", DateTime.Now.ToLongTimeString (), e.Data);

							if (e.Data.StartsWith ("Application launched. PID = ")) {
								var pidstr = e.Data.Substring ("Application launched. PID = ".Length);
								if (!int.TryParse (pidstr, out pid)) {
									Console.WriteLine ("Could not parse pid: {0}", pidstr);
								} else if (startup_timeout.HasValue) {
									ThreadPool.QueueUserWorkItem ((v2) =>
										{
											if (!listener.WaitForConnection (startup_timeout.Value))
												KillPid (proc, pid, 1000, startup_timeout.Value, "Startup");
										});
								}
							}
						};
						if (verbose)
							Console.WriteLine ("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
						proc.Start ();
						proc.BeginErrorReadLine ();
						proc.BeginOutputReadLine ();
						if (timeout.HasValue) {
							if (!proc.WaitForExit ((int) timeout.Value.TotalMilliseconds)) {
								if (pid != 0) {
									KillPid (proc, pid, 5000, timeout.Value, "Completion");
								} else {
									proc.StandardInput.WriteLine (); // this kills as well, but we won't be able to send SIGQUIT to get a stack trace.
								}
								if (!proc.WaitForExit (5000 /* wait another 5 seconds for mtouch to finish as well */))
									Console.WriteLine ("mtouch didn't complete within 5s of killing the simulator app. Touch.Server will exit anyway.");
							}
						} else {
							proc.WaitForExit ();
						}
						listener.Cancel ();
					}
				});
			}
			
			var result = listener.Start ();
			if (proc != null && !proc.WaitForExit (10000 /* wait another 10 seconds for mtouch to finish as well */))
				Console.WriteLine ("mtouch didn't complete within 10s of the simulator app exiting. Touch.Server will exit anyway.");
			// Wait up to 2 seconds to receive the last of the error/output data. This will only be received *after*
			// mtouch has exited.
			lastErrorDataReceived.WaitOne (2000);
			lastOutDataReceived.WaitOne (2000);
			return result;
		} catch (OptionException oe) {
			Console.WriteLine ("{0} for options '{1}'", oe.Message, oe.OptionName);
			return 1;
		} catch (Exception ex) {
			Console.WriteLine (ex);
			return 1;
		}
	}   
示例#33
0
        public static void Main()
        {
            TraceVerbose("Instance startup");
            try
            {
                Console.WriteLine(
                    @"Janus project. Copyright (C) 2002-2012 by Rsdn Team. " +
                    @"See rsdn.ru for more information.");

                // Проверка на единственность экземпляра приложения.
                bool cn;
                using (var m = new Mutex(true, "JanusRunningInstanceDetectionMutex", out cn))
                {
                    if (!m.WaitOne(0, false))
                    {
                        WindowActivator.ActivateWindow(MainForm.GetCaption());
                        return;
                    }

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    // Создаем контрол, чтобы инициализировать винформсный констекст синхронизации,
                    // если он еще не инициализирован
                    using (new Control()) { }

                    Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)Config.Instance.UILanguage);

                    if (!CheckEnvironment())
                    {
                        return;
                    }

                    TraceVerbose("ResMgr");

                    var rootManager = new ServiceManager(true);

                    rootManager.Publish <IUIShell>(
                        new UIShell(
                            () => ApplicationManager.Instance.MainForm,
                            freeze => ApplicationManager.Instance.MainForm.Enabled = freeze));

                    if (Config.Instance.ShowSplash)
                    {
                        EventHandler hider = null;
                        IServiceRegistrationCookie informerCookie = null;
                        IServiceRegistrationCookie progressCookie = null;

                        hider =
                            (sender, e) =>
                        {
                            // ReSharper disable AccessToModifiedClosure
                            if (progressCookie != null)
                            {
                                rootManager.Unpublish(progressCookie);
                            }

                            rootManager.Publish <IProgressService>(
                                new DefaultProgressService(rootManager));

                            if (informerCookie != null)
                            {
                                rootManager.Unpublish(informerCookie);
                            }
                            SplashHelper.Hide();
                            Application.Idle -= hider;
                            // ReSharper restore AccessToModifiedClosure
                        };

                        Application.Idle += hider;

                        informerCookie = rootManager.Publish(
                            SplashHelper.Show(rootManager));

                        progressCookie = rootManager.Publish(
                            SplashHelper.GetProgressService());

                        //Thread.Sleep(20000);
                    }
                    else
                    {
                        rootManager.Publish <IProgressService>(
                            new DefaultProgressService(rootManager));
                    }

                    using (var host = new JanusHost(rootManager))
                    {
                        using (host.InitScope())
                        {
                            rootManager.SetSplashMessage(SR.Splash.ApplicationStart);

                            TraceVerbose("JanusHost");

                            // Подписка сервиса на извещения об изменении конфигурации.
                            var configChangedNotifier = host.GetRequiredService <ConfigChangedNotifier>();
                            Config.Instance.ConfigChanged +=
                                (o, args) => configChangedNotifier.FireConfigChanged(Config.Instance);

                            try
                            {
                                //Проверка наличия пользователя
                                if (!LocalUser.UserExists())
                                {
                                    using (var ouf = new OptionsUserForm(host, true))
                                        ouf.ShowDialog();
                                }

                                rootManager.SetSplashMessage(SR.Splash.CheckDatabase);

                                if (!DBSchemaManager.CheckDB(host))
                                {
                                    // User cancelled.
                                    //
                                    TraceVerbose("User cancelled");
                                }

                                var signal = new AutoResetEvent(true);
                                if (DBSchemaManager.IsNeedRestructuring(host))
                                {
                                    signal.Reset();
                                    ProgressWorker.Run(rootManager, false,
                                                       progressVisualizer =>
                                    {
                                        progressVisualizer.SetProgressText(SR.Splash.RestructureDatabase);
                                        try
                                        {
                                            DBSchemaManager.Restruct(host);
                                            //DatabaseManager.ClearTopicInfo(host);
                                            Config.Instance.BadRestruct = false;
                                        }
                                        catch
                                        {
                                            Config.Instance.BadRestruct = true;
                                            Config.Save();
                                            throw;
                                        }
                                        finally
                                        {
                                            // разрешаем выполнение главного потока
                                            signal.Set();
                                        }
                                    });
                                }

                                // блокируем поток, пока не завершится реструктуризация БД
                                while (!signal.WaitOne(100))
                                {
                                    Application.DoEvents();
                                }

                                // Проверяем наличие таблички topic_info
                                DatabaseManager.CheckTopicInfoIntegrity(host);

                                TraceVerbose("DB ready");

                                rootManager.Publish <IMainWindowService>(
                                    new MainWindowService(() => ApplicationManager.Instance.MainForm));
                                rootManager.Publish(
                                    new DockManager(rootManager, () => ApplicationManager.Instance.MainForm.DockPanel));

                                Application.ThreadException +=
                                    (sender, e) =>
                                {
                                    using (var ef = new ExceptionForm(host, e.Exception, true))
                                        ef.ShowDialog(
                                            rootManager
                                            .GetRequiredService <IUIShell>()
                                            .GetMainWindowParent());
                                };

                                TraceVerbose("Ready to Run()");
                            }
                            catch (LocalUserNotFoundException)
                            {
                                MessageBox.Show(
                                    SR.JanusImpossibleWork,
                                    ApplicationInfo.ApplicationName,
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                                throw;
                            }
                        }
                        ApplicationManager.Instance.Run(host);
                    }
                }
            }
            catch (Exception ex)
            {
                using (var ef = new ExceptionForm(null, ex, false))
                    ef.ShowDialog();
            }
        }
        public void ChangeOffsetsWithAdditionalVelocityAndAttachedBiDirectionalScrollController()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone2))
            {
                Log.Comment("Skipping failing test on RS1.");
                return;
            }

            Scroller  scroller = null;
            Rectangle rectangleScrollerContent = null;
            BiDirectionalScrollController biDirectionalScrollController = null;
            AutoResetEvent loadedEvent          = new AutoResetEvent(false);
            AutoResetEvent scrollCompletedEvent = new AutoResetEvent(false);

            RunOnUIThread.Execute(() =>
            {
                rectangleScrollerContent = new Rectangle();
                scroller = new Scroller();
                biDirectionalScrollController = new BiDirectionalScrollController();

                biDirectionalScrollController.LogMessage += (BiDirectionalScrollController sender, string args) =>
                {
                    Log.Comment(args);
                };

                scroller.HorizontalScrollController = biDirectionalScrollController.HorizontalScrollController;
                scroller.VerticalScrollController   = biDirectionalScrollController.VerticalScrollController;

                SetupUIWithBiDirectionalScrollController(
                    scroller,
                    rectangleScrollerContent,
                    biDirectionalScrollController,
                    loadedEvent);

                biDirectionalScrollController.ScrollCompleted += (BiDirectionalScrollController sender, BiDirectionalScrollControllerScrollCompletedEventArgs args) =>
                {
                    Log.Comment("ScrollFrom completed. OffsetsChangeId=" + args.OffsetsChangeId);

                    Log.Comment("Setting completion event");
                    scrollCompletedEvent.Set();
                };
            });

            WaitForEvent("Waiting for Loaded event", loadedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("BiDirectionalScrollController size={0}, {1}", biDirectionalScrollController.ActualWidth, biDirectionalScrollController.ActualHeight);
            });

            Log.Comment("Jump to zoomFactor 0.75");
            ZoomTo(
                scroller,
                0.75f,
                0.0f,
                0.0f,
                AnimationMode.Disabled,
                SnapPointsMode.Ignore);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Adding velocity to offsets, with default inertia decay rates");
                biDirectionalScrollController.ScrollFrom(
                    new Vector2(100.0f) /*offsetsVelocity*/, null /*inertiaDecayRate*/);
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("scroller.HorizontalOffset={0}", scroller.HorizontalOffset);
                Log.Comment("scroller.VerticalOffset={0}", scroller.VerticalOffset);

                Verify.IsTrue(scroller.HorizontalOffset > 20.0);
                Verify.IsTrue(scroller.VerticalOffset > 20.0);

                Log.Comment("Adding negative velocity to offsets, with custom inertia decay rates");
                biDirectionalScrollController.ScrollFrom(
                    new Vector2(-50.0f) /*offsetsVelocity*/, new Vector2(0.9f) /*inertiaDecayRate*/);

                scrollCompletedEvent.Reset();
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("scroller.HorizontalOffset={0}", scroller.HorizontalOffset);
                Log.Comment("scroller.VerticalOffset={0}", scroller.VerticalOffset);

                Verify.IsTrue(scroller.HorizontalOffset < 20.0);
                Verify.IsTrue(scroller.VerticalOffset < 20.0);

                Log.Comment("Adding velocity to offsets, with no inertia decay rates");
                biDirectionalScrollController.ScrollFrom(
                    new Vector2(200.0f) /*offsetsVelocity*/, new Vector2(0.0f) /*inertiaDecayRate*/);

                scrollCompletedEvent.Reset();
            });

            WaitForEvent("Waiting for operation completion", scrollCompletedEvent);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("scroller.HorizontalOffset={0}", scroller.HorizontalOffset);
                Log.Comment("scroller.VerticalOffset={0}", scroller.VerticalOffset);

                Verify.AreEqual(600.0, scroller.HorizontalOffset);
                Verify.AreEqual(250.0, scroller.VerticalOffset);
            });
        }
示例#35
0
        public void CanBringIntoViewElements()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone5))
            {
                // Note that UIElement.BringIntoViewRequested was added in RS4, and effective viewport was added in RS5
                Log.Warning("Skipping since version is less than RS5 and effective viewport feature is not available below RS5");
                return;
            }

            Scroller      scroller         = null;
            ItemsRepeater repeater         = null;
            var           rootLoadedEvent  = new AutoResetEvent(initialState: false);
            var           viewChangedEvent = new AutoResetEvent(initialState: false);
            var           waitingForIndex  = -1;
            var           indexRealized    = new AutoResetEvent(initialState: false);

            var viewChangedOffsets = new List <double>();

            RunOnUIThread.Execute(() =>
            {
                var lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam laoreet erat vel massa rutrum, eget mollis massa vulputate. Vivamus semper augue leo, eget faucibus nulla mattis nec. Donec scelerisque lacus at dui ultricies, eget auctor ipsum placerat. Integer aliquet libero sed nisi eleifend, nec rutrum arcu lacinia. Sed a sem et ante gravida congue sit amet ut augue. Donec quis pellentesque urna, non finibus metus. Proin sed ornare tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam laoreet erat vel massa rutrum, eget mollis massa vulputate. Vivamus semper augue leo, eget faucibus nulla mattis nec. Donec scelerisque lacus at dui ultricies, eget auctor ipsum placerat. Integer aliquet libero sed nisi eleifend, nec rutrum arcu lacinia. Sed a sem et ante gravida congue sit amet ut augue. Donec quis pellentesque urna, non finibus metus. Proin sed ornare tellus.";
                var root  = (Grid)XamlReader.Load(TestUtilities.ProcessTestXamlForRepo(
                                                      @"<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
                             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                             xmlns:controls='using:Microsoft.UI.Xaml.Controls' 
                             xmlns:primitives='using:Microsoft.UI.Xaml.Controls.Primitives'> 
                         <Grid.Resources>
                           <controls:StackLayout x:Name='VerticalStackLayout' />
                           <controls:RecyclingElementFactory x:Key='ElementFactory'>
                             <controls:RecyclingElementFactory.RecyclePool>
                               <controls:RecyclePool />
                             </controls:RecyclingElementFactory.RecyclePool>
                             <DataTemplate x:Key='ItemTemplate'>
                               <Border Background='LightGray' Margin ='5'>
                                 <TextBlock Text='{Binding}' TextWrapping='WrapWholeWords' />
                               </Border>
                             </DataTemplate>
                           </controls:RecyclingElementFactory>
                         </Grid.Resources>
                         <primitives:Scroller x:Name='Scroller' Width='400' Height='600' ContentOrientation='Vertical' Background='Gray'>
                           <controls:ItemsRepeater
                             x:Name='ItemsRepeater'
                             ItemTemplate='{StaticResource ElementFactory}'
                             Layout='{StaticResource VerticalStackLayout}'
                             HorizontalCacheLength='0'
                             VerticalCacheLength='0' />
                         </primitives:Scroller>
                       </Grid>"));

                var elementFactory = (RecyclingElementFactory)root.Resources["ElementFactory"];
                scroller           = (Scroller)root.FindName("Scroller");
                repeater           = (ItemsRepeater)root.FindName("ItemsRepeater");

                repeater.ElementPrepared += (sender, args) =>
                {
                    Log.Comment($"Realized index: {args.Index} Wating for index {waitingForIndex}");
                    if (args.Index == waitingForIndex)
                    {
                        indexRealized.Set();
                    }
                };

                var items = Enumerable.Range(0, 400).Select(i => string.Format("{0}: {1}", i, lorem.Substring(0, 250)));

                repeater.ItemsSource = items;

                scroller.ViewChanged += (o, e) =>
                {
                    Log.Comment("Scroller.ViewChanged: VerticalOffset=" + scroller.VerticalOffset);
                    viewChangedOffsets.Add(scroller.VerticalOffset);
                    viewChangedEvent.Set();
                };

                scroller.BringingIntoView += (o, e) =>
                {
                    Log.Comment("Scroller.BringingIntoView:");
                    Log.Comment("TargetVerticalOffset=" + e.TargetVerticalOffset);
                    Log.Comment("RequestEventArgs.AnimationDesired=" + e.RequestEventArgs.AnimationDesired);
                    Log.Comment("RequestEventArgs.Handled=" + e.RequestEventArgs.Handled);
                    Log.Comment("RequestEventArgs.VerticalAlignmentRatio=" + e.RequestEventArgs.VerticalAlignmentRatio);
                    Log.Comment("RequestEventArgs.VerticalOffset=" + e.RequestEventArgs.VerticalOffset);
                    Log.Comment("RequestEventArgs.TargetRect=" + e.RequestEventArgs.TargetRect);
                };

                scroller.EffectiveViewportChanged += (o, args) =>
                {
                    Log.Comment("Scroller.EffectiveViewportChanged: VerticalOffset=" + scroller.VerticalOffset);
                };

                root.Loaded += delegate {
                    rootLoadedEvent.Set();
                };

                Content = root;
            });
            Verify.IsTrue(rootLoadedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();

            RunOnUIThread.Execute(() =>
            {
                waitingForIndex = 101;
                indexRealized.Reset();
                repeater.GetOrCreateElement(100).StartBringIntoView(new BringIntoViewOptions {
                    VerticalAlignmentRatio = 0.0
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.AreEqual(1, viewChangedOffsets.Count);
            viewChangedOffsets.Clear();
            Verify.IsTrue(indexRealized.WaitOne(DefaultWaitTimeInMS));

            ValidateRealizedRange(repeater, 99, 106);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Scroll into view item 105 (already realized) w/ animation.");
                waitingForIndex = 99;
                repeater.TryGetElement(105).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.5,
                    AnimationDesired       = true
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.IsLessThanOrEqual(1, viewChangedOffsets.Count);
            viewChangedOffsets.Clear();
            ValidateRealizedRange(repeater, 101, 109);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Scroll item 0 to the top w/ animation and 0.5 vertical alignment.");
                waitingForIndex = 1;
                indexRealized.Reset();
                repeater.GetOrCreateElement(0).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.5,
                    AnimationDesired       = true
                });
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            viewChangedOffsets.Clear();
            Verify.IsTrue(indexRealized.WaitOne(DefaultWaitTimeInMS));

            // Test Reliability fix. If offset is not 0 yet, give
            // some more time for the animation to settle down.
            double verticalOffset = 0;

            RunOnUIThread.Execute(() =>
            {
                verticalOffset = scroller.VerticalOffset;
            });

            if (verticalOffset != 0)
            {
                Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
                IdleSynchronizer.Wait();
                viewChangedOffsets.Clear();
            }

            ValidateRealizedRange(repeater, 0, 6);

            RunOnUIThread.Execute(() =>
            {
                // You can't align the first group in the middle obviously.
                Verify.AreEqual(0, scroller.VerticalOffset);

                Log.Comment("Scroll to item 20.");
                waitingForIndex = 21;
                indexRealized.Reset();
                repeater.GetOrCreateElement(20).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.0
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.IsTrue(indexRealized.WaitOne(DefaultWaitTimeInMS));

            ValidateRealizedRange(repeater, 19, 26);
        }