public void TestWaitOneMultiThreaded()
	{
		bool x;
		Thread thread1;

		if (!TestThread.IsThreadingSupported)
		{
			return;
		}

		e1 = new AutoResetEvent(false);

		x = e1.WaitOne(10,false);

		AssertEquals("WaitOne(unset)", x, false);

		thread1 = new Thread(new ThreadStart(SetE1));
		
		thread1.Start();

		x = e1.WaitOne(4000, false);

		AssertEquals("WaitOne(set)", x, true);

		// It should be reset now.

		x = e1.WaitOne(10, false);

		AssertEquals("WaitOne(set)", x, false);
	}
Exemple #2
0
	static int Main ()
	{
		receivedMsg = new AutoResetEvent (false);

		HttpChannel channel = new HttpChannel (0);
#if NET_2_0
		ChannelServices.RegisterChannel (channel, false);
#else
		ChannelServices.RegisterChannel (channel);
#endif

		ServerTalk _ServerTalk = (ServerTalk) Activator.GetObject (typeof (ServerTalk), "http://localhost:8081/hydraplus.soap");

		CallbackSink _CallbackSink = new CallbackSink ();
		_CallbackSink.OnHostToClient += new delCommsInfo (CallbackSink_OnHostToClient);

		_ServerTalk.RegisterHostToClient ("Me", 0, new delCommsInfo (_CallbackSink.HandleToClient));

		string messageSent = Guid.NewGuid ().ToString ();

		_ServerTalk.SendMessageToServer (new CommsInfo ("Me", "txt", messageSent));

		if (receivedMsg.WaitOne (5000, false)) {
			Assert.AreEqual (messageReceived, messageSent, "#1");
			return 0;
		} else {
			return 1;
		}
	}
Exemple #3
0
    public static void Main()
    {     	
    	e = new AutoResetEvent(false);

   	
        // Create the waiter thread's group
        Console.WriteLine("[  Main  ] - Creating first thread..");
        ThreadStart Thread_1 = new ThreadStart(ThreadMethod_waiter_1);
        ThreadStart Thread_2 = new ThreadStart(ThreadMethod_waiter_2);
        
        // Create the blocker thread
        Console.WriteLine("[  Main  ] - Creating second thread..");
        ThreadStart Thread_3 = new ThreadStart(ThreadMethod_blocker);

        Thread A = new Thread(Thread_1);
        Thread B = new Thread(Thread_2);
        Thread C = new Thread(Thread_3);
        
	A.Start();
    	B.Start();
    	C.Start();
    	
    	Thread.Sleep(500);
    	Console.WriteLine("[  Main  ] - Finish...");
    }
    private void DownloadWebpage()
    {
        string URL = TextBox1.Text;

        AutoResetEvent resultEvent = new AutoResetEvent(false);
        string result = null;

        bool visible = this.Checkbox1.Checked;

        IEBrowser browser = new IEBrowser(visible, URL, resultEvent);

        // wait for the third thread getting result and setting result event
        EventWaitHandle.WaitAll(new AutoResetEvent[] { resultEvent });
        // the result is ready later than the result event setting sometimes
        while (browser == null || browser.HtmlResult == null) Thread.Sleep(5);

        result = browser.HtmlResult;

        if (!visible) browser.Dispose();

        //把获取的html内容通过label显示出来
        Label2.Text = result;

        //保存结果到本程序的目录中
        string path = Request.PhysicalApplicationPath;
        TextWriter tw = new StreamWriter(path + @"softlab/result.html");
        tw.Write(result);
        tw.Close();

        //open a new web page to display result got from webbrowser.
        Response.Output.WriteLine("<script>window.open ('result.html','mywindow','location=1,status=0,scrollbars=1,resizable=1,width=600,height=600');</script>");
    }
    public bool PosTest1()
    {
        bool           retVal = true;
        AutoResetEvent are;

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

        try
        {
            // false means that the initial state should be not signaled
            are = new AutoResetEvent(false);

            // set the signal
            if (!are.Set())
            {
                TestLibrary.TestFramework.LogError("001", "AutoResetEvent.Set() failed");
                retVal = false;
            }

            // 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 not signaled it will hang");
            are.WaitOne();

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    static void Main()
        {
            // Create an event to signal the timeout count threshold in the 
            // timer callback.
            AutoResetEvent autoEvent     = new AutoResetEvent(false);

            StatusChecker  statusChecker = new StatusChecker(10);

            // Create an inferred delegate that invokes methods for the timer.
            TimerCallback tcb = statusChecker.CheckStatus;

            // Create a timer that signals the delegate to invoke  
            // CheckStatus after one second, and every 1/4 second  
            // thereafter.
            Console.WriteLine("{0} Creating timer.\n", 
                              DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);

            // When autoEvent signals, change the period to every 
            // 1/2 second.
            autoEvent.WaitOne(5000, false);
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");

            // When autoEvent signals the second time, dispose of  
            // the timer.
            autoEvent.WaitOne(5000, false);
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");
        }
		// Initialize Parallel class's instance creating required number of threads
		// and synchronization objects
		private void Initialize( )
		{
			threadsCount = System.Environment.ProcessorCount;
			
			//No point starting new threads for a single core computer
			if (threadsCount <= 1) {
				return;
			}
			
			// array of events, which signal about available job
			jobAvailable = new AutoResetEvent[threadsCount];
			// array of events, which signal about available thread
			threadIdle = new ManualResetEvent[threadsCount];
			// array of threads
			threads = new Thread[threadsCount];
		
			for ( int i = 0; i < threadsCount; i++ )
			{
				jobAvailable[i] = new AutoResetEvent( false );
				threadIdle[i]   = new ManualResetEvent( true );
		
				threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) );
				threads[i].IsBackground = false;
				threads[i].Start( i );
			}
		}
Exemple #8
0
 public static int Main(String[] args)
   {
   Console.WriteLine("MutexSample.cs ...");
   gM1 = new Mutex(true,"MyMutex");			
   gM2 = new Mutex(true);						
   Console.WriteLine(" - Main Owns gM1 and gM2");
   AutoResetEvent[]	evs	= new AutoResetEvent[4];
   evs[0] = Event1;			
   evs[1] = Event2;			
   evs[2] = Event3;			
   evs[3] = Event4;			
   MutexSample			tm	= new MutexSample( );
   Thread				t1	= new Thread(new ThreadStart(tm.t1Start));
   Thread				t2	= new Thread(new ThreadStart(tm.t2Start));
   Thread				t3	= new Thread(new ThreadStart(tm.t3Start));
   Thread				t4	= new Thread(new ThreadStart(tm.t4Start));
   t1.Start( );				
   t2.Start( );				
   t3.Start( );				
   t4.Start( );				
   Thread.Sleep(2000);
   Console.WriteLine(" - Main releases gM1");
   gM1.ReleaseMutex( );		
   Thread.Sleep(1000);
   Console.WriteLine(" - Main releases gM2");
   gM2.ReleaseMutex( );		
   WaitHandle.WaitAll(evs);	
   Console.WriteLine("... MutexSample.cs");
   return 0;
   }
Exemple #9
0
	public int Run()
	{
		AutoResetEvent are = new AutoResetEvent(true);
		Stopwatch sw = new Stopwatch();		
		
		if(!are.WaitOne(0))//,false))
{
			Console.WriteLine("Signalled event should always return true on call to !are.WaitOne(0,false).");
			return -3;
		}
		
		sw.Start();
		bool ret = are.WaitOne(1000);//,false);
		sw.Stop();
		//We should never get signaled
		if(ret)
		{
			Console.WriteLine("AutoResetEvent should never be signalled.");
			return -1;
		}

		if(sw.ElapsedMilliseconds < 900)
		{
			Console.WriteLine("It should take at least 900 milliseconds to call bool ret = are.WaitOne(1000,false);.");
			Console.WriteLine("sw.ElapsedMilliseconds = " + sw.ElapsedMilliseconds);			
			return -2;
		}
		return 100;
		
	}
Exemple #10
0
        public void Ctor()
        {
            using (AutoResetEvent are = new AutoResetEvent(false))
                Assert.False(are.WaitOne(0));

            using (AutoResetEvent are = new AutoResetEvent(true))
                Assert.True(are.WaitOne(0));
        }
Exemple #11
0
public static void Main()
{
AutoResetEvent auto = new AutoResetEvent(true);
bool state = auto.WaitOne(5000, true);
Console.WriteLine("After Frist Wait : " + state);
state  = auto.WaitOne(10000, true);
Console.WriteLine("After Second Wait : " + state);
}
Exemple #12
0
    private static void HandleCharacter(Match match, HttpListenerResponse response)
    {
        // here we are running in a thread different from the main thread
        int pid = Convert.ToInt32(match.Groups[1].Value);

        string responseString = "";

        // event used to wait the answer from the main thread.
        AutoResetEvent autoEvent = new AutoResetEvent(false);

        // var to store the character we are looking for
        Character character = null;
        // this bool is to check character is valid ... explanation below
        bool found = false;

        // we queue an 'action' to be executed in the main thread
        MainGameObject.QueueOnMainThread(()=>{
            // here we are in the main thread (see Update() in MainGameObject.cs)
            // retrieve the character
            character = MainGameObject.Instance().CharacterByID(pid);
            // if the character is null set found to false
            // have to do this because cannot call "character==null" elsewhere than the main thread
            // do not know why (yet?)
            // so if found this "trick"
            found = (character!=null?true:false);
            // set the event to "unlock" the thread
            autoEvent.Set();
        });

        // wait for the end of the 'action' executed in the main thread
        autoEvent.WaitOne();

        // generate the HTTP answer

        if (found==false) {
            responseString = "<html><body>character: not found (" + pid + ")</body></html>";
        } else {
            responseString = "<html><body>";
            responseString += "<img src='data:image/jpg;base64," + character.imageB64 + "'></img></br>";
            responseString += "name: " +  character.name + "</br>";
            responseString += "life: " +  character.life + "</br>";
            responseString += "streght " +  character.streght + "</br>";
            responseString += "dexterity " +  character.dexterity + "</br>";
            responseString += "consitution " +  character.consitution + "</br>";
            responseString += "intelligence " +  character.intelligence + "</br>";
            responseString += "</body></html>";
        }

        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer,0,buffer.Length);
        // You must close the output stream.
        output.Close();
    }
Exemple #13
0
	static int Main ()
	{
		SoapServerFormatterSinkProvider serverFormatter = new SoapServerFormatterSinkProvider ();
		serverFormatter.TypeFilterLevel = TypeFilterLevel.Full;

		Hashtable ht = new Hashtable ();
		ht ["name"] = "hydraplus";
		ht ["port"] = 8081;
		ht ["authorizedGroup"] = "everyone";

		HttpChannel channel = new HttpChannel (ht, null, serverFormatter);
#if NET_2_0
		ChannelServices.RegisterChannel (channel, false);
#else
		ChannelServices.RegisterChannel (channel);
#endif

		WellKnownServiceTypeEntry entry = new WellKnownServiceTypeEntry (
			typeof (ServerTalk), "hydraplus.soap",
			WellKnownObjectMode.Singleton);
		RemotingConfiguration.RegisterWellKnownServiceType (entry);

		ServerTalk.NewUser = new delUserInfo (NewClient);
		ServerTalk.DelUser = new delRemoveUser (RemoveClient);
		ServerTalk.ClientToHost = new delCommsInfo (ClientToHost);

		clientConnected = new AutoResetEvent (false);
		clientDisconnected = new AutoResetEvent (false);

		// wait for client to connect
		if (!clientConnected.WaitOne (20000, false)) {
			ReportFailure ("No client connected in time.");
			return 1;
		}

		// wait for message to arrive
		while (true) {
			Thread.Sleep (50);
			if (ServerTalk.ClientToServerQueue.Count > 0) {
				CommsInfo info = (CommsInfo) ServerTalk.ClientToServerQueue.Dequeue ();
				ClientToHost (info);
				break;
			}
		}

		// send message to client
		ServerTalk.RaiseHostToClient (client.Id, "txt", receivedMsg);

		// wait for client to disconnect
		if (clientConnected.WaitOne (2000, false)) {
			ReportFailure ("Client did not disconnect in time.");
			return 2;
		}

		return 0;
	}
 public void SetWaitHandle_Enqueue_Asynchronous()
 {
     using (AutoResetEvent waitHandle = new AutoResetEvent(false))
     {
         this.q = new EventQueue();
         this.q.SetWaitHandleForSynchronizedEvents(waitHandle);
         this.afterEnqueue = false;
         this.RunProducerConsumer();
     }
 }
Exemple #15
0
	static int Main ()
	{
		for (int i = 0; i < Count; i++) {
			events [i] = new AutoResetEvent (false);
			ThreadPool.QueueUserWorkItem (new WaitCallback (Callback), i);
		}

		AutoResetEvent.WaitAll (events);
		return exit_code;
	}
    public void Go()
    {
        // find all the upcoming UK horse races (EventTypeId 7)
        var marketFilter = new MarketFilter();
        marketFilter.EventTypeIds = new HashSet<string>() { "7" };
        marketFilter.MarketStartTime = new TimeRange()
        {
            From = DateTime.Now,
            To = DateTime.Now.AddDays(2)
        };
        marketFilter.MarketTypeCodes = new HashSet<String>() { "WIN" };

        Console.WriteLine("BetfairClient.ListEvents()");
        var events = _client.ListEvents(marketFilter).Result;
        if (events.HasError)
            throw new ApplicationException();
        var firstEvent = events.Response.First();
        Console.WriteLine("First Event {0} {1}", firstEvent.Event.Id, firstEvent.Event.Name);

        var marketCatalogues = _client.ListMarketCatalogue(
          BFHelpers.HorseRaceFilter(),
          BFHelpers.HorseRaceProjection(),
          MarketSort.FIRST_TO_START,
          25).Result.Response;

        marketCatalogues.ForEach(c =>
        {
            _markets.Enqueue(c);
            Console.WriteLine(c.MarketName);
        });
        Console.WriteLine();

        while (_markets.Count > 0)
        {
            AutoResetEvent waitHandle = new AutoResetEvent(false);
            MarketCatalogue marketCatalogue;
            _markets.TryDequeue(out marketCatalogue);

            var marketSubscription = _streamingClient.SubscribeMarket(marketCatalogue.MarketId)
                .SubscribeOn(Scheduler.Default)
                .Subscribe(
                tick =>
                {
                    Console.WriteLine(BFHelpers.MarketSnapConsole(tick, marketCatalogue.Runners));
                },
                () =>
                {
                    Console.WriteLine("Market finished");
                    waitHandle.Set();
                });

            waitHandle.WaitOne();
            marketSubscription.Dispose();
        }
    }
	protected override void Setup()
	{
		if (!TestThread.IsThreadingSupported)
			return;
		this.timer = new Timer(this.timerCallbackDelegate, this,
			Timeout.Infinite, Timeout.Infinite);
		this.timeTimerExpired = DateTime.MaxValue;
		this.checkTimeoutCount = 0;
		this.startTest = System.DateTime.Now;
		this.autoResetEvent = new AutoResetEvent(false);
	}
Exemple #18
0
 public void Running_Timer_CanBeFinalizedAndStopsFiring()
 {
     AutoResetEvent are = new AutoResetEvent(false);
     TimerCallback tc = new TimerCallback((object o) => are.Set());
     var t = new Timer(tc, null, 1, 500);
     Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Failed to get first timer fire");
     t = null; // Remove our refence so the timer can be GC'd
     GC.Collect();
     GC.WaitForPendingFinalizers();
     GC.Collect();
     Assert.False(are.WaitOne(500), "Should not have received a timer fire after it was collected");
 }
Exemple #19
0
    public void Timer_Fires_After_DueTime_Ellapses()
    {
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            are.Set();
        }), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
        }
    }
Exemple #20
0
 public void NonRepeatingTimer_ThatHasAlreadyFired_CanChangeAndFireAgain()
 {
     AutoResetEvent are = new AutoResetEvent(false);
     TimerCallback tc = new TimerCallback((object o) => are.Set());
     using (var t = new Timer(tc, null, 1, Timeout.Infinite))
     {
         Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received first timer event");
         Assert.False(are.WaitOne(500), "Should not have received a second timer event");
         t.Change(10, Timeout.Infinite);
         Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received a second timer event after changing it");
     }
 }
Exemple #21
0
        public void WaitHandleWaitAny()
        {
            AutoResetEvent[] handles = new AutoResetEvent[10];
            for (int i = 0; i < handles.Length; i++)
                handles[i] = new AutoResetEvent(false);

            Task<int> t = Task.Run(() => WaitHandle.WaitAny(handles, FailedWaitTimeout));
            handles[5].Set();
            Assert.Equal(5, t.Result);

            Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(handles, 0));
        }
Exemple #22
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));
     }
 }
Exemple #23
0
    public void Timer_Fires_AndPassesNullStateThroughCallback()
    {
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            Assert.Null(s);
            are.Set();
        }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
        }
    }
Exemple #24
0
    private void AbandonAllMutexes()
    {
        Mutex m = new Mutex();
        AutoResetEvent are = new AutoResetEvent(false);

        foreach(WaitHandle w in wh)
        {
            if(w.GetType() == m.GetType())
                w.WaitOne();
        }
        myMRE.Set();
        Thread.Sleep(1000);
    }
Exemple #25
0
    public void Timer_Change_BeforeDueTime_ChangesWhenTimerWillFire()
    {
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            are.Set();
        }), null, TimeSpan.FromSeconds(500), TimeSpan.FromMilliseconds(50)))
        {
            Assert.False(are.WaitOne(TimeSpan.FromMilliseconds(100)), "The reset event should not have been set yet");
            t.Change(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(-1));
            Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(500)), "Should have received a timer event after this new duration");
        }
    }
Exemple #26
0
	static int Main ()
	{
		AutoResetEvent ae = new AutoResetEvent (true);
		AutoResetEvent ae2 = new AutoResetEvent (true);

		if (Thread.CurrentThread.ApartmentState != ApartmentState.STA)
			return 1;

		try {
			WaitHandle.WaitAll (new WaitHandle [] { ae, ae2 }, 1000, true);
			return 2;
		} catch (NotSupportedException) {
			return 0;
		}
	}
Exemple #27
0
	static int Main ()
	{
#if NET_2_0
		if (Thread.CurrentThread.ApartmentState != ApartmentState.MTA)
#else
		if (Thread.CurrentThread.ApartmentState != ApartmentState.Unknown)
#endif
			return 1;

		AutoResetEvent ae = new AutoResetEvent (true);
		AutoResetEvent ae2 = new AutoResetEvent (true);
		if (WaitHandle.WaitAll (new WaitHandle [] { ae, ae2 }, 1000, true))
			return 0;
		return 2;
	}
Exemple #28
0
    /// <summary>
    /// class constructor 
    /// </summary>
    /// <param name="visible">whether or not the form and the WebBrowser control are visiable</param>
    /// <param name="userName">client user name</param>
    /// <param name="password">client password</param>
    /// <param name="resultEvent">functionality to keep the main thread waiting</param>
    public IEBrowser(bool visible, string URL, AutoResetEvent resultEvent)
    {
        //this.userName = userName;
        //this.password = password;
        this.resultEvent = resultEvent;
        htmlResult = null;

        thrd = new Thread(new ThreadStart(
            delegate {
                Init(visible,URL);
                System.Windows.Forms.Application.Run(this);
            }));
        // set thread to STA state before starting
        thrd.SetApartmentState(ApartmentState.STA);
        thrd.Start();
    }
Exemple #29
0
    public void Timer_FiresOnlyOnce_OnDueTime_With_InfinitePeriod()
    {
        int count = 0;
        AutoResetEvent are = new AutoResetEvent(false);

        using (var t = new Timer(new TimerCallback((object s) =>
        {
            if (Interlocked.Increment(ref count) >= 2)
            {
                are.Set();
            }
        }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
        {
            Assert.False(are.WaitOne(TimeSpan.FromMilliseconds(250 /*enough for 2 fires + buffer*/)));
        }
    }
Exemple #30
0
        public void WaitHandleWaitAll()
        {
            AutoResetEvent[] handles = new AutoResetEvent[10];
            for (int i = 0; i < handles.Length; i++)
                handles[i] = new AutoResetEvent(false);

            Task<bool> t = Task.Run(() => WaitHandle.WaitAll(handles, FailedWaitTimeout));
            for (int i = 0; i < handles.Length; i++)
            {
                Assert.False(t.IsCompleted);
                handles[i].Set();
            }
            Assert.True(t.Result);

            Assert.False(WaitHandle.WaitAll(handles, 0));
        }
Exemple #31
0
        /// <summary>
        /// Spawns a new process (platform independent)
        /// </summary>
        public static ProcessOutput ExecuteProcess(string processName, string args, int timeout = 300000)
        {
            var output = new ProcessOutput();

            using (var process = new Process())
            {
                process.StartInfo.FileName  = processName;
                process.StartInfo.Arguments = args;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                //Hide the python window if possible
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow  = true;
#if !NETCORE
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
#endif

                using (var outputWaitHandle = new AutoResetEvent(false))
                    using (var errorWaitHandle = new AutoResetEvent(false))
                    {
                        process.OutputDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                try
                                {
                                    outputWaitHandle.Set();
                                }
                                catch
                                {
                                    //probably is already disposed
                                }
                            }
                            else
                            {
                                output.OutputText.AppendLine(e.Data);
                            }
                        };
                        process.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                try
                                {
                                    errorWaitHandle.Set();
                                }
                                catch
                                {
                                    //probably is already disposed
                                }
                            }
                            else
                            {
                                output.OutputText.AppendLine(e.Data);
                            }
                        };

                        process.Start();

                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();

                        if (process.WaitForExit(timeout) &&
                            outputWaitHandle.WaitOne(timeout) &&
                            errorWaitHandle.WaitOne(timeout))
                        {
                            // Process completed.
                            output.ExitCode = process.ExitCode;
                        }
                        else
                        {
                            // Timed out.
                            output.ExitCode = -1;
                        }
                    }
            }
            return(output);
        }
        public void Run()
        {
            using (var ch = _host.Start("Run"))
            {
                IntArray[]         arrays     = CreateRandomIntArrays(ch);
                FeatureHistogram[] histograms =
                    arrays.Select(bins => new FeatureHistogram(bins, _bins, false)).ToArray(arrays.Length);
                long bytes = arrays.Sum(i => (long)i.SizeInBytes());
                ch.Info("Created {0} int arrays taking {1} bytes", arrays.Length, bytes);

                // Objects for the pool.
                ch.Info("Parallelism = {0}", _parallel);
                AutoResetEvent[] events              = Utils.BuildArray(_parallel, i => new AutoResetEvent(false));
                AutoResetEvent[] mainEvents          = Utils.BuildArray(_parallel, i => new AutoResetEvent(false));
                SumupInputData   data                = new SumupInputData(_len, 0, 0, new FloatType[_len], null, new int[_len]);
                Thread[]         threadPool          = new Thread[_parallel];
                Stopwatch        sw                  = new Stopwatch();
                long             ticksPerCycle       = (long)(Stopwatch.Frequency * _seconds);
                double[]         partitionProportion = { 1, 1, 0.5, 1e-1, 1e-2, 1e-3, 1e-4 };

                long completed = 0;

                for (int t = 0; t < threadPool.Length; ++t)
                {
                    Thread thread = threadPool[t] = Utils.RunOnForegroundThread((object io) =>
                    {
                        int w              = (int)io;
                        AutoResetEvent ev  = events[w];
                        AutoResetEvent mev = mainEvents[w];
                        for (int s = 0; s < partitionProportion.Length; s++)
                        {
                            ev.WaitOne();
                            long localCompleted = 0;
                            for (int f = w; ; f = f + threadPool.Length < arrays.Length ? f + threadPool.Length : w)
                            {
                                // This should repeat till done.
                                arrays[f].Sumup(data, histograms[f]);
                                if (sw.ElapsedTicks > ticksPerCycle)
                                {
                                    break;
                                }
                                Interlocked.Increment(ref completed);
                                ++localCompleted;
                            }
                            mev.Set();
                        }
                    });
                    thread.Start(t);
                }

                foreach (double partition in partitionProportion)
                {
                    InitSumupInputData(data, partition, _host.Rand);
                    completed = 0;
                    sw.Restart();
                    foreach (var e in events)
                    {
                        e.Set();
                    }
                    foreach (var e in mainEvents)
                    {
                        e.WaitOne();
                    }
                    double ticksPerDoc = (double)ticksPerCycle / (completed * data.TotalCount);
                    double nsPerDoc    = ticksPerDoc * 1e9 / Stopwatch.Frequency;
                    ch.Info("Partition {0} ({1} of {2}), completed {3} ({4:0.000} ns per doc)",
                            partition, data.TotalCount, _len, completed, nsPerDoc);
                }
            }
        }
Exemple #33
0
        public static string GetOrCreateEnvironmentVariable()
        {
            var envRuntime = System.Environment.GetEnvironmentVariable(Constants.NetCoreRuntimePath,
                                                                       EnvironmentVariableTarget.Process);

            var envVersion = System.Environment.GetEnvironmentVariable(Constants.NetCoreRuntimeVersion,
                                                                       EnvironmentVariableTarget.Process);

            if (envRuntime != null && envVersion != null)
            {
                return(Path.Combine(envRuntime, envVersion, Constants.NetStandardDllFile));
            }

            using (var process = new Process()
            {
                StartInfo =
                {
                    FileName               = "dotnet",
                    Arguments              = "--list-runtimes",
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true
                },
                EnableRaisingEvents = true
            })
            {
                var path    = new StringBuilder();
                var version = new StringBuilder();
                var error   = new StringBuilder();
                var timeout = TimeSpan.FromSeconds(10);

                using (var outputWaitHandle = new AutoResetEvent(false))
                    using (var errorWaitHandle = new AutoResetEvent(false))
                    {
                        process.OutputDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                outputWaitHandle.Set();
                            }
                            else
                            {
                                if (!e.Data.StartsWith("Microsoft.NETCore.App 2.1"))
                                {
                                    return;
                                }

                                var text        = e.Data;
                                var startIndex  = text.IndexOf('[') + 1;
                                var stopIndex   = text.IndexOf(']') - 1;
                                var firstSpace  = text.IndexOf(' ');
                                var secondSpace = text.IndexOf(' ', firstSpace + 1);
                                path.Clear();
                                path.Append(text.Substring(startIndex, stopIndex - startIndex + 1));
                                version.Clear();
                                version.Append(text.Substring(firstSpace + 1, secondSpace - (firstSpace + 1)));
                            }
                        };

                        process.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                errorWaitHandle.Set();
                            }
                            else
                            {
                                error.AppendLine(e.Data);
                            }
                        };

                        process.Start();

                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();

                        if (process.WaitForExit(Convert.ToInt32(timeout.TotalMilliseconds)) &&
                            outputWaitHandle.WaitOne(timeout) &&
                            errorWaitHandle.WaitOne(timeout))
                        {
                            var runtimePath    = path.ToString();
                            var runtimeVersion = version.ToString();
                            System.Environment.SetEnvironmentVariable(Constants.NetCoreRuntimePath, runtimePath);
                            System.Environment.SetEnvironmentVariable(Constants.NetCoreRuntimeVersion, runtimeVersion);
                            envRuntime = runtimePath;
                            envVersion = runtimeVersion;
                        }
                        else
                        {
                            throw new DotNetNotFoundException();
                        }
                    }
            }

            return(Path.Combine(envRuntime, envVersion, Constants.NetStandardDllFile));
        }
Exemple #34
0
        private void AnchoringAtFarEdgeWhileDecreasingViewport(Orientation orientation)
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone2))
            {
                Log.Comment("Skipping test on RS1 where InteractionTracker's AdjustPositionXIfGreaterThanThreshold/AdjustPositionYIfGreaterThanThreshold are ineffective in this scenario.");
                return;
            }

            using (ScrollerTestHooksHelper scrollerTestHooksHelper = new ScrollerTestHooksHelper())
            {
                Scroller       scroller                 = null;
                AutoResetEvent scrollerLoadedEvent      = new AutoResetEvent(false);
                AutoResetEvent scrollerViewChangedEvent = new AutoResetEvent(false);

                RunOnUIThread.Execute(() =>
                {
                    scroller = new Scroller();

                    SetupDefaultAnchoringUI(orientation, scroller, scrollerLoadedEvent);
                });

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

                ChangeZoomFactor(scroller, 2.0f, 0.0f, 0.0f, ScrollerViewKind.Absolute, ScrollerViewChangeKind.DisableAnimation);

                double horizontalOffset = 0.0;
                double verticalOffset   = 0.0;

                RunOnUIThread.Execute(() =>
                {
                    if (orientation == Orientation.Vertical)
                    {
                        verticalOffset = scroller.ExtentHeight * 2.0 - scroller.Height;
                        scroller.VerticalAnchorRatio = 1.0;
                    }
                    else
                    {
                        horizontalOffset = scroller.ExtentWidth * 2.0 - scroller.Width;
                        scroller.HorizontalAnchorRatio = 1.0;
                    }
                });

                ChangeOffsets(scroller, horizontalOffset, verticalOffset, ScrollerViewKind.Absolute, ScrollerViewChangeKind.DisableAnimation, ScrollerViewChangeSnapPointRespect.IgnoreSnapPoints, false /*hookViewChanged*/);

                RunOnUIThread.Execute(() =>
                {
                    scroller.ViewChanged += delegate(Scroller sender, object args)
                    {
                        Log.Comment("ViewChanged - HorizontalOffset={0}, VerticalOffset={1}, ZoomFactor={2}",
                                    sender.HorizontalOffset, sender.VerticalOffset, sender.ZoomFactor);
                        scrollerViewChangedEvent.Set();
                    };

                    if (orientation == Orientation.Vertical)
                    {
                        Log.Comment("Decreasing viewport height");
                        scroller.Height -= 100;
                    }
                    else
                    {
                        Log.Comment("Decreasing viewport width");
                        scroller.Width -= 100;
                    }
                });

                WaitForEvent("Waiting for Scroller.ViewChanged event", scrollerViewChangedEvent);
                IdleSynchronizer.Wait();

                RunOnUIThread.Execute(() =>
                {
                    if (orientation == Orientation.Vertical)
                    {
                        verticalOffset = scroller.ExtentHeight * 2.0 - scroller.Height;
                    }
                    else
                    {
                        horizontalOffset = scroller.ExtentWidth * 2.0 - scroller.Width;
                    }

                    Log.Comment("Scroller offset change expected");
                    Verify.AreEqual(scroller.HorizontalOffset, horizontalOffset);
                    Verify.AreEqual(scroller.VerticalOffset, verticalOffset);
                });
            }
        }
Exemple #35
0
        private void SetupDefaultAnchoringUI(
            Orientation orientation,
            Scroller scroller,
            AutoResetEvent scrollerLoadedEvent)
        {
            Log.Comment("Setting up default anchoring UI with Scroller");

            StackPanel stackPanel = new StackPanel();

            stackPanel.Name        = "stackPanel";
            stackPanel.Orientation = orientation;
            stackPanel.Margin      = new Thickness(30);

            Border border = new Border();

            border.Name            = "border";
            border.BorderThickness = new Thickness(3);
            border.BorderBrush     = new SolidColorBrush(Colors.Chartreuse);
            border.Margin          = new Thickness(15);
            border.Background      = new SolidColorBrush(Colors.Beige);
            border.Child           = stackPanel;

            Verify.IsNotNull(scroller);
            scroller.Name = "scroller";
            if (orientation == Orientation.Vertical)
            {
                scroller.IsChildAvailableWidthConstrained = true;
                scroller.Width  = c_defaultAnchoringUIScrollerConstrainedSize;
                scroller.Height = c_defaultAnchoringUIScrollerNonConstrainedSize;
            }
            else
            {
                scroller.IsChildAvailableHeightConstrained = true;
                scroller.Width  = c_defaultAnchoringUIScrollerNonConstrainedSize;
                scroller.Height = c_defaultAnchoringUIScrollerConstrainedSize;
            }
            scroller.Background = new SolidColorBrush(Colors.AliceBlue);
            scroller.Child      = border;

            InsertStackPanelChild(stackPanel, 0 /*operationCount*/, 0 /*newIndex*/, c_defaultAnchoringUIStackPanelChildrenCount /*newCount*/);

            if (scrollerLoadedEvent != null)
            {
                scroller.Loaded += (object sender, RoutedEventArgs e) =>
                {
                    Log.Comment("Scroller.Loaded event handler");
                    scrollerLoadedEvent.Set();
                };
            }

            scroller.AnchorRequested += (Scroller sender, ScrollerAnchorRequestedEventArgs args) =>
            {
                Log.Comment("Scroller.AnchorRequested event handler");

                Verify.IsNull(args.AnchorElement);
                Verify.AreEqual(args.AnchorCandidates.Count, 0);

                StackPanel sp = (sender.Child as Border).Child as StackPanel;
                foreach (Border b in sp.Children)
                {
                    args.AnchorCandidates.Add(b);
                }
            };

            Log.Comment("Setting window content");
            MUXControlsTestApp.App.TestContentRoot = scroller;
        }
Exemple #36
0
        private void AnchoringWithOffsetCoercion(bool reduceAnchorOffset)
        {
            using (ScrollerTestHooksHelper scrollerTestHooksHelper = new ScrollerTestHooksHelper())
            {
                Scroller       scroller                     = null;
                Border         anchorElement                = null;
                AutoResetEvent scrollerLoadedEvent          = new AutoResetEvent(false);
                AutoResetEvent scrollerViewChangedEvent     = new AutoResetEvent(false);
                AutoResetEvent scrollerAnchorRequestedEvent = new AutoResetEvent(false);

                // This test validates that the Scroller accounts for maximum vertical offset (based on viewport and child extent)
                // when calculating the vertical offset shift for anchoring. The vertical offset cannot exceed child extent - viewport.

                RunOnUIThread.Execute(() =>
                {
                    Log.Comment("Visual tree setup");
                    anchorElement = new Border
                    {
                        Width             = 100,
                        Height            = 100,
                        Background        = new SolidColorBrush(Colors.Red),
                        Margin            = new Thickness(0, 600, 0, 0),
                        VerticalAlignment = VerticalAlignment.Top
                    };

                    Grid grid = new Grid();
                    grid.Children.Add(anchorElement);
                    grid.Width      = 200;
                    grid.Height     = 1000;
                    grid.Background = new SolidColorBrush(Colors.Gray);

                    scroller = new Scroller
                    {
                        Child  = grid,
                        Width  = 200,
                        Height = 200
                    };

                    scroller.Loaded += (object sender, RoutedEventArgs e) =>
                    {
                        Log.Comment("Scroller.Loaded event handler");
                        scrollerLoadedEvent.Set();
                    };

                    scroller.ViewChanged += delegate(Scroller sender, object args)
                    {
                        Log.Comment("ViewChanged - HorizontalOffset={0}, VerticalOffset={1}, ZoomFactor={2}",
                                    sender.HorizontalOffset, sender.VerticalOffset, sender.ZoomFactor);
                        if ((reduceAnchorOffset && sender.VerticalOffset == 400) ||
                            (!reduceAnchorOffset && sender.VerticalOffset == 500))
                        {
                            scrollerViewChangedEvent.Set();
                        }
                    };

                    scroller.AnchorRequested += delegate(Scroller sender, ScrollerAnchorRequestedEventArgs args)
                    {
                        Log.Comment("Scroller.AnchorRequested event handler. Forcing the red Border to be the Scroller anchor.");
                        args.AnchorElement = anchorElement;
                        scrollerAnchorRequestedEvent.Set();
                    };

                    Log.Comment("Setting window content");
                    MUXControlsTestApp.App.TestContentRoot = scroller;
                });

                WaitForEvent("Waiting for Scroller.Loaded event", scrollerLoadedEvent);
                IdleSynchronizer.Wait();

                ChangeOffsets(scroller, 0.0, 600.0, ScrollerViewKind.Absolute, ScrollerViewChangeKind.DisableAnimation, ScrollerViewChangeSnapPointRespect.IgnoreSnapPoints);

                RunOnUIThread.Execute(() =>
                {
                    Verify.AreEqual(600, scroller.VerticalOffset);

                    Log.Comment("Scroller.Child height is reduced by 300px. Scroller.VerticalOffset is expected to be reduced by 100px (600 -> 500).");
                    (scroller.Child as Grid).Height = 700;
                    if (reduceAnchorOffset)
                    {
                        Log.Comment("Tracked element is shifted up by 200px within the Scroller.Child (600 -> 400). Anchoring is expected to reduce the VerticalOffset by half of that (500 -> 400).");
                        anchorElement.Margin = new Thickness(0, 400, 0, 0);
                    }
                    scrollerViewChangedEvent.Reset();
                });

                WaitForEvent("Waiting for Scroller.ViewChanged event", scrollerViewChangedEvent);
                WaitForEvent("Waiting for Scroller.AnchorRequested event", scrollerAnchorRequestedEvent);
                IdleSynchronizer.Wait();

                RunOnUIThread.Execute(() =>
                {
                    Verify.AreEqual(reduceAnchorOffset ? 400 : 500, scroller.VerticalOffset);
                });
            }
        }
Exemple #37
0
        static void Main(string[] args)
        {
            // Note that if you want to do halfmoon or stonehenge trials, place halfmoon and stonehenge in the center of the tank.
            // Fill their center with a barrier for the first mode. Then take the barrier out and take the mode again. Use the smallest barrier possible (so the fish can get close to the center) and, like in nb trials, get rid of the tracking restriction on barriers

            var options = new DataflowBlockOptions();

            options.BoundedCapacity = 10;
            var   pipe_buffer = new BufferBlock <CamData>(options);
            Point tank_center = new Point
            {
                X = 640,
                Y = 512,
            };
            int roidim = 80;

            string camera_id         = "img0"; //this is the ID of the NI-IMAQ board in NI MAX.
            var    _session          = new ImaqSession(camera_id);
            bool   reuse_background  = false;
            bool   drew_barriers     = false;
            bool   halfmoon          = false;
            bool   stonehenge        = false;
            bool   minefield         = false;
            bool   minefield_control = false;

            Console.WriteLine("Enter FishID   ");
            String fishid         = Console.ReadLine();
            String home_directory = "C:/Users/Deadpool/Desktop/Results/";
            String exp_directory  = home_directory + fishid;
            bool   exists_already = System.IO.Directory.Exists(exp_directory);

            if (!exists_already)
            {
                System.IO.Directory.CreateDirectory(exp_directory);
            }
            else
            {
                Console.WriteLine("Directory Already Exists. Overrite?  ");
                String overwrite = Console.ReadLine();
                if (overwrite == "y")
                {
                    System.IO.Directory.CreateDirectory(exp_directory);
                }
                else if (overwrite == "c")
                {
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            Console.WriteLine("Enter Light X Location  ");
            String lightloc_X = Console.ReadLine();

            Console.WriteLine("Enter Light Y Location  ");
            String lightloc_Y       = Console.ReadLine();
            int    light_location_X = Convert.ToInt32(lightloc_X) - 25;
            int    light_location_Y = Convert.ToInt32(lightloc_Y);

            Console.WriteLine("Enter Experiment Type  ");
            String exp_string = Console.ReadLine();

            Console.WriteLine("Use old background?  ");
            String reuse = Console.ReadLine();

            if (reuse == "y")
            {
                reuse_background = true;
            }
            if (exp_string == "n" || exp_string == "t" || exp_string == "v")
            {
                minefield_control = true;
            }
            else if (exp_string == "b")
            {
                minefield = true;
            }
            String camerawindow = "Camera Window";

            CvInvoke.NamedWindow(camerawindow);
            int  frameWidth  = 1280;
            int  frameHeight = 1024;
            uint bufferCount = 3;
            // Could try changing this to 2 or 100
            // Checked and there is no card memory. It makes a buffer on system mem. Tried increasing virtual memory so
            // HD can be used as RAM. Allocated an additional 32 GB to virtual mem.
            uint      buff_out    = 0;
            int       numchannels = 1;
            MCvScalar gray        = new MCvScalar(128, 128, 128);
            List <ContourProperties> barrierlist         = new List <ContourProperties>();
            ContourProperties        fishcontour         = new ContourProperties();
            ContourProperties        fishcontour_correct = new ContourProperties();
            ContourProperties        barrier             = new ContourProperties();

            System.Drawing.Size framesize = new System.Drawing.Size(frameWidth, frameHeight);
            System.Drawing.Size roi_size  = new System.Drawing.Size(roidim, roidim);
            Mat cvimage = new Mat(framesize, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);
            Mat modeimage_barrier_roi = new Mat(roi_size, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);
            Mat modeimage             = new Mat(framesize, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);
            //            Mat modeimage_barrier = new Mat(framesize, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);
            Mat            maxproj_cv = new Mat(framesize, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);
            AutoResetEvent event1     = new AutoResetEvent(true);
            AutoResetEvent event2     = new AutoResetEvent(false);
            MCvMoments     COM        = new MCvMoments();

            byte[,] data_2D             = new byte[frameHeight, frameWidth];
            byte[,] data_2D_roi         = new byte[roidim, roidim];
            byte[,] imagemode_nobarrier = new byte[frameHeight, frameWidth];
            byte[,] maxprojimage        = new byte[frameHeight, frameWidth];
            ImaqBuffer           image          = null;
            ImaqBufferCollection buffcollection = _session.CreateBufferCollection((int)bufferCount, ImaqBufferCollectionType.VisionImage);

            _session.RingSetup(buffcollection, 0, false);
            _session.Acquisition.AcquireAsync();
            RecordAndStim experiment = new RecordAndStim(event1, event2, pipe_buffer, exp_string);

            experiment.experiment_directory = exp_directory;
            var stimthread = new Thread(experiment.StartStim);

            stimthread.Start();

            // THIS GRABS THE MODE FOR THE TANK IN GENERAL BEFORE ALIGNMENT

            if (!experiment.alignment_complete)
            {
                CvInvoke.WaitKey(0);
                imglist      = GetImageList(_session, 500, 10);
                maxprojimage = FindMaxProjection(imglist);
                maxproj_cv.SetTo(maxprojimage);
                imglist.Clear();
                CvInvoke.Imshow(camerawindow, maxproj_cv);
                CvInvoke.WaitKey(0);
            }

            // IF CAMERA IS NOT YET ALIGNED TO THE PROJECTOR, THIS LOOP FINDS THE LOCATION OF THE CALIBRATION CONTOUR THE EXPERIMENT CLASS IS PLACING ON THE PROJECTOR.

            experiment.start_align = true;
            if (!experiment.alignment_complete)
            {
                while (!experiment.alignment_complete)
                {
                    imglist = GetImageList(_session, 500, 10);
                    data_2D = FindMaxProjection(imglist);
                    cvimage.SetTo(data_2D);
                    Console.WriteLine("Finding Largest Contour");
                    experiment.projcenter_camcoords = LargestContour(cvimage, maxproj_cv, true).center;
                    CvInvoke.Imshow(camerawindow, cvimage);
                    CvInvoke.WaitKey(1);
                    event2.Set();
                    event1.WaitOne();
                }
                imglist.Clear();
                CvInvoke.WaitKey(0);
                imglist = GetImageList(_session, 500, 10);
                data_2D = FindMaxProjection(imglist);
                cvimage.SetTo(data_2D);
                experiment.tankwidth = LargestContour(cvimage, maxproj_cv, true).height * 2;
                Console.WriteLine("Width Of Tank Contour");
                Console.WriteLine(experiment.tankwidth);
                CvInvoke.Imshow(camerawindow, cvimage);
                CvInvoke.WaitKey(0);
                imglist.Clear();
            }

            // Next, the opposite thread is going to display a black circle that is the same size as the tank. Do a max projection on this
            // contour in order to measure width of the tank in projector coordinates.


            // Now you've put the IR filter back over the camera and are ready to do an experiment.
            // Get mode of image with no barrier present so you can background subtract and find the barriers and fish.
            imglist.Clear();
            if (reuse_background)
            {
                modeimage = CvInvoke.Imread(home_directory + "/background_nobar" + exp_string + ".tif", 0);
            }
            else
            {
                imglist             = GetImageList(_session, 5000, 400);
                imagemode_nobarrier = FindMode(imglist);
                modeimage.SetTo(imagemode_nobarrier);
                imglist.Clear();
                CvInvoke.Imshow(camerawindow, modeimage);
                CvInvoke.WaitKey(0);
            }

            // Here you have just added barriers to the tank. Now get a new mode that contains the barriers for use in background subtraction to find fish
            // and for localizing barriers.

            if (halfmoon || stonehenge || minefield)
            {
                imglist = GetImageList(_session, 5000, 400);
                if (reuse_background)
                {
                    modeimage_barrier = CvInvoke.Imread(home_directory + "/background_" + exp_string + ".tif", 0);
                }
                else
                {
                    imagemode = FindMode(imglist);
                    modeimage_barrier.SetTo(imagemode);
                }

                modeimage_barrier.Save(exp_directory + "/background_" + exp_string + ".tif");
                imglist.Clear();
                barrierlist = BarrierLocations(modeimage_barrier, modeimage);
                for (int ind = 0; ind < barrierlist.Count; ind++)
                {
                    experiment.barrier_position_list.Add(barrierlist[ind].center);
                    experiment.barrier_radius_list.Add(barrierlist[ind].height / 2);
                }
            }
            else if (minefield_control)
            {
                modeimage_barrier.SetTo(imagemode_nobarrier);
                modeimage_barrier.Save(exp_directory + "/background_" + exp_string + ".tif");

                barrierlist = GenerateVirtualBarriers(experiment.tankwidth, tank_center.X, tank_center.Y);
                for (int ind = 0; ind < barrierlist.Count; ind++)
                {
                    experiment.barrier_position_list.Add(barrierlist[ind].center);
                    experiment.barrier_radius_list.Add(barrierlist[ind].height / 2);
                }
            }

            using (StreamWriter barrierfile = new StreamWriter(exp_directory + "/barrierstruct_" + exp_string + ".txt"))
            {
                for (int bar = 0; bar < barrierlist.Count; bar++)
                {
                    if (bar == 0)
                    {
                        barrierfile.WriteLine(experiment.templatewidth.ToString());
                        barrierfile.WriteLine(experiment.tankwidth.ToString());
                    }
                    barrierfile.WriteLine(barrierlist[bar].center.ToString());
                    barrierfile.WriteLine(barrierlist[bar].height.ToString());
                }
            }

            CvInvoke.Imshow(camerawindow, modeimage_barrier);
            CvInvoke.WaitKey(0);


            if (halfmoon) //THIS IS BECAUSE YOU TAKE THE BARRIER AWAY AFTER IT FINDS THE HOLE. IE FOR HALFMOON TRIALS, YOU FIRST KEEP THE HALFMOON THERE FOR MODEIMAGE, THEN ADD A BARRIER THE SIZE OF THE HOLE FOR FINDING OF THE HOLE OF THE BARRIER. IF YOU WANT TO RUN STONEHENGE OR HALFMOON, DECLARE MINEFIELD_CONTROL AS TRUE, but don't draw barriers.
            {
                modeimage_barrier = modeimage;
                imagemode         = imagemode_nobarrier;
            }


            // IMAGE ACQUISITION AND FISH FINDING.
            //            Idea is to first acquire the image and turn it into a cvimage matrix. find the fish by finding the largest contour on a background subtracted and thresholded image (LargestContour function).  Each time you find the fish, store its coords so you can just search within a small ROI on the next frame. If you lose the fish, go back out to full frame and find it again.
            Point f_center = new Point();
            Mat   cv_roi   = new Mat(roi_size, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);

            image = _session.Acquisition.Extract((uint)0, out buff_out);
            uint j = buff_out;
            int  experiment_phase = 0;
            int  xycounter        = 0;

            Console.WriteLine("j followed by buff_out");
            Console.WriteLine(j.ToString());
            Console.WriteLine(buff_out.ToString());
            List <Point> coordlist   = new List <Point>();
            List <int>   phasebounds = new List <int>();

            while (true)
            {
                if (mode_reset.WaitOne(0))
                {
                    Console.WriteLine("Clearing Imagelist");
                    imglist.Clear();
                    mode_reset.Reset();
                }
                image = _session.Acquisition.Extract(j, out buff_out);
                try
                {
                    data_2D = image.ToPixelArray().U8;
                }
                catch (NationalInstruments.Vision.VisionException e)
                {
                    Console.WriteLine(e);
                    continue;
                }

                byte[] stim_pixel_readout = new byte[100];
                for (int pix = 0; pix < 100; pix++)
                {
                    stim_pixel_readout[pix] = data_2D[light_location_Y, light_location_X + pix];
                }
                cvimage.SetTo(data_2D);
                fishcontour = FishContour(cvimage, modeimage_barrier, tank_center, barrierlist, minefield_control);

                // com makes sure that the head is near the barrier.
                if (fishcontour.height != 0)
                {
                    fishcontour_correct = fishcontour;
                    f_center.X          = fishcontour.com.X;
                    f_center.Y          = fishcontour.com.Y;
                }
                if (!experiment.stim_in_progress)
                {
                    drew_barriers = false;
                }
                if (experiment.stim_in_progress && !drew_barriers)
                {
                    if (halfmoon || stonehenge || minefield || minefield_control)
                    {
                        for (int ind = 0; ind < barrierlist.Count; ind++)
                        {
                            CvInvoke.Circle(cvimage, barrierlist[ind].center, barrierlist[ind].height / 2, new MCvScalar(255, 0, 0), 1);
                        }
                    }
                    Image <Gray, Byte> d2d = cvimage.ToImage <Gray, Byte>();
                    data_2D_roi   = SliceROIImage(d2d, f_center.X, f_center.Y, roidim);
                    drew_barriers = true;
                }
                else
                {
                    data_2D_roi = SliceROI(data_2D, f_center.X, f_center.Y, roidim);
                }
                cv_roi = new Mat(roi_size, Emgu.CV.CvEnum.DepthType.Cv8U, numchannels);
                cv_roi.SetTo(data_2D_roi);

                CamData camdat = new CamData(cv_roi, f_center, fishcontour_correct, buff_out, j, stim_pixel_readout);
                pipe_buffer.Post(camdat);
                if (j % 10 == 0)
                {
                    xycounter++;
                    coordlist.Add(camdat.fishcoord);
                    if (experiment.experiment_phase > experiment_phase)
                    {
                        experiment_phase = experiment.experiment_phase;
                        phasebounds.Add(xycounter);
                    }
                }
                if (j % 100 == 0 && !experiment.stim_in_progress)
                {
                    //    CvInvoke.Circle(cvimage, fishcontour_correct.center, 2,new MCvScalar(255, 255, 0));
                    CvInvoke.Circle(cvimage, fishcontour_correct.com, 2, new MCvScalar(255, 255, 255));
                    if (halfmoon || stonehenge || minefield || minefield_control)
                    {
                        for (int ind = 0; ind < barrierlist.Count; ind++)
                        {
                            CvInvoke.Circle(cvimage, barrierlist[ind].center, barrierlist[ind].height / 2, new MCvScalar(255, 0, 0), 3);
                        }
                    }
                    else
                    {
                        CvInvoke.Circle(cvimage, experiment.barrier_center, barrier.height / 2, new MCvScalar(255, 0, 0), 3);
                    }
                    CvInvoke.Imshow(camerawindow, cvimage);
                    CvInvoke.WaitKey(1);
                    if (j % 1000 == 0)
                    {
                        byte[,] mode_frame = new byte[frameHeight, frameWidth];
                        Buffer.BlockCopy(data_2D, 0, mode_frame, 0, data_2D.Length);
                        imglist.Add(mode_frame);
                        if (imglist.LongCount() == 40)
                        {
                            var modethread = new Thread(() => ModeWrapper(imglist, mode_reset, experiment, exp_directory));
                            modethread.Start();
                        }
                    }
                }
                if (experiment.experiment_complete)
                {
                    break;
                }

                j = buff_out + 1;
            }
            modeimage_barrier.Save(home_directory + "/background_" + exp_string + ".tif");
            modeimage.Save(home_directory + "/background_nobar" + exp_string + ".tif");
            string experiment_string   = exp_directory + "/all_xycoords_" + exp_string + ".txt";
            string phasestring         = exp_directory + "/phase_" + exp_string + ".txt";
            string numframes_gray      = exp_directory + "/numframesgray_" + exp_string + ".txt";
            string numframes_gray_dark = exp_directory + "/numframesgray_dark.txt";

            using (StreamWriter sr = new StreamWriter(experiment_string))
            {
                foreach (Point fishpoint in coordlist)
                {
                    sr.WriteLine(fishpoint.ToString());
                }
            }
            using (StreamWriter sr = new StreamWriter(phasestring))
            {
                foreach (int phase in phasebounds)
                {
                    sr.WriteLine(phase.ToString());
                }
            }
            using (StreamWriter sr = new StreamWriter(numframes_gray))
            {
                foreach (int ng in experiment.num_grayframes)
                {
                    sr.WriteLine(ng.ToString());
                }
            }
            if (exp_string == "b")
            {
                using (StreamWriter sr = new StreamWriter(numframes_gray_dark))
                {
                    foreach (int ngd in experiment.num_grayframes_d)
                    {
                        sr.WriteLine(ngd.ToString());
                    }
                }
            }
        }
Exemple #38
0
        void connect()
        {
            client = new TcpClient();

            //Notify we are connecting
            var eoc = this.OnConnecting;

            if (eoc != null)
            {
                eoc(this.appleSettings.Host, this.appleSettings.Port);
            }

            Log.Info("Connecting ");

            try
            {
                var connectDone = new AutoResetEvent(false);

                //Connect async so we can utilize a connection timeout
                client.BeginConnect(
                    appleSettings.Host, appleSettings.Port,
                    ar =>
                {
                    try
                    {
                        client.EndConnect(ar);

                        //Set keep alive on the socket may help maintain our APNS connection
                        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                        //client.Client.SetKeepAlive(1000, 2500);

                        //Trigger the reset event so we can continue execution below
                        connectDone.Set();
                    }
                    catch (Exception ex)
                    {
                        Log.Error("APNS Connect Callback Failed: " + ex);
                    }
                }, client
                    );

                if (!connectDone.WaitOne(appleSettings.ConnectionTimeout))
                {
                    Log.Info("Timeout!");
                    throw new TimeoutException("Connection to Host Timed Out!");
                }
            }
            catch (Exception ex)
            {
                Log.Info("failed!");
                throw new ConnectionFailureException("Connection to Host Failed", ex);
            }

            if (appleSettings.SkipSsl)
            {
                networkStream = client.GetStream();
            }
            else
            {
                stream = new SslStream(client.GetStream(), false,
                                       (sender, cert, chain, sslPolicyErrors) => true,                                  //Don't validate remote cert
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => certificate); //

                try
                {
                    stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
                    //stream.AuthenticateAsClient(this.appleSettings.Host);
                }
                catch (System.Security.Authentication.AuthenticationException ex)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate as Client", ex);
                }

                if (!stream.IsMutuallyAuthenticated)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate", null);
                }

                if (!stream.CanWrite)
                {
                    throw new ConnectionFailureException("SSL Stream is not Writable", null);
                }

                networkStream = stream;
            }

            //Start reading from the stream asynchronously
            Reader();
        }
Exemple #39
0
 public CustomMessageBox(AutoResetEvent eventFlag, string message)
     : this()
 {
     handler[0]  = eventFlag;
     txtMsg.Text = message;
 }
Exemple #40
0
        private static void InternalTestAsync(SessionBase session)
        {
            int faultCalls = 0;

            byte[] task_data = new byte[input_data_size];
            (new Random()).NextBytes(task_data);

            if (sleep_before_sending > 0)
            {
                Thread.Sleep(sleep_before_sending);
            }

            data.StartSendRequest = DateTime.Now;

            Binding binding;

            if (http)
            {
                binding = Utils.CreateHttpBinding();
            }
            else
            {
                binding = Utils.CreateNetTcpBinding();
            }

            int            counting = batchCount;
            AutoResetEvent evt      = new AutoResetEvent(false);

            data.SendStart = DateTime.Now;

            for (int i = 0; i < batchCount; i++)
            {
                int msg_count = req_count / batchCount;
                if (i == batchCount - 1)
                {
                    msg_count += req_count % batchCount;
                }

                string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString();
                Thread t        = new Thread(new ThreadStart(() =>
                {
                    int AsyncResultCount            = msg_count;
                    AutoResetEvent AsyncResultsDone = new AutoResetEvent(false);

                    Log("Client {0}: Begin to send requests", clientId);
                    if (req_count == 0)
                    {
                        AsyncResultsDone.Set();
                    }

                    List <ResultData> results = new List <ResultData>();
                    Service1Client client     = new Service1Client(binding, session.EndpointReference);

                    for (int k = 0; k < msg_count; k++)
                    {
                        ResultData result = new ResultData();
                        ComputeWithInputDataRequest request = new ComputeWithInputDataRequest
                        {
                            millisec   = millisec_for_each_req,
                            input_data = task_data,
                            commonData_dataClientId = commonData_dataClientId,
                            responseSize            = output_data_size,
                        };
                        client.BeginComputeWithInputData(request,
                                                         (AsyncCallback) delegate(IAsyncResult r)
                        {
                            try
                            {
                                ResultData rtn = r.AsyncState as ResultData;
                                ComputeWithInputDataResponse response = client.EndComputeWithInputData(r);
                                rtn.TaskId = int.Parse(response.ComputeWithInputDataResult.CCP_TASKINSTANCEID);
                                rtn.Start  = response.ComputeWithInputDataResult.requestStartTime;
                                rtn.End    = response.ComputeWithInputDataResult.requestEndTime;

                                lock (results)
                                {
                                    results.Add(rtn);
                                }
                            }
                            catch (Exception e)
                            {
                                Log(e.ToString());
                                lock (results)
                                {
                                    results.Add(new ResultData(DateTime.Now,
                                                               DateTime.Now,
                                                               -1,
                                                               DateTime.Now, DateTime.Now));
                                }
                                Interlocked.Increment(ref faultCalls);
                            }

                            if (Interlocked.Decrement(ref AsyncResultCount) <= 0)
                            {
                                AsyncResultsDone.Set();
                            }
                        },
                                                         result);
                    }


                    AsyncResultsDone.WaitOne();

                    Log("Client {0}: All requests returned.", clientId);

                    if (DateTime.Now > data.RetrieveEnd)
                    {
                        data.RetrieveEnd = DateTime.Now;
                    }

                    client.Close();

                    lock (data)
                    {
                        data.ResultCollection.AddRange(results);
                    }



                    if (Interlocked.Decrement(ref counting) <= 0)
                    {
                        evt.Set();
                    }
                }));

                t.Start();
            }

            evt.WaitOne();

            data.FaultCount = faultCalls;
        }
Exemple #41
0
        private static void InternalResponseHandlerTestMultiThreads(SessionBase session)
        {
            NetTcpBinding binding = Utils.CreateNetTcpBinding();

            byte[] task_data = new byte[input_data_size];
            (new Random()).NextBytes(task_data);

            AutoResetEvent allClientSendEvt   = new AutoResetEvent(false);
            AutoResetEvent allClientDoneEvt   = new AutoResetEvent(false);
            int            clientSendCounting = batchCount;
            int            clientDoneCounting = batchCount;

            data.SendStart = DateTime.Now;

            for (int i = 0; i < batchCount; i++)
            {
                int msg_count = req_count / batchCount;
                if (i == batchCount - 1)
                {
                    msg_count += req_count % batchCount;
                }

                string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString();
                Thread t        = new Thread(new ThreadStart(() =>
                {
                    AutoResetEvent batchDone = new AutoResetEvent(false);

                    using (var client = new BrokerClient <IService1>(clientId, session, binding))
                    {
                        ResponseHandlerBase handler;
                        handler = new ComputeWithInputDataResponseHandler(client, clientId, common_data_size, retryRequestAndIgnoreRetryOperationError);
                        client.SetResponseHandler <ComputeWithInputDataResponse>(((ComputeWithInputDataResponseHandler)handler).ResponseHandler <ComputeWithInputDataResponse>);

                        ClientSendRequest(client, clientId, msg_count, task_data);

                        if (Interlocked.Decrement(ref clientSendCounting) <= 0)
                        {
                            allClientSendEvt.Set();
                        }

                        handler.WaitOne();
                        Log("Client {0}: All requests returned.", clientId);

                        lock (lockobject)
                        {
                            data.ResultCollection.AddRange(handler.results);
                            data.FaultCount = handler.faultCalls;
                        }
                        try
                        {
                            client.Close(durable, 10 * 60 * 1000);
                        }
                        catch (Exception e)
                        {
                            Log("Purge client {0} failed: {1}", clientId, e.ToString());
                        }
                        if (Interlocked.Decrement(ref clientDoneCounting) <= 0)
                        {
                            allClientDoneEvt.Set();
                        }
                    }
                }));
                t.Start();
            }

            allClientSendEvt.WaitOne();
            data.SendEnd = DateTime.Now;
            allClientDoneEvt.WaitOne();
            data.RetrieveEnd = DateTime.Now;
        }
Exemple #42
0
        private void SendMessages(IOutputChannel channel)
        {
            channel.Open();

            AutoResetEvent doneSending      = new AutoResetEvent(false);
            int            threadsCompleted = 0;

            if (this.Parameters.NumberOfMessages > 0)
            {
                this.SendMessage(channel, "FirstMessage", true);
            }

            if (this.Parameters.NumberOfThreads == 1)
            {
                for (int j = 0; j < this.Parameters.NumberOfMessages; ++j)
                {
                    if (this.Parameters.SenderShouldAbort)
                    {
                        this.SendMessage(channel, "Message " + (j + 1), false);
                    }

                    this.SendMessage(channel, "Message " + (j + 1), true);
                }

                doneSending.Set();
            }
            else
            {
                for (int i = 0; i < this.Parameters.NumberOfThreads; ++i)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object unused)
                    {
                        for (int j = 0; j < this.Parameters.NumberOfMessages / this.Parameters.NumberOfThreads; ++j)
                        {
                            if (this.Parameters.SenderShouldAbort)
                            {
                                this.SendMessage(channel, "Message", false);
                            }

                            this.SendMessage(channel, "Message", true);
                        }
                        if (Interlocked.Increment(ref threadsCompleted) == this.Parameters.NumberOfThreads)
                        {
                            doneSending.Set();
                        }
                    }));
                }
            }

            TimeSpan threadTimeout = TimeSpan.FromMinutes(2.0);

            if (!doneSending.WaitOne(threadTimeout, false))
            {
                lock (this.Results)
                {
                    this.Results.Add(String.Format("Threads did not complete within {0}.", threadTimeout));
                }
            }

            doneSending.Close();
            channel.Close();
        }
Exemple #43
0
        private void SetupRepeaterAnchoringUI(
            Scroller scroller,
            AutoResetEvent scrollerLoadedEvent)
        {
            Log.Comment("Setting up ItemsRepeater anchoring UI with Scroller and ItemsRepeater");

            TestDataSource dataSource = new TestDataSource(
                Enumerable.Range(0, c_defaultAnchoringUIRepeaterChildrenCount).Select(i => string.Format("Item #{0}", i)).ToList());

            RecyclingElementFactory elementFactory = new RecyclingElementFactory();

            elementFactory.RecyclePool       = new RecyclePool();
            elementFactory.Templates["Item"] = XamlReader.Load(
                @"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                        <Border BorderThickness='3' BorderBrush='Chartreuse' Width='100' Height='100' Margin='3' Background='BlanchedAlmond'>
                          <TextBlock Text='{Binding}' HorizontalAlignment='Center' VerticalAlignment='Center'/>
                        </Border>
                      </DataTemplate>") as DataTemplate;

            ItemsRepeater repeater = new ItemsRepeater()
            {
                Name        = "repeater",
                ItemsSource = dataSource,
#if BUILD_WINDOWS
                ItemTemplate = (Windows.UI.Xaml.IElementFactory)elementFactory,
#else
                ItemTemplate = elementFactory,
#endif
                Layout = new UniformGridLayout()
                {
                    MinItemWidth     = 125,
                    MinItemHeight    = 125,
                    MinRowSpacing    = 10,
                    MinColumnSpacing = 10
                },
                Margin = new Thickness(30)
            };

            Border border = new Border()
            {
                Name            = "border",
                BorderThickness = new Thickness(3),
                BorderBrush     = new SolidColorBrush(Colors.Chartreuse),
                Margin          = new Thickness(15),
                Background      = new SolidColorBrush(Colors.Beige),
                Child           = repeater
            };

            Verify.IsNotNull(scroller);
            scroller.Name = "scroller";
            scroller.IsChildAvailableWidthConstrained = true;
            scroller.Width      = 400;
            scroller.Height     = 600;
            scroller.Background = new SolidColorBrush(Colors.AliceBlue);
            scroller.Child      = border;

            if (scrollerLoadedEvent != null)
            {
                scroller.Loaded += (object sender, RoutedEventArgs e) =>
                {
                    Log.Comment("Scroller.Loaded event handler");
                    scrollerLoadedEvent.Set();
                };
            }

            scroller.AnchorRequested += (Scroller sender, ScrollerAnchorRequestedEventArgs args) =>
            {
                Log.Comment("Scroller.AnchorRequested event handler");

                Verify.IsNull(args.AnchorElement);
                Verify.IsGreaterThan(args.AnchorCandidates.Count, 0);
            };

            Log.Comment("Setting window content");
            MUXControlsTestApp.App.TestContentRoot = scroller;
        }
        public void FixScheduleMessageTest(int delayMs, int count)
        {
            //helper vars
            const double tolerancePerc  = 0.15;
            var          messageCounter = 0;
            var          expectedRuns   = new DateTime[count];
            var          isErrTolerance = false;
            Timer        t = null;

            using (var waitHandle = new AutoResetEvent(false))
            {
                //setup
                using (var actorSystem = new ActorSystem(ActorSystemOptions.Default))
                {
                    var actorMock = new Mock <IActor>();
                    actorMock.Setup(a => a.CanReceive).Returns(true);

                    actorMock.Setup(a => a.ReceiveTarget).Returns(env =>
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} Message received");
                        if (messageCounter > 1) //heat time
                        {
                            if (Math.Abs((DateTime.Now - expectedRuns[messageCounter]).Milliseconds) >
                                delayMs * tolerancePerc)
                            {
                                output.WriteLine("ERR: Delay higher than tolerance");
                                isErrTolerance = true;
                            }
                        }

                        messageCounter++;
                        if (messageCounter == count)
                        {
                            output.WriteLine($"{DateTime.Now:mm:ss.fff} Init stop timer");
                            //wait a bit to check no more messages coming and stop the test
                            t = new Timer(x =>
                            {
                                output.WriteLine($"{DateTime.Now:mm:ss.fff} Stopping the test");
                                // ReSharper disable once AccessToDisposedClosure
                                waitHandle.Set(); //stop the test
                            }, null, TimeSpan.FromMilliseconds(delayMs * 2), TimeSpan.FromMilliseconds(-1));
                        }

                        return(true);
                    });

                    //schedule messages
                    var actorRef = actorSystem.RegisterActor(actorMock.Object, "test actor");
                    for (var i = 0; i < count; i++)
                    {
                        expectedRuns[i] = DateTime.Now + TimeSpan.FromMilliseconds(100 + delayMs * (i + 1));
                        actorSystem.ScheduleMessage(ActorRefs.Empty, actorRef, expectedRuns[i], $"TST{i}");
                    }

                    //keep the test alive while processing the messages
                    if (!waitHandle.WaitOne(delayMs * (count + 5) + 3000, false))
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} ERR: Message receive timeout");
                        Assert.True(false, "Timeout");
                    }

                    Assert.Equal(count, messageCounter); //check the counter
                    if (isErrTolerance)                  //check the timeout
                    {
                        Assert.True(false, "Error - schedule tolerance");
                    }
                }
            }
            t?.Dispose();
        }
Exemple #45
0
        public void AnchoringAtRepeaterMiddle()
        {
            using (ScrollerTestHooksHelper scrollerTestHooksHelper = new ScrollerTestHooksHelper())
            {
                Scroller       scroller                 = null;
                AutoResetEvent scrollerLoadedEvent      = new AutoResetEvent(false);
                AutoResetEvent scrollerViewChangedEvent = new AutoResetEvent(false);

                RunOnUIThread.Execute(() =>
                {
                    scroller = new Scroller();

                    SetupRepeaterAnchoringUI(scroller, scrollerLoadedEvent);

                    scroller.HorizontalAnchorRatio = double.NaN;
                    scroller.VerticalAnchorRatio   = 0.5;
                });

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

                ChangeZoomFactor(scroller, 2.0f, 0.0f, 0.0f, ScrollerViewKind.Absolute, ScrollerViewChangeKind.AllowAnimation);
                ChangeOffsets(scroller, 0.0, 250.0, ScrollerViewKind.Absolute, ScrollerViewChangeKind.AllowAnimation, ScrollerViewChangeSnapPointRespect.IgnoreSnapPoints, false /*hookViewChanged*/);

                ItemsRepeater  repeater   = null;
                TestDataSource dataSource = null;

                RunOnUIThread.Execute(() =>
                {
                    repeater   = (scroller.Child as Border).Child as ItemsRepeater;
                    dataSource = repeater.ItemsSource as TestDataSource;

                    scroller.ViewChanged += delegate(Scroller sender, object args)
                    {
                        Log.Comment("ViewChanged - HorizontalOffset={0}, VerticalOffset={1}, ZoomFactor={2}",
                                    sender.HorizontalOffset, sender.VerticalOffset, sender.ZoomFactor);
                        scrollerViewChangedEvent.Set();
                    };

                    Log.Comment("Inserting items at the beginning");
                    dataSource.Insert(0 /*index*/, 2 /*count*/);
                });

                WaitForEvent("Waiting for Scroller.ViewChanged event", scrollerViewChangedEvent);

                RunOnUIThread.Execute(() =>
                {
                    Log.Comment("Scroller offset change expected");
                    Verify.AreEqual(scroller.VerticalOffset, 520.0);
                });

                RunOnUIThread.Execute(() =>
                {
                    scrollerViewChangedEvent.Reset();

                    Log.Comment("Removing items from the beginning");
                    dataSource.Remove(0 /*index*/, 2 /*count*/);
                });

                WaitForEvent("Waiting for Scroller.ViewChanged event", scrollerViewChangedEvent);

                RunOnUIThread.Execute(() =>
                {
                    Log.Comment("Scroller offset change expected");
                    Verify.AreEqual(scroller.VerticalOffset, 250.0);
                });
            }
        }
Exemple #46
0
 public override void OnResponse(int buttonID, int[] switches)
 {
     Result = buttonID == 1;
     AutoResetEvent.Set();
 }
 public FurioosSignaling(string url, float timeout, SynchronizationContext mainThreadContext)
 {
     m_timeout           = timeout;
     m_mainThreadContext = mainThreadContext;
     m_wsCloseEvent      = new AutoResetEvent(false);
 }
Exemple #48
0
 public PathfindingCallback(AutoResetEvent arEvent)
 {
     _event        = arEvent;
     CallbackCount = 0;
 }
Exemple #49
0
        private void AnchoringElementWithResizedViewport(Orientation orientation, double viewportSizeChange)
        {
            using (ScrollerTestHooksHelper scrollerTestHooksHelper = new ScrollerTestHooksHelper())
            {
                Scroller       scroller                 = null;
                AutoResetEvent scrollerLoadedEvent      = new AutoResetEvent(false);
                AutoResetEvent scrollerViewChangedEvent = new AutoResetEvent(false);

                RunOnUIThread.Execute(() =>
                {
                    scroller = new Scroller();

                    SetupDefaultAnchoringUI(orientation, scroller, scrollerLoadedEvent);
                });

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

                ChangeZoomFactor(scroller, 2.0f, 0.0f, 0.0f, ScrollerViewKind.Absolute, ScrollerViewChangeKind.DisableAnimation);

                double horizontalOffset = 0.0;
                double verticalOffset   = 0.0;

                RunOnUIThread.Execute(() =>
                {
                    if (orientation == Orientation.Vertical)
                    {
                        verticalOffset = (scroller.ExtentHeight * 2.0 - scroller.Height) / 2.0;
                        scroller.VerticalAnchorRatio = 0.5;
                    }
                    else
                    {
                        horizontalOffset = (scroller.ExtentWidth * 2.0 - scroller.Width) / 2.0;
                        scroller.HorizontalAnchorRatio = 0.5;
                    }
                });

                ChangeOffsets(scroller, horizontalOffset, verticalOffset, ScrollerViewKind.Absolute, ScrollerViewChangeKind.DisableAnimation, ScrollerViewChangeSnapPointRespect.IgnoreSnapPoints, false /*hookViewChanged*/);

                RunOnUIThread.Execute(() =>
                {
                    Log.Comment("Scroller view prior to viewport size change: HorizontalOffset={0}, VerticalOffset={1}, ZoomFactor={2}",
                                scroller.HorizontalOffset, scroller.VerticalOffset, scroller.ZoomFactor);

                    scroller.ViewChanged += delegate(Scroller sender, object args)
                    {
                        Log.Comment("ViewChanged - HorizontalOffset={0}, VerticalOffset={1}, ZoomFactor={2}",
                                    sender.HorizontalOffset, sender.VerticalOffset, sender.ZoomFactor);
                        scrollerViewChangedEvent.Set();
                    };

                    if (orientation == Orientation.Vertical)
                    {
                        Log.Comment("Changing viewport height");
                        scroller.Height += viewportSizeChange;
                    }
                    else
                    {
                        Log.Comment("Changing viewport width");
                        scroller.Width += viewportSizeChange;
                    }
                });

                WaitForEvent("Waiting for Scroller.ViewChanged event", scrollerViewChangedEvent);
                IdleSynchronizer.Wait();

                RunOnUIThread.Execute(() =>
                {
                    Log.Comment("Scroller view after viewport size change: HorizontalOffset={0}, VerticalOffset={1}, ZoomFactor={2}",
                                scroller.HorizontalOffset, scroller.VerticalOffset, scroller.ZoomFactor);
                    Log.Comment("Expecting offset change equal to half the viewport size change");
                    if (orientation == Orientation.Vertical)
                    {
                        Verify.AreEqual(scroller.VerticalOffset, verticalOffset - viewportSizeChange / 2.0);
                    }
                    else
                    {
                        Verify.AreEqual(scroller.HorizontalOffset, horizontalOffset - viewportSizeChange / 2.0);
                    }
                });
            }
        }
 public SocketAsyncEventArgsPool()
 {
     stack         = new ConcurrentStack <SocketAsyncEventArgs>();
     returnedEvent = new AutoResetEvent(false);
 }
        public void CancelFixScheduleMessageTest(
            int delayMs,
            int countStrMessage, int countIntMessages,
            int cancelAfterStrMessage, int cancelAfterIntMessages)
        {
            //helper vars
            var   messageCounterInt   = 0;
            var   messageCounterStr   = 0;
            var   messageCounterTotal = 0;
            Timer t = null;

            using (var waitHandle = new AutoResetEvent(false))
            {
                //setup
                using (var actorSystem = new ActorSystem(ActorSystemOptions.Default))
                {
                    var actorMock = new Mock <IActor>();
                    actorMock.Setup(a => a.CanReceive).Returns(true);

                    actorMock.Setup(a => a.ReceiveTarget).Returns(env =>
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} Message received {env.Message}");

                        if (env.Message is string)
                        {
                            messageCounterStr++;
                            if (messageCounterStr == cancelAfterStrMessage)
                            {
                                // ReSharper disable once AccessToDisposedClosure
                                actorSystem.CancelScheduledMessages(env.Recipient, typeof(string));
                                output.WriteLine($"{DateTime.Now:mm:ss.fff} No more STR messages after this");
                            }
                        }

                        if (env.Message is int)
                        {
                            messageCounterInt++;
                            if (messageCounterInt == cancelAfterIntMessages)
                            {
                                // ReSharper disable once AccessToDisposedClosure
                                actorSystem.CancelScheduledMessages(env.Recipient, typeof(int));
                                output.WriteLine($"{DateTime.Now:mm:ss.fff} No more INT messages after this");
                            }
                        }

                        messageCounterTotal++;
                        output.WriteLine($"T:{messageCounterTotal}");
                        if (messageCounterTotal == cancelAfterIntMessages + cancelAfterStrMessage)
                        {
                            output.WriteLine($"{DateTime.Now:mm:ss.fff} Init stop timer");
                            //wait a bit to check no more messages coming and stop the test
                            t = new Timer(x =>
                            {
                                output.WriteLine($"{DateTime.Now:mm:ss.fff} Stopping the test");
                                // ReSharper disable once AccessToDisposedClosure
                                waitHandle.Set(); //stop the test
                            }, null, TimeSpan.FromMilliseconds(delayMs * 2), TimeSpan.FromMilliseconds(-1));
                        }

                        return(true);
                    });

                    //schedule messages
                    var actorRef = actorSystem.RegisterActor(actorMock.Object, "test actor");
                    for (var i = 0; i < Math.Max(countIntMessages, countStrMessage); i++)
                    {
                        var expectedRun = DateTime.Now + TimeSpan.FromMilliseconds(100 + delayMs * (i + 1));
                        if (i < countStrMessage)
                        {
                            actorSystem.ScheduleMessage(ActorRefs.Empty, actorRef, expectedRun, $"TST{i}");
                        }

                        // ReSharper disable once InvertIf
                        if (i < countIntMessages)
                        {
                            actorSystem.ScheduleMessage(ActorRefs.Empty, actorRef, expectedRun, i);
                        }
                    }

                    //keep the test alive while processing the messages
                    if (!waitHandle.WaitOne(delayMs * (Math.Max(countIntMessages, countStrMessage) + 5) + 3000,
                                            false))
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} ERR: Message receive timeout");
                        Assert.True(false, "Timeout");
                    }

                    Assert.Equal(cancelAfterIntMessages, messageCounterInt); //check the counter - INT
                    Assert.Equal(cancelAfterStrMessage, messageCounterStr);  //check the counter - INT
                }
            }
            t?.Dispose();
        }
 internal void SetUnmanagedStructures(object objectsToPin)
 {
     if (!this.m_DisableOverlapped)
     {
         object[] pinnedObjectsArray = null;
         bool     alreadyTriedCast   = false;
         bool     flag2 = false;
         if (this.m_Cache != null)
         {
             if ((objectsToPin == null) && (this.m_Cache.PinnedObjects == null))
             {
                 flag2 = true;
             }
             else if (this.m_Cache.PinnedObjects != null)
             {
                 if (this.m_Cache.PinnedObjectsArray == null)
                 {
                     if (objectsToPin == this.m_Cache.PinnedObjects)
                     {
                         flag2 = true;
                     }
                 }
                 else if (objectsToPin != null)
                 {
                     alreadyTriedCast   = true;
                     pinnedObjectsArray = objectsToPin as object[];
                     if ((pinnedObjectsArray != null) && (pinnedObjectsArray.Length == 0))
                     {
                         pinnedObjectsArray = null;
                     }
                     if ((pinnedObjectsArray != null) && (pinnedObjectsArray.Length == this.m_Cache.PinnedObjectsArray.Length))
                     {
                         flag2 = true;
                         for (int i = 0; i < pinnedObjectsArray.Length; i++)
                         {
                             if (pinnedObjectsArray[i] != this.m_Cache.PinnedObjectsArray[i])
                             {
                                 flag2 = false;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
         if (!flag2 && (this.m_Cache != null))
         {
             this.m_Cache.Free();
             this.m_Cache = null;
         }
         Socket asyncObject = (Socket)base.AsyncObject;
         if (this.m_UseOverlappedIO)
         {
             this.m_UnmanagedBlob = SafeOverlappedFree.Alloc(asyncObject.SafeHandle);
             this.PinUnmanagedObjects(objectsToPin);
             this.m_OverlappedEvent = new AutoResetEvent(false);
             Marshal.WriteIntPtr(this.m_UnmanagedBlob.DangerousGetHandle(), Win32.OverlappedhEventOffset, this.m_OverlappedEvent.SafeWaitHandle.DangerousGetHandle());
         }
         else
         {
             asyncObject.BindToCompletionPort();
             if (this.m_Cache == null)
             {
                 if (pinnedObjectsArray != null)
                 {
                     this.m_Cache = new OverlappedCache(new Overlapped(), pinnedObjectsArray, s_IOCallback);
                 }
                 else
                 {
                     this.m_Cache = new OverlappedCache(new Overlapped(), objectsToPin, s_IOCallback, alreadyTriedCast);
                 }
             }
             this.m_Cache.Overlapped.AsyncResult = this;
         }
     }
 }
        public void CancelScheduledMessagesTest(int delayMs, int countStrMessage, int countIntMessages)
        {
            //helper vars
            var    messageCounterStr   = 0;
            var    messageCounterInt   = 0;
            var    messageCounterTotal = 0;
            string err = null;
            Timer  t   = null;

            using (var waitHandle = new AutoResetEvent(false))
            {
                //setup
                using (var actorSystem = new ActorSystem(ActorSystemOptions.Default))
                {
                    var actorMock = new Mock <IActor>();
                    actorMock.Setup(a => a.CanReceive).Returns(true);

                    actorMock.Setup(a => a.ReceiveTarget).Returns(env =>
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} Message received: {env.Message}");


                        // ReSharper disable AccessToDisposedClosure
                        actorSystem.CancelScheduledMessages(env.Sender, typeof(string)); //should have no impact to test - check that it will not cancel wrong messages
                        actorSystem.CancelScheduledMessage("1234567");                   //should have no impact to test - check that it will not cancel wrong messages
                        // ReSharper restore AccessToDisposedClosure


                        if (env.Message is string)
                        {
                            messageCounterStr++;
                        }
                        if (env.Message is int)
                        {
                            messageCounterInt++;
                        }
                        messageCounterTotal++;

                        if (messageCounterStr == countStrMessage && env.Message is string)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            actorSystem.CancelScheduledMessages(env.Recipient, typeof(string)); //cancel string message after  {count} messages
                            output.WriteLine($"{DateTime.Now:mm:ss.fff} No more STR messages after this point");
                        }

                        if (messageCounterStr > countStrMessage)
                        {
                            err = "didn't cancel string"; //should not get string message
                        }

                        if (messageCounterInt == countIntMessages && env.Message is int)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            actorSystem.CancelScheduledMessages(env.Recipient, typeof(int)); //cancel int message
                            output.WriteLine($"{DateTime.Now:mm:ss.fff} No more INT messages after this point");
                        }

                        if (messageCounterInt > countIntMessages)
                        {
                            err = "didn't cancel int"; //should not get int message
                        }

                        if (messageCounterTotal == countStrMessage + countIntMessages)
                        {
                            output.WriteLine($"{DateTime.Now:mm:ss.fff} Init stop timer");
                            //wait a bit to check no more messages coming and stop the test
                            t = new Timer(x =>
                            {
                                output.WriteLine($"{DateTime.Now:mm:ss.fff} Stopping the test");
                                // ReSharper disable once AccessToDisposedClosure
                                waitHandle.Set(); //stop the test
                            }, null, TimeSpan.FromMilliseconds(delayMs * 2), TimeSpan.FromMilliseconds(-1));
                        }

                        return(true);
                    });

                    //schedule messages
                    var actorRef = actorSystem.RegisterActor(actorMock.Object, "test actor");
                    actorSystem.ScheduleMessage(ActorRefs.Empty, actorRef, TimeSpan.FromMilliseconds(delayMs), "TST");
                    actorSystem.ScheduleMessage(ActorRefs.Empty, actorRef, TimeSpan.FromMilliseconds(delayMs), 5);

                    //keep the test alive while processing the messages
                    if (!waitHandle.WaitOne(delayMs * (countStrMessage + countIntMessages + 5) + 3000, false))
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} ERR: Message receive timeout");
                        Assert.True(false, "Timeout");
                    }

                    if (err != null)
                    {
                        Assert.True(false, $"Error - {err}");
                    }
                }
            }
            t?.Dispose();
        }
        public void PeriodicScheduledMessageTest(int delayMs, int count)
        {
            //setup
            const double tolerancePerc  = 0.1;
            var          messageCounter = 0;
            var          lastRun        = DateTime.MinValue;
            string       messageId      = null;
            var          isErrTolerance = false;
            Timer        t = null;

            using (var waitHandle = new AutoResetEvent(false))
            {
                using (var actorSystem = new ActorSystem(ActorSystemOptions.Default))
                {
                    var actorMock = new Mock <IActor>();
                    actorMock.Setup(a => a.CanReceive).Returns(true);

                    actorMock.Setup(a => a.ReceiveTarget).Returns(env =>
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} Message received");
                        if (messageCounter > 1) //heat time
                        {
                            if (Math.Abs((DateTime.Now - lastRun).Milliseconds - delayMs) > delayMs * tolerancePerc)
                            {
                                output.WriteLine("ERR: Delay higher than tolerance");
                                isErrTolerance = true;
                            }
                        }

                        lastRun = DateTime.Now;
                        messageCounter++;
                        if (messageCounter == count)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            // ReSharper disable once AccessToModifiedClosure
                            actorSystem.CancelScheduledMessage(messageId);

                            output.WriteLine($"{DateTime.Now:mm:ss.fff} Init stop timer");
                            //wait a bit to check no more messages coming and stop the test
                            t = new Timer(x =>
                            {
                                output.WriteLine($"{DateTime.Now:mm:ss.fff} Stopping the test");
                                // ReSharper disable once AccessToDisposedClosure
                                waitHandle.Set();     //stop the test
                            }, null, TimeSpan.FromMilliseconds(delayMs * 2), TimeSpan.FromMilliseconds(-1));
                        }

                        return(true);
                    });

                    //schedule message
                    var actorRef = actorSystem.RegisterActor(actorMock.Object, "test actor");
                    messageId = actorSystem.ScheduleMessage(ActorRefs.Empty, actorRef,
                                                            TimeSpan.FromMilliseconds(delayMs), "TST");

                    //keep the test alive while processing the messages
                    if (!waitHandle.WaitOne(delayMs * (count + 5) + 3000, false))
                    {
                        output.WriteLine($"{DateTime.Now:mm:ss.fff} ERR: Message receive timeout");
                        Assert.True(false, "Timeout");
                    }

                    //check
                    Assert.Equal(count, messageCounter); //check the counter
                    if (isErrTolerance)                  //check the timeout
                    {
                        Assert.True(false, "Error - schedule tolerance");
                    }
                }
            }
            t?.Dispose();
        }
Exemple #55
0
 public SeeedE5LoRaWANDevice()
 {
     response             = new StringBuilder(128);
     this.atExpectedEvent = new AutoResetEvent(false);
 }
Exemple #56
0
 public FenceD3D12(D3D12GraphicsDevice device, long initialValue)
 {
     Device      = device;
     _fence      = device.D3D12Device.CreateFence(initialValue, FenceFlags.None);
     _fenceEvent = new AutoResetEvent(false);
 }
        public List <string> ProcessFilesMultiThread(string FileOrDir)
        {
            //============================
            // root path
            string rootPath = Path.Combine("C:\\", "Lateetud");

            if (!Directory.Exists(rootPath))
            {
                Directory.CreateDirectory(rootPath);
            }
            if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.License)))
            {
                Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.License));
            }
            if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.OCRInput)))
            {
                Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.OCRInput));
            }
            if (!Directory.Exists(Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets)))
            {
                Directory.CreateDirectory(Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets));
            }
            //============================

            //============================
            // set the license
            RasterSupport.SetLicense(Path.Combine(rootPath, TheVarSubDir.License, "LEADTOOLS.lic"),
                                     File.ReadAllText(Path.Combine(rootPath, TheVarSubDir.License, "LEADTOOLS.lic.key")));

            // Ocr Engine started
            IOcrEngine    TheOcrEngine = null;
            OcrEngineType engineType;

            if (!Enum.TryParse("LEAD", true, out engineType))
            {
                return(null);
            }
            if (engineType == OcrEngineType.LEAD)
            {
                TheOcrEngine = OcrEngineManager.CreateEngine(engineType, true);
                TheOcrEngine.Startup(null, null, null, null);

                TheOcrEngine.SettingManager.SetEnumValue("Recognition.Fonts.DetectFontStyles", 0);
                TheOcrEngine.SettingManager.SetBooleanValue("Recognition.Fonts.RecognizeFontAttributes", false);
                if (TheOcrEngine.SettingManager.IsSettingNameSupported("Recognition.RecognitionModuleTradeoff"))
                {
                    TheOcrEngine.SettingManager.SetEnumValue("Recognition.RecognitionModuleTradeoff", "Accurate");
                }
            }
            else
            {
                TheOcrEngine = OcrEngineManager.CreateEngine(engineType, true);
                TheOcrEngine.Startup(null, null, null, null);
            }

            // initialize RasterCodecs instance
            RasterCodecs _RasterCodecs = new RasterCodecs();

            // initialize DiskMasterFormsRepository instance
            DiskMasterFormsRepository _DiskMasterFormsRepository = new DiskMasterFormsRepository(_RasterCodecs, Path.Combine(rootPath, TheVarSubDir.OCRMasterFormSets));

            var managers = AutoFormsRecognitionManager.Ocr | AutoFormsRecognitionManager.Default;
            // initialize AutoFormsEngine instance
            AutoFormsEngine _AutoFormsEngine = new AutoFormsEngine(_DiskMasterFormsRepository, TheOcrEngine, null, managers, 30, 80, false)
            {
                UseThreadPool = TheOcrEngine != null && TheOcrEngine.EngineType == OcrEngineType.LEAD
            };

            //============================

            // files to be processed
            string[] _files    = GetFiles(Path.Combine(rootPath, TheVarSubDir.OCRInput), FileOrDir);
            int      fileCount = _files.Length;

            List <string> _FileResults = new List <string>();

            // Event to notify us when all work is finished
            using (AutoResetEvent finishedEvent = new AutoResetEvent(false))
            {
                // Loop through all Files in the given Folder
                foreach (string _file in _files)
                {
                    string _FileResult = null;

                    // Process it in a thread
                    ThreadPool.QueueUserWorkItem((state) =>
                    {
                        try
                        {
                            // Process it
                            //var _result = _AutoFormsEngine.Run(_file, null).RecognitionResult;    // geting error with this statement


                            var imageInfo   = _RasterCodecs.GetInformation(_file, true);
                            var targetImage = _RasterCodecs.Load(_file, 0, CodecsLoadByteOrder.Bgr, 1, imageInfo.TotalPages);
                            targetImage.ChangeViewPerspective(RasterViewPerspective.TopLeft);
                            var _result = _AutoFormsEngine.Run(targetImage, null, targetImage, null).RecognitionResult;
                            if (_result == null)
                            {
                                _FileResult = "Not Recognized";
                            }
                            else
                            {
                                _FileResult = "Successfully Recognized";
                            }
                        }
                        catch (Exception ex)
                        {
                            _FileResult = "Not Recognized - " + ex.Message;
                        }
                        finally
                        {
                            _FileResults.Add(_FileResult);
                            if (Interlocked.Decrement(ref fileCount) == 0)
                            {
                                // We are done, inform the main thread
                                finishedEvent.Set();
                            }
                        }
                    });
                }

                // Wait till all operations are finished
                finishedEvent.WaitOne();
            }

            _AutoFormsEngine.Dispose();
            _RasterCodecs.Dispose();
            if (TheOcrEngine != null && TheOcrEngine.IsStarted)
            {
                TheOcrEngine.Shutdown();
            }

            return(_FileResults);
        }
Exemple #58
0
        private string StartInNoRedirectMode()
        {
            using var outputWaitHandle = new AutoResetEvent(false);
            using var errorWaitHandle  = new AutoResetEvent(false);
            using var process          = new Process();

            // preparing ProcessStartInfo
            process.StartInfo.FileName  = _cmd;
            process.StartInfo.Arguments = _arguments;
            if (!string.IsNullOrEmpty(WorkingDirectory))
            {
                process.StartInfo.WorkingDirectory = WorkingDirectory;
            }

            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.EnableRaisingEvents = true;

            var timeout = WaitForExitTimeout;

            try
            {
                var outputBuilder = new StringBuilder();
                process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        outputBuilder.AppendLine(e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        outputBuilder.AppendLine(e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                if (timeout == 0)
                {
                    timeout = -1;
                }
                if (process.WaitForExit(timeout))
                {
                    var exitCode = process.ExitCode;
                }
                else
                {
                    // timed out
                    return("process timed out");
                }

                var output = outputBuilder.ToString();
                return(output);
            }
            finally
            {
                outputWaitHandle.WaitOne(timeout);
                errorWaitHandle.WaitOne(timeout);
            }
        }
Exemple #59
0
        private static void InternalGetResponseTestMultiThreads(SessionBase session)
        {
            NetTcpBinding binding = Utils.CreateNetTcpBinding();

            int faultCalls = 0;

            byte[] task_data = new byte[input_data_size];
            (new Random()).NextBytes(task_data);

            AutoResetEvent allClientSendEvt   = new AutoResetEvent(false);
            AutoResetEvent allClientDoneEvt   = new AutoResetEvent(false);
            int            clientSendCounting = batchCount;
            int            clientDoneCounting = batchCount;

            data.SendStart = DateTime.Now;

            for (int i = 0; i < batchCount; i++)
            {
                int msg_count = req_count / batchCount;
                if (i == batchCount - 1)
                {
                    msg_count += req_count % batchCount;
                }

                string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString();
                //Console.WriteLine("--Client Id = {0}", clientId);
                var client = new BrokerClient <IService1>(clientId, session, binding);

                Thread t = new Thread(new ThreadStart(() =>
                {
                    ClientSendRequest(client, clientId, msg_count, task_data);
                    if (Interlocked.Decrement(ref clientSendCounting) <= 0)
                    {
                        allClientSendEvt.Set();
                    }
                }));

                Thread t2 = new Thread(new ThreadStart(() =>
                {
                    List <ResultData> results = ClientGetResponse(client, clientId);
                    lock (lockobject)
                    {
                        data.ResultCollection.AddRange(results);
                    }
                    try
                    {
                        client.Close(durable, 10 * 60 * 1000);
                    }
                    catch (Exception e)
                    {
                        Log("Purge client {0} failed: {1}", clientId, e.ToString());
                    }
                    finally
                    {
                        client.Close();
                        client.Dispose();
                        if (Interlocked.Decrement(ref clientDoneCounting) <= 0)
                        {
                            allClientDoneEvt.Set();
                        }
                    }
                }));
                t.Start();
                t2.Start();
            }

            allClientSendEvt.WaitOne();
            data.SendEnd = DateTime.Now;
            allClientDoneEvt.WaitOne();
            data.RetrieveEnd = DateTime.Now;
            data.FaultCount  = faultCalls;
        }
Exemple #60
0
        static void Main(string[] args)
        {
            Console.WriteLine("Zoom autojoin bot by SnakePin, this time made with .NET!");
            Console.WriteLine("Version: " + GetVersionString());

            string csvFilePath;

            if (args.Length >= 1 && !string.IsNullOrWhiteSpace(args[0]))
            {
                csvFilePath = args[0];
            }
            else
            {
                Console.WriteLine("Enter CSV file path: ");
                csvFilePath = Console.ReadLine();;
            }

            if (!File.Exists(csvFilePath))
            {
                Console.WriteLine("Invalid file path specified!");
                return;
            }

            var engine = new FileHelperEngine <ScheduleEntry>();

            engine.BeforeReadRecord += new FileHelpers.Events.BeforeReadHandler <ScheduleEntry>(
                (EngineBase _engine, FileHelpers.Events.BeforeReadEventArgs <ScheduleEntry> e)
                => e.SkipThisRecord = string.IsNullOrWhiteSpace(e.RecordLine) || e.RecordLine.StartsWith("#")
                );
            var result = engine.ReadFile(csvFilePath);

            Console.WriteLine("Fully loaded and initialized.");

            while (true)
            {
                foreach (var schedule in result)
                {
                    //1 to the 7 starting from Monday
                    int day = (DateTime.Now.DayOfWeek == DayOfWeek.Sunday) ? 7 : (int)DateTime.Now.DayOfWeek;

                    if (schedule.DayOfWeek == day)
                    {
                        DateTime meetingStartDate = DateTime.Today + Utils.TimeSpanFrom24HString(schedule.TimeIn24H);
                        DateTime meetingEndDate   = meetingStartDate.AddSeconds(schedule.MeetingTimeInSeconds);
                        DateTime currentDate      = DateTime.Now;

                        if ((currentDate > meetingStartDate) && (currentDate < meetingEndDate))
                        {
                            Console.WriteLine("Joining a session...");
                            Console.WriteLine($"-> Comment: {schedule.Comment}");
                            Console.WriteLine($"-> ID: {schedule.MeetingID}");
                            Console.WriteLine($"-> Password: {schedule.MeetingPassword}");
                            Console.WriteLine($"-> MeetingTimeInSeconds: {schedule.MeetingTimeInSeconds}");

                            try
                            {
                                if (!zoomAutomation.JoinZoom(schedule.MeetingID, schedule.MeetingPassword))
                                {
                                    Console.WriteLine("Failed joining the session for an unknown reason.");
                                    continue;
                                }
                                Console.WriteLine("Joined the session.");


                                var autoResetEvent     = new AutoResetEvent(false);
                                var millisecondsToWait = (meetingEndDate - DateTime.Now).TotalMilliseconds;

                                if (millisecondsToWait > 0)
                                {
                                    using (var timer = new Timer(_ => autoResetEvent.Set(), null, (uint)millisecondsToWait, Timeout.Infinite))
                                    {
                                        autoResetEvent.WaitOne();
                                    }
                                }

                                zoomAutomation.KillZoom();
                                Console.WriteLine("Session finished.");
                            }
                            catch (Exception exc)
                            {
                                Console.WriteLine("Failed joining the session. Sorry! Exception: " + exc);
                            }
                        }
                    }
                }
                Thread.Sleep(1000);
            }
        }