示例#1
0
        public void Dispose()
        {
#if !CONTRACTS_ONLY
            if (!_IsDisposed)
            {
#if SUPPORTS_APPDOMAIN
                AppDomain.CurrentDomain.DomainUnload       -= CurrentDomain_DomainUnload;
                AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
                AppDomain.CurrentDomain.ProcessExit        -= CurrentDomain_ProcessExit;
#endif

                _IsDisposed = true;
                _BufferTimeoutTimer?.Dispose();

                _WriteBufferedEventsSignal?.Set();
                WaitForBackgroundThreadToExit();

                (_LogWriter as IDisposable)?.Dispose();
                _WriteBufferedEventsSignal?.Dispose();

                var emptySignal = _QueueEmptySignal;
                _QueueEmptySignal = null;
                emptySignal?.Dispose();

                _LogEventPool?.Dispose();
            }
#endif
        }
		public override Task<Result> Scan (MobileBarcodeScanningOptions options)
		{
			return Task.Factory.StartNew(() => {

				try
				{
					var scanResultResetEvent = new System.Threading.ManualResetEvent(false);
					Result result = null;

					this.appController.InvokeOnMainThread(() => {
						// Free memory first and release resources
						if (viewController != null)
						{
							viewController.Dispose();
							viewController = null;
						}

						viewController = new ZxingCameraViewController(options, this);

						viewController.BarCodeEvent += (BarCodeEventArgs e) => {

							viewController.DismissViewController();

							result = e.BarcodeResult;
							scanResultResetEvent.Set();

						};

						viewController.Canceled += (sender, e) => {

							viewController.DismissViewController();

							scanResultResetEvent.Set();
						};

						appController.PresentViewController(viewController, true, () => { });

					});

					scanResultResetEvent.WaitOne();

					return result;
				}
				catch (Exception ex)
				{
					return null;
				}
			});

		}
		public void RunUpdate()
		{
			var u = Updater.Instance;
			var waitHandler = new System.Threading.ManualResetEvent(false);


			u.NoUpdatesFound += (s, e) => waitHandler.Set();
			u.Error += (s, e) => waitHandler.Set();
			u.ExternalUpdateStarted += (s, e) => waitHandler.Set();
			u.UpdateCancelled += (s, e) => waitHandler.Set();

			Updater.CheckUpdateSimple();

			waitHandler.WaitOne();
		}
        public override Task<Result> Scan(MobileBarcodeScanningOptions options)
        {
            return Task.Factory.StartNew(new Func<Result>(() =>
            {
                var scanResultResetEvent = new System.Threading.ManualResetEvent(false);

                Result result = null;

                //Navigate: /ZxingSharp.WindowsPhone;component/Scan.xaml

                ScanPage.ScanningOptions = options;
                ScanPage.ResultFoundAction = (r) => 
                {
                    result = r;
                    scanResultResetEvent.Set();
                };

                ScanPage.UseCustomOverlay = this.UseCustomOverlay;
                ScanPage.CustomOverlay = this.CustomOverlay;
                ScanPage.TopText = TopText;
                ScanPage.BottomText = BottomText;

                Dispatcher.BeginInvoke(() =>
				{
					((Microsoft.Phone.Controls.PhoneApplicationFrame)Application.Current.RootVisual).Navigate(
						new Uri("/ZXingNetMobile;component/ScanPage.xaml", UriKind.Relative));
				});

                scanResultResetEvent.WaitOne();

                return result;
            }));            
        }
        public void ConnectionManagerAddsNewServicesFromServiceDiscovery()
        {
            var manualResetEvent = new System.Threading.ManualResetEvent(false);
            var serviceUri1 = new ServiceUri() { Address = "1" };
            var serviceUri2 = new ServiceUri() { Address = "2" };
            Dictionary<ServiceUri, PerformanceStatistics> services
                = new Dictionary<ServiceUri, PerformanceStatistics>()
                {
                    {serviceUri1, new PerformanceStatistics()},
                    {serviceUri2, new PerformanceStatistics()}
                };
            var serviceDiscoveryMock = new Mock<IServiceDiscovery>(MockBehavior.Strict);
            serviceDiscoveryMock.Setup(sd => sd.GetPerformanceStatistics()).Returns(() => services).Callback(() => manualResetEvent.Set());

            var manager = new ConnectionManager(remoteService: null, listener: null,
                serviceDiscovery: serviceDiscoveryMock.Object,
                serviceDiscoveryPeriod: new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 10));

            manualResetEvent.WaitOne();
            manager.RemoteServices.Count().ShouldBe(2);
            services.Add(new ServiceUri(), new PerformanceStatistics());
            manualResetEvent.Reset();
            manualResetEvent.WaitOne();

            manager.RemoteServices.Count().ShouldBe(3);
        }
        public override Task<Result> Scan(MobileBarcodeScanningOptions options)
        {
            var rootFrame = RootFrame ?? Window.Current.Content as Frame ?? ((FrameworkElement) Window.Current.Content).GetFirstChildOfType<Frame>();
            var dispatcher = Dispatcher ?? Window.Current.Dispatcher;

            return Task.Factory.StartNew(new Func<Result>(() =>
            {
                var scanResultResetEvent = new System.Threading.ManualResetEvent(false);

                Result result = null;

                ScanPage.ScanningOptions = options;
                ScanPage.ResultFoundAction = (r) => 
                {
                    result = r;
                    scanResultResetEvent.Set();
                };

                ScanPage.UseCustomOverlay = this.UseCustomOverlay;
                ScanPage.CustomOverlay = this.CustomOverlay;
                ScanPage.TopText = TopText;
                ScanPage.BottomText = BottomText;

                dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    rootFrame.Navigate(typeof(ScanPage));
                });
                
                scanResultResetEvent.WaitOne();

                return result;
            }));            
        }
示例#7
0
        public void SendMessage_Test()
        {

            RequestMessage message = new RequestMessage()
            {

                Device = "test",
                Level = MessageLevel.High,
                Message = "test",
                Source = "unitest",
                Title = "test"
            };


            ResponseMessage resmessage = CatsAgent.SendMessage(message);

            var t1 = resmessage.Message;
            var t2 = resmessage.Result;

            Assert.IsTrue(t1.Length > 0);
            Assert.AreEqual(t2, MessageSendingResult.Succeed);


            System.Threading.ManualResetEvent hand = new System.Threading.ManualResetEvent(false);

            CatsAgent.SendMessageAsync(message, new
                 Action<ResponseMessage>((ar) => { hand.Set(); }));

            hand.WaitOne();
        }
示例#8
0
 static void Main()
 {
     System.Threading.ManualResetEvent close = new System.Threading.ManualResetEvent(false);
     SystemEvents.SessionEnding += (object sender, SessionEndingEventArgs e) =>
         close.Set();
     BaseClass();
     close.WaitOne();
 }
 private void SafeSetSignal()
 {
     try
     {
         _DataArrivedSignal?.Set();
     }
     catch (ObjectDisposedException)
     {
     }
 }
示例#10
0
		static void Parse()
		{
			var e = new System.Threading.ManualResetEvent(false);
			Console.WriteLine ("Parsing...");

			GlobalParseCache.BeginAddOrUpdatePaths (new[]{ srcDir }, false, (ea) => {
				Console.WriteLine ("Finished parsing. {0} files. {1} ms.", ea.FileAmount, ea.ParseDuration);
				e.Set();
			});

			e.WaitOne ();
		}
        public override Task<Result> Scan(MobileBarcodeScanningOptions options)
		{
			var task = Task.Factory.StartNew(() => {
			      
				var waitScanResetEvent = new System.Threading.ManualResetEvent(false);

				var scanIntent = new Intent(lifecycleListener.Context, typeof(ZxingActivity));

				scanIntent.AddFlags(ActivityFlags.NewTask);

				ZxingActivity.UseCustomOverlayView = this.UseCustomOverlay;
				ZxingActivity.CustomOverlayView = this.CustomOverlay;
				ZxingActivity.ScanningOptions = options;
                ZxingActivity.ScanContinuously = false;
				ZxingActivity.TopText = TopText;
				ZxingActivity.BottomText = BottomText;
                ZxingActivity.Orientation = Orientation;

                Result scanResult = null;

				ZxingActivity.CanceledHandler = () => 
				{
					waitScanResetEvent.Set();
				};

				ZxingActivity.ScanCompletedHandler = (Result result) => 
				{
					scanResult = result;
					waitScanResetEvent.Set();
				};

				lifecycleListener.Context.StartActivity(scanIntent);

				waitScanResetEvent.WaitOne();

				return scanResult;
			});

			return task;
		}
 private void Fatal(XplatManualResetEvent handle, Exception exception = null)
 {
     if (exception != null)
     {
         this.Exception = exception;
     }
     handle?.Set();
     this.Stop();
     if (exception != null)
     {
         this._blockingSubject.OnError(exception);
     }
 }
示例#13
0
		public async Task RunAsync ( Action act )
		{
			await Task.Run ( ( ) =>
			{
				System.Threading.ManualResetEvent evt = new System.Threading.ManualResetEvent ( false );
				m_dispatcher.BeginInvoke ( ( ) =>
				{
					act ( );
					evt.Set ( );
				} );
				evt.WaitOne ( );
			} );
		}
示例#14
0
		public override Task<Result> Scan(MobileBarcodeScanningOptions options)
		{
			Console.WriteLine("ZXING MOBILE: Scan");

			var waitScanResetEvent = new System.Threading.ManualResetEvent(false);
			var scanIntent = new Intent(this.Context, typeof(ZxingActivity));

			ZxingActivity.UseCustomView = this.UseCustomOverlay;
			ZxingActivity.CustomOverlayView = this.CustomOverlay;
			ZxingActivity.ScanningOptions = options;
			ZxingActivity.TopText = TopText;
			ZxingActivity.BottomText = BottomText;

			var task = Task.Factory.StartNew(() => {
			
				Result scanResult = null;

				ZxingActivity.OnCanceled += () => 
				{
					waitScanResetEvent.Set();
				};

				ZxingActivity.OnScanCompleted += (Result result) => 
				{
					scanResult = result;
					waitScanResetEvent.Set();
				};

				this.Context.RunOnUiThread(() => this.Context.StartActivity(scanIntent));

				waitScanResetEvent.WaitOne();

				return scanResult;
			});

			return task;
		}
        private void Fatal(XplatManualResetEvent handle, Exception exception = null)
        {
            Console.WriteLine("FATAL called: " + exception?.Message);

            if (exception != null)
            {
                this.Exception = exception;
            }
            handle?.Set();
            this.Stop();
            if (exception != null)
            {
                this._blockingSubject.OnError(exception);
            }
        }
        static void Main(string[] args)
        {
            //Load initial settings

            Logger.Logger.Get("Runner").Message("App started");

            //Logger.Logger.Get().Message("App started");
            WorkerProcess.GetInstance().Process();

            System.Threading.ManualResetEvent _quitEvent = new System.Threading.ManualResetEvent(false);
            Console.CancelKeyPress += (sender, eArgs) => {
                _quitEvent.Set(); eArgs.Cancel = true;
            };

            _quitEvent.WaitOne();
        }
示例#17
0
 public TimeCommonExt(Action <Delegate> proc, Action <Delegate> timeoutHandle)
 {
     _proc          = proc;
     _timeoutHandle = timeoutHandle;
     _procHandle    = delegate
     {
         //计算代码执行的时间
         System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
         sw.Start();
         _proc?.Invoke(null);
         sw.Stop();
         //如果执行时间小于超时时间则通知用户线程
         if (sw.ElapsedMilliseconds < _timeout)
         {
             _event?.Set();
         }
     };
 }
示例#18
0
		internal async Task<Connection> AskForConnectionAsync()
		{
			using (var closedEvent = new System.Threading.ManualResetEvent(false))
			{
				var dialog = new ConnectionDialog();
				dialog.Closed += (sender, e) =>
				{
					closedEvent.Set();
				};
				dialog.Show();

				await Task.Run(new Action(() => closedEvent.WaitOne()));

				if (dialog.Ok ?? false)
					return dialog.Connection;
				else
					return null;
			}
		}
示例#19
0
        private void BackgroundWriteEvents()
        {
            LogEvent[] buffer = new LogEvent[_BatchSize];
            PooledObject <LogEvent>[] poolObjects = new PooledObject <LogEvent> [_BatchSize];

            while (!_IsDisposed)
            {
                try
                {
                    _WriteBufferedEventsSignal?.WaitOne();
                    _WriteBufferedEventsSignal.Reset();
                }
                catch (ObjectDisposedException) { }
                catch (System.Threading.AbandonedMutexException) { }
                catch (System.InvalidOperationException) { }

                PooledObject <LogEvent> pooledLogEvent = null;
                int eventsRead = 1;
                while (eventsRead > 0)
                {
                    eventsRead = 0;
                    while (_BufferedLogEvents.TryDequeue(out pooledLogEvent))
                    {
                        poolObjects[eventsRead] = pooledLogEvent;
                        buffer[eventsRead]      = pooledLogEvent.Value;
                        eventsRead++;

                        if (eventsRead >= buffer.Length)
                        {
                            break;
                        }
                    }
                    if (eventsRead > 0)
                    {
                        WriteBatch(buffer, poolObjects, eventsRead);
                    }
                }

                _QueueEmptySignal?.Set();
            }
        }
		public bool GetIsCertificateTrusted (string uri, string certificateFingerprint)
		{
			bool value;
			
			if (!TrustedCertificates.TryGetValue (certificateFingerprint, out value)) {
				using (var handle = new System.Threading.ManualResetEvent (false)) {
					Gtk.Application.Invoke (delegate {
						value = MessageService.AskQuestion (
							"Untrusted HTTP certificate detected",
							string.Format ("Do you want to temporarily trust this certificate in order to" +
							" connect to the server at {0}?", uri),
							AlertButton.Yes, AlertButton.No) == AlertButton.Yes;
						TrustedCertificates [certificateFingerprint] = value;
						handle.Set ();
					});
					handle.WaitOne ();
				}
			}

			return value;
		}
示例#21
0
        public void ManagerFileWatcher()
        {
            // PluginManager should be able to reload plugins that exist on file when the
            // plugin's file is changed.
            System.Threading.ManualResetEvent reset = new System.Threading.ManualResetEvent(false);
            IronPlugins.PluginManager mgr = new IronPlugins.PluginManager();
            mgr.PluginReloaded += new IronPlugins.PluginManager.PluginReloadedEventHandler(
                delegate(object sender, IronPlugins.PluginReloadEventArgs args)
                {
                    reset.Set();
                }
            );
            IronPlugins.Plugin.FilePlugin filePlugin = new IronPlugins.Plugin.FilePlugin("file_manager_test.py");
            mgr.AddPlugin(filePlugin);
            // Write a new attribute to the file. This imitates someone changing a plugin file.
            using (System.IO.TextWriter writer = new System.IO.StreamWriter("file_manager_test.py"))
            {
                writer.Write("new_attribute = 82");
            }
            reset.WaitOne(); // Wait for the plugin to be reloaded
            Assert.IsTrue(filePlugin.Invoke("new_attribute") == 82); // Check if the new attribute exists

            mgr.Dispose();
        }
示例#22
0
    protected override void Main()
    {
      var endPoint = new IPEndPoint(IPAddress.Loopback, 15005);

      IObservable<int> clientQuery = Observable.Using(
        () => new TcpClient(),
        client => from _ in client.ConnectObservable(endPoint.Address, endPoint.Port)
                  let socket = client.Client
                  let message = Encoding.UTF8.GetBytes(Text.Rock + Text.Scissors + Text.Paper)
                  from __ in socket.SendUntilCompleted(message, 0, message.Length, SocketFlags.None)
                  select message.Length);

      IObservable<string> serverQuery =
        from client in ObservableTcpListener.Start(endPoint)
          .Synchronize()
          .Take(1)
          .Do(_ =>
          {
            TraceLine(Text.ServerReceivedRequest);

            PressAnyKeyToContinue();
          })
        let stream = new NetworkStream(client.Client, ownsSocket: false)
        from buffer in Observable.Using(
         () => client,
         _ => stream.ReadToEndObservable().SelectMany(b => b).ToArray())
        let message = Encoding.UTF8.GetString(buffer)
        select message;

      using (var responded = new System.Threading.ManualResetEvent(false))
      using (serverQuery.Finally(() => responded.Set()).Subscribe(ConsoleOutput(Text.Server)))
      using (clientQuery.Subscribe(ConsoleOutputFormat(Text.Client, Text.SentBytesFormat)))
      {
        responded.WaitOne();
      }
    }
    public void whenProductIsPurchasedAndItCostsLessThanInsertedMakeChange()
    {
      // Special arrangements here as we need to ensure events are complete 
      // before enforcing our assertions
      System.Threading.ManualResetEvent eventProduct = new System.Threading.ManualResetEvent(false);
      bool wasProductRaised = false;

      // Insert coins
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter);
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter);
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter);
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfDime, InsertableCoinSizes.SizeOfDime);
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfNickel, InsertableCoinSizes.SizeOfNickel);

      // Tricky, after product is dispensed, begin dispensing change, so we need to know when event happens
      this._vendingMachine.ProductSelectorButtons.OnSelectedProductChanged += delegate (object sender, ProductForSale e)
      {
        wasProductRaised = true;
        eventProduct.Set();
      };

      // This will start the events firing
      this._vendingMachine.ProductSelectorButtons.SelectedProduct = ProductForSale.Chips;

      eventProduct.WaitOne(5000, false);
      Assert.IsTrue(wasProductRaised);       // Ensures no false positive from a timeout

      // Check for our left over change
      Assert.AreEqual(1, this._vendingMachine.CoinReturn[InsertedCoin.Quarter]);
      Assert.AreEqual(1, this._vendingMachine.CoinReturn[InsertedCoin.Dime]);
      Assert.AreEqual(1, this._vendingMachine.CoinReturn[InsertedCoin.Nickel]);
    }
        public void UpdateShouldPublishWithinRefreshInterval()
        {
            var eventAggregator = new MockPriceUpdatedEventAggregator();

            using (var marketFeed = new TestableMarketFeedService(eventAggregator))
            {
                marketFeed.RefreshInterval = 500; // ms

                var callCompletedEvent = new System.Threading.ManualResetEvent(false);

                eventAggregator.MockMarketPriceUpdatedEvent.PublishCalledEvent +=
                        delegate { callCompletedEvent.Set(); };
#if SILVERLIGHT
                callCompletedEvent.WaitOne(5000); // Wait up to 5 seconds
#else
                callCompletedEvent.WaitOne(5000, true); // Wait up to 5 seconds
#endif
            }
            Assert.IsTrue(eventAggregator.MockMarketPriceUpdatedEvent.PublishCalled);
        }
示例#25
0
		private void WaitForGameState(EngineGameState target)
		{
			// Immediately returns if the engine is in the target state,
			// or if the engine has previously crashed.
			lock (_SyncRoot)
			{
				if (_IsInCrash)
				{
					return;
				}
			}
			try
			{
				CheckStateIs(target, null);
				
				// If we get here, it means that the engine is in the target state.
				return;
			}
			catch (InvalidOperationException)
			{
				// The engine is performing a concurrent operation.
				// Let's keep on going.
			}

			// Sets up a manual reset event that is set when the engine state
			// changes to the target game state.
			System.Threading.ManualResetEvent resetEvent = new System.Threading.ManualResetEvent(false);
			PropertyChangedEventHandler handler = new PropertyChangedEventHandler((o, e) =>
			{
				if (e.PropertyName == "GameState")
				{
					try
					{
						CheckStateIs(target, null);

						// The engine is not in a concurrent game operation.
						// Let's signal the event.
						resetEvent.Set();
					}
					catch (InvalidOperationException)
					{
						// The engine is performing a concurrent operation.
						// Let's wait some more.
						return;
					}
				}
			});
			PropertyChanged += handler;

			// Waits on the event.
			resetEvent.WaitOne();

			// Removes the handler.
			PropertyChanged -= handler;
		}
示例#26
0
 public void Execute()
 {
     _callback(_state);
     _manualReset?.Set();
 }
示例#27
0
        private void SendMessages(string message)
        {
            Exception ex = null;
            var waitEvent = new System.Threading.ManualResetEvent(false);

            var uri = new Library.Utility.Uri(m_username.Contains("://") ? m_username : "******" + m_username);
            var con = new agsXMPP.XmppClientConnection(uri.Host, uri.Port == -1 ? (uri.Scheme == "https" ? 5223 :5222) : uri.Port);
            if (uri.Scheme == "https")
                con.UseSSL = true;

            var resource = uri.Path ?? "";
            if (resource.StartsWith("/"))
                resource = resource.Substring(1);

            if (string.IsNullOrWhiteSpace(resource))
                resource = "Duplicati";

            agsXMPP.ObjectHandler loginDelegate = (sender) =>
            {
                try
                {
                    foreach(var recipient in m_to.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        con.Send(new agsXMPP.protocol.client.Message(recipient, agsXMPP.protocol.client.MessageType.chat, message));
                }
                catch (Exception e)
                {
                    ex = e;
                }
                finally
                {
                    waitEvent.Set();
                }
            };

            agsXMPP.ErrorHandler errorHandler = (sender, e) => {
                ex = e;
                waitEvent.Set();
            };

            agsXMPP.XmppElementHandler loginErroHandler = (sender, e) => {
                ex = new Exception(string.Format("Failed to log in: {0}", e.ToString()));
                waitEvent.Set();
            };

            con.OnLogin += loginDelegate;
            con.OnError += errorHandler;
            con.OnAuthError += loginErroHandler;
            //con.OnBinded += (sender) => {Console.WriteLine("Binded: {0}", sender);};
            //con.OnIq += (sender, iq) => {Console.WriteLine("Iq: {0}", iq);};
            //con.OnReadXml += (sender, xml) => {Console.WriteLine("ReadXml: {0}", xml);};
            //con.OnWriteXml += (sender, xml) => {Console.WriteLine("writeXml: {0}", xml);};;
            con.Open(uri.Username, string.IsNullOrWhiteSpace(m_password) ? uri.Password : m_password, resource);

            var timeout = !waitEvent.WaitOne(TimeSpan.FromSeconds(30), true);

            con.OnLogin -= loginDelegate;
            con.OnError -= errorHandler;
            con.OnAuthError -= loginErroHandler;

            try
            {
                con.Close();
            }
            catch
            {
            }

            if (ex != null)
                throw ex;
            if (timeout)
                throw new TimeoutException(Strings.SendJabberMessage.LoginTimeoutError);
        }
示例#28
0
        /// <summary>
        /// Start converting the specified track. For a track in an audio CD playlist, this
        /// is equivalent to importing the song.  Use CurrentEncoder to set the current
        /// encoder before converting
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Track ConvertTrack2(Track convertible)
        {
            return Invoke((Func<Track>)delegate
            {
                System.Threading.ManualResetEvent reset =
                    new System.Threading.ManualResetEvent(false);

                object refTrack = convertible.AsInternal;
                iTunesConvertOperationStatus status = itunes.ConvertTrack2(ref refTrack);

                status.OnConvertOperationCompleteEvent +=
                    delegate
                    {
                        // this anonymous callback delegate signals the scanner
                        // thread to continue...
                        reset.Set();
                    };

                // wait for the current conversion to complete, otherwise iTunes
                // raises an exception when concurrent conversions are requested
                reset.WaitOne();
                reset.Reset();
                reset = null;

                Track track = null;

                try
                {
                    if (status.Tracks.Count > 0)
                    {
                        track = new Track(status.Tracks[1]);
                    }
                }
                catch (NullReferenceException exc)
                {
                    // NullRefException can occur when iTunes displays the "protected" dialog.
                    // We cannot test if status.Tracks is even null because that alone will
                    // throw a COMException

                    throw new ProtectedException(
                        "Possible protection fault in Controller.ConvertTrack2", exc);
                }
                finally
                {
                    Release(status);
                }

                return track;
            });
        }
示例#29
0
 /// <summary>
 /// Signals that the producers are done and no more elements will be put into the queue
 /// </summary>
 public void SetCompleted()
 {
     m_completed = true;
     m_itemsProduced.Set();
     m_itemsConsumed.Set();
 }
示例#30
0
 public void SignalComplete()
 {
     DoneEvent.Set();
 }
示例#31
0
 public void OnError(Exception error)
 {
     this.ex = error;
     semaphore.Set();
 }
示例#32
0
        public static void TestIOCook(string[] args)
        {
            int    writecnt      = 2;
            int    readcnt       = 3;
            string curdir        = Environment.CurrentDirectory;
            string writedir      = curdir + @"\TestIOCook\write\";
            string readdir       = curdir + @"\TestIOCook\read\";
            bool   readexisting  = false;
            bool   writeexisting = false;

            for (int i = 1; i < args.Length; i++)
            {
                string arg     = args[i];
                string optname = arg;
                string optval  = "";
                int    del     = arg.IndexOf('=');
                if (del > -1)
                {
                    optname = arg.Substring(0, del);
                    optval  = arg.Substring(del + 1).ToLower();
                }
                optname = optname.ToLower();

                switch (optname)
                {
                case "writecount":
                    writecnt = Int32.Parse(optval);
                    break;

                case "readcount":
                    readcnt = Int32.Parse(optval);
                    break;

                case "writedir":
                    writedir = optval;
                    break;

                case "readdir":
                    readdir = optval;
                    break;

                case "readexisting":
                    if (optval == "1" || optval == "true")
                    {
                        readexisting = true;
                    }
                    else
                    {
                        readexisting = false;
                    }
                    break;

                case "writeexisting":
                    if (optval == "1" || optval == "true")
                    {
                        writeexisting = true;
                    }
                    else
                    {
                        writeexisting = false;
                    }
                    break;

                default:
                    Console.Error.WriteLine("Invalid argument");
                    return;
                }
            }

            if (writedir[writedir.Length - 1] != '\\')
            {
                writedir = writedir + @"\";
            }
            if (readdir[readdir.Length - 1] != '\\')
            {
                readdir = readdir + @"\";
            }

            System.Threading.Thread[] readths  = null;
            System.Threading.Thread[] writeths = null;
            Worker[] readworkers  = null;
            Worker[] writeworkers = null;
            System.Threading.ManualResetEvent evt = new System.Threading.ManualResetEvent(false);

            //Read
            if (readcnt > 0)
            {
                if (!System.IO.Directory.Exists(readdir))
                {
                    System.IO.Directory.CreateDirectory(readdir);
                }

                string[] readfns = null;
                if (readexisting)
                {
                    readfns = System.IO.Directory.GetFiles(readdir);
                    if (readfns.Length < readcnt)
                    {
                        Console.Error.WriteLine("Not enough files to read from: You have {0} files.  Need {1} files.", readfns.Length, readcnt);
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("-");
                    Console.WriteLine("Preparing files for reading...");

                    int    byteremain          = 1024 * 1024 * 1;
                    string seed                = readdir + Guid.NewGuid().ToString() + ".txt";
                    byte[] buf                 = new byte[100];
                    System.IO.FileStream fseed = new System.IO.FileStream(seed, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read);
                    while (byteremain > 0)
                    {
                        fseed.Write(buf, 0, buf.Length);
                        byteremain -= buf.Length;
                    }
                    fseed.Close();

                    readfns    = new string[readcnt];
                    readfns[0] = seed;
                    for (int i = 1; i < readcnt; i++)
                    {
                        string fn = readdir + Guid.NewGuid().ToString() + ".txt";
                        readfns[i] = fn;
                        System.IO.File.Copy(seed, fn);
                    }

                    Console.WriteLine("-");
                    Console.WriteLine("Done preparing files for reading...");
                }

                readworkers = new Worker[readcnt];
                readths     = new System.Threading.Thread[readcnt];
                Console.WriteLine("-");
                Console.WriteLine("Creating threads for reading...");
                for (int i = 0; i < readcnt; i++)
                {
                    Worker worker = new Worker();
                    worker.ID       = i;
                    worker.FilePath = readfns[i];
                    worker.Evt      = evt;
                    readworkers[i]  = worker;
                    System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(worker.ReadThreadProc));
                    readths[i] = th;
                    th.Start();
                }
                Console.WriteLine("-");
                Console.WriteLine("Done creating threads for reading...");
            }

            //Write
            if (writecnt > 0)
            {
                if (!System.IO.Directory.Exists(writedir))
                {
                    System.IO.Directory.CreateDirectory(writedir);
                }

                string[] writefns = null;
                if (writeexisting)
                {
                    writefns = System.IO.Directory.GetFiles(writedir);
                    if (writefns.Length < writecnt)
                    {
                        Console.Error.WriteLine("Not enough files to write to.  You have {0} files.  Need {1} files.", writefns.Length, writecnt);
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("-");
                    Console.WriteLine("Preparing files for writing...");
                    byte[] buf = new byte[0];
                    writefns = new string[writecnt];
                    for (int i = 0; i < writecnt; i++)
                    {
                        string fn = writedir + Guid.NewGuid().ToString() + ".txt";
                        writefns[i] = fn;
                        System.IO.File.WriteAllBytes(fn, buf);
                    }
                    Console.WriteLine("-");
                    Console.WriteLine("Done preparing files for writing...");
                }

                writeworkers = new Worker[writecnt];
                writeths     = new System.Threading.Thread[writecnt];
                Console.WriteLine("-");
                Console.WriteLine("Creating threads for writing...");
                for (int i = 0; i < writecnt; i++)
                {
                    Worker worker = new Worker();
                    worker.ID       = i;
                    worker.FilePath = writefns[i];
                    worker.Evt      = evt;
                    writeworkers[i] = worker;
                    System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(worker.WriteThreadProc));
                    writeths[i] = th;
                    th.Start();
                }
                Console.WriteLine("-");
                Console.WriteLine("Done creating threads for writing...");
            }

            evt.Set();
            Console.WriteLine("-");
            Console.WriteLine("Event set.  Waiting for all threads to complete...");
            if (readths != null)
            {
                for (int i = 0; i < readths.Length; i++)
                {
                    readths[i].Join();
                }
            }
            if (writeths != null)
            {
                for (int i = 0; i < writeths.Length; i++)
                {
                    writeths[i].Join();
                }
            }

            Console.WriteLine("-");
            Console.WriteLine("IOCook tests completed.");

            if (readworkers != null)
            {
                Console.WriteLine("-");
                Console.WriteLine("Read results:");

                int readerr = 0;
                foreach (Worker worker in readworkers)
                {
                    readerr += worker.ErrMsg.Count;
                    foreach (string msg in worker.ErrMsg)
                    {
                        Console.WriteLine(msg);
                    }
                }

                Console.WriteLine("-");
                Console.WriteLine("Total read errors: {0}", readerr);
            }

            if (writeworkers != null)
            {
                Console.WriteLine("-");
                Console.WriteLine("Write results:");

                int writeerr = 0;
                foreach (Worker worker in writeworkers)
                {
                    writeerr += worker.ErrMsg.Count;
                    foreach (string msg in worker.ErrMsg)
                    {
                        Console.WriteLine(msg);
                    }
                }

                Console.WriteLine("-");
                Console.WriteLine("Total write errors: {0}", writeerr);
            }

            int xxxx = 0;
        }
示例#33
0
 // イベント待ちを解除
 private void button2_Click(object sender, EventArgs e)
 {
     mre.Set();
 }
        /// <summary>
        /// Process message
        /// </summary>
        private void MessageProc()
        {
            try
            {
                while (true)
                {
                    _Event.WaitOne();

                    if (Closing)
                    {
                        try
                        {
                            bool close = true;

                            lock (_LockObj)
                            {
                                if (_Queue.Count > 0)
                                {
                                    close = false;
                                }
                            }

                            if (close)
                            {
                                _CloseEvent.Set();
                                return;
                            }
                        }
                        catch
                        {
                        }
                    }

                    ReceiveEventArgs msg = default(ReceiveEventArgs);

                    try
                    {
                        int queueCount = 0;

                        lock (_LockObj)
                        {
                            while (_Queue.Count > 0)
                            {
                                msg = _Queue.Dequeue();

                                if ((msg.Flag & MessageFlag.Sync) == 0)
                                {
                                    //only asyncronize message need wait
                                    queueCount++;
                                }

                                if (_OnMessageEvent != null)
                                {
                                    try
                                    {
                                        _OnMessageEvent(msg);
                                    }
                                    catch (Exception e)
                                    {
                                        if (OnErrorEvent != null)
                                        {
                                            try
                                            {
                                                OnErrorEvent(e);
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        //Exit current context, realse the processor resource for other thread
                        //This is very importent for improve the performance
                        System.Threading.Thread.Sleep(0);
                        //if (queueCount > 2)
                        //{
                        //    System.Threading.Thread.Sleep(1);
                        //}
                    }
                    catch (Exception e)
                    {
                        if (OnErrorEvent != null)
                        {
                            try
                            {
                                OnErrorEvent(e);
                            }
                            catch
                            {
                            }
                        }
                    }
                    finally
                    {
                    }
                }
            }
            catch
            {
            }
        }
示例#35
0
 private void programResumeButton_Click(object sender, RoutedEventArgs e)
 {
     cpu.Running = CPUStatus.Running;
     pauseEvent.Set();
 }
示例#36
0
 public void SetReady()
 {
     m_readyEvent.Set();
 }
示例#37
0
        public void Run(
            EasyHook.RemoteHooking.IContext context,
            String channelName,
            CaptureConfig config)
        {
            // When not using GAC there can be issues with remoting assemblies resolving correctly
            // this is a workaround that ensures that the current assembly is correctly associated
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += (sender, args) =>
            {
                return this.GetType().Assembly.FullName == args.Name ? this.GetType().Assembly : null;
            };

            // NOTE: This is running in the target process
            _interface.Message(MessageType.Information, "Injected into process Id:{0}.", EasyHook.RemoteHooking.GetCurrentProcessId());

            _runWait = new System.Threading.ManualResetEvent(false);
            _runWait.Reset();
            try
            {
                // Initialise the Hook
                if (!InitialiseDirectXHook(config))
                {
                    return;
                }
                _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler;

                // Important Note:
                // accessing the _interface from within a _clientEventProxy event handler must always 
                // be done on a different thread otherwise it will cause a deadlock

                _clientEventProxy.Disconnected += () =>
                {
                    // We can now signal the exit of the Run method
                    _runWait.Set();
                };

                // We start a thread here to periodically check if the host is still running
                // If the host process stops then we will automatically uninstall the hooks
                StartCheckHostIsAliveThread();

                // Wait until signaled for exit either when a Disconnect message from the host 
                // or if the the check is alive has failed to Ping the host.
                _runWait.WaitOne();

                // we need to tell the check host thread to exit (if it hasn't already)
                StopCheckHostIsAliveThread();

                // Dispose of the DXHook so any installed hooks are removed correctly
                DisposeDirectXHook();
            }
            catch (Exception e)
            {
                _interface.Message(MessageType.Error, "An unexpected error occured: {0}", e.ToString());
            }
            finally
            {
                try
                {
                    _interface.Message(MessageType.Information, "Disconnecting from process {0}", EasyHook.RemoteHooking.GetCurrentProcessId());
                }
                catch
                {
                }

                // Remove the client server channel (that allows client event handlers)
                System.Runtime.Remoting.Channels.ChannelServices.UnregisterChannel(_clientServerChannel);

                // Always sleep long enough for any remaining messages to complete sending
                System.Threading.Thread.Sleep(100);
            }
        }
示例#38
0
        public void TestsMultiThreading()
        {
            int MultiThreadAmount = Amount * 10;

            System.Threading.ManualResetEvent sharedResetEvent = new System.Threading.ManualResetEvent(false);

            int statLevelCountIn = 0;

            int stackLevelCountOut = 0;

            int product = ThreadCount * MultiThreadAmount;

            int enumerateCount = 0;

            //In these threads populate
            System.Threading.Thread[] enqueueThreads = new System.Threading.Thread[ThreadCount];

            System.Threading.Thread[] dequeueThreads = new System.Threading.Thread[ThreadCount];

            System.Threading.Thread[] enumerateThreads = new System.Threading.Thread[ThreadCount];

            Func <System.Threading.Thread> createEnumerateThread = () => {
                if (enumerateCount >= ThreadCount)
                {
                    enumerateCount = 0;
                }

                return(enumerateThreads[enumerateCount] = new System.Threading.Thread(() =>
                {
                    try
                    {
                        long peek = 0;

                        if (LinkedQueue.TryPeek(ref peek))
                        {
                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> TryPeek: " + peek);

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Count" + LinkedQueue.Count);
                        }
                        else if (false == LinkedQueue.IsEmpty)
                        {
                            if (LinkedQueue.TryPeek(ref peek))
                            {
                                System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> First = " + System.Threading.Thread.VolatileRead(ref LinkedQueue.First.Value));
                            }

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Last = " + System.Threading.Thread.VolatileRead(ref LinkedQueue.Last.Value));
                        }
                    }
                    catch (Exception)
                    {
                        System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + " => Exception");
                    }
                })
                {
                    Name = "enumerateThreads" + enumerateCount++,

                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Priority = System.Threading.ThreadPriority.AboveNormal
                });
            };

            for (int t = ThreadCount - 1; t >= 0; --t)
            {
                enqueueThreads[t] = new System.Threading.Thread(() =>
                {
                    int threadLocalCountIn = 0;

                    while (threadLocalCountIn < MultiThreadAmount)
                    {
                        ++LastInputOutput;

                        if (Common.Binary.IsEven(ref LastInputOutput) && LinkedQueue.TryEnqueue(ref LastInputOutput))
                        {
                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + " @ TryEnqueue => " + LastInputOutput);

                            ++threadLocalCountIn;

                            System.Threading.Interlocked.Increment(ref statLevelCountIn);

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                        else
                        {
                            LinkedQueue.Enqueue(LastInputOutput);

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + " @ Enqueue => " + LastInputOutput);

                            ++threadLocalCountIn;

                            System.Threading.Interlocked.Increment(ref statLevelCountIn);

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                    }

                    if (LinkedQueue.IsEmpty)
                    {
                        System.Console.WriteLine("enqueueThread Empty");
                    }

                    System.Console.WriteLine("enqueueThread Exit");
                })
                {
                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Priority = System.Threading.ThreadPriority.Normal,

                    Name = "enqueueThreads_" + t
                };

                dequeueThreads[t] = new System.Threading.Thread(() =>
                {
                    int threadLocalCountOut = 0;

                    while (threadLocalCountOut < MultiThreadAmount)
                    {
                        long dequeue;

                        if (LinkedQueue.TryDequeue(out dequeue))
                        {
                            ++threadLocalCountOut;

                            System.Threading.Interlocked.Increment(ref stackLevelCountOut);

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + ": " + dequeue);

                            //if(dequeue <= dequeueLast) throw new System.Exception("Unexpected value");

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                    }

                    //if (false == LinkedQueue.IsEmpty) throw new System.Exception("dequeueThread");

                    System.Console.WriteLine("dequeueThread Exit");
                })
                {
                    Priority = System.Threading.ThreadPriority.BelowNormal,

                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Name = "dequeueThreads_" + t
                };

                enumerateThreads[t] = createEnumerateThread();
            }

            System.Linq.ParallelEnumerable.ForAll(enqueueThreads.AsParallel(), t => t.Start());

            System.Linq.ParallelEnumerable.ForAll(dequeueThreads.AsParallel(), t => t.Start());

            while (stackLevelCountOut == 0 && statLevelCountIn == 0)
            {
                sharedResetEvent.WaitOne(0);
            }

            while (stackLevelCountOut < product)
            {
                sharedResetEvent.Reset();

                System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Count: " + LinkedQueue.Count + "," + "CountIn: " + statLevelCountIn + "," + "CountOut: " + stackLevelCountOut);

                (enumerateThreads.FirstOrDefault(t => t.ThreadState == System.Threading.ThreadState.Unstarted) ?? createEnumerateThread()).Start();

                sharedResetEvent.WaitOne(ThreadCount);
            }

            if (statLevelCountIn != stackLevelCountOut)
            {
                throw new System.Exception("count");
            }

            if (false == LinkedQueue.IsEmpty)
            {
                throw new System.Exception("IsEmpty");
            }

            System.Console.WriteLine("Count: " + LinkedQueue.Count);
        }
示例#39
0
 private void on_Connection_Opened(Object sender, EventArgs e)
 {
     reset_Event.Set();
     webSocket.Send("Get_Token|^|" + username + "|^|" + company_Name);
 }
示例#40
0
        public void TestsThreading()
        {
            System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);

            int countIn = 0;

            //In a thread populate
            System.Threading.Thread enqueueThread = new System.Threading.Thread(() =>
            {
                while (countIn < Amount)
                {
                    ++LastInputOutput;

                    if (LinkedQueue.TryEnqueue(ref LastInputOutput))
                    {
                        System.Console.WriteLine("enqueueThread: " + LastInputOutput);

                        ++countIn;

                        mre.Set();

                        System.Threading.Thread.Sleep(1);
                    }
                }

                if (LinkedQueue.IsEmpty)
                {
                    System.Console.WriteLine("enqueueThread Empty");
                }

                System.Console.WriteLine("enqueueThread Exit");
            });

            int countOut = 0;

            //In another thread write
            System.Threading.Thread dequeueThread = new System.Threading.Thread(() =>
            {
                while (countOut < Amount)
                {
                    long dequeue;

                    if (LinkedQueue.TryDequeue(out dequeue))
                    {
                        ++countOut;

                        System.Console.WriteLine("dequeueThread: " + dequeue);

                        mre.Set();

                        System.Threading.Thread.Sleep(2);
                    }
                }

                //if (false == LinkedQueue.IsEmpty) throw new System.Exception("dequeueThread");

                System.Console.WriteLine("dequeueThread Exit");
            });

            enqueueThread.Start();

            dequeueThread.Start();

            while (countOut == 0 && countIn == 0)
            {
                mre.WaitOne(0);
            }

            while (countOut < Amount)
            {
                mre.Reset();

                System.Console.WriteLine("Count: " + LinkedQueue.Count + "," + "CountIn: " + countIn + "," + "CountOut: " + countOut);

                new System.Threading.Thread(() =>
                {
                    try
                    {
                        System.Console.WriteLine("Enumerate Count: " + LinkedQueue.Count);

                        long peek = 0;

                        if (LinkedQueue.TryPeek(ref peek))
                        {
                            System.Console.WriteLine("Enumerate TryPeek: " + peek);
                        }

                        if (false == LinkedQueue.IsEmpty)
                        {
                            System.Console.WriteLine("Enumerate Last: " + LinkedQueue.Last.Value);

                            System.Console.WriteLine("Enumerate First: " + LinkedQueue.First.Value);

                            //Increases test time by 10 and keeps the main thread busy
                            ////foreach (long value in LinkedQueue)
                            ////{
                            ////    System.Console.WriteLine("Enumerate Value: " + value);
                            ////}
                        }
                    }
                    catch { }
                })
                {
                    Priority = System.Threading.ThreadPriority.Highest
                }.Start();

                mre.WaitOne(0);
            }

            if (countIn != countOut)
            {
                throw new System.Exception("count");
            }

            if (false == LinkedQueue.IsEmpty)
            {
                throw new System.Exception("IsEmpty");
            }

            System.Console.WriteLine("Count: " + LinkedQueue.Count);
        }
示例#41
0
 public bool PreFilterTransaction(DdeTransaction t)
 {
     _Transactions.Add(t);
     _Received.Set();
     return false;
 }
示例#42
0
        public void TestTwoWayReceive_XML_MediumRequestResponse()
        {
            inboundHandler.StartListener(null, new TimeSpan(0, 0, 60));

            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost",
                                                                                connectionUri.Uri.AbsolutePath, PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                int    bytesCountRead = 0;
                int    fileLength     = 0;
                byte[] xmlBytes       = new byte[256];

                pipeClient.Connect(10000);

                using (FileStream fs = File.OpenRead("MediumMessage.xml"))
                {
                    fileLength = (int)fs.Length;

                    while ((bytesCountRead = fs.Read(xmlBytes, 0, xmlBytes.Length)) > 0)
                    {
                        pipeClient.Write(xmlBytes, 0, bytesCountRead);
                    }
                }

                //Send the EOF bytes
                pipeClient.WriteByte(0x00);
                pipeClient.WaitForPipeDrain();

                //Now we read the message in the inbound handler
                Message       msg = null;
                IInboundReply reply;
                inboundHandler.TryReceive(new TimeSpan(0, 0, 10), out msg, out reply);

                Assert.IsNotNull(msg, "Message instance was not returned");

                byte[] msgBytes = GeneralTestHelper.GetBodyAsBytes(msg);

                Assert.AreEqual(fileLength, msgBytes.Length, "The message length is not correct");

                string requestMessageHash = GeneralTestHelper.CalculateBytesHash(msgBytes);
                string fileHash           = GeneralTestHelper.CalculateFileHash("MediumMessage.xml");

                Assert.AreEqual(fileHash,
                                requestMessageHash, "Message contents of received message is different");
                //we send the response message

                Message responseMessage = GeneralTestHelper.CreateMessageWithBase64EncodedBody(File.ReadAllBytes("MediumMessage.xml"));

                byte[] inBuffer = new byte[512];

                using (MemoryStream memStream = new MemoryStream(512))
                {
                    System.Threading.ManualResetEvent manualEvent = new System.Threading.ManualResetEvent(false);
                    //We queue up the reply so that it executes from the context of another thread.
                    System.Threading.ThreadPool.QueueUserWorkItem(cb =>
                    {
                        bool eof = false;
                        //we try to read from the pipe
                        while (!eof)
                        {
                            bytesCountRead = pipeClient.Read(inBuffer, 0, inBuffer.Length);

                            if (bytesCountRead > 0)
                            {
                                //if (inBuffer[bytesCountRead - 1] == 0x00 &&
                                //    inBuffer[bytesCountRead - 2] == 0x00)
                                if (inBuffer[bytesCountRead - 1] == 0x00)
                                {
                                    eof = true;
                                }

                                memStream.Write(inBuffer, 0, !eof ? bytesCountRead : bytesCountRead - 1);
                            }
                            else
                            {
                                eof = true;
                            }
                        }

                        manualEvent.Set();
                    }
                                                                  );

                    reply.Reply(responseMessage, new TimeSpan(0, 0, 10));
                    //We wait for the event to be signalled
                    manualEvent.WaitOne(10000);

                    string responseHash = GeneralTestHelper.CalculateBytesHash(memStream.ToArray());

                    Assert.AreEqual(fileHash, responseHash,
                                    "The received response is not correct");
                }
            }
        }
		public void CryptoRandom_ConcurrentAccess()
		{
			const int ParallelTasks = 16;
			const int PerTaskIterationCount = 20;
			const int RandomSize = 1024;

			var tasks = new System.Threading.Tasks.Task[ParallelTasks];
			byte[][] taskArrays = new byte[ParallelTasks][];

			var rng = new CryptoRandom();
			using (var sync = new System.Threading.ManualResetEvent(false))
			{
				for (int iTask = 0; iTask < ParallelTasks; iTask++)
				{
					taskArrays[iTask] = new byte[RandomSize];
					byte[] taskLocal = taskArrays[iTask];

					tasks[iTask] = System.Threading.Tasks.Task.Run(
						() =>
						{
							sync.WaitOne();

							for (int i = 0; i < PerTaskIterationCount; i++)
							{
								rng.NextBytes(taskLocal);
							}
						});
				}

				// Ready? Set() Go!
				sync.Set();
				System.Threading.Tasks.Task.WaitAll(tasks);
			}

			for (int i = 0; i < ParallelTasks; i++)
			{
				// The Real test would be to ensure independence of data, but that's difficult.
				// The other end of the spectrum is to test that they aren't all just new byte[RandomSize].
				// Middle ground is to assert that each of the chunks has neutral(ish) bit parity.
				AssertNeutralParity(taskArrays[i]);
			}
		}
示例#44
0
 public void Start()
 {
     block.Set();
     active = true;
     usage  = 0;
 }
示例#45
0
        public void ConnectionManagerRemovesServicesNotExistingInServiceDiscovery()
        {
            var manualResetEvent = new System.Threading.ManualResetEvent(false);
            var serviceUri1 = new ServiceUri()
            {
                Address = "jack",
                BindingType = BindingType.BasicHttpBinding
            };

            var serviceUri2 = new ServiceUri()
            {
                Address = "jackie",
                BindingType = BindingType.BasicHttpBinding
            };

            Dictionary<ServiceUri, PerformanceStatistics> services
                = new Dictionary<ServiceUri, PerformanceStatistics>()
                {
                    {serviceUri1, new PerformanceStatistics()},
                    {serviceUri2, new PerformanceStatistics()}
                };
            var serviceDiscoveryMock = new Mock<IServiceDiscovery>(MockBehavior.Strict);
            serviceDiscoveryMock.Setup(sd => sd.GetPerformanceStatistics()).Returns(() => services).Callback(() => manualResetEvent.Set());

            var manager = new ConnectionManager(remoteService: null, listener: null,
                serviceDiscovery: serviceDiscoveryMock.Object,
                serviceDiscoveryPeriod: new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 10));

            manualResetEvent.WaitOne();
            System.Threading.Thread.Sleep(10);
            manager.RemoteServices.Count().ShouldBe(2);
            services.Remove(serviceUri1);
            manualResetEvent.Reset();
            manualResetEvent.WaitOne();

            manager.RemoteServices.Count().ShouldBe(1);
        }
示例#46
0
        public void StandardAsynchronousTest()
        {
            // Arrange
            var mockAccumulator = new Mock <IDataAccumulator>();
            var mockIndexer     = new Mock <ILogIndexer>();
            var mockRecorder    = new Mock <ILogRecorder>();
            var config          = new LogConfiguration()
            {
                Accumulators = { mockAccumulator.Object },
                Indexers     = { mockIndexer.Object },
                Recorders    = { mockRecorder.Object },
            };
            var target              = (ILogger) new Logger(config);
            var entry               = new LogEntry();
            var mutexIndex          = new System.Threading.ManualResetEvent(false);
            var mutexIndexCompleted = new System.Threading.ManualResetEvent(false);
            var mutexRecord         = new System.Threading.ManualResetEvent(false);

            mockIndexer.Setup(idx => idx.IndexData(entry)).Returns(Task.Run(() => { mutexIndex.WaitOne(); mutexIndexCompleted.Set(); }));
            mockRecorder.Setup(idx => idx.Save(entry)).Returns(() => Task.Run(() => { mutexIndexCompleted.WaitOne(); mutexRecord.Set(); }));

            // Act
            target.Record(entry).Wait();

            // Assert
            mockAccumulator.Verify(acc => acc.AccumulateData(entry), Times.Once());
            mockIndexer.Verify(acc => acc.IndexData(entry), Times.Once());
            mockRecorder.Verify(acc => acc.Save(entry), Times.Never());
            mutexIndex.Set();
            mutexRecord.WaitOne();
            mockRecorder.Verify(acc => acc.Save(entry), Times.Once());
        }
示例#47
0
        private void SendInternal(EmailMessage message)
        {
            var mailMessage = (System.Net.Mail.MailMessage)message;

            if (message.Attachments == null ||
                message.Attachments.Count == 0)
            {
                AddDkimHeader(mailMessage);
            }

            var htmlView = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");

            htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            mailMessage.AlternateViews.Add(htmlView);

            Exception sentFailException = null;
            bool      isCanceled        = false;
            string    senderHost        = null;

            using (var sender = GlobalConfiguration.Configuration.SmtpClientFactory.Create(message.Recipients))
            {
                senderHost = sender.Host;
                using (var mailSentEvent = new System.Threading.ManualResetEvent(false))
                {
                    sender.SendCompleted += (s, arg) =>
                    {
                        if (arg.Error != null)
                        {
                            sentFailException = arg.Error;
                        }

                        if (arg.Cancelled)
                        {
                            isCanceled = true;
                        }

                        try
                        {
                            if (!mailSentEvent.SafeWaitHandle.IsClosed)
                            {
                                mailSentEvent.Set();
                            }
                        }
                        catch (Exception ex)
                        {
                            GlobalConfiguration.Configuration.Logger.Error(ex);
                        }
                    };

                    sender.SendAsync(mailMessage, message);

                    var isSent = mailSentEvent.WaitOne(30 * 1000);
                    if (!isSent)
                    {
                        sender.SendAsyncCancel();
                        isCanceled = true;
                    }
                    else
                    {
                        GlobalConfiguration.Configuration.Logger.Debug("mail for {0} sent", mailMessage.To.First().Address);
                    }
                }
            }

            var sentFailQueueName = message.SentFailQueueName;

            if (string.IsNullOrWhiteSpace(sentFailQueueName))
            {
                sentFailQueueName = GlobalConfiguration.Configuration.SentFailQueueName;
            }

            if (isCanceled)
            {
                var sentFail = new SentFail();
                sentFail.Message    = "Canceled";
                sentFail.Stack      = "Canceled";
                sentFail.MessageId  = message.MessageId;
                sentFail.Recipients = message.Recipients;
                sentFail.Subject    = message.Subject;

                Bus.Send(sentFailQueueName, sentFail);

                GlobalConfiguration.Configuration.Logger.Warn("Email '{0}' sending was canceled", message.Subject);
            }
            else if (sentFailException != null)
            {
                var sentFail = new SentFail();
                sentFail.Message    = sentFailException.Message;
                sentFail.Stack      = sentFailException.ToString();
                sentFail.MessageId  = message.MessageId;
                sentFail.Recipients = message.Recipients;
                sentFail.Subject    = message.Subject;

                GlobalConfiguration.Configuration.Logger.Error(sentFailException);

                Bus.Send(sentFailQueueName, sentFail);
            }
            else if (!message.DoNotTrack)
            {
                var sentMessage = new SentMessage();
                sentMessage.Body       = message.Body;
                sentMessage.MessageId  = message.MessageId;
                sentMessage.Recipients = message.Recipients;
                sentMessage.Subject    = message.Subject;
                sentMessage.SmtpInfo   = senderHost;
                sentMessage.Sender     = message.Sender;
                sentMessage.EntityId   = message.EntityId;
                sentMessage.EntityName = message.EntityName;

                if (message.SenderAlias != null)
                {
                    sentMessage.Sender = message.SenderAlias;
                }

                var queueName = message.SentMessageQueueName ?? GlobalConfiguration.Configuration.SentMessageQueueName;
                Bus.Send(queueName, sentMessage);
            }
        }
示例#48
0
        public void NLogTargetFlushesTelemetryClient()
        {
            var aiLogger = this.CreateTargetWithGivenInstrumentationKey();

            var       flushEvent     = new System.Threading.ManualResetEvent(false);
            Exception flushException = null;

            NLog.Common.AsyncContinuation asyncContinuation = (ex) => { flushException = ex; flushEvent.Set(); };
            aiLogger.Factory.Flush(asyncContinuation, 5000);
            Assert.IsTrue(flushEvent.WaitOne(5000));
            Assert.IsNotNull(flushException);
            Assert.AreEqual("Flush called", flushException.Message);
        }
示例#49
0
        public Form_Reminder()
        {
            InitializeComponent();

            crypting_Object = new Useful_Functions.SimpleAES();
            load_Values_From_Registry();

            reset_Event       = new System.Threading.ManualResetEvent(false);
            login_Reset_Event = new System.Threading.ManualResetEvent(false);
            db_Connect        = new DBConnect(database_Server, database_Name, database_Uid, database_Password);

            wipe_Out_The_User_Name_In_The_Registry();
            LoginWindow  login_Window      = new LoginWindow();
            bool         cancel_Pressed    = false;
            Company_Info temp_Company_Info = null;

            login_Window.button_Ok_Login.Click += new EventHandler((sender_0, e_0) =>
            {
                if (login_Window.textBox_Username_Login.Text == "")
                {
                    MessageBox.Show(login_Window, "Username can't be Empty", "Suggestion");
                    return;
                }
                else if (login_Window.textBox_Password_Login.Text == "")
                {
                    MessageBox.Show(login_Window, "Password can't be Empty");
                    return;
                }
                string encrypted_General_password = crypting_Object.EncryptToString(login_Window.textBox_Password_Login.Text);
                if (!db_Connect.Check_User_Account(login_Window.textBox_Username_Login.Text, encrypted_General_password, company_Name))
                {
                    MessageBox.Show(login_Window, "Username/Password is wrong");
                }
                else
                {
                    temp_Company_Info = db_Connect.get_Company_Info_For_This_Company_Name(company_Name);
                    username          = login_Window.textBox_Username_Login.Text;
                    put_This_User_Name_In_The_Registry(username);
                    login_Window.Hide();
                }
                login_Reset_Event.Set();
            });
            login_Window.button_Cancel_Login.Click += new EventHandler((sender_0, e_0) => {
                login_Window.Hide();
                cancel_Pressed = true;
                login_Reset_Event.Set();
            });
            login_Window.FormClosed += new FormClosedEventHandler((sender_0, e_0) => {
                login_Window.Hide();
                cancel_Pressed = true;
                login_Reset_Event.Set();
            });
            login_Window.ShowDialog();
            login_Reset_Event.WaitOne();

            if (cancel_Pressed)
            {
                Environment.Exit(0);
            }

            if (temp_Company_Info != null)
            {
                if (temp_Company_Info.message_Image_Path != "")
                {
                    Welcome_Window temp_Welcome_Window = new Welcome_Window(temp_Company_Info.message_Image_Path, temp_Company_Info.message);
                    temp_Welcome_Window.ShowDialog();
                }
            }

            Initialize_WebSocket();
            reset_Event.WaitOne();

            this.MouseClick += new MouseEventHandler(form_Reminder_MouseClick);

            clicked_My_PictureBox = null;
            picture_Boxes         = new List <My_PictureBox>();
            align_Picture_Boxes();

            this.Load   += new EventHandler(Form_Reminder_Load);
            this.Resize += new EventHandler((sender, e) => {
                if (WindowState == FormWindowState.Minimized)
                {
                    this.Hide();
                }
            });
            this.MinimizeBox = true;
            this.MaximizeBox = false;

            job_Display_Form = new Job_Display_Form();
            job_Display_Form.Hide();

            threads        = new List <System.Threading.Thread>();
            exit_Requested = false;
        }
示例#50
0
        public static int RealMain(string[] args)
        {
            //If we are on Windows, append the bundled "win-tools" programs to the search path
            //We add it last, to allow the user to override with other versions
            if (Library.Utility.Utility.IsClientWindows)
            {
                Environment.SetEnvironmentVariable("PATH",
                                                   Environment.GetEnvironmentVariable("PATH") +
                                                   System.IO.Path.PathSeparator.ToString() +
                                                   System.IO.Path.Combine(
                                                       System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
                                                       "win-tools")
                                                   );
            }

            //If this executable is invoked directly, write to console, otherwise throw exceptions
            var writeConsole = System.Reflection.Assembly.GetEntryAssembly() == System.Reflection.Assembly.GetExecutingAssembly();

            //Find commandline options here for handling special startup cases
            var commandlineOptions = Duplicati.Library.Utility.CommandLineParser.ExtractOptions(new List <string>(args));

            foreach (var s in args)
            {
                if (
                    s.Equals("help", StringComparison.OrdinalIgnoreCase) ||
                    s.Equals("/help", StringComparison.OrdinalIgnoreCase) ||
                    s.Equals("usage", StringComparison.OrdinalIgnoreCase) ||
                    s.Equals("/usage", StringComparison.OrdinalIgnoreCase))
                {
                    commandlineOptions["help"] = "";
                }
            }

            //If the commandline issues --help, just stop here
            if (commandlineOptions.ContainsKey("help"))
            {
                if (writeConsole)
                {
                    Console.WriteLine(Strings.Program.HelpDisplayDialog);

                    foreach (Library.Interface.ICommandLineArgument arg in SupportedCommands)
                    {
                        Console.WriteLine(Strings.Program.HelpDisplayFormat(arg.Name, arg.LongDescription));
                    }

                    return(0);
                }
                else
                {
                    throw new Exception("Server invoked with --help");
                }
            }

#if DEBUG
            //Log various information in the logfile
            if (!commandlineOptions.ContainsKey("log-file"))
            {
                commandlineOptions["log-file"]  = System.IO.Path.Combine(StartupPath, "Duplicati.debug.log");
                commandlineOptions["log-level"] = Duplicati.Library.Logging.LogMessageType.Profiling.ToString();
            }
#endif

            try
            {
                // Setup the log redirect
                Duplicati.Library.Logging.Log.CurrentLog = Program.LogHandler;

                if (commandlineOptions.ContainsKey("log-file"))
                {
#if DEBUG
                    // Only delete the --log-file when in DEBUG mode. Otherwise, don't delete and just append logs.
                    if (System.IO.File.Exists(commandlineOptions["log-file"]))
                    {
                        System.IO.File.Delete(commandlineOptions["log-file"]);
                    }
#endif

                    var loglevel = Duplicati.Library.Logging.LogMessageType.Error;

                    if (commandlineOptions.ContainsKey("log-level"))
                    {
                        Enum.TryParse <Duplicati.Library.Logging.LogMessageType>(commandlineOptions["log-level"], true, out loglevel);
                    }

                    Program.LogHandler.SetServerFile(commandlineOptions["log-file"], loglevel);
                }

                DataConnection = GetDatabaseConnection(commandlineOptions);

                if (!DataConnection.ApplicationSettings.FixedInvalidBackupId)
                {
                    DataConnection.FixInvalidBackupId();
                }

                try
                {
                    //This will also create DATAFOLDER if it does not exist
                    Instance = new SingleInstance(Duplicati.Library.AutoUpdater.AutoUpdateSettings.AppName, DataFolder);
                }
                catch (Exception ex)
                {
                    if (writeConsole)
                    {
                        Console.WriteLine(Strings.Program.StartupFailure(ex));
                        return(200);
                    }

                    throw new Exception(Strings.Program.StartupFailure(ex));
                }

                if (!Instance.IsFirstInstance)
                {
                    if (writeConsole)
                    {
                        Console.WriteLine(Strings.Program.AnotherInstanceDetected);
                        return(200);
                    }

                    throw new SingleInstance.MultipleInstanceException(Strings.Program.AnotherInstanceDetected);
                }

                StartOrStopUsageReporter();

                if (commandlineOptions.ContainsKey("webservice-password"))
                {
                    Program.DataConnection.ApplicationSettings.SetWebserverPassword(commandlineOptions["webservice-password"]);
                }

                Program.DataConnection.ApplicationSettings.GenerateWebserverPasswordTrayIcon();

                ApplicationExitEvent = new System.Threading.ManualResetEvent(false);

                Duplicati.Library.AutoUpdater.UpdaterManager.OnError += (Exception obj) =>
                {
                    Program.DataConnection.LogError(null, "Error in updater", obj);
                };

                UpdatePoller = new UpdatePollThread();
                DateTime lastPurge = new DateTime(0);

                System.Threading.TimerCallback purgeTempFilesCallback = (x) => {
                    try
                    {
                        if (Math.Abs((DateTime.Now - lastPurge).TotalHours) < 23)
                        {
                            return;
                        }

                        lastPurge = DateTime.Now;

                        foreach (var e in Program.DataConnection.GetTempFiles().Where((f) => f.Expires < DateTime.Now))
                        {
                            try
                            {
                                if (System.IO.File.Exists(e.Path))
                                {
                                    System.IO.File.Delete(e.Path);
                                }
                            }
                            catch (Exception ex)
                            {
                                Program.DataConnection.LogError(null, string.Format("Failed to delete temp file: {0}", e.Path), ex);
                            }

                            Program.DataConnection.DeleteTempFile(e.ID);
                        }


                        Duplicati.Library.Utility.TempFile.RemoveOldApplicationTempFiles((path, ex) => {
                            Program.DataConnection.LogError(null, string.Format("Failed to delete temp file: {0}", path), ex);
                        });

                        string pts;
                        if (!commandlineOptions.TryGetValue("log-retention", out pts))
                        {
                            pts = DEFAULT_LOG_RETENTION;
                        }

                        Program.DataConnection.PurgeLogData(Library.Utility.Timeparser.ParseTimeInterval(pts, DateTime.Now, true));
                    }
                    catch (Exception ex)
                    {
                        Program.DataConnection.LogError(null, "Failed during temp file cleanup", ex);
                    }
                };

                try
                {
                    PurgeTempFilesTimer = new System.Threading.Timer(purgeTempFilesCallback, null, TimeSpan.FromHours(1), TimeSpan.FromDays(1));
                }
                catch (ArgumentOutOfRangeException)
                {
                    //Bugfix for older Mono, slightly more resources used to avoid large values in the period field
                    PurgeTempFilesTimer = new System.Threading.Timer(purgeTempFilesCallback, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
                }

                LiveControl = new LiveControls(DataConnection.ApplicationSettings);
                LiveControl.StateChanged          += new EventHandler(LiveControl_StateChanged);
                LiveControl.ThreadPriorityChanged += new EventHandler(LiveControl_ThreadPriorityChanged);
                LiveControl.ThrottleSpeedChanged  += new EventHandler(LiveControl_ThrottleSpeedChanged);

                Program.WorkThread = new Duplicati.Library.Utility.WorkerThread <Runner.IRunnerData>((x) =>
                {
                    Runner.Run(x, true);
                }, LiveControl.State == LiveControls.LiveControlState.Paused);
                Program.Scheduler = new Scheduler(WorkThread);

                Program.WorkThread.StartingWork     += (worker, task) => { SignalNewEvent(null, null); };
                Program.WorkThread.CompletedWork    += (worker, task) => { SignalNewEvent(null, null); };
                Program.WorkThread.WorkQueueChanged += (worker) => { SignalNewEvent(null, null); };
                Program.Scheduler.NewSchedule       += new EventHandler(SignalNewEvent);
                Program.WorkThread.OnError          += (worker, task, exception) => { Program.DataConnection.LogError(task == null ? null : task.BackupID, "Error in worker", exception); };

                var lastscheduleid = LastDataUpdateID;
                Program.StatusEventNotifyer.NewEvent += (sender, e) =>
                {
                    if (lastscheduleid != LastDataUpdateID)
                    {
                        lastscheduleid = LastDataUpdateID;
                        Program.Scheduler.Reschedule();
                    }
                };

                Action <long, Exception> registerTaskResult = (id, ex) => {
                    lock (Program.MainLock) {
                        // If the new results says it crashed, we store that instead of success
                        if (Program.TaskResultCache.Count > 0 && Program.TaskResultCache.Last().Key == id)
                        {
                            if (ex != null && Program.TaskResultCache.Last().Value == null)
                            {
                                Program.TaskResultCache.RemoveAt(Program.TaskResultCache.Count - 1);
                            }
                            else
                            {
                                return;
                            }
                        }

                        Program.TaskResultCache.Add(new KeyValuePair <long, Exception>(id, ex));
                        while (Program.TaskResultCache.Count > MAX_TASK_RESULT_CACHE_SIZE)
                        {
                            Program.TaskResultCache.RemoveAt(0);
                        }
                    }
                };

                Program.WorkThread.CompletedWork += (worker, task) => { registerTaskResult(task.TaskID, null); };
                Program.WorkThread.OnError       += (worker, task, exception) => { registerTaskResult(task.TaskID, exception); };


                Program.WebServer = new WebServer.Server(commandlineOptions);

                if (Program.WebServer.Port != DataConnection.ApplicationSettings.LastWebserverPort)
                {
                    ServerPortChanged = true;
                }
                DataConnection.ApplicationSettings.LastWebserverPort = Program.WebServer.Port;

                if (Library.Utility.Utility.ParseBoolOption(commandlineOptions, "ping-pong-keepalive"))
                {
                    Program.PingPongThread = new System.Threading.Thread(PingPongMethod);
                    Program.PingPongThread.IsBackground = true;
                    Program.PingPongThread.Start();
                }

                ServerStartedEvent.Set();
                ApplicationExitEvent.WaitOne();
            }
            catch (SingleInstance.MultipleInstanceException mex)
            {
                System.Diagnostics.Trace.WriteLine(Strings.Program.SeriousError(mex.ToString()));
                if (writeConsole)
                {
                    Console.WriteLine(Strings.Program.SeriousError(mex.ToString()));
                    return(100);
                }
                else
                {
                    throw mex;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(Strings.Program.SeriousError(ex.ToString()));
                if (writeConsole)
                {
                    Console.WriteLine(Strings.Program.SeriousError(ex.ToString()));
                    return(100);
                }
                else
                {
                    throw new Exception(Strings.Program.SeriousError(ex.ToString()), ex);
                }
            }
            finally
            {
                StatusEventNotifyer.SignalNewEvent();

                if (UpdatePoller != null)
                {
                    UpdatePoller.Terminate();
                }
                if (Scheduler != null)
                {
                    Scheduler.Terminate(true);
                }
                if (WorkThread != null)
                {
                    WorkThread.Terminate(true);
                }
                if (Instance != null)
                {
                    Instance.Dispose();
                }
                if (PurgeTempFilesTimer != null)
                {
                    PurgeTempFilesTimer.Dispose();
                }

                Library.UsageReporter.Reporter.ShutDown();

                if (PingPongThread != null)
                {
                    try { PingPongThread.Abort(); }
                    catch { }
                }

                if (LogHandler != null)
                {
                    LogHandler.Dispose();
                }
            }

            if (UpdatePoller != null && UpdatePoller.IsUpdateRequested)
            {
                return(Library.AutoUpdater.UpdaterManager.MAGIC_EXIT_CODE);
            }

            return(0);
        }
示例#51
0
        public void DeviceLocator_Notifications_RaisesDeviceUnavailableWithMatchedNotificationFilter()
        {
            var publishedDevice = CreateDeviceTree();

            var server = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);
            var discoveredDevices = new List<DiscoveredSsdpDevice>();

            using (var eventSignal = new System.Threading.ManualResetEvent(false))
            {
                deviceLocator.DeviceUnavailable += (sender, args) =>
                {
                    discoveredDevices.Add(args.DiscoveredDevice);
                    eventSignal.Set();
                };
                deviceLocator.NotificationFilter = publishedDevice.Devices.First().Udn;
                deviceLocator.StartListeningForNotifications();

                server.MockReceiveBroadcast(GetMockByeByeNotification(publishedDevice));
                server.WaitForMessageToProcess(10000);
                server.MockReceiveBroadcast(GetMockByeByeNotification(publishedDevice.Devices.First().Devices.First()));
                server.WaitForMessageToProcess(10000);
                server.MockReceiveBroadcast(GetMockByeByeNotification(publishedDevice.Devices.First()));
                server.WaitForMessageToProcess(10000);
                eventSignal.WaitOne(10000);
            }

            Assert.IsTrue(discoveredDevices.Any());
            Assert.IsFalse(discoveredDevices.Any((d) => { return !d.Usn.StartsWith(publishedDevice.Devices.First().Udn); }));
        }
示例#52
0
        public void TestForSensorNodeDisconnectionWhileInUse()
        {
            Console.WriteLine("Please ensure that the sensor arduino ('sens') is connected for this test. Press ENTER when ready");
            Console.ReadLine();

            ArduinoCommsBase sensorArduino = new SensorNodeArduino(mLogger);
            TestDelegate connectDel = new TestDelegate(delegate() { sensorArduino.StartArduinoComms(); });

            Assert.DoesNotThrow(connectDel);
            Assert.IsTrue(sensorArduino.IsConnected);

            sensorArduino.ToggleHeartbeat(true, 500, 3);

            Console.WriteLine(string.Format("Arduino {0} has now been connected. The test will validate behaviour when it is unplugged. Uplug the arduino to continue", sensorArduino.ArduinoID));

            System.Threading.ManualResetEvent disconnectEvent = new System.Threading.ManualResetEvent(false);
            sensorArduino.Disconnected += delegate(ArduinoCommsBase ard)
            {
                disconnectEvent.Set();
            };

            disconnectEvent.WaitOne();
            Assert.IsFalse(sensorArduino.IsConnected);

            Assert.DoesNotThrow(delegate() { sensorArduino.StopArduinoComms(true); });
        }
    public void whenEnoughMoneyHasBeenInsertedToBuyItemThenThankTheUserAndNextReadResetsDisplay()
    {
      // Special arrangements here as we need to ensure events are complete 
      // before enforcing our assertions
      System.Threading.ManualResetEvent eventProduct = new System.Threading.ManualResetEvent(false);
      System.Threading.ManualResetEvent eventNextRead = new System.Threading.ManualResetEvent(false);
      bool wasProductRaised = false;
      bool wasReadRaised = false;

      // Insert coins
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter);
      this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter);

      // Tricky, after product is dispensed, we will set thank you message, but ALSO on next read
      // it will be a different message.   Wait for product changed handler to complete.
      this._vendingMachine.ProductSelectorButtons.OnSelectedProductChanged += delegate (object sender, ProductForSale e)
      {
        wasProductRaised = true;
        eventProduct.Set();
      };
      this._vendingMachine.Display.OnNextRead += delegate (object sender, EventArgs e)
      {
        wasReadRaised = true;
        eventNextRead.Set();
      };

      // This will start the events firing
      this._vendingMachine.ProductSelectorButtons.SelectedProduct = ProductForSale.Chips;

      eventProduct.WaitOne(5000, false);
      Assert.IsTrue(wasProductRaised);       // Ensures no false positive from a timeout
      Assert.AreEqual((decimal)0.50, this._vendingMachine.CurrentAmountInserted);         // Make sure current amount inserted remains untouched until next read

      string dummy = this._vendingMachine.Display.Message;
      eventNextRead.WaitOne(5000, false);
      Assert.IsTrue(wasReadRaised);         // Ensures no false positive from a timeout

      Assert.AreEqual((decimal)0.00, this._vendingMachine.CurrentAmountInserted);         // Make sure current amount inserted is reset after read
      Assert.AreEqual(VendingMachine.VendingMachine.ThankYouMessage, this._vendingMachine.Display.PreviousMessage);
      Assert.AreEqual(VendingMachine.VendingMachine.InsertCoinsMessage, this._vendingMachine.Display.Message);
    }
        private void deleteFiles()
        {
            var psi = new System.Diagnostics.ProcessStartInfo(Path.Combine(_myDir.FullName, "delete_files.cmd"));
            psi.EnvironmentVariables.Add("DATFILES_DIR", _dataDirectory);
            psi.EnvironmentVariables.Add("INSTALL_DIR", _installDirectory);

            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;

            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.ErrorDialog = false;

            var errorWH = new System.Threading.ManualResetEvent(false);
            var outputWH = new System.Threading.ManualResetEvent(false);

            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                p.StartInfo = psi;

                p.OutputDataReceived += (s, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWH.Set();
                        }
                        else
                        {
                            _logger.WriteLine(e.Data);
                        }
                    };

                p.ErrorDataReceived += (s, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWH.Set();
                    }
                    else
                    {
                        _logger.WriteLine(e.Data);
                    }
                };

                p.Start();

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

                p.WaitForExit();

                errorWH.WaitOne();
                outputWH.WaitOne();

                if (p.ExitCode != 0)
                {
                    throw new Exception("Batch file returned with exit code of " + p.ExitCode);
                }
            }
        }
示例#55
0
		public static int RunCommand (string path, string args, string[] env = null, StringBuilder output = null, bool suppressPrintOnErrors = false)
		{
			Exception stdin_exc = null;
			var info = new ProcessStartInfo (path, args);
			info.UseShellExecute = false;
			info.RedirectStandardInput = false;
			info.RedirectStandardOutput = true;
			info.RedirectStandardError = true;
			System.Threading.ManualResetEvent stdout_completed = new System.Threading.ManualResetEvent (false);
			System.Threading.ManualResetEvent stderr_completed = new System.Threading.ManualResetEvent (false);

			if (output == null)
				output = new StringBuilder ();

			if (env != null){
				if (env.Length % 2 != 0)
					throw new Exception ("You passed an environment key without a value");

				for (int i = 0; i < env.Length; i+= 2)
					info.EnvironmentVariables [env[i]] = env[i+1];
			}

			if (verbose > 0)
				Console.WriteLine ("{0} {1}", path, args);

			using (var p = Process.Start (info)) {

				p.OutputDataReceived += (s, e) => {
					if (e.Data != null) {
						lock (output)
							output.AppendLine (e.Data);
					} else {
						stdout_completed.Set ();
					}
				};

				p.ErrorDataReceived += (s, e) => {
					if (e.Data != null) {
						lock (output)
							output.AppendLine (e.Data);
					} else {
						stderr_completed.Set ();
					}
				};

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

				p.WaitForExit ();

				stderr_completed.WaitOne (TimeSpan.FromSeconds (1));
				stdout_completed.WaitOne (TimeSpan.FromSeconds (1));

				if (p.ExitCode != 0) {
					// note: this repeat the failing command line. However we can't avoid this since we're often
					// running commands in parallel (so the last one printed might not be the one failing)
					if (!suppressPrintOnErrors)
						Console.Error.WriteLine ("Process exited with code {0}, command:\n{1} {2}{3}", p.ExitCode, path, args, output.Length > 0 ? "\n" + output.ToString () : string.Empty);
					return p.ExitCode;
				} else if (verbose > 0 && output.Length > 0 && !suppressPrintOnErrors) {
					Console.WriteLine (output.ToString ());
				}

				if (stdin_exc != null)
					throw stdin_exc;
			}

			return 0;
		}
示例#56
0
        private void SendMessages(string message)
        {
            Exception ex        = null;
            var       waitEvent = new System.Threading.ManualResetEvent(false);

            var uri = new Library.Utility.Uri(m_username.Contains("://") ? m_username : "******" + m_username);
            var con = new agsXMPP.XmppClientConnection(uri.Host, uri.Port == -1 ? (uri.Scheme == "https" ? 5223 :5222) : uri.Port);

            if (uri.Scheme == "https")
            {
                con.UseSSL = true;
            }

            var resource = uri.Path ?? "";

            if (resource.StartsWith("/"))
            {
                resource = resource.Substring(1);
            }

            if (string.IsNullOrWhiteSpace(resource))
            {
                resource = "Duplicati";
            }

            agsXMPP.ObjectHandler loginDelegate = (sender) =>
            {
                try
                {
                    foreach (var recipient in m_to.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        con.Send(new agsXMPP.protocol.client.Message(recipient, agsXMPP.protocol.client.MessageType.chat, message));
                    }
                }
                catch (Exception e)
                {
                    ex = e;
                }
                finally
                {
                    waitEvent.Set();
                }
            };

            agsXMPP.ErrorHandler errorHandler = (sender, e) => {
                ex = e;
                waitEvent.Set();
            };

            agsXMPP.XmppElementHandler loginErroHandler = (sender, e) => {
                ex = new Exception(string.Format("Failed to log in: {0}", e.ToString()));
                waitEvent.Set();
            };

            con.OnLogin     += loginDelegate;
            con.OnError     += errorHandler;
            con.OnAuthError += loginErroHandler;
            //con.OnBinded += (sender) => {Console.WriteLine("Binded: {0}", sender);};
            //con.OnIq += (sender, iq) => {Console.WriteLine("Iq: {0}", iq);};
            //con.OnReadXml += (sender, xml) => {Console.WriteLine("ReadXml: {0}", xml);};
            //con.OnWriteXml += (sender, xml) => {Console.WriteLine("writeXml: {0}", xml);};;
            con.Open(uri.Username, string.IsNullOrWhiteSpace(m_password) ? uri.Password : m_password, resource);

            var timeout = !waitEvent.WaitOne(TimeSpan.FromSeconds(30), true);

            con.OnLogin     -= loginDelegate;
            con.OnError     -= errorHandler;
            con.OnAuthError -= loginErroHandler;

            try
            {
                con.Close();
            }
            catch
            {
            }

            if (ex != null)
            {
                throw ex;
            }
            if (timeout)
            {
                throw new TimeoutException(Strings.SendJabberMessage.LoginTimeoutError);
            }
        }
示例#57
0
        /// <summary>
        /// Start converting the specified file or folder.  The file or files will added to the
        /// main library after conversion. For a file on an audio CD, this is equivalent to
        /// importing the song.  Use CurrentEncoder to set the current encoder before converting.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Track ConvertFile2(string path)
        {
            return Invoke((Func<Track>)delegate
            {
                System.Threading.ManualResetEvent reset =
                    new System.Threading.ManualResetEvent(false);

                iTunesConvertOperationStatus status = itunes.ConvertFile2(path);

                status.OnConvertOperationCompleteEvent +=
                    delegate
                    {
                        // this anonymous callback delegate signals the scanner
                        // thread to continue...
                        reset.Set();
                    };

                // wait for the current conversion to complete, otherwise iTunes
                // raises an exception when concurrent conversions are requested
                reset.WaitOne();
                reset.Reset();
                reset = null;

                Track track = null;

                if (status.Tracks.Count > 0)
                {
                    track = new Track(status.Tracks[1]);
                }

                Release(status);

                return track;
            });
        }
示例#58
0
        public void Run(
            EasyHook.RemoteHooking.IContext context,
            String channelName,
            CaptureConfig config)
        {
            // When not using GAC there can be issues with remoting assemblies resolving correctly
            // this is a workaround that ensures that the current assembly is correctly associated
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += (sender, args) => {
                return(this.GetType().Assembly.FullName == args.Name ? this.GetType().Assembly : null);
            };

            // NOTE: This is running in the target process
            _interface.Message(MessageType.Information, "Injected into process Id:{0}.", EasyHook.RemoteHooking.GetCurrentProcessId());

            _runWait = new System.Threading.ManualResetEvent(false);
            _runWait.Reset();
            try {
                // Initialise the Hook
                if (!InitialiseDirectXHook(config))
                {
                    return;
                }
                _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler;

                // Important Note:
                // accessing the _interface from within a _clientEventProxy event handler must always
                // be done on a different thread otherwise it will cause a deadlock

                _clientEventProxy.Disconnected += () => {
                    // We can now signal the exit of the Run method
                    _runWait.Set();
                };

                // We start a thread here to periodically check if the host is still running
                // If the host process stops then we will automatically uninstall the hooks
                StartCheckHostIsAliveThread();

                // Wait until signaled for exit either when a Disconnect message from the host
                // or if the the check is alive has failed to Ping the host.
                _runWait.WaitOne();

                // we need to tell the check host thread to exit (if it hasn't already)
                StopCheckHostIsAliveThread();

                // Dispose of the DXHook so any installed hooks are removed correctly
                DisposeDirectXHook();
            }
            catch (Exception e) {
                _interface.Message(MessageType.Error, "An unexpected error occured: {0}", e.ToString());
            }
            finally {
                try {
                    _interface.Message(MessageType.Information, "Disconnecting from process {0}", EasyHook.RemoteHooking.GetCurrentProcessId());
                }
                catch {
                }

                // Remove the client server channel (that allows client event handlers)
                System.Runtime.Remoting.Channels.ChannelServices.UnregisterChannel(_clientServerChannel);

                // Always sleep long enough for any remaining messages to complete sending
                System.Threading.Thread.Sleep(100);
            }
        }
示例#59
0
        public static int RunCommand(string path, string args, string[] env = null, StringBuilder output = null, bool suppressPrintOnErrors = false)
        {
            Exception stdin_exc = null;
            var       info      = new ProcessStartInfo(path, args);

            info.UseShellExecute        = false;
            info.RedirectStandardInput  = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError  = true;
            System.Threading.ManualResetEvent stdout_completed = new System.Threading.ManualResetEvent(false);
            System.Threading.ManualResetEvent stderr_completed = new System.Threading.ManualResetEvent(false);

            if (output == null)
            {
                output = new StringBuilder();
            }

            if (env != null)
            {
                if (env.Length % 2 != 0)
                {
                    throw new Exception("You passed an environment key without a value");
                }

                for (int i = 0; i < env.Length; i += 2)
                {
                    info.EnvironmentVariables [env[i]] = env[i + 1];
                }
            }

            if (verbose > 0)
            {
                Console.WriteLine("{0} {1}", path, args);
            }

            using (var p = Process.Start(info)) {
                p.OutputDataReceived += (s, e) => {
                    if (e.Data != null)
                    {
                        lock (output)
                            output.AppendLine(e.Data);
                    }
                    else
                    {
                        stdout_completed.Set();
                    }
                };

                p.ErrorDataReceived += (s, e) => {
                    if (e.Data != null)
                    {
                        lock (output)
                            output.AppendLine(e.Data);
                    }
                    else
                    {
                        stderr_completed.Set();
                    }
                };

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

                p.WaitForExit();

                stderr_completed.WaitOne(TimeSpan.FromSeconds(1));
                stdout_completed.WaitOne(TimeSpan.FromSeconds(1));

                if (p.ExitCode != 0)
                {
                    // note: this repeat the failing command line. However we can't avoid this since we're often
                    // running commands in parallel (so the last one printed might not be the one failing)
                    if (!suppressPrintOnErrors)
                    {
                        Console.Error.WriteLine("Process exited with code {0}, command:\n{1} {2}{3}", p.ExitCode, path, args, output.Length > 0 ? "\n" + output.ToString() : string.Empty);
                    }
                    return(p.ExitCode);
                }
                else if (verbose > 0 && output.Length > 0 && !suppressPrintOnErrors)
                {
                    Console.WriteLine(output.ToString());
                }

                if (stdin_exc != null)
                {
                    throw stdin_exc;
                }
            }

            return(0);
        }
示例#60
0
 public void SetFinished()
 {
     m_finishEvent.Set();
 }