Пример #1
0
	public TestHelper(int num)
	{
		m_Event = new ManualResetEvent(false);
		m_iSharedData = 0;
		m_iRequestedEntries = num;
		m_bError = false;
	}
Пример #2
0
 public void PingPong()
 {
     using (ManualResetEvent mre1 = new ManualResetEvent(true), mre2 = new ManualResetEvent(false))
     {
         const int Iters = 10;
         Task.WaitAll(
             Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < Iters; i++)
                 {
                     Assert.True(mre1.WaitOne(FailedWaitTimeout));
                     mre1.Reset();
                     mre2.Set();
                 }
             }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
             Task.Factory.StartNew(() =>
             {
                 for (int i = 0; i < Iters; i++)
                 {
                     Assert.True(mre2.WaitOne(FailedWaitTimeout));
                     mre2.Reset();
                     mre1.Set();
                 }
             }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
     }
 }
Пример #3
0
	public State (int id, HttpWebRequest req)
	{
		this.id = id;
		request = req;
		handle = new ManualResetEvent (false);
		handleList.Add (handle);
	}
Пример #4
0
 public MockAsyncResult(TimeSpan timeout, AsyncCallback callback, object state)
 {
     Timeout = timeout;
     Callback = callback;
     AsyncState = state;
     AsyncWaitHandle = new ManualResetEvent(false);
 }
    /// <summary>
    /// Constructor
    /// </summary>
    public CreateJoinForm(Peer peerObject, Address addressObject, ConnectWizard connectionWizard)
    {
        //
        // Required for Windows Form Designer support
        //
        InitializeComponent();
        peer = peerObject;
        this.connectionWizard = connectionWizard;
        this.Text = connectionWizard.SampleName + " - " + this.Text;
        deviceAddress = addressObject;

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

        //Set up our timer
        updateListTimer = new System.Timers.Timer(300); // A 300 ms interval
        updateListTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.UpdateTimer);
        updateListTimer.SynchronizingObject = this;
        updateListTimer.Start();
        //Set up our connect timer
        connectTimer = new System.Timers.Timer(100); // A 100ms interval
        connectTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.ConnectTimer);
        connectTimer.SynchronizingObject = this;
        // Set up our connect event
        connectEvent = new ManualResetEvent(false);
    }
Пример #6
0
    static void Main()
    {
        const int FibonacciCalculations = 10;

        // One event is used for each Fibonacci object
        var doneEvents = new ManualResetEvent[FibonacciCalculations];
        var fibArray = new Fibonacci[FibonacciCalculations];
        var r = new Random();

        // Configure and launch threads using ThreadPool:
        Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
        for (int i = 0; i < FibonacciCalculations; i++)
        {
            doneEvents[i] = new ManualResetEvent(false);
            Fibonacci f = new Fibonacci(r.Next(20,40), doneEvents[i]);
            fibArray[i] = f;
            ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
        }

        // Wait for all threads in pool to calculation...
        WaitHandle.WaitAll(doneEvents);
        Console.WriteLine("All calculations are complete.");

        // Display the results...
        for (int i= 0; i<FibonacciCalculations; i++)
        {
            Fibonacci f = fibArray[i];
            Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
        }
    }
Пример #7
0
    //volatile bool shouldFinish=false;
    /*
        constructor sets up the OPCODE6DIR64 directory that holds the Csound plugins.
        also creates na instance of Csound and compiles it
    */
    public CsoundUnityBridge(string csoundDir, string csdFile)
    {
        #if WINDOWS
            manualReset = new ManualResetEvent(false);
        #endif

        #if WINDOWS
            //string path = System.Environment.GetEnvironmentVariable("Path");
            //System.Environment.SetEnvironmentVariable("Path", path + "/" + csoundDir);
            Csound6.NativeMethods.csoundSetGlobalEnv("OPCODE6DIR64", csoundDir);
        #elif OSX
            Csound6.NativeMethods.csoundSetGlobalEnv("OPCODE6DIR64", csoundDir+"/CsoundLib64.framework/Resources/Opcodes64");
        #elif Android
            Csound6.NativeMethods.csoundSetGlobalEnv("OPCODE6DIR64", opcodeDir+"/libcsoundandroid.so");
        #endif

        csound = Csound6.NativeMethods.csoundCreate(System.IntPtr.Zero);
        Csound6.NativeMethods.csoundCreateMessageBuffer(csound, 0);
        string[] runargs = new string[] { "csound", csdFile };
        int ret = Csound6.NativeMethods.csoundCompile(csound, 2, runargs);

        #if WINDOWS
        manualReset.Set();
        #endif
        performanceThread = new Thread(new ThreadStart(performCsound));
        if (ret == 0)
            performanceThread.Start();
    }
Пример #8
0
 public RestrictedTaskDispatcher(int maxParallelism)
 {
     workWaiter = new ManualResetEvent(false);
     workSemaphore = new Semaphore(maxParallelism, maxParallelism);
     workDispatchThread = new Thread(WorkDispatcher);
     workDispatchThread.Start();
 }
 public static void Sleep(int milliseconds)
 {
     using (ManualResetEvent waitEvent = new ManualResetEvent(false))
     {
         waitEvent.WaitOne(milliseconds);
     }
 }
Пример #10
0
    public static void Main()
    {     	
    	e = new ManualResetEvent(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...");
    }
            public void AquireWillBlockIfAnotherLockAlreadyAquiredOnSameAggregate()
            {
                var correlationId = GuidStrategy.NewGuid();
                var firstLockAquired = new ManualResetEvent(initialState: false);
                var secondLockAquired = new ManualResetEvent(initialState: false);
                var blockedTime = TimeSpan.Zero;

                Task.Factory.StartNew(() =>
                {
                    firstLockAquired.WaitOne();
                    using (var aggregateLock = new AggregateLock(typeof(Aggregate), correlationId))
                    {
                        var timer = Stopwatch.StartNew();

                        aggregateLock.Aquire();
                        timer.Stop();

                        blockedTime = timer.Elapsed;
                        secondLockAquired.Set();
                    }
                });

                using (var aggregateLock = new AggregateLock(typeof(Aggregate), correlationId))
                {
                    aggregateLock.Aquire();
                    firstLockAquired.Set();

                    Thread.Sleep(100);
                }

                secondLockAquired.WaitOne();

                Assert.InRange(blockedTime, TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(150));
            }
Пример #12
0
	private static void EvalPerf(Synch synch, int numThreads) {
		ManualResetEvent startEvent = new ManualResetEvent(false);
		int endTime = 0;
		int totalOps = 0;
		
		Thread[] threads = new Thread[numThreads];
		for (int n = 0; n < numThreads; ++n) {
			threads[n] = new Thread(() => {
				int numOps = 0; 
				startEvent.WaitOne();
				
				do {
					for (int i = 0; i < LOCKS_PER_LOOP; ++i) {
						synch.Synchronize(() => {
							// Busy variant:
                     // Thread.Yield();
						});
					}
					numOps += LOCKS_PER_LOOP;
				} while (Environment.TickCount < endTime);
				
				Interlocked.Add(ref totalOps, numOps);
			});
			threads[n].Start();
		}
		
		endTime = Environment.TickCount + MS_PER_TEST;
		startEvent.Set();
		
		foreach (Thread t in threads) {
			t.Join();
		}
		Console.WriteLine("[{0}] {1}", numThreads, totalOps);
	}
Пример #13
0
        public static void AbortSuspendTest()
        {
            var e = new ManualResetEvent(false);
            Action waitForThread;
            var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait);
            t.IsBackground = true;

            Action verify = () =>
            {
                Assert.Throws<PlatformNotSupportedException>(() => t.Abort());
                Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t));
            #pragma warning disable 618 // Obsolete members
                Assert.Throws<PlatformNotSupportedException>(() => t.Suspend());
                Assert.Throws<PlatformNotSupportedException>(() => t.Resume());
            #pragma warning restore 618 // Obsolete members
            };
            verify();

            t.Start();
            verify();

            e.Set();
            waitForThread();

            Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort());
        }
Пример #14
0
 private int Run()
 {
     int iRet = -1;
     Console.WriteLine("Abandoning more than one mutex " +
         "mix with other WaitHandles");
     CreateArray(64);
     myMRE = new ManualResetEvent(false);
     Thread t = new Thread(new ThreadStart(this.AbandonAllMutexes));
     t.Start();
     myMRE.WaitOne();
     try
     {
         Console.WriteLine("Waiting...");
         int i = WaitHandle.WaitAny(wh);
         Console.WriteLine("WaitAny did not throw an " +
             "exception, i = " + i);
     }
     catch(AbandonedMutexException)
     {
         // Expected
         iRet = 100;
     }
     catch(Exception e)
     {
         Console.WriteLine("Unexpected exception thrown: " + 
             e.ToString());
     }
     Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
     return iRet;
 }
 public void Start()
 {
     // create a new ManualResetEvent. This will be used to make the main application
     // thread wait until the full server reply has been received.
     m_ResetEvent = new ManualResetEvent(false);
     // initialize the security options
     SecurityOptions options = new SecurityOptions(
         SecureProtocol.Ssl3 | SecureProtocol.Tls1,	// use SSL3 or TLS1
         null,										// do not use client authentication
         ConnectionEnd.Client,						// this is the client side
         CredentialVerification.None,				// do not check the certificate -- this should not be used in a real-life application :-)
         null,										// not used with automatic certificate verification
         "www.microsoft.com",						// this is the common name of the Microsoft web server
         SecurityFlags.Default,						// use the default security flags
         SslAlgorithms.SECURE_CIPHERS,				// only use secure ciphers
         null);										// do not process certificate requests.
     try {
         // create the securesocket with the specified security options
         m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // resolve www.microsoft.com
         IPEndPoint endpoint = new IPEndPoint(Dns.GetHostEntry("www.microsoft.com").AddressList[0], 443);
         // start connecting to www.microsoft.com
         m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null);
         // wait until the entire web page has been received
         m_ResetEvent.WaitOne();
         // close the SecureSocket
         m_Socket.Close();
     } catch {
         OnError("Could not connect to the website");
     }
 }
Пример #16
0
	/* expected exit code: 255 */
	static void Main (string[] args)
	{
		if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
			AppDomain.CurrentDomain.UnhandledException += (s, e) => {};

		ManualResetEvent mre = new ManualResetEvent (false);

		var a = new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } });
		var ares = a.BeginInvoke (null, null);

		if (!mre.WaitOne (5000))
			Environment.Exit (2);

		try {
			a.EndInvoke (ares);
			Environment.Exit (4);
		} catch (CustomException) {
			/* expected behaviour */
			Environment.Exit (255);
		} catch (Exception ex) {
			Console.WriteLine (ex);
			Environment.Exit (3);
		}

		Environment.Exit (5);
	}
Пример #17
0
        public static void RunBlockedInjectionTest()
        {
            Debug.WriteLine("* RunBlockedInjectionTest() -- if it deadlocks, it failed");

            ManualResetEvent mre = new ManualResetEvent(false);

            // we need to run this test in a local task scheduler, because it needs to to perform 
            // the verification based on a known number of initially available threads.
            //
            //
            // @TODO: When we reach the _planB branch we need to add a trick here using ThreadPool.SetMaxThread
            //        to bring down the TP worker count. This is because previous activity in the test process might have 
            //        injected workers.
            TaskScheduler tm = TaskScheduler.Default;

            // Create many tasks blocked on the MRE.

            int processorCount = Environment.ProcessorCount;
            Task[] tasks = new Task[processorCount];
            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Factory.StartNew(delegate { mre.WaitOne(); }, CancellationToken.None, TaskCreationOptions.None, tm);
            }

            // Create one task that signals the MRE, and wait for it.
            Task.Factory.StartNew(delegate { mre.Set(); }, CancellationToken.None, TaskCreationOptions.None, tm).Wait();

            // Lastly, wait for the others to complete.
            Task.WaitAll(tasks);
        }
	public void TestWaitAny()
	{
		int x;

		e1 = new ManualResetEvent(false);
		e2 = new ManualResetEvent(false);

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2}, 100,false);

		AssertEquals("WaitAny(unset, unset)", x, WaitHandle.WaitTimeout);

		e1.Set();

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAny(set, unset)", x, 0);

		e1.Reset();
		e2.Set();

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAny(set, unset)", x, 1);

		e1.Set();
		e2.Set();

		x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAny(set, set)", x, 0);
	}
	public void TestWaitAll()
	{
		bool x;

		e1 = new ManualResetEvent(false);
		e2 = new ManualResetEvent(false);

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2}, 100,false);

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

		e1.Set();

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAll(set, unset)", x, false);

		e1.Reset();
		e2.Set();

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2},100, false);

		AssertEquals("WaitAll(set, unset)", x, false);

		e1.Set();
		e2.Set();

		x = WaitHandle.WaitAll(new WaitHandle[] {e1,e2},100, true);

		AssertEquals("WaitAll(set, set)", x, true);
	}
Пример #20
0
	static void Test2 (Process p)
	{
		ManualResetEvent mre_output = new ManualResetEvent (false);
		ManualResetEvent mre_error = new ManualResetEvent (false);

		p.Start ();

		p.OutputDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_output.Set ();
				return;
			}
		};

		p.ErrorDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_error.Set ();
				return;
			}
		};

		p.BeginOutputReadLine ();
		p.BeginErrorReadLine ();

		if (!p.WaitForExit (10000))
			Environment.Exit (4);
		if (!mre_output.WaitOne (1000))
			Environment.Exit (5);
		if (!mre_error.WaitOne (1000))
			Environment.Exit (6);
	}
Пример #21
0
	void Terminate()
	{

		if (ms_Instance == null || ms_Instance != this || !AkSoundEngine.IsInitialized())
			return; //Don't term twice        
				
		// Mop up the last callbacks that will be sent from Term with blocking.  
		// It may happen that the term sends so many callbacks that it will use up 
		// all the callback memory buffer and lock the calling thread. 

		// WG-25356 Thread is unsupported in Windows Store App API.

		AkSoundEngine.StopAll();
		AkSoundEngine.RenderAudio();
		const double IdleMs = 1.0;
		const uint IdleTryCount = 50;
		for(uint i=0; i<IdleTryCount; i++)
		{
			AkCallbackManager.PostCallbacks();
			using (EventWaitHandle tmpEvent = new ManualResetEvent(false)) {
				tmpEvent.WaitOne(System.TimeSpan.FromMilliseconds(IdleMs));
			}
		}

		AkSoundEngine.Term();
	
		ms_Instance = null;

		AkCallbackManager.Term();
		AkBankManager.Reset ();
	}
Пример #22
0
    public bool PosTest2()
    {
        bool retVal = true;

        ManualResetEvent expectedValue = new ManualResetEvent(false);
        ManualResetEvent actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest2:Set initialState as false and Create a instance");
        try
        {
            actualValue = (ManualResetEvent)(new ManualResetEvent(false));
            if (expectedValue.Equals(actualValue))
            {
                TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }
Пример #23
0
	/* expected exit code: 255 */
	static void Main (string[] args)
	{
		if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
			AppDomain.CurrentDomain.UnhandledException += (s, e) => {};

		ManualResetEvent mre = new ManualResetEvent (false);

		var t = Task.Factory.StartNew (new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }));

		if (!mre.WaitOne (5000))
			Environment.Exit (2);

		try {
			t.Wait ();
			Environment.Exit (5);
		} catch (AggregateException ae) {
			Console.WriteLine (ae);
			if (ae.InnerExceptions [0] is CustomException) {
				/* expected behaviour */
				Environment.Exit (255);
			}
		} catch (Exception ex) {
			Console.WriteLine (ex);
			Environment.Exit (3);
		}

		Environment.Exit (6);
	}
Пример #24
0
		// 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 );
			}
		}
Пример #25
0
    public static void PropertyTest1()
    {
        IAsyncResult asyncResult = new Task(() => Console.WriteLine("this is a dummy task"));
        var obj = new Overlapped();

        Assert.Null(obj.AsyncResult);
        obj.AsyncResult = asyncResult;
        Assert.Same(obj.AsyncResult, asyncResult);

#pragma warning disable 618
        Assert.Equal(obj.EventHandle, 0);
        obj.EventHandle = 3;
        Assert.Equal(obj.EventHandle, 3);
#pragma warning restore 618

        var _handle = new ManualResetEvent(false).SafeWaitHandle;
        Assert.NotSame(obj.EventHandleIntPtr, IntPtr.Zero);
        obj.EventHandleIntPtr = _handle.DangerousGetHandle();
        Assert.Equal(obj.EventHandleIntPtr, _handle.DangerousGetHandle());

        Assert.Equal(obj.OffsetHigh, 0);
        obj.OffsetHigh = 3;
        Assert.Equal(obj.OffsetHigh, 3);

        Assert.Equal(obj.OffsetLow, 0);
        obj.OffsetLow = 1;
        Assert.Equal(obj.OffsetLow, 1);
    }
Пример #26
0
	public static int Main ()
	{
		main_thread_id = Thread.CurrentThread.ManagedThreadId;
		Console.WriteLine ("{0}:Main start", main_thread_id);

		mre = new ManualResetEvent (false);
		mre2 = new ManualResetEvent (false);
		tcs = new TaskCompletionSource<bool> ();

		Task.Factory.StartNew (new Func<Task> (ExecuteAsync), new CancellationToken (), TaskCreationOptions.LongRunning, TaskScheduler.Default);

		if (!mre.WaitOne (1000))
			return 1;

		// Have to wait little bit longer for await not to take quick path
		Thread.Sleep (10);

		Console.WriteLine ("{0}:Main Set Result", Thread.CurrentThread.ManagedThreadId);

		SynchronizationContext.SetSynchronizationContext (new MyContext ());

		tcs.SetResult (true);

		if (!mre2.WaitOne (1000))
			return 2;

		Console.WriteLine ("ok");
		return 0;
	}
Пример #27
0
	static void Test1 (Process p)
	{
		ManualResetEvent mre_exit = new ManualResetEvent (false);
		ManualResetEvent mre_output = new ManualResetEvent (false);
		ManualResetEvent mre_error = new ManualResetEvent (false);

		p.EnableRaisingEvents = true;
		p.Exited += (s, a) => mre_exit.Set ();

		p.Start ();

		p.OutputDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_output.Set ();
				return;
			}
		};

		p.ErrorDataReceived += (s, a) => {
			if (a.Data == null) {
				mre_error.Set ();
				return;
			}
		};

		p.BeginOutputReadLine ();
		p.BeginErrorReadLine ();

		if (!mre_exit.WaitOne (10000))
			Environment.Exit (1);
		if (!mre_output.WaitOne (1000))
			Environment.Exit (2);
		if (!mre_error.WaitOne (1000))
			Environment.Exit (3);
	}
            public void BlockQueueUntilBelowBoundedCapacity()
            {
                var monitor = new FakeMonitor();
                var threadPool = new FakeThreadPool();
                var blocked = new ManualResetEvent(false);
                var released = new ManualResetEvent(false);
                var taskScheduler = new BlockingThreadPoolTaskScheduler(1, threadPool, monitor);

                monitor.BeforeWait = () => blocked.Set();
                monitor.AfterPulse = () => released.Set();

                Task.Factory.StartNew(() =>
                    {
                        // Schedule first task (non-blocking).
                        Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);

                        // Schedule second task (blocking).
                        Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.AttachedToParent, taskScheduler);
                    });

                // Wait for second task to be blocked.
                Assert.True(blocked.WaitOne(TimeSpan.FromMilliseconds(100)));
                Assert.Equal(1, threadPool.UserWorkItems.Count);

                threadPool.RunNext();

                // Wait for second task to be released.
                Assert.True(released.WaitOne(TimeSpan.FromMilliseconds(100)));

                threadPool.RunNext();

                Assert.Equal(0, taskScheduler.ScheduledTasks.Count());
            }
Пример #29
0
 internal void Wait(ManualResetEvent latch, TimeSpan timeSpan)
 {
     Assert.IsTrue(latch.WaitOne(timeSpan), "waiting on a latch timed out");
 }
Пример #30
0
        // -------------------------
        // Axiom Self-Update Download
        // -------------------------
        public void StartDownload()
        {
            // Start New Thread
            Thread worker = new Thread(() =>
            {
                // -------------------------
                // Download
                // -------------------------
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                // Use SecurityProtocolType.Ssl3 if needed for compatibility reasons

                WebClient wc = new WebClient();
                wc.Headers.Add(HttpRequestHeader.UserAgent, "Axiom (https://github.com/MattMcManis/Axiom)" + " v" + MainWindow.currentVersion + "-" + MainWindow.currentBuildPhase + " Update");
                //wc.Headers.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); //error
                //wc.Headers.Add("accept-language", "en-US,en;q=0.9"); //error
                //wc.Headers.Add("dnt", "1"); //error
                //wc.Headers.Add("upgrade-insecure-requests", "1"); //error
                //wc.Headers.Add("accept-encoding", "gzip, deflate, br"); //error

                waiter = new ManualResetEvent(false);                                                                                                                                               //start a new waiter for next pass (clicking update again)

                Uri url = new Uri("https://github.com/MattMcManis/Axiom/releases/download/" + "v" + Convert.ToString(MainWindow.latestVersion) + "-" + MainWindow.latestBuildPhase + "/Axiom.zip"); // v1.0.0.0-alpha/Axiom.zip

                // Async
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
                wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
                wc.DownloadFileAsync(url, MainWindow.tempDir + "Axiom.zip");

                // Progress Info
                progressInfo = "Downloading Axiom...";

                // Wait for Download to finish
                waiter.WaitOne();


                // -------------------------
                // Extract
                // -------------------------
                // Progress Info
                progressInfo = "Extracting Axiom...";

                List <string> extractArgs = new List <string>()
                {
                    // Powershell Launch Parameters
                    "-nologo -noprofile -command",
                    "$Host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size (80, 30); ",
                    "$Host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size (80, 30); ",
                    // Message
                    "Write-Host \"Updating Axiom to version " + Convert.ToString(MainWindow.latestVersion) + ".\";",
                    "Write-Host \"`nPlease wait for program to close.\";",
                    // Wait
                    "timeout 3;",
                    // Extract
                    "$shell = new-object -com shell.application;",
                    "$zip = $shell.NameSpace('" + MainWindow.tempDir + "Axiom.zip');",
                    //"foreach ($item in $zip.items()) {$shell.Namespace('" + MainWindow.appDir + "').CopyHere($item, 0x14)};", //all files
                    "foreach ($item in $zip.items()) {$name = [string]$item.Name; if ($name -match 'Axiom.exe') {$shell.Namespace('" + MainWindow.appDir + "').CopyHere($item, 0x14)}};",
                    // Delete Temp
                    "Write-Host \"`nDeleting Temp File\";",
                    "del " + "\"" + MainWindow.tempDir + "Axiom.zip" + "\";",
                    // Complete
                    "Write-Host \"`nUpdate Complete. Relaunching Axiom.\";",
                    "timeout 3;",
                    // Relaunch Axiom
                    "& '" + MainWindow.appDir + "Axiom.exe'",
                };

                // Join List with Spaces
                string arguments = string.Join(" ", extractArgs.Where(s => !string.IsNullOrEmpty(s)));

                // Start
                Process.Start("powershell.exe", arguments);

                // Close Axiom before updating exe
                Environment.Exit(0);
            });


            // Start Download Thread
            //
            worker.Start();
        }
        public void ThreadSynchronizationUsingManualResetEventExample()
        {
            Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Thread synchonization example using ManualResetEvent example started");

            var count = new int[] { 1, 2 };

            using (var threadBegin = new CountdownEvent(count.Count() * 3))
                using (var threadEnd = new CountdownEvent(count.Count() * 3))
                    using (var thread1lock = new ManualResetEvent(false))
                        using (var thread2lock = new ManualResetEvent(false))
                            using (var thread3lock = new ManualResetEvent(false))
                            {
                                count.Select(s => new Thread(() =>
                                {
                                    threadBegin.Signal();
                                    thread1lock.WaitOne();

                                    Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Set 1 thread " + s + ": Started");

                                    Thread.Sleep(10000);

                                    Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Set 1 thread " + s + ": Finished");
                                    threadEnd.Signal();
                                }))
                                .ToList()
                                .ForEach(f => f.Start());

                                count.Select(s => new Thread(() =>
                                {
                                    threadBegin.Signal();
                                    thread2lock.WaitOne();

                                    Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Set 2 thread " + s + ": Started");

                                    Thread.Sleep(5000);

                                    Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Set 2 thread " + s + ": Finished");
                                    threadEnd.Signal();
                                }))
                                .ToList()
                                .ForEach(f => f.Start());

                                count.Select(s => new Thread(() =>
                                {
                                    threadBegin.Signal();
                                    thread3lock.WaitOne();

                                    Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Set 3 thread " + s + ": Started");

                                    Thread.Sleep(500);

                                    Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Set 3 thread " + s + ": Finished");
                                    threadEnd.Signal();
                                }))
                                .ToList()
                                .ForEach(f => f.Start());

                                threadBegin.Wait();
                                thread1lock.Set();
                                Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Thread Set 1 Started.");
                                thread2lock.Set();
                                Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Thread Set 2 Started.");
                                thread3lock.Set();
                                Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Thread Set 3 Started.");
                                threadEnd.Wait();

                                Clients.Caller.ThreadSynchronizationUsingManualResetEventExample("Thread synchonization example using ManualResetEvent example ended");
                            }
        }
Пример #32
0
 public SleepSticker(ManualResetEvent wait)
 {
     Wait = wait;
 }
Пример #33
0
        static void Main(string[] args)
        {
            Console.WriteLine("SIPSorcery client user agent example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            ManualResetEvent exitMre       = new ManualResetEvent(false);
            bool             isCallHungup  = false;
            bool             hasCallFailed = false;

            AddConsoleLogger();

            SIPURI callUri = SIPURI.ParseSIPURI(DEFAULT_DESTINATION_SIP_URI);

            if (args != null && args.Length > 0)
            {
                if (!SIPURI.TryParse(args[0], out callUri))
                {
                    Log.LogWarning($"Command line argument could not be parsed as a SIP URI {args[0]}");
                }
            }
            Log.LogInformation($"Call destination {callUri}.");

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport();

            EnableTraceLogs(sipTransport);

            // Get the IP address the RTP will be sent from. While we can listen on IPAddress.Any | IPv6Any
            // we can't put 0.0.0.0 or [::0] in the SDP or the callee will treat our RTP stream as inactive.
            var lookupResult = SIPDNSManager.ResolveSIPService(callUri, false);

            Log.LogDebug($"DNS lookup result for {callUri}: {lookupResult?.GetSIPEndPoint()}.");
            var dstAddress        = lookupResult.GetSIPEndPoint().Address;
            var localOfferAddress = NetServices.GetLocalAddressForRemote(dstAddress);

            // Initialise an RTP session to receive the RTP packets from the remote SIP server.
            var audioOptions = new AudioOptions
            {
                AudioSource = AudioSourcesEnum.CaptureDevice,
                AudioCodecs = new List <SDPMediaFormatsEnum> {
                    SDPMediaFormatsEnum.PCMA, SDPMediaFormatsEnum.PCMU
                },
                OutputDeviceIndex = AudioOptions.DEFAULT_OUTPUTDEVICE_INDEX
            };
            var rtpSession = new RtpAVSession(audioOptions, null);
            var offerSDP   = rtpSession.CreateOffer(localOfferAddress);

            // Create a client user agent to place a call to a remote SIP server along with event handlers for the different stages of the call.
            var uac = new SIPClientUserAgent(sipTransport);

            uac.CallTrying  += (uac, resp) => Log.LogInformation($"{uac.CallDescriptor.To} Trying: {resp.StatusCode} {resp.ReasonPhrase}.");
            uac.CallRinging += (uac, resp) =>
            {
                Log.LogInformation($"{uac.CallDescriptor.To} Ringing: {resp.StatusCode} {resp.ReasonPhrase}.");
                if (resp.Status == SIPResponseStatusCodesEnum.SessionProgress)
                {
                    rtpSession.Start();
                }
            };
            uac.CallFailed += (uac, err, resp) =>
            {
                Log.LogWarning($"{uac.CallDescriptor.To} Failed: {err}");
                hasCallFailed = true;
            };
            uac.CallAnswered += (iuac, resp) =>
            {
                if (resp.Status == SIPResponseStatusCodesEnum.Ok)
                {
                    Log.LogInformation($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");

                    var result = rtpSession.SetRemoteDescription(SdpType.answer, SDP.ParseSDPDescription(resp.Body));
                    if (result == SetDescriptionResultEnum.OK)
                    {
                        rtpSession.Start();
                    }
                    else
                    {
                        Log.LogWarning($"Failed to set remote description {result}.");
                        uac.Hangup();
                    }
                }
                else
                {
                    Log.LogWarning($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");
                }
            };

            // The only incoming request that needs to be explicitly handled for this example is if the remote end hangs up the call.
            sipTransport.SIPTransportRequestReceived += async(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) =>
            {
                if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    SIPResponse okResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    await sipTransport.SendResponseAsync(okResponse);

                    if (uac.IsUACAnswered)
                    {
                        Log.LogInformation("Call was hungup by remote server.");
                        isCallHungup = true;
                        exitMre.Set();
                    }
                }
            };

            // Start the thread that places the call.
            SIPCallDescriptor callDescriptor = new SIPCallDescriptor(
                SIPConstants.SIP_DEFAULT_USERNAME,
                null,
                callUri.ToString(),
                SIPConstants.SIP_DEFAULT_FROMURI,
                callUri.CanonicalAddress,
                null, null, null,
                SIPCallDirection.Out,
                SDP.SDP_MIME_CONTENTTYPE,
                offerSDP.ToString(),
                null);

            uac.Call(callDescriptor);
            uac.ServerTransaction.TransactionTraceMessage += (tx, msg) => Log.LogInformation($"UAC tx trace message. {msg}");

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                exitMre.Set();
            };

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            exitMre.WaitOne();

            Log.LogInformation("Exiting...");

            rtpSession.Close(null);

            if (!isCallHungup && uac != null)
            {
                if (uac.IsUACAnswered)
                {
                    Log.LogInformation($"Hanging up call to {uac.CallDescriptor.To}.");
                    uac.Hangup();
                }
                else if (!hasCallFailed)
                {
                    Log.LogInformation($"Cancelling call to {uac.CallDescriptor.To}.");
                    uac.Cancel();
                }

                // Give the BYE or CANCEL request time to be transmitted.
                Log.LogInformation("Waiting 1s for call to clean up...");
                Task.Delay(1000).Wait();
            }

            SIPSorcery.Net.DNSManager.Stop();

            if (sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }
        }
Пример #34
0
        public Task <bool> ActivateProfile(SetupProfile profile)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile");
            }
            var captureSignal = new ManualResetEvent(false);
            var trackerSignal = new ManualResetEvent(false);
            var deviceSignal  = new ManualResetEvent(false);
            var cancel        = new CancellationToken();

            CaptureSystem.Instance.Invoke((object sender, EventArgs args) => {
                var system = (CaptureSystem)sender;
                foreach (int i in profile.VideoCaptureIndexes)
                {
                    var settings = profile.GetVideoCapture(i);
                    var sensor   = new WebcamCapture(settings);
                    int index    = system.ConnectSensor(sensor, i);
                    if (index != i)
                    {
                        LogManager.Instance.LogWarning(this, string.Format("VideoCapture {0} assigned to different index {1}",
                                                                           i, index));
                    }
                }
                captureSignal.Set();
            });

            TrackingSystem.Instance.Invoke(delegate {
                foreach (int i in profile.TrackerIndexes)
                {
                    var settings = profile.GetTracker(i);
                    var tracker  = new P3CapTracker(settings);
                    int index    = TrackingSystem.Instance.StartTracker(tracker);
                }
                trackerSignal.Set();
            });

            VirtualDeviceManager.Instance.Invoke(delegate {
                foreach (int i in profile.DeviceIndexes)
                {
                    var settings = profile.GetDevice(i);
                    var device   = VirtualDevice.CreateFromSettings(settings);
                    int index    = VirtualDeviceManager.Instance.ConnectDevice(device);
                }
                deviceSignal.Set();
            });
            return(Task.Factory.StartNew(delegate {
                captureSignal.WaitOne();
                trackerSignal.WaitOne();
                deviceSignal.WaitOne();
                return true;
            }, cancel));

            // we need to wait for the detection system to update tracker equipment
//			DetectionSystem.Instance.Invoke(delegate {
//				Invoke(delegate {
//					foreach (int iTracker in profile.BindingIndexes) {
//						if (!bindingsFactory.ApplyBindings(iTracker, profile.GetBindings(iTracker))) {
//							LogManager.Instance.LogError(this, "Failed to restore tracker bindings");
//							return;
//						}
//					}
//				});
//			});
        }
Пример #35
0
        private void OnConnectAsyncCompleted(object sender, SocketAsyncEventArgs args)
        {
            ManualResetEvent complete = (ManualResetEvent)args.UserToken;

            complete.Set();
        }
Пример #36
0
        /// <summary>Waits for the associated process to exit.</summary>
        /// <param name="millisecondsTimeout">The amount of time to wait, or -1 to wait indefinitely.</param>
        /// <returns>true if the process exited; false if the timeout occurred.</returns>
        internal bool WaitForExit(int millisecondsTimeout)
        {
            Debug.Assert(!Monitor.IsEntered(_gate));

            if (_isChild)
            {
                lock (_gate)
                {
                    // If we already know that the process exited, we're done.
                    if (_exited)
                    {
                        return true;
                    }
                }
                ManualResetEvent exitEvent = EnsureExitedEvent();
                return exitEvent.WaitOne(millisecondsTimeout);
            }
            else
            {
                // Track the time the we start waiting.
                long startTime = Stopwatch.GetTimestamp();

                // Polling loop
                while (true)
                {
                    bool createdTask = false;
                    CancellationTokenSource cts = null;
                    Task waitTask;

                    // We're in a polling loop... determine how much time remains
                    int remainingTimeout = millisecondsTimeout == Timeout.Infinite ?
                        Timeout.Infinite :
                        (int)Math.Max(millisecondsTimeout - ((Stopwatch.GetTimestamp() - startTime) / (double)Stopwatch.Frequency * 1000), 0);

                    lock (_gate)
                    {
                        // If we already know that the process exited, we're done.
                        if (_exited)
                        {
                            return true;
                        }

                        // If a timeout of 0 was supplied, then we simply need to poll
                        // to see if the process has already exited.
                        if (remainingTimeout == 0)
                        {
                            // If there's currently a wait-in-progress, then we know the other process
                            // hasn't exited (barring races and the polling interval).
                            if (_waitInProgress != null)
                            {
                                return false;
                            }

                            // No one else is checking for the process' exit... so check.
                            // We're currently holding the _gate lock, so we don't want to
                            // allow CheckForNonChildExit to block indefinitely.
                            CheckForNonChildExit();
                            return _exited;
                        }

                        // The process has not yet exited (or at least we don't know it yet)
                        // so we need to wait for it to exit, outside of the lock.
                        // If there's already a wait in progress, we'll do so later
                        // by waiting on that existing task.  Otherwise, we'll spin up
                        // such a task.
                        if (_waitInProgress != null)
                        {
                            waitTask = _waitInProgress;
                        }
                        else
                        {
                            createdTask = true;
                            CancellationToken token = remainingTimeout == Timeout.Infinite ?
                                CancellationToken.None :
                                (cts = new CancellationTokenSource(remainingTimeout)).Token;
                            waitTask = WaitForExitAsync(token);
                        }
                    } // lock(_gate)

                    if (createdTask)
                    {
                        // We created this task, and it'll get canceled automatically after our timeout.
                        // This Wait should only wake up when either the process has exited or the timeout
                        // has expired.  Either way, we'll loop around again; if the process exited, that'll
                        // be caught first thing in the loop where we check _exited, and if it didn't exit,
                        // our remaining time will be zero, so we'll do a quick remaining check and bail.
                        waitTask.Wait();
                        cts?.Dispose();
                    }
                    else
                    {
                        // It's someone else's task.  We'll wait for it to complete. This could complete
                        // either because our remainingTimeout expired or because the task completed,
                        // which could happen because the process exited or because whoever created
                        // that task gave it a timeout.  In any case, we'll loop around again, and the loop
                        // will catch these cases, potentially issuing another wait to make up any
                        // remaining time.
                        waitTask.Wait(remainingTimeout);
                    }
                }
            }
        }
Пример #37
0
        /// <summary>
        /// Runs an isolated task in a host.
        /// </summary>
        /// <typeparam name="TIsolatedTask">The isolated task type.</typeparam>
        /// <param name="hostSetup">The host setup which includes the test isolation option properties copied down, not null.</param>
        /// <param name="statusReporter">The status reporter, not null.</param>
        /// <param name="args">The task arguments.</param>
        /// <returns>The task result.</returns>
        protected virtual object RunIsolatedTaskInHost <TIsolatedTask>(HostSetup hostSetup, StatusReporter statusReporter, object[] args)
            where TIsolatedTask : IsolatedTask
        {
            IHost host = null;

            try
            {
                statusReporter("Creating test host.");
                host = hostFactory.CreateHost(hostSetup, logger);

                RemoteLogger remoteLogger = new RemoteLogger(logger);
                RuntimeSetup runtimeSetup = RuntimeAccessor.Instance.GetRuntimeSetup().Copy();

                Shim shim = HostUtils.CreateInstance <Shim>(host);
                try
                {
                    statusReporter("Initializing the runtime.");
                    shim.Initialize(runtimeSetup, remoteLogger);
                    statusReporter("");

                    var isolatedTask = HostUtils.CreateInstance <TIsolatedTask>(host);

                    ManualResetEvent disconnectedEvent        = new ManualResetEvent(false);
                    EventHandler     disconnectedEventHandler = (sender, e) => disconnectedEvent.Set();
                    try
                    {
                        host.Disconnected += disconnectedEventHandler;

                        RunIsolatedTaskDelegate isolatedTaskDelegate = isolatedTask.Run;
                        IAsyncResult            asyncResult          = isolatedTaskDelegate.BeginInvoke(args, null, null);

                        WaitHandle.WaitAny(new[] { disconnectedEvent, asyncResult.AsyncWaitHandle });

                        if (asyncResult.IsCompleted)
                        {
                            return(isolatedTaskDelegate.EndInvoke(asyncResult));
                        }

                        throw new TestIsolationException("The host disconnected or was terminated prematurely while the task was running.");
                    }
                    finally
                    {
                        host.Disconnected -= disconnectedEventHandler;
                    }
                }
                finally
                {
                    statusReporter("Shutting down the runtime.");
                    shim.Shutdown();

                    GC.KeepAlive(remoteLogger);
                }
            }
            finally
            {
                statusReporter("Disposing test host.");

                try
                {
                    if (host != null)
                    {
                        host.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    UnhandledExceptionPolicy.Report("An exception occurred while disposing the test host.", ex);
                }

                statusReporter("");
            }
        }
Пример #38
0
 public SyncWaiter()
 {
     this.signal = new ManualResetEvent(false);
 }
Пример #39
0
 /// <summary>
 /// Returns a perfectly boring NetAsyncDownloader.
 /// </summary>
 public NetAsyncDownloader(IUser user)
 {
     User                 = user;
     downloads            = new List <NetAsyncDownloaderDownloadPart>();
     complete_or_canceled = new ManualResetEvent(false);
 }
Пример #40
0
        static void Main(string[] args)
        {
            var interfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var item in interfaces.Select((i, idx) => new { nr = idx + 1, inter = i }))
            {
                Console.WriteLine($"-{item.nr}- {item.inter.Name}");
            }
            Console.Write("> Choose a interface: ");
            int selection     = int.Parse(Console.ReadLine());
            var mainInterface = interfaces[selection - 1];

            var    random            = new Random();
            ushort packetId          = (ushort)random.Next();
            uint   dhcpTransactionId = (uint)random.Next();

            ITransportPacketFactory   transportPacketFactory   = new TransportPacketFactoryImpl();
            IApplicationPacketFactory applicationPacketFactory = new ApplicationPacketFactoryImpl();

            var dhcpDiscover = BuildDhcpDiscoverMessage(mainInterface, packetId, dhcpTransactionId);

            bool             running       = true;
            bool             rcvAck        = false;
            ManualResetEvent rcvAckEvent   = new ManualResetEvent(false);
            DhcpOffer        selectedOffer = null;
            var socket = SetupPromiscousSocket(mainInterface);

            Console.WriteLine("Send DHCP Discover...");
            dhcpDiscover.Send(socket);

            ISet <DhcpOffer> offers = new HashSet <DhcpOffer>();
            var recieverThread      = new Thread(() =>
            {
                while (running)
                {
                    IPv4Packet rcvPacket = IPv4Packet.Recieve(socket, transportPacketFactory, applicationPacketFactory);

                    if (rcvPacket != null && rcvPacket.Payload is UdpPacket udpPacket)
                    {
                        if (udpPacket.Payload is DhcpPacket responseDhcpPacket)
                        {
                            switch (responseDhcpPacket.MessageType)
                            {
                            case DhcpMessageType.Offer:
                                DhcpOffer offer = DhcpOffer.FromDhcpPacket(responseDhcpPacket);
                                offers.Remove(offer);     // remove old offer from server if necassary
                                offers.Add(offer);
                                Console.WriteLine($"New Offer from {rcvPacket.Source}");
                                break;

                            case DhcpMessageType.Ack:
                                if (!rcvAck)
                                {
                                    Console.WriteLine("OK from server - ready to launch!");

                                    int exitCodeInter = ExecuteNetshCommand(
                                        $"interface ipv4 set address name=\"{mainInterface.Name}\" static" +
                                        $" {selectedOffer.ClientAddress} {selectedOffer.SubnetMask} {selectedOffer.Gateway} 1"
                                        );
                                    Console.WriteLine($"netsh Interface exit code - {exitCodeInter}");

                                    int exitCodeDns = ExecuteNetshCommand(
                                        $"interface ipv4 set dnsservers \"{mainInterface.Name}\" static {selectedOffer.DnsServer} primary no"
                                        );
                                    Console.WriteLine($"netsh DNS exit code - {exitCodeDns}");
                                    rcvAckEvent.Set();
                                }
                                rcvAck = true;
                                break;
                            }
                        }
                    }
                }
            });

            recieverThread.Start();

            Thread.Sleep(500);
            if (offers.Count == 0)
            {
                Console.WriteLine("Resending DHCP Discover...");
                dhcpDiscover.Send(socket);
            }

            Console.WriteLine("> Press any key to stop adding new offers\n");
            Console.ReadKey();

            Console.WriteLine();
            Console.WriteLine("-- Select DHCP server offer --");
            DhcpOffer[] finalOffers = offers.ToArray();
            foreach (var item in finalOffers.Select((o, idx) => new { nr = idx + 1, offer = o }))
            {
                Console.WriteLine($"-{item.nr}- Offer from {item.offer.DhcpServer}");
                Console.WriteLine($"   Client address: {item.offer.ClientAddress}");
                Console.WriteLine($"   Gateway address: {item.offer.Gateway}");
                Console.WriteLine($"   DNS server: {item.offer.DnsServer}");
                Console.WriteLine($"   Domain: {item.offer.Domain}");
            }

            Console.Write("> Choose a offer: ");
            selection     = int.Parse(Console.ReadLine());
            selectedOffer = finalOffers[selection - 1];

            Console.WriteLine("Send DHCP Request");
            IPv4Packet dhcpRequest = BuildDhcpRequestMessage(selectedOffer, mainInterface, ++packetId, dhcpTransactionId);

            dhcpRequest.Send(socket);

            Console.WriteLine("Waiting for DHCP Ack and netsh...");
            rcvAckEvent.WaitOne();
            running = false;
            socket.Close();

            Console.WriteLine("> Press any key to close");
            Console.ReadKey();
        }
 public void FixtureSetUp()
 {
     // this occurs with a "clean" stack (full trust)
     reset = new ManualResetEvent(false);
 }
Пример #42
0
        //
        // Concurrency and Coordination
        //

        internal void Wait(ManualResetEvent latch)
        {
            Assert.IsTrue(latch.WaitOne(TimeSpan.FromSeconds(10)), "waiting on a latch timed out");
        }
Пример #43
0
        public void Bus_PublishedMessage_EachSubscriberGetsMessageCopy()
        {
            Person actual = new Person
            {
                Id = 5
            };

            Person b1 = null, b2 = null, c1 = null;

            ManualResetEvent ev1 = new ManualResetEvent(false), ev2 = new ManualResetEvent(false), ev3 = new ManualResetEvent(false);

            using (MessageBus.Core.RabbitMQBus busA = new MessageBus.Core.RabbitMQBus(), busB = new MessageBus.Core.RabbitMQBus(), busC = new MessageBus.Core.RabbitMQBus())
            {
                using (ISubscriber subscriberB1 = busB.CreateSubscriber(), subscriberB2 = busB.CreateSubscriber(), subscriberC1 = busC.CreateSubscriber())
                {
                    subscriberB1.Subscribe <Person>(p => { b1 = p; ev1.Set(); });
                    subscriberB2.Subscribe <Person>(p => { p.Id *= 2; b2 = p; ev2.Set(); });
                    subscriberC1.Subscribe <Person>(p => { c1 = p; ev3.Set(); });

                    subscriberB1.Open();
                    subscriberB2.Open();
                    subscriberC1.Open();

                    using (IPublisher publisher = busA.CreatePublisher())
                    {
                        publisher.Send(actual);
                    }

                    bool wait = ev1.WaitOne(TimeSpan.FromSeconds(5)) &&
                                ev2.WaitOne(TimeSpan.FromSeconds(5)) &&
                                ev3.WaitOne(TimeSpan.FromSeconds(5));

                    wait.Should().BeTrue("Message should arrive to all subscribers");

                    b1.Should().NotBeNull();
                    b2.Should().NotBeNull();
                    c1.Should().NotBeNull();

                    b1.ShouldBeEquivalentTo(actual);
                    b2.ShouldBeEquivalentTo(new Person
                    {
                        Id = actual.Id * 2
                    });
                    c1.ShouldBeEquivalentTo(actual);
                }
            }
        }
Пример #44
0
 public ExecutorLocksHeldException(ManualResetEvent handle)
 {
     this.handle = handle;
 }
Пример #45
0
 public FakeMessageSender()
 {
     messageReceived = new ManualResetEvent(false);
 }
Пример #46
0
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            this.OutputPath = Directory.GetCurrentDirectory();
            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                var bgcolor = Console.BackgroundColor;
                var fgcolor = Console.ForegroundColor;

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#######################################");
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                       ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.Write("    .NETCore 2.1 + SQLServer 生成器    ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("                                       ");
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = fgcolor;
                Console.WriteLine("");

                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("##");
                Console.Write("#######################################");
                Console.Write("##");

                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write(@"

用于快速创建和更新 .NETCore 2.1 + SQLServer 项目,非常合适敏捷开发;
Github: https://github.com/2881099/dotnetgen_sqlserver

");
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write("Example:");
                Console.ForegroundColor = fgcolor;
                Console.WriteLine(@"

	> GenMs 127.0.0.1 -U sa -P 123456 -D dyschool -N dyschool -S -A -R
	> GenMs 127.0.0.1 -D dyschool -N dyschool -S -A -R //使用windows登陆

		-U	SQLServer账号
		-P	SQLServer密码
		-D	需要生成的数据库

		-N	字符串,生成代码的解决方案名和命名空间
		-S	生成解决方案,在项目第一次生成时使用
		-A	生成后台管理
		-R	下载资源
		
		-O	输出路径(默认:当前目录)"            );
                wait.Set();
                return;
            }
            this.Server = args[0];
            for (int a = 1; a < args.Length; a++)
            {
                switch (args[a])
                {
                case "-U":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-U 参数错误");
                    }
                    else
                    {
                        this.Username = args[a + 1];
                    }
                    a++;
                    break;

                case "-P":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-P 参数错误");
                    }
                    else
                    {
                        this.Password = args[a + 1];
                    }
                    a++;
                    break;

                case "-D":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-D 参数错误");
                    }
                    else
                    {
                        this.Database = args[a + 1];
                    }
                    a++;
                    break;

                case "-N":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-N 参数错误");
                    }
                    else
                    {
                        this.SolutionName = args[a + 1];
                    }
                    a++;
                    break;

                case "-O":
                    if (a + 1 >= args.Length)
                    {
                        Console.WriteLine("-O 参数错误");
                    }
                    else
                    {
                        this.OutputPath = args[a + 1];
                    }
                    a++;
                    break;

                case "-S":
                    this.IsMakeSolution = true;
                    break;

                case "-A":
                    this.IsMakeWebAdmin = true;
                    break;

                case "-R":
                    this.IsDownloadRes = true;
                    break;
                }
            }
            this._client = new ClientInfo(this.Server, this.Username, this.Password);
            StreamReader sr     = new StreamReader(System.Net.WebRequest.Create("https://files.cnblogs.com/files/kellynic/GenMs_server.css").GetResponse().GetResponseStream(), Encoding.UTF8);
            string       server = sr.ReadToEnd()?.Trim();
            //server = "127.0.0.1:29918";
            Uri uri = new Uri("tcp://" + server + "/");

            this._socket          = new ClientSocket();
            this._socket.Error   += Socket_OnError;
            this._socket.Receive += Socket_OnReceive;
            this._socket.Connect(uri.Host, uri.Port);
            Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
            if (this._socket.Running == false)
            {
                wait.Set();
                return;
            }

            WriteLine("正在生成,稍候 …", ConsoleColor.DarkGreen);

            SocketMessager messager = new SocketMessager("GetDatabases", this._client);

            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                List <DatabaseInfo> dbs = e2.Messager.Arg as List <DatabaseInfo>;
            });
            this._client.Database = this.Database;
            List <TableInfo> tables = null;

            messager = new SocketMessager("GetTablesByDatabase", this._client.Database);
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                tables = e2.Messager.Arg as List <TableInfo>;
            });
            if (tables == null)
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] 无法读取表");
                this._socket.Close();
                this._socket.Dispose();

                wait.Set();
                return;
            }
            tables.ForEach(a => a.IsOutput = true);
            List <BuildInfo> bs = null;

            messager = new SocketMessager("Build", new object[] {
                SolutionName,
                IsMakeSolution,
                string.Join("", tables.ConvertAll <string>(delegate(TableInfo table){
                    return(string.Concat(table.IsOutput ? 1 : 0));
                }).ToArray()),
                IsMakeWebAdmin,
                IsDownloadRes
            });
            this._socket.Write(messager, delegate(object sender2, ClientSocketReceiveEventArgs e2) {
                bs = e2.Messager.Arg as List <BuildInfo>;
                if (e2.Messager.Arg is Exception)
                {
                    throw e2.Messager.Arg as Exception;
                }
            }, TimeSpan.FromSeconds(60 * 5));
            if (bs != null)
            {
                foreach (BuildInfo b in bs)
                {
                    string path = Path.Combine(OutputPath, b.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    string   fileName = Path.GetFileName(b.Path);
                    string   ext      = Path.GetExtension(b.Path);
                    Encoding encode   = Encoding.UTF8;

                    if (fileName.EndsWith(".rar") || fileName.EndsWith(".zip") || fileName.EndsWith(".dll"))
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                            fs.Write(b.Data, 0, b.Data.Length);
                            fs.Close();
                        }
                        continue;
                    }

                    byte[] data    = Deflate.Decompress(b.Data);
                    string content = Encoding.UTF8.GetString(data);

                    if (string.Compare(fileName, "web.config") == 0)
                    {
                        string place = System.Web.HttpUtility.HtmlEncode(this.ConnectionString);
                        content = content.Replace("{connectionString}", place);
                    }
                    if (fileName.EndsWith(".json"))
                    {
                        content = content.Replace("{connectionString}", this.ConnectionString);
                    }
                    if (string.Compare(ext, ".refresh") == 0)
                    {
                        encode = Encoding.Unicode;
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, encode)) {
                        sw.Write(content);
                        sw.Close();
                    }
                }
                var appsettingsPath        = Path.Combine(OutputPath, "appsettings.json");
                var appsettingsPathWebHost = Path.Combine(OutputPath, @"src\WebHost\appsettings.json");
                var htmZipPath             = Path.Combine(OutputPath, "htm.zip");
                //解压htm.zip
                if (this.IsDownloadRes && File.Exists(htmZipPath))
                {
                    try {
                        System.IO.Compression.ZipFile.ExtractToDirectory(htmZipPath, OutputPath, Encoding.UTF8, true);
                    } catch (Exception ex) {
                        var color = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"解压 htm.zip 失败:{ex.Message}");
                        Console.ForegroundColor = color;
                    }
                }
                if (this.IsMakeSolution)
                {
                    WriteLine("代码已生成完毕!使用 -S 生成完整项目,正在建立脚手架,大约需要10秒 …", ConsoleColor.DarkGreen);

                    var shellret = ShellRun(OutputPath, "gulp -v");

                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine("");
                        WriteLine(@"正在安装gulp-cli …", ConsoleColor.DarkGreen);
                        shellret = ShellRun(OutputPath, "npm install --global gulp-cli");
                        if (!string.IsNullOrEmpty(shellret.err))
                        {
                            WriteLine(shellret.err, ConsoleColor.Red);
                        }
                        if (!string.IsNullOrEmpty(shellret.warn))
                        {
                            WriteLine(shellret.warn, ConsoleColor.Yellow);
                        }
                        if (!string.IsNullOrEmpty(shellret.info))
                        {
                            WriteLine(shellret.info, ConsoleColor.DarkGray);
                        }
                    }

                    //WriteLine("");
                    //WriteLine("正在还原项目 …", ConsoleColor.DarkGreen);
                    //shellret = ShellRun(OutputPath, "dotnet1 restore");
                    //if (!string.IsNullOrEmpty(shellret.err)) WriteLine(shellret.err, ConsoleColor.Red);
                    //if (!string.IsNullOrEmpty(shellret.warn)) WriteLine(shellret.warn, ConsoleColor.Yellow);
                    //if (!string.IsNullOrEmpty(shellret.info)) WriteLine(shellret.info, ConsoleColor.DarkGray);

                    WriteLine("");
                    WriteLine(@"正在编译Module\Test …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Test"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine(@"正在编译Module\Admin …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\Module\Admin"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine("正在安装npm包 …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "npm install");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine("正在编译WebHost …", ConsoleColor.DarkGreen);
                    shellret = ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet build");
                    if (!string.IsNullOrEmpty(shellret.err))
                    {
                        WriteLine(shellret.err, ConsoleColor.Red);
                    }
                    if (!string.IsNullOrEmpty(shellret.warn))
                    {
                        WriteLine(shellret.warn, ConsoleColor.Yellow);
                    }
                    if (!string.IsNullOrEmpty(shellret.info))
                    {
                        WriteLine(shellret.info, ConsoleColor.DarkGray);
                    }

                    WriteLine("");
                    WriteLine($"脚手架建立完成。", ConsoleColor.DarkGreen);

                    //WriteLine("");
                    //Write($"项目运行依赖 ", ConsoleColor.DarkYellow);
                    //Write($"redis-server", ConsoleColor.Green);
                    //Write($",安装地址:", ConsoleColor.DarkYellow);
                    //Write("https://files.cnblogs.com/files/kellynic/Redis-x64-2.8.2402.zip", ConsoleColor.Blue);
                    //WriteLine($",或前往官方下载", ConsoleColor.DarkYellow);

                    WriteLine($"{Path.Combine(OutputPath, @"src\WebHost")} 目执行 dotnet run", ConsoleColor.DarkYellow);
                    WriteLine("");
                    //Console.WriteLine(ShellRun(Path.Combine(OutputPath, @"src\WebHost"), "dotnet run"));

                    var pro = new System.Diagnostics.Process();
                    pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "run --urls=http://0.0.0.0:5000")
                    {
                        WorkingDirectory     = Path.Combine(OutputPath, @"src\WebHost"),
                        EnvironmentVariables = { ["ASPNETCORE_ENVIRONMENT"] = "Development" }
                    };
                    pro.Start();
                    pro.WaitForExit();
                }
                //如果三个选项为false,并且 src\WebHost\appsettings.json 不存在,则在当前目录使用 appsettings.json
                if (this.IsDownloadRes == false && this.IsMakeSolution == false && this.IsMakeWebAdmin == false && File.Exists(appsettingsPathWebHost) == false)
                {
                    var appsettings = Newtonsoft.Json.JsonConvert.DeserializeObject(File.Exists(appsettingsPath) ? File.ReadAllText(appsettingsPath) : "{}") as JToken;
                    var oldtxt      = appsettings.ToString();
                    if (appsettings["ConnectionStrings"] == null)
                    {
                        appsettings["ConnectionStrings"] = new JObject();
                    }
                    if (appsettings["ConnectionStrings"][$"{this.SolutionName}_mssql"] == null)
                    {
                        appsettings["ConnectionStrings"][$"{this.SolutionName}_mssql"] = this.ConnectionString + "Pooling=true;Max Pool Size=100";
                    }
                    if (appsettings["ConnectionStrings"]["redis1"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis1"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings["ConnectionStrings"]["redis2"] == null)
                    {
                        appsettings["ConnectionStrings"]["redis2"] = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=10,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                    }
                    if (appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] == null)
                    {
                        appsettings[$"{this.SolutionName}_BLL_ITEM_CACHE"] = JToken.FromObject(new {
                            Timeout = 180
                        });
                    }
                    if (appsettings["Logging"] == null)
                    {
                        appsettings["Logging"] = new JObject();
                    }
                    if (appsettings["Logging"]["IncludeScopes"] == null)
                    {
                        appsettings["Logging"]["IncludeScopes"] = false;
                    }
                    if (appsettings["Logging"]["LogLevel"] == null)
                    {
                        appsettings["Logging"]["LogLevel"] = new JObject();
                    }
                    if (appsettings["Logging"]["LogLevel"]["Default"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Default"] = "Debug";
                    }
                    if (appsettings["Logging"]["LogLevel"]["System"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["System"] = "Information";
                    }
                    if (appsettings["Logging"]["LogLevel"]["Microsoft"] == null)
                    {
                        appsettings["Logging"]["LogLevel"]["Microsoft"] = "Information";
                    }
                    var newtxt = appsettings.ToString();
                    if (newtxt != oldtxt)
                    {
                        File.WriteAllText(appsettingsPath, newtxt, Encoding.UTF8);
                    }
                    //增加当前目录 .csproj nuguet 引用 <PackageReference Include="dng.Mssql" Version="" />
                    string csprojPath = Directory.GetFiles(OutputPath, "*.csproj").FirstOrDefault();
                    if (!string.IsNullOrEmpty(csprojPath) && File.Exists(csprojPath))
                    {
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"dng\.Mssql""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package dng.Mssql")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"CSRedisCore""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package CSRedisCore")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }
                    }
                    //向startup.cs注入代码
                    string startupPath = Path.Combine(OutputPath, "Startup.cs");
                    if (!string.IsNullOrEmpty(startupPath) && File.Exists(startupPath))
                    {
                        //web项目才需要 Caching.CSRedis
                        if (Regex.IsMatch(File.ReadAllText(csprojPath), @"Caching.CSRedis""\s+Version=""", RegexOptions.IgnoreCase) == false)
                        {
                            System.Diagnostics.Process pro = new System.Diagnostics.Process();
                            pro.StartInfo = new System.Diagnostics.ProcessStartInfo("dotnet", "add package Caching.CSRedis")
                            {
                                WorkingDirectory = OutputPath
                            };
                            pro.Start();
                            pro.WaitForExit();
                        }

                        bool isChanged   = false;
                        var  startupCode = File.ReadAllText(startupPath);
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Caching\.Distributed;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Caching.Distributed;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Logging;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Logging;\r\n" + startupCode;
                        }
                        if (Regex.IsMatch(startupCode, @"using\s+Microsoft\.Extensions\.Configuration;") == false)
                        {
                            isChanged   = true;
                            startupCode = "using Microsoft.Extensions.Configuration;\r\n" + startupCode;
                        }

                        var servicesName = "services";
                        if (startupCode.IndexOf("RedisHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;

                                var connStr1 = @"Configuration[""ConnectionStrings:redis2""]";
                                var connStr2 = @"Configuration[""ConnectionStrings:redis1""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr1 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                    connStr2 = $"127.0.0.1:6379,password=,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=20480,prefix={this.SolutionName}";
                                }

                                return(m.Groups[0].Value + $@"


			//单redis节点模式,如需开启集群负载,请将注释去掉并做相应配置
			RedisHelper.Initialization(
				csredis: new CSRedis.CSRedisClient(//null,
					//{connStr1},
					{connStr2}),
				serialize: value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
				deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
			{servicesName = m.Groups[1].Value}.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));


");
                            }, RegexOptions.Multiline);
                        }
                        if (Regex.IsMatch(startupCode, @"\s+IConfiguration(Root)?\s+Configuration(;|\s+\{)") == false)
                        {
                            startupCode = Regex.Replace(startupCode, @"[\t ]+public\s+void\s+ConfigureServices\s*\(\s*IServiceCollection\s+(\w+)[^\{]+\{", m => {
                                isChanged = true;
                                return($@"
		public IConfiguration Configuration {{ get; set; }}
{m.Groups[0].Value}

			Configuration = {servicesName = m.Groups[1].Value}.BuildServiceProvider().GetService<IConfiguration>();"            );
                            }, RegexOptions.Multiline);
                        }
                        if (startupCode.IndexOf(this.SolutionName + ".BLL.SqlHelper.Initialization") == -1)
                        {
                            startupCode = Regex.Replace(startupCode, @"([\t ]+public\s+void\s+Configure\s*\()([^\{]+)\{", m => {
                                isChanged         = true;
                                var str1          = m.Groups[1].Value;
                                var str2          = m.Groups[2].Value;
                                var loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                if (loggerFactory.Success == false)
                                {
                                    str2 = "ILoggerFactory loggerFactory, " + str2;
                                }
                                loggerFactory = Regex.Match(str2, @"\bILoggerFactory\s+(\w+)");
                                var appName   = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");
                                if (appName.Success == false)
                                {
                                    str2 = "IApplicationBuilder app, " + str2;
                                }
                                appName = Regex.Match(str2, @"\bIApplicationBuilder\s+(\w+)");

                                var connStr = $@"Configuration[""ConnectionStrings:{this.SolutionName}_mssql""]";
                                if (File.Exists(appsettingsPath) == false)
                                {
                                    connStr = $"{this.ConnectionString};Pooling=true;Maximum Pool Size=100";
                                }

                                return(str1 + str2 + $@"{{

			
			{this.SolutionName}.BLL.SqlHelper.Initialization({appName.Groups[1].Value}.ApplicationServices.GetService<IDistributedCache>(), Configuration.GetSection(""{this.SolutionName}_BLL_ITEM_CACHE""),
				{connStr}, /* 此参数可以配置【从数据库】 */ null, {loggerFactory.Groups[1].Value}.CreateLogger(""{this.SolutionName}_DAL_sqlhelper""));


");
                            }, RegexOptions.Multiline);
                        }
                        if (isChanged)
                        {
                            File.WriteAllText(startupPath, startupCode);
                        }
                    }
                }
                if (File.Exists(Path.Combine(OutputPath, "GenMs只更新db.bat")) == false)
                {
                    var batPath = Path.Combine(OutputPath, $"GenMs_{this.SolutionName}_{this.Server}_{this.Database}.bat");
                    if (File.Exists(batPath) == false)
                    {
                        if (string.IsNullOrEmpty(this.Username))
                        {
                            File.WriteAllText(batPath, $@"
GenMs {this.Server} -D {this.Database} -N {this.SolutionName}");
                        }
                        else
                        {
                            File.WriteAllText(batPath, $@"
GenMs {this.Server} -U {this.Username} -P {this.Password} -D {this.Database} -N {this.SolutionName}");
                        }
                    }
                }
            }
            this._socket.Close();
            this._socket.Dispose();
            GC.Collect();

            ConsoleColor fc = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + OutputPath + "\", please check.");
            Console.ForegroundColor = fc;
            wait.Set();
        }
Пример #47
0
 /// <summary>
 /// Creates a new logger that sends tool output to the tool task's log handler.
 /// </summary>
 public WixToolTaskLogger(Queue <string> messageQueue, ManualResetEvent messagesAvailable) : base(CultureInfo.CurrentCulture)
 {
     this.messageQueue      = messageQueue;
     this.messagesAvailable = messagesAvailable;
     this.buffer            = new StringBuilder();
 }
Пример #48
0
        public void Bus_PublishedMessage_FilterByHeader()
        {
            Person actualT1 = new Person
            {
                Id = 5
            };

            Person actualT2 = new Person
            {
                Id = 15
            };

            Person b1 = null, b2 = null, c1 = null;

            const string header = "type";

            ManualResetEvent ev1 = new ManualResetEvent(false), ev2 = new ManualResetEvent(false), ev3 = new ManualResetEvent(false);

            using (MessageBus.Core.RabbitMQBus busA = new MessageBus.Core.RabbitMQBus(), busB = new MessageBus.Core.RabbitMQBus(), busC = new MessageBus.Core.RabbitMQBus())
            {
                using (ISubscriber subscriberB1 = busB.CreateSubscriber(), subscriberB2 = busB.CreateSubscriber(), subscriberC1 = busC.CreateSubscriber())
                {
                    subscriberB1.Subscribe <Person>(p => { b1 = p; ev1.Set(); }, filter: new[] { new BusHeader {
                                                                                                     Name = header, Value = "T1"
                                                                                                 } });
                    subscriberB2.Subscribe <Person>(p => { b2 = p; ev2.Set(); }, filter: new[] { new BusHeader {
                                                                                                     Name = header, Value = "T2"
                                                                                                 } });
                    subscriberC1.Subscribe <Person>(p => { c1 = p; ev3.Set(); }, filter: new[] { new BusHeader {
                                                                                                     Name = header, Value = "T1"
                                                                                                 } });

                    subscriberB1.Open();
                    subscriberB2.Open();
                    subscriberC1.Open();

                    using (IPublisher publisher = busA.CreatePublisher())
                    {
                        BusMessage <Person> m1 = new BusMessage <Person> {
                            Data = actualT1
                        };
                        m1.Headers.Add(new BusHeader {
                            Name = header, Value = "T1"
                        });

                        publisher.Send(m1);

                        BusMessage <Person> m2 = new BusMessage <Person> {
                            Data = actualT2
                        };
                        m2.Headers.Add(new BusHeader {
                            Name = header, Value = "T2"
                        });

                        publisher.Send(m2);
                    }

                    bool wait = ev1.WaitOne(TimeSpan.FromSeconds(5)) &&
                                ev2.WaitOne(TimeSpan.FromSeconds(5)) &&
                                ev3.WaitOne(TimeSpan.FromSeconds(5));

                    wait.Should().BeTrue("Message should arrive to all subscribers");

                    b1.Should().NotBeNull();
                    b2.Should().NotBeNull();
                    c1.Should().NotBeNull();

                    b1.ShouldBeEquivalentTo(actualT1);
                    b2.ShouldBeEquivalentTo(actualT2);
                    c1.ShouldBeEquivalentTo(actualT1);
                }
            }
        }
Пример #49
0
        public void TestConsumerCanReceivesMessagesWhenConnectionLostDuringAutoAck()
        {
            using (TestAmqpPeer originalPeer = new TestAmqpPeer())
                using (TestAmqpPeer finalPeer = new TestAmqpPeer())
                {
                    ManualResetEvent consumerReady     = new ManualResetEvent(false);
                    ManualResetEvent originalConnected = new ManualResetEvent(false);
                    ManualResetEvent finalConnected    = new ManualResetEvent(false);

                    // Connect to the first peer
                    originalPeer.ExpectSaslAnonymous();
                    originalPeer.ExpectOpen();
                    originalPeer.ExpectBegin();
                    originalPeer.ExpectBegin();

                    NmsConnection connection = EstablishAnonymousConnection(originalPeer, finalPeer);

                    Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>();

                    connectionListener
                    .Setup(listener => listener.OnConnectionEstablished(It.IsAny <Uri>()))
                    .Callback(() => { originalConnected.Set(); });

                    connectionListener
                    .Setup(listener => listener.OnConnectionRestored(It.IsAny <Uri>()))
                    .Callback(() => { finalConnected.Set(); });

                    connection.AddConnectionListener(connectionListener.Object);

                    connection.Start();

                    Assert.True(originalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to original peer");

                    originalPeer.ExpectReceiverAttach();
                    originalPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);
                    originalPeer.RunAfterLastHandler(() => consumerReady.WaitOne(TimeSpan.FromSeconds(2)));
                    originalPeer.DropAfterLastMatcher();

                    // Post Failover Expectations of FinalPeer
                    finalPeer.ExpectSaslAnonymous();
                    finalPeer.ExpectOpen();
                    finalPeer.ExpectBegin();
                    finalPeer.ExpectBegin();
                    finalPeer.ExpectReceiverAttach();
                    finalPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);
                    finalPeer.ExpectDispositionThatIsAcceptedAndSettled();

                    ISession         session          = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                    IQueue           queue            = session.GetQueue("myQueue");
                    IMessageConsumer messageConsumer  = session.CreateConsumer(queue);
                    CountdownEvent   msgReceivedLatch = new CountdownEvent(2);
                    messageConsumer.Listener += message =>
                    {
                        if (msgReceivedLatch.CurrentCount == 2)
                        {
                            consumerReady.Set();
                            finalConnected.WaitOne(2000);
                        }

                        msgReceivedLatch.Signal();
                    };

                    finalPeer.WaitForAllMatchersToComplete(5000);

                    Assert.IsTrue(msgReceivedLatch.Wait(TimeSpan.FromSeconds(10)), $"Expected 2 messages, but got {2 - msgReceivedLatch.CurrentCount}");
                }
        }
Пример #50
0
 public Game()
 {
     mouse    = new Mouse();
     keyboard = new Keyboard();
     running  = new ManualResetEvent(false);
 }
Пример #51
0
        public void TestCreateConsumerAfterConnectionDrops()
        {
            using (TestAmqpPeer originalPeer = new TestAmqpPeer())
                using (TestAmqpPeer finalPeer = new TestAmqpPeer())
                {
                    ManualResetEvent originalConnected = new ManualResetEvent(false);
                    ManualResetEvent finalConnected    = new ManualResetEvent(false);

                    // Create a peer to connect to, then one to reconnect to
                    var originalUri = CreatePeerUri(originalPeer);
                    var finalUri    = CreatePeerUri(finalPeer);

                    // Connect to the first peer
                    originalPeer.ExpectSaslAnonymous();
                    originalPeer.ExpectOpen();
                    originalPeer.ExpectBegin();
                    originalPeer.ExpectBegin();
                    originalPeer.DropAfterLastMatcher();

                    NmsConnection connection = EstablishAnonymousConnection(originalPeer, finalPeer);

                    Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>();

                    connectionListener
                    .Setup(listener => listener.OnConnectionEstablished(It.Is <Uri>(uri => originalUri == uri.ToString())))
                    .Callback(() => { originalConnected.Set(); });

                    connectionListener
                    .Setup(listener => listener.OnConnectionRestored(It.Is <Uri>(uri => finalUri == uri.ToString())))
                    .Callback(() => { finalConnected.Set(); });

                    connection.AddConnectionListener(connectionListener.Object);

                    connection.Start();

                    Assert.True(originalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to original peer");

                    // Post Failover Expectations of FinalPeer
                    finalPeer.ExpectSaslAnonymous();
                    finalPeer.ExpectOpen();
                    finalPeer.ExpectBegin();
                    finalPeer.ExpectBegin();
                    finalPeer.ExpectReceiverAttach();
                    finalPeer.ExpectLinkFlow(drain: false, sendDrainFlowResponse: false, creditMatcher: credit => Assert.AreEqual(credit, 200));
                    finalPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                    finalPeer.ExpectClose();

                    ISession         session  = connection.CreateSession();
                    IQueue           queue    = session.GetQueue("myQueue");
                    IMessageConsumer consumer = session.CreateConsumer(queue);

                    Assert.IsNull(consumer.Receive(TimeSpan.FromMilliseconds(500)));

                    Assert.True(finalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to final peer");

                    consumer.Close();

                    // Shut it down
                    connection.Close();

                    finalPeer.WaitForAllMatchersToComplete(1000);
                }
        }
Пример #52
0
        void Lock(Transaction transaction)
        {
            bool taken = false;

            Monitor.Enter(this, ref taken);

            Debug.Assert(taken);

            if (OwningTransaction == null)
            {
                if (transaction == null)
                {
                    Monitor.Exit(this);
                    return;
                }
                else
                {
                    Debug.Assert(transaction.IsolationLevel == IsolationLevel.Serializable);

                    //Acquire the lock
                    OwningTransaction = transaction;
                    Monitor.Exit(this);
                    return;
                }
            }
            else //Some transaction owns the lock
            {
                //Is it the same one?
                if (OwningTransaction == transaction)
                {
                    Monitor.Exit(this);
                    return;
                }
                else //Need to lock
                {
                    ManualResetEvent manualEvent = new ManualResetEvent(false);

                    KeyValuePair <Transaction, ManualResetEvent> pair;
                    pair = new KeyValuePair <Transaction, ManualResetEvent>(transaction, manualEvent);
                    m_PendingTransactions.AddLast(pair);

                    if (transaction != null)
                    {
                        Debug.Assert(transaction.TransactionInformation.Status == TransactionStatus.Active);
                        //Since the transaction can abort or just time out while blocking,unblock it when it is completed and remove from the queue
                        transaction.TransactionCompleted += delegate
                        {
                            lock (this)
                            {
                                //Note that the pair may have already been removed if unlocked
                                m_PendingTransactions.Remove(pair);
                            }
                            lock (manualEvent)                            //To deal with race condition of the handle closed between the check and the set
                            {
                                if (manualEvent.SafeWaitHandle.IsClosed == false)
                                {
                                    manualEvent.Set();
                                }
                            }
                        };
                    }
                    Monitor.Exit(this);
                    //Block the transaction or the calling thread
                    manualEvent.WaitOne();
                    lock (manualEvent)//To deal with race condition of the other threads setting the handle
                    {
                        manualEvent.Close();
                    }
                }
            }
        }
 public FileTokenReplace(string filePath, ReplaceTokensService tokensService, ManualResetEvent done)
 {
     FilePath       = filePath;
     _tokensService = tokensService;
     _doneEvent     = done;
 }
Пример #54
0
        public void TestTempDestinationRecreatedAfterConnectionFailsOver()
        {
            using (TestAmqpPeer originalPeer = new TestAmqpPeer())
                using (TestAmqpPeer finalPeer = new TestAmqpPeer())
                {
                    ManualResetEvent originalConnected = new ManualResetEvent(false);
                    ManualResetEvent finalConnected    = new ManualResetEvent(false);

                    // Create a peer to connect to, then one to reconnect to
                    var originalUri = CreatePeerUri(originalPeer);
                    var finalUri    = CreatePeerUri(finalPeer);

                    originalPeer.ExpectSaslAnonymous();
                    originalPeer.ExpectOpen();
                    originalPeer.ExpectBegin();
                    originalPeer.ExpectBegin();
                    string dynamicAddress1 = "myTempTopicAddress";
                    originalPeer.ExpectTempTopicCreationAttach(dynamicAddress1);
                    originalPeer.DropAfterLastMatcher();

                    NmsConnection connection = EstablishAnonymousConnection(originalPeer, finalPeer);

                    Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>();

                    connectionListener
                    .Setup(listener => listener.OnConnectionEstablished(It.Is <Uri>(uri => originalUri == uri.ToString())))
                    .Callback(() => { originalConnected.Set(); });

                    connectionListener
                    .Setup(listener => listener.OnConnectionRestored(It.Is <Uri>(uri => finalUri == uri.ToString())))
                    .Callback(() => { finalConnected.Set(); });

                    connection.AddConnectionListener(connectionListener.Object);

                    connection.Start();

                    Assert.True(originalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to original peer");

                    // Post Failover Expectations of FinalPeer
                    finalPeer.ExpectSaslAnonymous();
                    finalPeer.ExpectOpen();
                    finalPeer.ExpectBegin();
                    String dynamicAddress2 = "myTempTopicAddress2";
                    finalPeer.ExpectTempTopicCreationAttach(dynamicAddress2);

                    // Session is recreated after previous temporary destinations are recreated on failover.
                    finalPeer.ExpectBegin();

                    ISession        session        = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                    ITemporaryTopic temporaryTopic = session.CreateTemporaryTopic();

                    Assert.True(finalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to final peer");

                    // Delete the temporary Topic and close the session.
                    finalPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                    finalPeer.ExpectEnd();

                    temporaryTopic.Delete();

                    session.Close();

                    // Shut it down
                    finalPeer.ExpectClose();
                    connection.Close();

                    originalPeer.WaitForAllMatchersToComplete(2000);
                    finalPeer.WaitForAllMatchersToComplete(1000);
                }
        }
Пример #55
0
        ///<summary>metodo che gestisce la connessione socket con un rilevatore</summary>
        ///<exception cref = "SnifferAppSocketException">Eccezione lanciata in caso di errore su una operazione sul socket</exception>
        public void gestioneDevice(TcpClient client)
        {
            IPEndPoint    remoteIpEndPoint = null;
            Device        device;
            NetworkStream stream = client.GetStream();

            stream.ReadTimeout  = 120000; //timeout in lettura in millis
            stream.WriteTimeout = 15000;  //timeout in scrittura in millis

            try {
                remoteIpEndPoint = client.Client.RemoteEndPoint as IPEndPoint;
            } catch (Exception e) {
                string message = "Errore nel riconoscere il socket remoto";
                Utils.logMessage(this.ToString(), Utils.LogCategory.Error, message);
                throw new SnifferAppSocketException(message, e);
            }

            //verifico che non scattino timeout sulla connessione socket
            try {
                //verifico se il dispositivo con quell'IP era già connesso (l'IP del dispositivo era contentuto già nella lstConfDevices)
                if (ConfDevice.lstConfDevices.TryGetValue(remoteIpEndPoint.Address.ToString(), out device))
                {
                    //il dispositivo era gia configurato
                    Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "RECONNECTED with device: " + remoteIpEndPoint.Address.ToString());
                }
                else
                {
                    //se non era già configurato aspetto l'evento di Configurazione dall'interfaccia grafica
                    Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "CONNECTED with device: " + remoteIpEndPoint.Address.ToString());

                    //event per gestire la sincronizzazione con il thread della GUI
                    ManualResetEvent deviceConfEvent = new ManualResetEvent(false);
                    //aggiungo il dispositivo (con il rispettivo Event) nella lista dei dispositivi non configurati
                    NoConfDevice.lstNoConfDevices.TryAdd(remoteIpEndPoint.Address.ToString(), deviceConfEvent);
                    //delegato per gestire la variazione della lista dei device da configurare
                    NoConfDevice.OnLstNoConfDevicesChanged(this, EventArgs.Empty);

                    //mi risveglio quando dalla GUI è richiesta la configurazione del dispositivo o si vuole inviare al rilevatore il segnale "IDENTIFICA"
                    bool isSignalled = false;
                    while (!isSignalled && !stopThreadElaboration)
                    {
                        isSignalled = deviceConfEvent.WaitOne(TimeSpan.FromSeconds(20));
                    }

                    //mi sono risvegliato dall'evento ma il thread deve fermarsi
                    if (stopThreadElaboration)
                    {
                        //chiudo il client TCP
                        client.Close();
                        Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Socket chiuso");
                        return;
                    }

                    do
                    {
                        //controllo se il device è stato eliminato dalla lista dei device non configurati
                        if (!NoConfDevice.lstNoConfDevices.TryGetValue(remoteIpEndPoint.Address.ToString(), out deviceConfEvent))
                        {
                            //il device è stato configurato
                            break;
                        }
                        else
                        {
                            //il device non è stato configurato e quindi il thread si è risvegliato per richiedere un "IDENTIFICA"
                            Utils.sendMessage(stream, remoteIpEndPoint, "IDENTIFICA");

                            deviceConfEvent.Reset();

                            //come su, volutare se realizzare un wrapper sull'evento
                            isSignalled = false;
                            while (!isSignalled && !stopThreadElaboration)
                            {
                                isSignalled = deviceConfEvent.WaitOne(TimeSpan.FromSeconds(20));
                            }

                            //mi sono risvegliato dall'evento ma il thread deve fermarsi
                            if (stopThreadElaboration)
                            {
                                //chiudo il client TCP
                                client.Close();
                                Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Socket chiuso");
                                return;
                            }
                        }
                    } while (true);
                }

                //incremento il numero di socket associati al device
                //non faccio il check se il device c'è nella lista perchè in questo punto del codice c'è sicuramente
                ConfDevice.lstConfDevices.TryGetValue(remoteIpEndPoint.Address.ToString(), out device);
                device.openSocket = device.openSocket + 1;
                ConfDevice.lstConfDevices.AddOrUpdate(device.ipAddress, device, (k, v) => v);
                Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Socket aperti con " + remoteIpEndPoint.Address.ToString() + ": " + device.openSocket);

                string messageReceived;
                //count per triggerare la sincronizzazione dei clock tra il server e il rilevatore
                int countSyncTimestamp = 0;

                //ciclo fin quando non viene invocato il metodo stop in attesa di messaggi da parte dei rilevatori
                while (!stopThreadElaboration)
                {
                    //se il count è a 0 eseguo la sincronizzazione
                    if (countSyncTimestamp == 0)
                    {
                        //invio il messaggio per iniziare la sincronizzazione
                        Utils.sendMessage(stream, remoteIpEndPoint, "SYNC_CLOCK");
                        messageReceived = Utils.receiveMessage(stream, remoteIpEndPoint);

                        //posso ricevere SYNC_CLOCK_START (devo sincronizzare) o SYNC_CLOCK_STOP (sincronizzazione terminata)
                        while (messageReceived == "SYNC_CLOCK_START")
                        {
                            //invio il segnale di sincronizzazione
                            Utils.syncClock(client.Client);
                            messageReceived = Utils.receiveMessage(stream, remoteIpEndPoint);
                        }
                        //resetto il count; sincronizzo i timestamp ogni 50 interazioni
                        countSyncTimestamp = 50;
                    }

                    //invio messaggio per indicare che può iniziare l'invio dei dati
                    Utils.sendMessage(stream, remoteIpEndPoint, "START_SEND");

                    //attendo il JSON dal rilevatore con i pacchetti catturati dall'ultima interazione
                    messageReceived = Utils.receiveMessage(stream, remoteIpEndPoint);

                    PacketsInfo packetsInfo = null;

                    try {
                        //deserializzazione del JSON ricevuto
                        packetsInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <PacketsInfo>(messageReceived);
                    } catch (Exception) {
                        Utils.logMessage(this.ToString(), Utils.LogCategory.Warning, "Errore nella deserializzazione del messaggio JSON. Il messaggio verrà scartato");
                    }
                    //controllo che ci siano messaggi e che ci siano almeno 2 device configurati
                    if (packetsInfo != null && packetsInfo.listPacketInfo.Count > 0 && ConfDevice.lstConfDevices.Count >= 2)
                    {
                        //salvo i dati nella tabella raw del DB
                        dbManager.saveReceivedData(packetsInfo, remoteIpEndPoint.Address);
                    }

                    Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Device: " + remoteIpEndPoint.Address.ToString() + " -- Numero pacchetti ricevuti: " + packetsInfo.listPacketInfo.Count);

                    //decremento il contatore per la sincronizzazione dei timestamp
                    countSyncTimestamp--;
                }
            } catch (SnifferAppSocketTimeoutException e) {
                Utils.logMessage(this.ToString(), Utils.LogCategory.Warning, "Device:" + remoteIpEndPoint.Address.ToString() + " -- " + e.Message);
            }

            //chiudo il client TCP
            stream.Close();
            client.Close();
            Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Socket con " + remoteIpEndPoint.Address.ToString() + " chiuso");

            //decremento il numero di socket aperti sul device
            ConfDevice.lstConfDevices.TryGetValue(remoteIpEndPoint.Address.ToString(), out device);
            device.openSocket = device.openSocket - 1;
            ConfDevice.lstConfDevices.AddOrUpdate(device.ipAddress, device, (k, v) => v);
            Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Socket aperti con " + remoteIpEndPoint.Address.ToString() + ": " + device.openSocket);

            //se il numero di socket aperti è zero devo togliere il device dalla lista dei configurati
            if (device.openSocket <= 0 && !stopThreadElaboration)
            {
                ConfDevice.lstConfDevices.TryRemove(remoteIpEndPoint.Address.ToString(), out device);
                Utils.logMessage(this.ToString(), Utils.LogCategory.Info, "Device " + remoteIpEndPoint.Address.ToString() + " eliminato dalla lista dei device configurati");
                ConfDevice.OnLstConfDevicesChanged(this, EventArgs.Empty);
            }
        }
Пример #56
0
        public void TestFailoverHandlesDropThenRejectionCloseAfterConnect()
        {
            using (TestAmqpPeer originalPeer = new TestAmqpPeer())
                using (TestAmqpPeer rejectingPeer = new TestAmqpPeer())
                    using (TestAmqpPeer finalPeer = new TestAmqpPeer())
                    {
                        ManualResetEvent originalConnected = new ManualResetEvent(false);
                        ManualResetEvent finalConnected    = new ManualResetEvent(false);

                        // Create a peer to connect to, one to fail to reconnect to, and a final one to reconnect to
                        var originalUri  = CreatePeerUri(originalPeer);
                        var rejectingUri = CreatePeerUri(rejectingPeer);
                        var finalUri     = CreatePeerUri(finalPeer);

                        Logger.Info($"Original peer is at: {originalUri}");
                        Logger.Info($"Rejecting peer is at: {rejectingUri}");
                        Logger.Info($"Final peer is at: {finalUri}");

                        // Connect to the first
                        originalPeer.ExpectSaslAnonymous();
                        originalPeer.ExpectOpen();
                        originalPeer.ExpectBegin();

                        long ird = 0;
                        long rd  = 2000;

                        NmsConnection connection = EstablishAnonymousConnection("failover.initialReconnectDelay=" + ird + "&failover.reconnectDelay=" + rd + "&failover.maxReconnectAttempts=10", originalPeer,
                                                                                rejectingPeer, finalPeer);

                        Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>();

                        connectionListener
                        .Setup(listener => listener.OnConnectionEstablished(It.Is <Uri>(uri => originalUri == uri.ToString())))
                        .Callback(() => { originalConnected.Set(); });

                        connectionListener
                        .Setup(listener => listener.OnConnectionRestored(It.Is <Uri>(uri => finalUri == uri.ToString())))
                        .Callback(() => { finalConnected.Set(); });

                        connection.AddConnectionListener(connectionListener.Object);

                        connection.Start();

                        Assert.True(originalConnected.WaitOne(TimeSpan.FromSeconds(5)), "Should connect to original peer");
                        Assert.False(finalConnected.WaitOne(TimeSpan.FromMilliseconds(100)), "Should not yet have connected to final peer");

                        // Set expectations on rejecting and final peer
                        rejectingPeer.RejectConnect(AmqpError.NOT_FOUND, "Resource could not be located");

                        finalPeer.ExpectSaslAnonymous();
                        finalPeer.ExpectOpen();
                        finalPeer.ExpectBegin();

                        // Close the original peer and wait for things to shake out.
                        originalPeer.Close(sendClose: true);

                        rejectingPeer.WaitForAllMatchersToComplete(2000);

                        Assert.True(finalConnected.WaitOne(TimeSpan.FromSeconds(10)), "Should connect to final peer");

                        finalPeer.ExpectClose();
                        connection.Close();

                        finalPeer.WaitForAllMatchersToComplete(1000);
                    }
        }
Пример #57
0
        private static bool Test(
            string kql,
            Func <IEnumerable <StockQuote>, IEnumerable <Summary> > linq,
            StockQuote[] quotes)
        {
            KqlNode node = new KqlNode();

            node.AddKqlQuery(new KqlQuery
            {
                Comment = "Blank Comment",
                Query   = kql
            });

            Console.WriteLine(kql);
            Console.WriteLine();

            var linqResult = linq(quotes)
                             .Select(a => string.Format("{0} {1} {2}", a.Time, a.Symbol, a.Result))
                             .ToArray();

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

            var obs = quotes.ToObservable()
                      .ToDynamic(e => e);

            KqlNode         kqlNode             = new KqlNode();
            List <KqlQuery> kustoQueryUserInput = new List <KqlQuery>
            {
                new KqlQuery
                {
                    Comment = "Blank Comment",
                    Query   = kql.Trim()
                }
            };

            kqlNode.AddKqlQueryList(kustoQueryUserInput, true);

            ManualResetEvent completedEvent = new ManualResetEvent(false);

            kqlNode.Subscribe(evt =>
            {
                kqlResult.Add(string.Format("{0} {1} {2}",
                                            ((DateTime)evt.Output["Time"]),
                                            evt.Output["Symbol"],
                                            evt.Output["r"]));
            },
                              () =>
            {
                completedEvent.Set();
            });

            using (obs.Subscribe(kqlNode))
            {
                completedEvent.WaitOne();
                kqlNode.OnCompleted();
            }

            Console.WriteLine("  LINQ            Rx.KQL");

            for (int i = 0; i < linqResult.Length; i++)
            {
                Console.WriteLine("{0}\t{1}", linqResult[i], kqlResult[i]);
            }

            return(linqResult.Length == kqlResult.Count);
        }
Пример #58
0
 public ManualResetSignal(bool initialState)
 {
     wrappedEvent = new ManualResetEvent(initialState);
 }
Пример #59
-1
	static void Main ()
	{
		for (int i = 0; i < 1000; ++i) {
			ProcessStartInfo psi = new ProcessStartInfo () {
				FileName = "echo",
				Arguments = "hello 1>/dev/null",
			};

			Process p = Process.Start (psi);

			ManualResetEvent mre = new ManualResetEvent (false);

			Task t = Task.Run (() => {
				mre.Set ();
				if (!p.WaitForExit (1000))
					Environment.Exit (1);
			});

			if (!mre.WaitOne (1000))
				Environment.Exit (2);
			if (!p.WaitForExit (1000))
				Environment.Exit (3);

			if (!t.Wait (1000))
				Environment.Exit (4);
		}
	}
Пример #60
-1
Файл: test.cs Проект: mono/gert
	static int Test (IPEndPoint ep)
	{
		ManualResetEvent [] evts = new ManualResetEvent [10];

		Uri uri = new Uri ("http://"+ ep.ToString ());

		for (int i = 0; i < 10; i++) {
			evts [i] = new ManualResetEvent (false);
			GetRequestStreamAsync (uri, i, evts [i]);
		}

		if (!EventWaitHandle.WaitAll (evts, 20000)) {
			Console.WriteLine ("Not all requests completed.");
			return 4;
		}

		string quit = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"quit");
		while (true) {
			if (File.Exists (quit))
				break;
			Thread.Sleep (500);
		}

		return 0;
	}