/// <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); }
public Fiber(bool shouldDispose = true) : base(shouldDispose) { ManualResetEvent = new System.Threading.ManualResetEventSlim(); UpdateTokenSource = new System.Threading.CancellationTokenSource(); }
private long WaitNextTimestamp(int milli) { using (var handle = new System.Threading.ManualResetEventSlim(false)) handle.Wait(milli); return(GetTimestamp()); }
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); }
public UpdateableBase(bool initialState, int spinCount, System.TimeSpan delay, bool shouldDispose = true) : base(shouldDispose) { m_ResetEvent = new System.Threading.ManualResetEventSlim(initialState, spinCount); m_TokenSource = new System.Threading.CancellationTokenSource(delay); }
protected virtual void Dispose(bool disposing) { if (!IsDisposed) { IsDisposed = true; if (disposing) { ResetTimers(); Stop(); gracePeriodTimer?.Dispose(); doubleCheckTimer?.Dispose(); crashSignal?.Dispose(); startSignal?.Dispose(); checkSignal?.Dispose(); resetTimer?.Dispose(); } gracePeriodTimer = null; doubleCheckTimer = null; crashSignal = null; startSignal = null; checkSignal = null; resetTimer = null; } }
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(); } }
// [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)) { } } })) ); } }
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); }
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); }
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); }
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); }
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); }); }
public bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation) { if (oauth == null || oauth.CallbackUrl == null) { return(false); } // Make sure we're redirecting from our SFSafariViewController and not some other app if (sourceApplication != "com.apple.SafariViewService") { return(false); } var uri = new Uri(url.AbsoluteString); // Only handle schemes we expect if (!WebUtil.CanHandleCallback(oauth.CallbackUrl, uri)) { return(false); } var resp = oauth.ParseCallback(uri); var waitReq = new System.Threading.ManualResetEventSlim(); IDictionary <string, string> items = null; var accessTokenTask = Task.Run(async() => { items = await oauth.GetAccessTokenAsync(resp); }); accessTokenTask.Wait(); var account = oauth.GetAccountFromResponse <OAuth1Account>(items); Plugin.SocialAuth.iOS.SocialAuth.PresentingViewController.InvokeOnMainThread(async() => await Plugin.SocialAuth.iOS.SocialAuth.PresentingViewController.DismissViewControllerAsync(true)); if (account == null) { tcsAuth?.TrySetException(new Exception("Failed to parse server response.")); } else { tcsAuth?.TrySetResult(account); } // Reset oauth for next request oauth = null; return(true); }
/// <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(); } }
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); }
/// <summary> /// More acurate delay implementation /// </summary> /// <returns>The delay.</returns> /// <param name="miliseconds">Miliseconds.</param> public static Task DelayAsync(int miliseconds) { if (miliseconds >= 60) { return(Task.Delay(miliseconds)); } return(Task.Factory.StartNew(() => { using (var mres = new System.Threading.ManualResetEventSlim(false)) { mres.Wait(miliseconds); } }, TaskCreationOptions.PreferFairness)); }
public void RunsTheCallbackAsExpected() { var called = false; using var waitEvent = new ManualResetEventSlim(false); using var target = new Timer(); target.Start(TimeSpan.FromSeconds(1), () => { called = true; }, error => { }); waitEvent.Wait(5000); Assert.True(called); }
//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(); } }
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); }
public void RunsTheErrorCallbackAsExpected() { var called = false; using var waitEvent = new ManualResetEventSlim(false); using var target = new Timer(); target.Start(TimeSpan.FromSeconds(1), () => throw new InvalidOperationException(), error => { Assert.IsInstanceOf <InvalidOperationException>(error); called = true; }); waitEvent.Wait(5000); Assert.True(called); }
/// <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); }
public ProcessRunner(ProcessOptions opts) { Stopwatch = new Stopwatch(); currentState = opts.InitialStateEnumValue; previousState = Status.Invalid; resetTimer = new Signal(true); startSignal = new Signal(false); checkSignal = new Signal(false); crashSignal = new Signal(false); options = opts.Clone() as ProcessOptions; gracePeriodTimer = new Timer { AutoReset = false, Enabled = false }; doubleCheckTimer = new Timer { AutoReset = false, Enabled = false }; gracePeriodTimer.Elapsed += OnGracePeriodTimeElapsed; doubleCheckTimer.Elapsed += OnDoubleCheckTimeElapsed; SetupOptions(); }
static void Main(string[] args) { Dictionary <int, ChainsAPM.Interfaces.ICommand <byte> > CommandList = new Dictionary <int, ICommand <byte> >(); var cmd1 = new ChainsAPM.Commands.Common.SendString(""); CommandList.Add(cmd1.Code, cmd1); CallContext.LogicalSetData("CommandProviders", CommandList); for (int i = 0; i < MAX; i++) { var whand = new System.Threading.ManualResetEventSlim(); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((object o) => { var rand = new Random(); var hostname = System.Configuration.ConfigurationManager.AppSettings["hostname"]; var port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["port"]); System.Net.Sockets.TcpClient tcpC = new System.Net.Sockets.TcpClient(hostname, port); TcpByteAgentHandler tcbah = new TcpByteAgentHandler(new TcpByteTransport(tcpC), TcpByteAgentHandler.HandlerType.SendHeavy); tcbah.AddCommand(new ChainsAPM.Commands.Common.SendString("")); itemCounter.GetOrAdd(tcbah.GetHashCode(), System.Threading.Interlocked.Increment(ref counter2)); System.Threading.Interlocked.Increment(ref counter3); tcbah.HasData += tcbah_HasData; tcbah.Disconnected += tcbah_Disconnected; tcpC.NoDelay = true; int counter = 0; int msgCounter = 0; int stopCount = 10000; do { tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); msgCounter += 72; System.Threading.Thread.Sleep(rand.Next(5, 25)); } while (++counter != stopCount); Console.WriteLine("Messages Sent: {0}", msgCounter); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString("Done!")); Console.WriteLine("Done Sent!"); lock (msgLock) { totalMessagesSent += msgCounter + 1; } })); } waitHandl.Wait(); Console.WriteLine("Messages Sent: {0}", totalMessagesSent); }
static void Main(string[] args) { Dictionary<int, ChainsAPM.Interfaces.ICommand<byte>> CommandList = new Dictionary<int, ICommand<byte>>(); var cmd1 = new ChainsAPM.Commands.Common.SendString(""); CommandList.Add(cmd1.Code, cmd1); CallContext.LogicalSetData("CommandProviders", CommandList); for (int i = 0; i < MAX; i++) { var whand = new System.Threading.ManualResetEventSlim(); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((object o) => { var rand = new Random(); var hostname = System.Configuration.ConfigurationManager.AppSettings["hostname"]; var port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["port"]); System.Net.Sockets.TcpClient tcpC = new System.Net.Sockets.TcpClient(hostname, port); TcpByteAgentHandler tcbah = new TcpByteAgentHandler(new TcpByteTransport(tcpC), TcpByteAgentHandler.HandlerType.SendHeavy); tcbah.AddCommand(new ChainsAPM.Commands.Common.SendString("")); itemCounter.GetOrAdd(tcbah.GetHashCode(), System.Threading.Interlocked.Increment(ref counter2)); System.Threading.Interlocked.Increment(ref counter3); tcbah.HasData += tcbah_HasData; tcbah.Disconnected += tcbah_Disconnected; tcpC.NoDelay = true; int counter = 0; int msgCounter = 0; int stopCount = 10000; do { tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(10, 100))); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString(randString(5, 1000))); msgCounter += 72; System.Threading.Thread.Sleep(rand.Next(5, 25)); } while (++counter != stopCount); Console.WriteLine("Messages Sent: {0}", msgCounter); tcbah.SendCommand(new ChainsAPM.Commands.Common.SendString("Done!")); Console.WriteLine("Done Sent!"); lock (msgLock) { totalMessagesSent += msgCounter + 1; } })); } waitHandl.Wait(); Console.WriteLine("Messages Sent: {0}", totalMessagesSent); }
static void Main(string[] args) { var dir = args.FirstOrDefault(x => !x.StartsWith("/") && !x.StartsWith("-") && System.IO.Directory.Exists(x)) .NotEmpty(Environment.CurrentDirectory); var options = new HashSet<string>(args.Where(x => x != dir).Select(x => x.TrimStart('/', '-').ToLower()).Distinct()); var buildAll = options.Contains("build"); var helper = new Helper(dir); HashSet<string> files_in_project = null; Action reindex_project_files = () => { files_in_project = helper.ProjectFiles = new HashSet<string>(FindProjectFiles(dir, false).SelectMany(x => GetFilesInProject(x)), StringComparer.OrdinalIgnoreCase); helper.IndexFiles(); }; reindex_project_files(); helper.OnChanged = file => Console.WriteLine(DateTime.Now.TimeOfDay + " - " + file); var minifier1 = new Microsoft.Ajax.Utilities.Minifier(); CssBundleHelper.MinifyCss = (file, css) => { var cssParser = new Microsoft.Ajax.Utilities.CssParser(); cssParser.FileContext = file; cssParser.Settings = new Microsoft.Ajax.Utilities.CssSettings { CommentMode = Microsoft.Ajax.Utilities.CssComment.None }; return cssParser.Parse(css); }; var vsExtDir = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\VisualStudio\11.0\Extensions"); var lessc_wsf = Utilities.GetFiles(vsExtDir, file => file.Split('\\').Last().ToLower() == "lessc.wsf").FirstOrDefault(); if (string.IsNullOrEmpty(lessc_wsf)) { Console.Error.WriteLine("lessc.wsf could not be found under {0}", vsExtDir); return; } JsHelper.MinifyJs = minifier1.MinifyJavaScript; JsHelper.MinifyJsWithSourceMap = (file, js) => { var baseFile = file.Substring(0, file.Length - ".js".Length); var min_file = baseFile + ".min.js"; var map_file = min_file + ".map"; var min_filename = Path.GetFileName(min_file); var map_filename = Path.GetFileName(map_file); using (var min_writer = new System.IO.StreamWriter(min_file, false, new System.Text.UTF8Encoding(true))) using (var map_writer = new System.IO.StreamWriter(map_file, false, new System.Text.UTF8Encoding(false))) using (var v3SourceMap = new Microsoft.Ajax.Utilities.V3SourceMap(map_writer)) { v3SourceMap.StartPackage(min_file, map_file); var jsParser = new Microsoft.Ajax.Utilities.JSParser(js); jsParser.FileContext = file; var block = jsParser.Parse(new Microsoft.Ajax.Utilities.CodeSettings { SymbolsMap = v3SourceMap, PreserveImportantComments = false, TermSemicolons = true }); min_writer.Write(block.ToCode() + Environment.NewLine + "//@ sourceMappingURL=" + map_filename); v3SourceMap.EndPackage(); } }; LessHelper.CompileLess = (fileName, less) => { var tempFileName = System.IO.Path.GetTempFileName(); var processStartInfo = new System.Diagnostics.ProcessStartInfo("cscript", "/nologo /s \"" + lessc_wsf + "\" \"" + fileName + "\" \"" + tempFileName + "\"") { CreateNoWindow = true, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, UseShellExecute = false }; using (var proc = new System.Diagnostics.Process { StartInfo = processStartInfo }) { proc.Start(); proc.WaitForExit(); var content = System.IO.File.ReadAllText(tempFileName); System.IO.File.Delete(tempFileName); return content; } }; var mre = new System.Threading.ManualResetEventSlim(false); using (var fileSystem = new System.IO.FileSystemWatcher(dir) { EnableRaisingEvents = true, IncludeSubdirectories = true }) { fileSystem.Changed += (s, e) => { if (rx_project_file.IsMatch(e.FullPath)) { reindex_project_files(); return; } if (!files_in_project.Contains(e.FullPath)) return; mre.Wait(500); if (!System.IO.File.Exists(e.FullPath)) return; helper.FileChangedAsync(e.FullPath).Wait(); }; fileSystem.Deleted += (s, e) => { if (!files_in_project.Contains(e.FullPath)) return; mre.Wait(500); helper.FileDeleted(e.FullPath); }; fileSystem.Renamed += (s, e) => { if (!files_in_project.Contains(e.FullPath)) return; mre.Wait(500); helper.FileRenamed(e.OldFullPath, e.FullPath); }; ((Action)(async () => { if (buildAll) { var alldependencies = helper.Files.SelectMany(x => x.Dependencies).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); await System.Threading.Tasks.Task.WhenAll(alldependencies.Select(x => helper.FileChangedAsync(x)).ToArray()); } Console.Beep(); Console.WriteLine("Build Complete"); }))(); while (true) { mre.Wait(500); } } }
private void InitializeAgentThread(JvmtiEnvironment environment, JniEnvironment nativeEnvironment) { _agentStartedEvent = new ManualResetEventSlim(false); _agentThread = CreateAgentThread(nativeEnvironment); _agentCallbackDelegate = AgentDispatcherThread; JvmtiErrorHandler.ThrowOnFailure(environment.RawInterface.RunAgentThread(environment, _agentThread, _agentCallbackDelegate, IntPtr.Zero, JvmThreadPriority.Maximum)); _agentStartedEvent.Wait(); }
private void StartSubscription(PubnubSubscription subscription) { Task.Factory.StartNew(() => { int failureCount = 0; // check if the subscription still exists in the dictionary // if not, then end this task, otherwise, repeat. using (var handle = new System.Threading.ManualResetEventSlim(false)) { while (_subscriptions.ContainsKey(subscription.Channel)) { try { var url = PubnubRequest.BuildUrl(PubnubConfiguration.EnableSsl, "subscribe", PubnubConfiguration.SubscribeKey, subscription.Channel, "0", subscription.TimeToken.ToString(CultureInfo.InvariantCulture)); var request = new PubnubRequest(); string json; request.Execute(url, out json); var result = JsonConvert.DeserializeObject<List<object>>(json); #if DEBUG System.Diagnostics.Debug.WriteLine(json); #endif if (result[0] is JArray && result[0].ToString() != "[]") { // loop through each message and fire individually for (var i = 0; i < ((JArray)result[0]).Count; i++) { var message = ((JArray)result[0])[i].ToString(); if (MessageRecieved != null && !string.IsNullOrEmpty(message)) try { MessageRecieved(null, new PubNubEventArgs { Channel = subscription.Channel, Message = message }); } catch (Exception exp) { // adding this try catch because if we have multiple messages and one of // them encouters an unhandled exception it should not impact the others // or the subscription time token. System.Diagnostics.Debug.WriteLine("MessageRecievedException: " + exp.Message); } } } // update the time token PubnubSubscription retrievedSubscription; if (_subscriptions.TryGetValue(subscription.Channel, out retrievedSubscription)) retrievedSubscription.TimeToken = Convert.ToInt64(result[1].ToString()); // reset the failure count failureCount = 0; } catch (Exception exp) { System.Diagnostics.Debug.WriteLine("SubscriptionException: " + exp.Message); failureCount++; handle.Wait(GetWaitTimeForErrorCount(failureCount)); // rather than throwing the errors, we collect them for // periodic analysis, the idea is to enhance this with error limits // and a backoff strategy incase there is a problem with Pubnub // or the local connection to pubnub PubnubSubscription retrievedSubscription; if (_subscriptions.TryGetValue(subscription.Channel, out retrievedSubscription)) retrievedSubscription.Errors.Add(exp); } } } }); }
} // 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)
} // 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(); }
static public void ExecuteShellVerb(ShellVerbOptions invokedVerbOptions) { using (var sshClient = DeploymentManager.CreateClient(invokedVerbOptions)) { var exitEvent = new System.Threading.ManualResetEventSlim(false); sshClient.Connect(); var terminalModes = new Dictionary <TerminalModes, uint>(); terminalModes.Add(TerminalModes.ECHO, 0); terminalModes.Add(TerminalModes.IGNCR, 1); var bufferWidth = (uint)Console.BufferWidth; var bufferHeight = (uint)Console.BufferHeight; var windowWidth = (uint)Console.WindowWidth; var windowHeight = (uint)Console.WindowHeight; var bufferSize = Console.BufferWidth * Console.BufferHeight; var encoding = System.Text.Encoding.ASCII; using (var shell = sshClient.CreateShellStream(TerminalName, bufferWidth, bufferHeight, windowWidth, windowHeight, bufferSize, terminalModes)) { var escapeSequenceBytes = new List <byte>(128); var isInEscapeSequence = false; byte rxBytePrevious = 0; byte rxByte = 0; byte escapeSequenceType = 0; shell.DataReceived += (s, e) => { var rxBuffer = e.Data; for (var i = 0; i < rxBuffer.Length; i++) { rxByte = rxBuffer[i]; // We've found the beginning of an escapr sequence if (isInEscapeSequence == false && rxByte == Escape) { isInEscapeSequence = true; escapeSequenceBytes.Clear(); rxBytePrevious = rxByte; continue; } // Print out the character if we are not in an escape sequence and it is a printable character if (isInEscapeSequence == false) { if (rxByte >= 32 || (rxByte >= 8 && rxByte <= 13)) { Console.Write((char)rxByte); } else { var originalColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("[NPC " + rxByte.ToString() + "]"); Console.ForegroundColor = originalColor; } rxBytePrevious = rxByte; continue; } if (isInEscapeSequence == true) { // Add the byte to the escape sequence escapeSequenceBytes.Add(rxByte); // Ignore the second escape byte 91 '[' or ']' if (rxBytePrevious == Escape) { rxBytePrevious = rxByte; if (ControlSequenceInitiators.Contains(rxByte)) { escapeSequenceType = rxByte; continue; } else { escapeSequenceType = 0; } } // Detect if it's the last byte of the escape sequence (64 to 126) // This last character determines the command to execute var endOfSequenceType91 = escapeSequenceType == (byte)'[' && (rxByte >= 64 && rxByte <= 126); var endOfSequenceType93 = escapeSequenceType == (byte)']' && (rxByte == 7); if (endOfSequenceType91 || endOfSequenceType93) { try { // Execute the command of the given escape sequence HandleShellEscapeSequence(escapeSequenceBytes.ToArray()); } finally { isInEscapeSequence = false; escapeSequenceBytes.Clear(); rxBytePrevious = rxByte; } continue; } } rxBytePrevious = rxByte; } }; shell.ErrorOccurred += (s, e) => { System.Diagnostics.Debug.WriteLine(e.Exception.Message); }; while (true) { var line = Console.ReadLine(); var lineData = encoding.GetBytes(line + "\r\n"); shell.Write(lineData, 0, lineData.Length); shell.Flush(); if (line.Equals("exit")) { var expectResult = shell.Expect("logout", TimeSpan.FromSeconds(2)); if (string.IsNullOrWhiteSpace(expectResult) == false && expectResult.Trim().EndsWith("logout")) { break; } } } } sshClient.Disconnect(); } }