Ejemplo n.º 1
0
        //public System.Threading.CancellationToken BeginUpdate(int x, bool e)
        //{
        //    CheckDisposed();

        //    if (System.Threading.WaitHandle.SignalAndWait(m_UpdateTokenSource.Token.WaitHandle, m_Update.WaitHandle, x, e))
        //    {
        //        m_Update.Reset();
        //    }

        //    return m_UpdateTokenSource.Token;
        //}

        /// <summary>
        /// Ends a previous started update with <see cref="BeginUpdate"/>
        /// </summary>
        /// <param name="token">The token obtained to begin the update</param>
        public void EndUpdate(System.Threading.CancellationToken token, bool updateVersion)
        {
            CheckDisposed();

            //Ensure a token
            if (token == null)
            {
                return;
            }

            //That came from out cancellation source
            if (token != m_UpdateTokenSource.Token)
            {
                throw new InvalidOperationException("Must obtain the CancellationToken from a call to BeginUpdate.");
            }

            // check for manually removed state or a call without an update..
            //if(m_Update.Wait(1, token)) { would check that the event was manually cleared... }

            // acknowledge cancellation
            if (token.IsCancellationRequested)
            {
                throw new OperationCanceledException(token);
            }

            //if the version should be updated, then do it now.
            if (updateVersion)
            {
                UpdateVersion(token);
            }

            //Allow threads to modify
            m_Update.Set(); //To unblocked
        }
Ejemplo n.º 2
0
        public static ResultCompletionEventArgs ExecuteAndWait(this IResult action, CoroutineExecutionContext context,
                                                               System.Action executeAfterActionStarted = null)
        {
            ResultCompletionEventArgs retVal = null;
            var handle = new System.Threading.ManualResetEventSlim(false);

            action.Completed += (sender, args) =>
            {
                if (args == null)
                {
                    throw new Exception("Args = null");
                }
                retVal = args;
                handle.Set();
            };
            action.Execute(context);
            if (executeAfterActionStarted != null)
            {
                executeAfterActionStarted();
            }
            handle.Wait();

            if (retVal == null)
            {
                throw new Exception("Completed not triggered");
            }
            return(retVal);
        }
Ejemplo n.º 3
0
        public void IDLE()
        {
            var mre1 = new System.Threading.ManualResetEventSlim(false);
            var mre2 = new System.Threading.ManualResetEventSlim(false);

            using (var imap = GetClient <ImapClient>()) {
                bool fired = false;
                imap.MessageDeleted += (sender, e) => {
                    fired = true;
                    mre2.Set();
                };

                var count = imap.GetMessageCount();
                count.Should().Be.InRange(1, int.MaxValue);                 //interupt the idle thread

                System.Threading.ThreadPool.QueueUserWorkItem(_ => {
                    Delete_Message();
                    mre1.Set();
                });

                mre1.Wait();
                mre2.Wait(TimeSpan.FromSeconds(15));                //give the other thread a moment
                fired.Should().Be.True();
            }
        }
Ejemplo n.º 4
0
        // [Benchmark]
        public void Queue()
        {
            var queue = new ConcurrentQueue <int>();

            using (var wend = new System.Threading.ManualResetEventSlim(false))
            {
                Task.WaitAll(
                    Task.WhenAll(Enumerable.Range(0, WTaskNum).Select(async(idx) =>
                {
                    await Task.Yield();
                    for (int i = 0; i < LoopNum / WTaskNum; i++)
                    {
                        queue.Enqueue(i);
                    }
                })).ContinueWith(t => wend.Set())
                    ,
                    Task.WhenAll(Enumerable.Range(0, TaskNum).Select(async(idx) =>
                {
                    await Task.Yield();
                    while (!wend.IsSet)
                    {
                        await Task.Yield();
                        while (queue.TryDequeue(out var item))
                        {
                        }
                    }
                }))
                    );
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Blocking wait for a task, equivalent to calling Task.Wait(),
        /// but works around a race in Mono that causes Wait() to hang
        /// </summary>
        /// <param name="task">The task to wait for</param>
        /// <returns>The task</returns>
        public static Task WaitForTask(this Task task)
        {
            // Mono has a race when waiting for a
            // task to complete, this workaround
            // ensures that the wait call does not hang
            if (IsRunningMono)
            {
                if (!task.IsCompleted)
                {
                    using (var lck = new System.Threading.ManualResetEventSlim(false))
                    {
                        task.ContinueWith(x => lck.Set());
                        // This ensures we never return with
                        // an incomplete task, but may casue
                        // some spin waiting
                        while (!task.IsCompleted)
                        {
                            lck.Wait();
                        }
                    }
                }
            }
            else
            {
                // Don't throw the exception here
                // let the caller access the task
                try { task.Wait(); }
                catch { }
            }

            return(task);
        }
Ejemplo n.º 6
0
        public void TestElapsedEventPrevented()
        {
            bool watchdogElapsed = false;
            var  testComplete    = new System.Threading.ManualResetEventSlim(false);

            using (Timer watchdog = new Timer(50))
            {
                using (Timer resetTimer = new Timer(10))
                {
                    using (Timer testLength = new Timer(500))
                    {
                        watchdog.Elapsed   += (s, e) => { watchdogElapsed = true; };
                        resetTimer.Elapsed += (s, e) => { watchdog.Restart(); };
                        testLength.Elapsed += (s, e) => { testComplete.Set(); };

                        watchdog.Start();
                        resetTimer.Start();
                        testLength.Start();

                        testComplete.Wait();

                        watchdog.Stop();
                        resetTimer.Stop();
                        testLength.Stop();
                    }
                }
            }

            Assert.IsFalse(watchdogElapsed);
        }
Ejemplo n.º 7
0
        public async Task AcceptorConnectorTest()
        {
            var  address        = Guid.NewGuid().ToString();
            bool isClientClosed = false;
            bool isServerClosed = false;

            var config = new Config {
                DefaultRequestTimeout = System.Threading.Timeout.InfiniteTimeSpan
            };

            using (var transport = new Transport <global::Bond.Box <int>, global::Bond.Box <int> >(config))
                using (var acceptor = transport.MakeServerAcceptor(address, (inMemory, outMemory) => x => Task.FromResult(x)))
                    using (var connector = transport.MakeClientConnector())
                    {
                        var servers        = new List <Transport <global::Bond.Box <int>, global::Bond.Box <int> > .Server>();
                        var newServerEvent = new System.Threading.ManualResetEventSlim(false);

                        acceptor.Accepted += (sender, args) =>
                        {
                            lock (servers)
                            {
                                servers.Add(args.Component);
                            }

                            newServerEvent.Set();
                        };

                        Transport <global::Bond.Box <int>, global::Bond.Box <int> > .Server server;

                        using (var client = await connector.ConnectAsync(address))
                        {
                            newServerEvent.Wait();

                            lock (servers)
                            {
                                Assert.AreEqual(1, servers.Count);
                                server = servers.First();
                            }

                            Assert.IsFalse(server.IsClosed);
                            server.Closed += (sender, args) => { isServerClosed = true; };

                            Assert.IsFalse(client.IsClosed);
                            client.Closed += (sender, args) => { isClientClosed = true; };

                            var request = new global::Bond.Box <int> {
                                value = 100
                            };
                            var response = await client.InvokeAsync(request);

                            Assert.IsTrue(global::Bond.Comparer.Equal(request, response));
                        }

                        server.Dispose();
                    }

            Assert.IsTrue(isClientClosed);
            Assert.IsTrue(isServerClosed);
        }
Ejemplo n.º 8
0
        public async Task SerializableTransactionTest()
        {
            var store = await StoreBuilder.New().CreateAsync();

            var schema = await store.Schemas.New <TestDomainDefinition>().CreateAsync();

            var domain = await store.DomainModels.New().CreateAsync("Test");

            Identity aid;
            dynamic  a;

            using (var s = store.BeginSession(new SessionConfiguration {
                IsolationLevel = SessionIsolationLevel.ReadCommitted
            }))
            {
                a       = new DynamicModelEntity(domain, schema.Definition.XExtendsBaseClass);
                aid     = a.Id;
                a.Value = 10;
                s.AcceptChanges();
            }

            var factory = new TaskFactory();
            var signal  = new System.Threading.ManualResetEventSlim();
            var signal2 = new System.Threading.ManualResetEventSlim();

            var t1 = factory.StartNew(() =>
            {
                using (var s = store.BeginSession(new SessionConfiguration {
                    IsolationLevel = SessionIsolationLevel.Serializable
                }))
                {
                    // Accès sur A pour ouvrir une transaction Serializable (la session ne fait rien). Ce n'est que qu'en on
                    // accède à la donnée que la transaction est crèèe
                    var x = a.Value; // Ou n'importe quoi
                    signal2.Set();
                    signal.Wait();
                    Assert.Equal(a.Value, 10); // On ne "voit" pas les modifications des autres transactions
                }
            });

            Sleep(50);

            var t2 = factory.StartNew(() =>
            {
                signal2.Wait();
                using (var s = store.BeginSession(new SessionConfiguration {
                    IsolationLevel = SessionIsolationLevel.ReadCommitted
                }))
                {
                    a.Value = 11;
                    s.AcceptChanges();
                }
                signal.Set();
            });

            Task.WaitAll(t1, t2);
        }
Ejemplo n.º 9
0
        public async Task ReadPhantomTest()
        {
            var store = await StoreBuilder.New().CreateAsync();

            var schema = await store.Schemas.New <TestDomainDefinition>().CreateAsync();

            var domain = await store.DomainModels.New().CreateAsync("Test");

            Identity aid;
            dynamic  a;

            // Création d'une valeur
            using (var s = store.BeginSession(new SessionConfiguration {
                IsolationLevel = SessionIsolationLevel.ReadCommitted
            }))
            {
                a       = new DynamicModelEntity(domain, schema.Definition.XExtendsBaseClass);
                aid     = a.Id;
                a.Value = 10;
                s.AcceptChanges();
            }

            var factory = new TaskFactory();
            var signal  = new System.Threading.ManualResetEventSlim();
            var signal2 = new System.Threading.ManualResetEventSlim();

            var t1 = factory.StartNew(() =>
            {
                // Cette transaction démarre avant l'autre mais elle va pouvoir 'voir' ses modifs commités
                using (var s = store.BeginSession(new SessionConfiguration {
                    IsolationLevel = SessionIsolationLevel.ReadCommitted
                }))
                {
                    signal2.Set();
                    signal.Wait();             // On attend le commit de l'autre
                    Assert.Equal(11, a.Value); // On "voit" dèja que la valeur a été modifiée
                }
            });

            Sleep(50);

            var t2 = factory.StartNew(() =>
            {
                signal2.Wait(); // On s'assure de démarrer aprés l'autre transaction
                using (var s = store.BeginSession(new SessionConfiguration {
                    IsolationLevel = SessionIsolationLevel.ReadCommitted
                }))
                {
                    a.Value = 11;
                    s.AcceptChanges();
                }
                signal.Set();
            });

            Task.WaitAll(t1, t2);
        }
Ejemplo n.º 10
0
        public void IsBrowserMainJsControllerReady(string mainControllerName, Action <bool> callback)
        {
            string checkscript = "typeof " + mainControllerName + " === 'undefined' ? false : " + mainControllerName + ".ready";

            System.Threading.ManualResetEventSlim waitForBrowser = new System.Threading.ManualResetEventSlim(false);
            var t = browser.EvaluateScriptAsync(checkscript).ContinueWith((resp) => {
                bool ret = Convert.ToBoolean(resp.Result.Result);
                waitForBrowser.Set();
                callback(ret);
            });
        }
Ejemplo n.º 11
0
 public void SendMessage(byte[] messageContents)
 {
                 #if TRACE
     Console.WriteLine(new System.Diagnostics.StackTrace(true).GetFrame(0));
                 #endif
     if (!thread_tx.IsAlive)
     {
         throw new InvalidOperationException("thread_tx is not alive.");
     }
     sendQueue.Enqueue(messageContents);
     mre_tx.Set();
 }
Ejemplo n.º 12
0
        private ConsoleUI(ApplicationViewModel application)
        {
            Application = application;

            ComponentLibraryScannningWaiter = new System.Threading.ManualResetEventSlim();
            if (Application.ComponentLibraryViewModel.IsRescanning == false)
            {
                ComponentLibraryScannningWaiter.Set();
            }

            //attach event to the rescanned event of components library, so that console prompt is shown after rescan is done
            Application.ComponentLibraryViewModel.Rescanned += new EventHandler(ComponentLibraryViewModel_Rescanned);
        }
Ejemplo n.º 13
0
        private ConsoleUI(ApplicationViewModel application)
        {
            Application = application;

            ComponentLibraryScannningWaiter = new System.Threading.ManualResetEventSlim();
            if (Application.ComponentLibraryViewModel.IsRescanning == false)
            {
                ComponentLibraryScannningWaiter.Set();
            }

            //attach event to the rescanned event of components library, so that console prompt is shown after rescan is done
            Application.ComponentLibraryViewModel.Rescanned += new EventHandler(ComponentLibraryViewModel_Rescanned);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Runs the experiment asynchronously... it will wait till the experiment runner thread completes before returning.
        /// </summary>
        /// <param name="experiment">The experiment.</param>
        /// <param name="progress">The progress.</param>
        private void RunExperimentAsync(Experiment experiment, IProgress progress, Workspace workspace, ComponentsLibrary library)
        {
            using (var waiter = new System.Threading.ManualResetEventSlim())
            {
                experiment.RunExperiment(progress, workspace, library);
                experiment.ExperimentCompleted += (sender, args) =>
                {
                    waiter.Set();
                };

                waiter.Wait();
            }
        }
Ejemplo n.º 15
0
        private void SetupOptions()
        {
            if (currentState == Status.Invalid)
            {
                currentState = Status.Stopped;
            }

            if (options.InitialStateEnumValue == Status.Running)
            {
                startSignal.Set();
            }

            if (options.GracePeriodEnabled)
            {
                gracePeriodTimer.Interval = TimeSpan.FromSeconds(options.GracePeriodDuration).TotalMilliseconds;
            }

            if (options.DoubleCheckEnabled)
            {
                doubleCheckTimer.Interval = TimeSpan.FromSeconds(options.DoubleCheckDuration).TotalMilliseconds;
            }

            ResetTimers();
        }
Ejemplo n.º 16
0
        //const string OGG_FILE = @"..\TestFiles\2test.ogg";

        static void Main()
        {
            using (var fs = File.OpenRead(OGG_FILE))
                //using (var fwdStream = new ForwardOnlyStream(fs))
                using (var waveStream = new VorbisWaveStream(fs))
                    using (var waveOut = new WaveOutEvent())
                    {
                        var wait = new System.Threading.ManualResetEventSlim(false);
                        waveOut.PlaybackStopped += (s, e) => wait.Set();

                        waveOut.Init(waveStream);
                        waveOut.Play();

                        wait.Wait();
                    }
        }
Ejemplo n.º 17
0
        static int Main(string[] args)
        {
            Options options;

            try
            {
                options = Options.Parse(args);
            } catch (Options.UsageException usageException)
            {
                System.Console.Error.WriteLine(usageException.Message);
                return(1);
            }

            if (options.Service)
            {
                System.ServiceProcess.ServiceBase.Run(new Service(options));
            }
            else
            {
                using var audioMeterEvent = CreateAudioMeterEvent(options, new ConsoleLogger());
                audioMeterEvent.Start();

                Microsoft.Win32.SystemEvents.PowerModeChanged += (object sender, Microsoft.Win32.PowerModeChangedEventArgs eventArgs) =>
                {
                    if (eventArgs.Mode == Microsoft.Win32.PowerModes.Suspend)
                    {
                        audioMeterEvent.Stop();
                    }
                    if (eventArgs.Mode == Microsoft.Win32.PowerModes.Resume)
                    {
                        audioMeterEvent.Start();
                    }
                };

                var cancelKeyPressed = new System.Threading.ManualResetEventSlim();
                System.Console.CancelKeyPress += (object sender, System.ConsoleCancelEventArgs eventArgs) =>
                {
                    cancelKeyPressed.Set();
                    eventArgs.Cancel = true;
                };
                cancelKeyPressed.Wait();
                audioMeterEvent.Stop();
                audioMeterEvent.Wait();
            }

            return(0);
        }
Ejemplo n.º 18
0
            public void Complete(bool completedSynchronously)
            {
                CompletedSynchronously = completedSynchronously;
                if (completedSynchronously)
                {
                    IsCompleted = true;
                }

                lock ( _sync )
                {
                    IsCompleted = true;
                    if (_resetEvent != null)
                    {
                        _resetEvent.Set();
                    }
                }
            }
Ejemplo n.º 19
0
        /// <summary>
        /// Establishes a secure connection and calls the DataRecieved and MessageReceived multi-cast delegates
        /// </summary>
        /// <param name="bytes">The data received from the remote machine</param>
        /// <returns>The data received from the remote machine</returns>
        protected override byte[] OnDataReceived(byte[] bytes)
        {
            byte[] result = base.OnDataReceived(bytes);
            if (_remotePublicKey != null)     //then we're secure
            {
                OnSecureDataReceived(result); //not sure we want to set the result to the unencrypted bytes
            }
            else
            {
                string json = string.Empty;

                try
                {
                    var json_str = bytes.FromBase64();
                    //var json_str = result.AsString();
                    json = json_str;//.FromBase64();
                    Console.WriteLine("Remote Public Key (json): " + json);
                    //if (TcpHelpers.IsBase64Encoded(json))
                    //{
                    //    System.Diagnostics.Debug.WriteLine("Remote public key is curiously Base64 encoded");
                    //    json = json.FromBase64(); //still not sure how this gets base64 encoded in the first place
                    //}
                    Logging.Log.v((IsServerSide ? "Server" : "Client") + " obtaining remote public key");
                    _remotePublicKey = Newtonsoft.Json.JsonConvert.DeserializeObject <RSAParameters>(json);

                    Logging.Log.v("{0} received {1}'s public Key", IsServerSide ? "Server" : "Client", IsServerSide ? "client" : "server");

                    //Complete the connection
                    base.OnConnected(Socket.RemoteEndPoint);
                    //IsConnectedResetEvent.Set();
                    //Connected?.Invoke(this, Socket.RemoteEndPoint);
                    _mreSecured.Set();
                }
                catch (Exception e)
                {
                    //ignore this message and move on
                    Log.e("SecureClient.OnDataReceived.Exception: " + e.ToString());
                    Log.v("json = {0}", json);
                    //System.Diagnostics.Debug.WriteLine(e.ToString());
                    //System.Diagnostics.Debugger.Break();
                }
            }
            return(result);
        }
Ejemplo n.º 20
0
        static void tcbah_HasData(object sender)
        {
            var tcbah = sender as TcpByteAgentHandler;

            foreach (var item in tcbah.GetCommands())
            {
                if (item != null)
                {
                }
                if (item is ChainsAPM.Commands.Common.SendString)
                {
                    tcbah.Dispose();
                    if (counter3 == 0)
                    {
                        waitHandl.Set();
                    }
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Does the async call as synchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="act">The act.</param>
        /// <returns></returns>
        protected T DoAsyncCallAsSynchronous <T>(Action <Callback <T> > act) where T : Response, new()
        {
            T response = null;

            using (var waiter = new System.Threading.ManualResetEventSlim())
            {
                var callback = new Callback <T>();
                callback.CallCompleted += (sender, args) =>
                {
                    response = args.Response;
                    waiter.Set();
                };

                act(callback);

                waiter.Wait(); //wait until call service is done (when waiter is set)
            }

            return(response);
        }
Ejemplo n.º 22
0
        } // End Sub NotMain

        public static async System.Threading.Tasks.Task runVote()
        {
            // synchronization
            System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim();

            // STEP 1 - Run Chrome
            IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());

            using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true))
            {
                // STEP 2 - Create a debugging session
                ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo();

                ChromeSessionInfo sessionInfo = (sessionInfos != null && sessionInfos.Length > 0) ?
                                                sessionInfos[sessionInfos.Length - 1]
                    : new ChromeSessionInfo();

                IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory();
                IChromeSession        chromeSession        = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);



                CommandResponse <ClearBrowserCacheCommandResponse> clearCache = await chromeSession.SendAsync(new ClearBrowserCacheCommand());

                System.Console.WriteLine(clearCache.Result);


                CommandResponse <ClearBrowserCookiesCommandResponse> clearCookies = await chromeSession.SendAsync(new ClearBrowserCookiesCommand());

                System.Console.WriteLine(clearCookies.Result);

                // CommandResponse<ClearObjectStoreCommandResponse> clearObjectStorage = await chromeSession.SendAsync(new ClearObjectStoreCommand());
                // System.Console.WriteLine(clearObjectStorage.Result);


                // CommandResponse<ClearDataForOriginCommandResponse> clearStorage = await chromeSession.SendAsync(new ClearDataForOriginCommand() { Origin= "www.20min.ch", StorageTypes = "all" });
                // Whatever the correct command for clear everything is...
                await ClearData(chromeSession, "www.20min.ch", "all");
                await ClearData(chromeSession, "20min.ch", "all");
                await ClearData(chromeSession, "*", "all");
                await ClearData(chromeSession, "all", "all");



                // STEP 3 - Send a command
                //
                // Here we are sending a commands to tell chrome to set the viewport size
                // and navigate to the specified URL
                await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                {
                    Width  = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
                    Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height,
                    Scale  = 1
                });


                CommandResponse <NavigateCommandResponse> navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                {
                    // Url = "http://www.google.com"
                    // Url = "about:blank"
                    Url = "https://www.20min.ch/schweiz/news/story/GA-wird-teurer--kein-Studentenrabatt-mehr-27426069"
                });

                System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id);



                // STEP 4 - Register for events (in this case, "Page" domain events)
                // send an command to tell chrome to send us all Page events
                // but we only subscribe to certain events in this session

                ICommandResponse pageEnableResult = await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Page.EnableCommand>();

                System.Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired =>
                {
                    // we cannot block in event handler, hence the task
                    System.Threading.Tasks.Task2.Run(async() =>
                    {
                        System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);

                        /*
                         * long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId;
                         * long bodyNodeId =
                         *  (await chromeSession.SendAsync(new QuerySelectorCommand
                         *  {
                         *      NodeId = documentNodeId,
                         *      Selector = "body"
                         *  })).Result.NodeId;
                         *
                         * long height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height;
                         */


                        CommandResponse <EvaluateCommandResponse> removePopOver = await chromeSession.SendAsync(new EvaluateCommand
                        {
                            Expression = @"
    window.setTimeout(function(){ 
        var one = document.getElementById('onesignal-popover-cancel-button');
            if(one != null)
        one.click();
    }, 2000);

/*
window.setTimeout(function(){ 
        window.close();
    }, 4000);
*/
    ",
                            // ContextId = 123
                        });



                        CommandResponse <EvaluateCommandResponse> closeWindow = await chromeSession.SendAsync(new EvaluateCommand
                        {
                            // <a href="javascript:window.close(self);">run</a>
                            Expression = @"
console.log('closing');
var a = document.createElement('a');
var linkText = document.createTextNode('T');
a.id = 'lolz';
a.appendChild(linkText);
a.href = 'javascript:window.close(self);';
document.body.appendChild(a);
document.getElementById('lolz').click();
// window.close();
// open(location, '_self').close();
"
                                         // ContextId = 123
                            ,
                            UserGesture = true
                        });
                        System.Console.WriteLine(closeWindow.Result);



                        System.Console.WriteLine("Closing page");
                        var closeTargetResponse = chromeSession.SendAsync(
                            new CloseTargetCommand()
                        {
                            TargetId = navigateResponse.Result.FrameId
                        }
                            );

                        /*
                         * MasterDevs.ChromeDevTools.CommandResponse<CloseTargetCommandResponse> closeTargetResponse =
                         *  await chromeSession.SendAsync(
                         *  new CloseTargetCommand()
                         *  {
                         *      TargetId = navigateResponse.Result.FrameId
                         *  }
                         * );
                         */
                        System.Console.WriteLine("Page closed");
                        System.Console.WriteLine(closeTargetResponse);



                        if (true)
                        {
                            // document.querySelector("#thread3367_msg3367 > div.rate_button > div.clickable.top").click()
                            // document.querySelector("#thread3367_msg3367 > div.rate_button > div.clickable.bottom").click()
                            string threadId      = "3399";
                            string msgId         = "3399";
                            string voteDirection = "bottom"; // top / bottom

                            string votingElement = "#thread" + threadId + "_msg" + msgId + @" > div.rate_button > div.clickable." + voteDirection;

                            string javaScriptToExecute = @"
    (function()
    {
        var elmnt = document.querySelector('" + votingElement + @"');
        if (elmnt != null)
        {
            elmnt.scrollIntoView();
            window.scrollBy(0, -70)
            elmnt.click();
            console.log('https://www.youtube.com/watch?v=h6mJw50OdZ4&t=163');
            console.log('The first honest vote ever in a rotten borough !');
            console.log('CopyLeft 2019 StS');
        }
    })();
    ";


                            CommandResponse <EvaluateCommandResponse> evr = await chromeSession.SendAsync(new EvaluateCommand
                            {
                                Expression = javaScriptToExecute,
                                // ContextId = 123
                            });

                            if (evr.Result.ExceptionDetails != null)
                            {
                                System.Console.WriteLine(evr.Result.ExceptionDetails);
                            }
                            else
                            {
                                System.Console.WriteLine("voted");
                            }
                        }

                        await System.Threading.Tasks.Task2.Delay(3000);

                        // tell the main thread we are done
                        screenshotDone.Set();
                    });
                }); // End Sub LoadEventFired

                // wait for screenshoting thread to (start and) finish
                screenshotDone.Wait();

                System.Console.WriteLine("Exiting ..");
            } // End Using chromeProcess
        }     // End Sub Main(string[] args)
Ejemplo n.º 23
0
 private void OnProcessStopped(object sender, EventArgs e)
 {
     crashSignal.Set();
     gracePeriodTimer.Stop();
 }
Ejemplo n.º 24
0
        } // End Sub KillHeadless

        private static void Main(string[] args)
        {
            KillHeadless();

            Task.Run(async() =>
            {
                // synchronization
                System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim();

                // STEP 1 - Run Chrome
                IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
                using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true))
                {
                    // STEP 2 - Create a debugging session
                    //ChromeSessionInfo sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault();
                    ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo();
                    ChromeSessionInfo sessionInfo    = (sessionInfos != null && sessionInfos.Length > 0) ?
                                                       sessionInfos[sessionInfos.Length - 1]
                        : new ChromeSessionInfo();

                    IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory();
                    IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

                    // STEP 3 - Send a command
                    //
                    // Here we are sending a commands to tell chrome to set the viewport size
                    // and navigate to the specified URL
                    await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                    {
                        Width  = ViewPortWidth,
                        Height = ViewPortHeight,
                        Scale  = 1
                    });

                    var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                    {
                        Url = "http://www.google.com"
                    });
                    System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id);

                    // STEP 4 - Register for events (in this case, "Page" domain events)
                    // send an command to tell chrome to send us all Page events
                    // but we only subscribe to certain events in this session
                    ICommandResponse pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>();
                    System.Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                    chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired =>
                    {
                        // we cannot block in event handler, hence the task
                        Task.Run(async() =>
                        {
                            System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);

                            long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId;
                            long bodyNodeId     =
                                (await chromeSession.SendAsync(new QuerySelectorCommand
                            {
                                NodeId = documentNodeId,
                                Selector = "body"
                            })).Result.NodeId;

                            long height = (await chromeSession.SendAsync(new GetBoxModelCommand {
                                NodeId = bodyNodeId
                            })).Result.Model.Height;

                            await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                            {
                                Width  = ViewPortWidth,
                                Height = height,
                                Scale  = 1
                            });

                            System.Console.WriteLine("Taking screenshot");
                            var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                                Format = "png"
                            });

                            byte[] data = System.Convert.FromBase64String(screenshot.Result.Data);
                            System.IO.File.WriteAllBytes("output.png", data);
                            System.Console.WriteLine("Screenshot stored");


                            PrintToPDFCommand printCommand = new PrintToPDFCommand()
                            {
                                Scale           = 1,
                                MarginTop       = 0,
                                MarginLeft      = 0,
                                MarginRight     = 0,
                                MarginBottom    = 0,
                                PrintBackground = true,
                                Landscape       = false,
                                PaperWidth      = cm2inch(21),
                                PaperHeight     = cm2inch(29.7)
                            };


                            System.Console.WriteLine("Printing PDF");
                            CommandResponse <PrintToPDFCommandResponse> pdf = await chromeSession.SendAsync(printCommand);
                            System.Console.WriteLine("PDF printed.");

                            byte[] pdfData = System.Convert.FromBase64String(pdf.Result.Data);
                            System.IO.File.WriteAllBytes("output.pdf", pdfData);
                            System.Console.WriteLine("PDF stored");


                            // tell the main thread we are done
                            screenshotDone.Set();
                        });
                    });

                    // wait for screenshoting thread to (start and) finish
                    System.Console.WriteLine("Exiting ..");
                    screenshotDone.Wait();
                }
            }).Wait();
        }
Ejemplo n.º 25
0
 private void OnDoubleCheckTimeElapsed(object sender, ElapsedEventArgs e)
 {
     checkSignal.Set();
     doubleCheckTimer.Stop();
 }
Ejemplo n.º 26
0
 private void ResetTimers()
 {
     resetTimer.Set();
     gracePeriodTimer.Stop();
     doubleCheckTimer.Stop();
 }
        /// <summary>
        /// Runs the experiment asynchronously... it will wait till the experiment runner thread completes before returning.
        /// </summary>
        /// <param name="experiment">The experiment.</param>
        /// <param name="progress">The progress.</param>
        private void RunExperimentAsync(Experiment experiment, IProgress progress, Workspace workspace, ComponentsLibrary library)
        {
            using (var waiter = new System.Threading.ManualResetEventSlim())
            {
                experiment.RunExperiment(progress, workspace, library);
                experiment.ExperimentCompleted += (sender, args) =>
                {
                    waiter.Set();
                };

                waiter.Wait();
            }
        }