public void WorkerProcessMain(string argument, string passwordBase64)
		{
			int port = int.Parse(argument, CultureInfo.InvariantCulture);
			
			client = new TcpClient();
			client.Connect(new IPEndPoint(IPAddress.Loopback, port));
			Stream stream = client.GetStream();
			receiver = new PacketReceiver();
			sender = new PacketSender(stream);
			shutdownEvent = new ManualResetEvent(false);
			receiver.ConnectionLost += OnConnectionLost;
			receiver.PacketReceived += OnPacketReceived;
			sender.WriteFailed += OnConnectionLost;
			
			// send password
			sender.Send(Convert.FromBase64String(passwordBase64));
			
			receiver.StartReceive(stream);
			while (!shutdownEvent.WaitOne(SendKeepAliveInterval, false)) {
				Program.Log("Sending keep-alive packet");
				sender.Send(new byte[0]);
			}
			
			Program.Log("Closing client (end of WorkerProcessMain)");
			client.Close();
			shutdownEvent.Close();
		}
Example #2
0
        /// <summary>
        /// Marks message as deleted.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception>
        public void MarkForDeletion()
        {
            if(this.IsDisposed){
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if(this.IsMarkedForDeletion){
                return;
            }

            using(MarkForDeletionAsyncOP op = new MarkForDeletionAsyncOP()){
                using(ManualResetEvent wait = new ManualResetEvent(false)){
                    op.CompletedAsync += delegate(object s1,EventArgs<MarkForDeletionAsyncOP> e1){
                        wait.Set();
                    };
                    if(!this.MarkForDeletionAsync(op)){
                        wait.Set();
                    }
                    wait.WaitOne();
                    wait.Close();

                    if(op.Error != null){
                        throw op.Error;
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Wait Event State to Set 
        /// </summary>
        public void Wait() {
            if(IsDebugEnabled)
                log.Debug("Wait event state to SET...");

            var spinWait = new System.Threading.SpinWait();
            var spinCount = 0;

            while(_state == UN_SET) {
                if(spinCount++ < SpinCount) {
                    spinWait.SpinOnce();

                    if(_eventObj == null) {
                        var mre = new ManualResetEvent(_state == SET);

                        if(Interlocked.CompareExchange(ref _eventObj, mre, null) != null) {
                            // If someone set the flag before seeing the new event object, we must ensure it's been set.
                            if(_state == SET)
                                _eventObj.Set();
                                // Lost the race w/ another thread. Just use its event.
                            else
                                mre.Close();
                        }
                        if(_eventObj != null)
                            _eventObj.WaitOne();
                    }
                }
            }
        }
 public void Dispose()
 {
   WaitHandle notifyObject = new ManualResetEvent(false);
   _superLayerHideTimer.Dispose(notifyObject);
   notifyObject.WaitOne();
   notifyObject.Close();
 }
        public void EventLoggerLogErrorException()
        {
            ManualResetEvent handle = new ManualResetEvent(false);

            try
            {
                EventLogger logger = new EventLogger();
                Exception ex = new Exception();

                logger.Log += (sender, args) =>
                {
                    Assert.AreEqual(EventLoggerEventType.Error, args.EventType);
                    Assert.AreEqual(string.Empty, args.Message);
                    Assert.AreEqual(ex, args.Exception);
                    handle.Set();
                };

                logger.Error(ex);
                WaitHandle.WaitAll(new WaitHandle[] { handle });
            }
            finally
            {
                handle.Close();
            }
        }
Example #6
0
        public void Run()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            CheckToSeeIfWinServiceRunning();

            try
            {
                _log.Debug("Starting up as a console application");

                _exit = new ManualResetEvent(false);

                Console.CancelKeyPress += HandleCancelKeyPress;

                _coordinator.Start(); //user code starts

                _log.InfoFormat("[Topshelf] Running, press Control+C to exit.");

                _exit.WaitOne();
            }
            catch (Exception ex)
            {
                _log.Error("An exception occurred", ex);
            }
            finally
            {
                ShutdownCoordinator();
            }
            _exit.Close();
            _exit = null;
        }
Example #7
0
        public void Can_send_a_message_to_initiate_a_saga_and_retreive_the_saga_instance_from_the_saga_repository()
        {
            _wait = new ManualResetEvent(false);
            using (var bus = _container.Resolve<IMessageBus>())
            {
                    bus.Start();
                    bus.Publish(new TestSagaMessage1());
                    _wait.WaitOne(TimeSpan.FromSeconds(5));

                    Assert.Equal(typeof(TestSagaMessage1), _received_message.GetType());

                    // create the persister from generic instance and resolve from container:
                    var persisterType = _container.Resolve<IReflection>()
                                    .GetGenericVersionOf(typeof(ISagaPersister<>), typeof(LocalSaga));
                    Assert.NotNull(persisterType);

                    var persister = _container.Resolve(persisterType) as ISagaPersister<LocalSaga>;
                    Assert.NotNull(persister);

                    Assert.NotEqual(Guid.Empty, _saga_id);

                    var saga = persister.Find(_saga_id);
                    Assert.NotNull(saga);
            }

            _wait.Close();
        }
        public void BootstrapsBasicApplicationFileChange()
        {
            string path = ApplicationUtils.CreateValidExampleApplication();
            string filePath = Path.Combine(path, Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".dll");
            ManualResetEvent handle = new ManualResetEvent(false);

            try
            {
                using (Bootstraps bootstraps = new Bootstraps(path, null, 500))
                {
                    bootstraps.ApplicationFilesChanged += (sender, e) =>
                    {
                        Assert.AreEqual(filePath, e.FullPath);
                        handle.Set();
                    };

                    Assert.AreEqual(BootstrapsPullupResultType.Success, bootstraps.PullUp().ResultType);

                    using (File.Create(filePath))
                    {
                    }

                    WaitHandle.WaitAll(new WaitHandle[] { handle });
                }
            }
            finally
            {
                handle.Close();
            }
        }
		public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
		{
			var readyEvent = new ManualResetEvent(false);
			var mainEvent = new ManualResetEvent(false);
			var listenSocket = new Socket(
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			var serverSocket = new Socket(
					AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			Socket acceptedSocket = null;
			Exception ex = null;
			ThreadPool.QueueUserWorkItem(_ =>
			{
				SocketAsyncEventArgs asyncEventArgs;
				try {
					listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
					listenSocket.Listen(1);

					asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
					asyncEventArgs.Completed += (s, e) =>
					{
						acceptedSocket = e.AcceptSocket;
						mainEvent.Set();
					};

				} catch (Exception e) {
					ex = e;
					return;
				} finally {
					readyEvent.Set();
				}

				try {
					if (listenSocket.AcceptAsync(asyncEventArgs))
						return;
					acceptedSocket = asyncEventArgs.AcceptSocket;
					mainEvent.Set();
				} catch (Exception e) {
					ex = e;
				}
			});
			Assert.IsTrue(readyEvent.WaitOne(1500));
			if (ex != null)
				throw ex;

			var clientSocket = new Socket(
				AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			clientSocket.Connect(listenSocket.LocalEndPoint);
			clientSocket.NoDelay = true;

			Assert.IsTrue(mainEvent.WaitOne(1500));
			Assert.AreEqual(serverSocket, acceptedSocket, "x");
			mainEvent.Reset();

			if (acceptedSocket != null)
				acceptedSocket.Close();

			listenSocket.Close();
			readyEvent.Close();
			mainEvent.Close();
		}
        internal static bool UsbIOSync(SafeHandle dev, int code, Object inBuffer, int inSize, IntPtr outBuffer, int outSize, out int ret)
        {
            SafeOverlapped deviceIoOverlapped = new SafeOverlapped();
            ManualResetEvent hEvent = new ManualResetEvent(false);
            deviceIoOverlapped.ClearAndSetEvent(hEvent.SafeWaitHandle.DangerousGetHandle());
            ret = 0;

            if (!Kernel32.DeviceIoControlAsObject(dev, code, inBuffer, inSize, outBuffer, outSize, ref ret, deviceIoOverlapped.GlobalOverlapped))
            {
                int iError = Marshal.GetLastWin32Error();
                if (iError != ERROR_IO_PENDING)
                {
                    // Don't log errors for these control codes.
                    do
                    {
                        if (code == LibUsbIoCtl.GET_REG_PROPERTY) break;
                        if (code == LibUsbIoCtl.GET_CUSTOM_REG_PROPERTY) break;
                        UsbError.Error(ErrorCode.Win32Error, iError, String.Format("DeviceIoControl code {0:X8} failed:{1}", code, Kernel32.FormatSystemMessage(iError)), typeof(LibUsbDriverIO));
                    } while (false);

                    hEvent.Close();
                    return false;
                }
            }
            if (Kernel32.GetOverlappedResult(dev, deviceIoOverlapped.GlobalOverlapped, out ret, true))
            {
                hEvent.Close();
                return true;
            }
            UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetOverlappedResult failed.\nIoCtlCode:" + code, typeof(LibUsbDriverIO));
            hEvent.Close();
            return false;
        }
Example #11
0
        public void Run()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            _osCommands.CheckToSeeIfServiceRunning(_description);

            try
            {
                _log.Debug("Starting up as Azure worker role");

                _exit = new ManualResetEvent(false);

                _coordinator.Start(); //user code starts

                _log.InfoFormat("[Topshelf] Running.");

                _exit.WaitOne();
            }
            catch (Exception ex)
            {
                _log.Error("An exception occurred", ex);
            }
            finally
            {
                ShutdownCoordinator();
                _exit.Close();
            }
        }
		public void GetConfig_CanLoadConfigsFromMultipleThreads() {

			const string configKey = "MyCustomConfig";
			var configLoader = new FakeLoader(false, true);
			var configRepository = new ConfigRepository(configLoader);

			const int maxThreads = 10;

			Exception ex = null;
			IConfig config = null;

			var getConfigCompletedEvent = new ManualResetEvent(false);
			for(int i = 0; i < maxThreads; i++) {
				int remainingThreads = i;
				ThreadPool.QueueUserWorkItem(s => {
					try {
						config = configRepository.GetConfig(configKey, false);
						if(Interlocked.Decrement(ref remainingThreads) == 0) {
							getConfigCompletedEvent.Set();
						}
					} catch(Exception innerEx) {
						getConfigCompletedEvent.Set();
						ex = innerEx;
						throw;
					}
				});
			}
			getConfigCompletedEvent.WaitOne();
			getConfigCompletedEvent.Close();
			Assert.IsNotNull(config);
			Assert.IsNull(ex);
			
		}
        /// <summary>
        /// Called when the service is started.
        /// </summary>
        protected void OnStart(string[] args)
        {
            try
            {
                Thread serviceThread = new Thread(new ParameterizedThreadStart(StartAsync));

                ManualResetEvent serviceStarting = new ManualResetEvent(false);
                serviceThread.Start(serviceStarting);
                serviceStarting.WaitOne();
                serviceStarting.Close();

                foreach (ScheduleBase schedule in ScheduleManager.GetSchedules())
                {
                    schedule.Settings.LastElapsed = new DateTime(0);

                    ObjectHelper wrapper = new ObjectHelper(schedule);

                    if (wrapper.HasProperty("TimeOfDay"))
                    {
                        wrapper.SetValue("TimeOfDay", DateTime.Now.TimeOfDay);
                    }

                    if (wrapper.HasProperty("DayOfMonth"))
                    {
                        wrapper.SetValue("DayOfMonth", DayOfMonth.AllDays);
                    }
                }

            }
            catch (ThreadAbortException)
            {
                // do nothing.
            }
        }
 public void Wait()
 {
     SpinWait s = new SpinWait();
     while (m_state == 0)
     {
         if (s.Spin() >= s_spinCount)
         {
             if (m_eventObj == null)
             {
                 ManualResetEvent newEvent =
                     new ManualResetEvent(m_state == 1);
                 if (Interlocked.CompareExchange<EventWaitHandle>(
                         ref m_eventObj, newEvent, null) == null)
                 {
                     // If someone set the flag before seeing the new
                     // event obj, we must ensure it’s been set.
                     if (m_state == 1)
                         m_eventObj.Set();
                 }
                 else
                 {
                     // Lost the race w/ another thread. Just use
                     // its event.
                     newEvent.Close();
                 }
             }
             m_eventObj.WaitOne();
         }
     }
 }
Example #15
0
 /// <summary>
 /// Create a <see cref="ManualResetEvent"/> wrapper around the given native event.
 /// </summary>
 /// <param name="handle">The handle of the native event.</param>
 /// <returns>A <see cref="ManualResetEvent"/> wrapping the given <paramref name="handle"/>.</returns>
 public static ManualResetEvent GetManualResetEvent( IntPtr handle )
 {
     ManualResetEvent ev = new ManualResetEvent( false );
     ev.Close();
     GC.ReRegisterForFinalize( ev );
     ev.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle( handle, false );
     return ev;
 }
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            Thread serviceThread = new Thread(new ParameterizedThreadStart(RunProcess));

            ManualResetEvent serviceStarting = new ManualResetEvent(false);
            serviceThread.Start(serviceStarting);
            serviceStarting.WaitOne();
            serviceStarting.Close();
        }
 /// <summary>The Dispose method</summary>
 protected override void Dispose(bool disposeManagedResources)
 {
     if (disposeManagedResources)
     {
         StopProducer();
         // dispose managed resources
         _producerDone.Close();
         _haveData.Close();
         _needData.Close();
     }
 }
Example #18
0
    /// <summary>
    /// Splashフォームを消す
    /// </summary>
    public static void CloseSplash()
    {
        lock (syncObject)
        {
            if (_thread == null)
            {
                return;
            }

            if (_mainForm != null)
            {
                _mainForm.Activated -= new EventHandler(_mainForm_Activated);
            }

            //Splashが表示されるまで待機する
            if (splashShownEvent != null)
            {
                splashShownEvent.WaitOne();
                splashShownEvent.Close();
                splashShownEvent = null;
            }

            //Splashフォームを閉じる
            //Invokeが必要か調べる
            if (_form != null)
            {
                if (_form.InvokeRequired)
                {
                    _form.Invoke(new MethodInvoker(CloseLogoWindow));
                }
                else
                {
                    CloseLogoWindow();
                }
            }

            //メインフォームをアクティブにする
            if (_mainForm != null)
            {
                if (_mainForm.InvokeRequired)
                {
                    _mainForm.Invoke(new MethodInvoker(ActivateMainForm));
                }
                else
                {
                    ActivateMainForm();
                }
            }

            _form     = null;
            _thread   = null;
            _mainForm = null;
        }
    }
Example #19
0
    /// <summary>
    /// Tries to get text contents from the Windows clipboard. If the clipboard contains any other type then text, the returned result will be <c>false</c>.
    /// </summary>
    /// <returns><c>true</c> if text could be retrieved.</returns>
    public bool GetClipboardText(out string text)
    {
      string result = null;
      ManualResetEvent finishedEvent = new ManualResetEvent(false);
      Thread thread = ThreadingUtils.RunSTAThreaded(() => GetClipboardText_STA(finishedEvent, ref result));
      if (!finishedEvent.WaitOne(MAX_WAIT_MS))
        thread.Abort();

      finishedEvent.Close();
      text = result;
      return !string.IsNullOrWhiteSpace(result);
    }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing && Interlocked.CompareExchange(ref _disposeRequested, 1, 0) == 0)
     {
         if (_cancelRequested == 0)
         {
             UnregisterLinkedTokens();
             _callbacks = null;
         }
         var timer = Interlocked.Exchange(ref _timeout, null);
         timer?.Dispose();
         _handle?.Close();
     }
 }
 void Lock(Transaction transaction)
 {
     Monitor.Enter(this);
     if (OwningTransaction == null)
     {
         //Acquire the transaction lock if(transaction != null) 
         OwningTransaction = transaction;
         Monitor.Exit(this);
         return;
     }
     else //Some transaction owns the lock 
     {
         //We're done if it's the same one as the method parameter 
         if (OwningTransaction == transaction)
         {
             Monitor.Exit(this);
             return;
         } //Otherwise, need to acquire the transaction lock 
         else
         {
             ManualResetEvent manualEvent = new ManualResetEvent(false);
             KeyValuePair<Transaction, ManualResetEvent> pair = new KeyValuePair<Transaction, ManualResetEvent>(transaction, manualEvent);
             PendingTransactions.AddLast(pair);
             if (transaction != null)
             {
                 transaction.TransactionCompleted += (sender, e) =>
                 {
                     lock (this)
                     {
                         //Pair may have already been removed if unlocked 
                         PendingTransactions.Remove(pair);
                     }
                     lock (manualEvent)
                     {
                         if (!manualEvent.SafeWaitHandle.IsClosed)
                         {
                             manualEvent.Set();
                         }
                     }
                 };
             }
             Monitor.Exit(this);
             //Block the transaction or the calling thread
             manualEvent.WaitOne();
             lock (manualEvent)
                 manualEvent.Close();
         }
     }
 }
        /// <summary>
        /// Starts the video download.
        /// </summary>
        /// <exception cref="IOException">The video file could not be saved.</exception>
        /// <exception cref="WebException">An error occured while downloading the video.</exception>
        public override void Execute()
        {
            // We need a handle to keep the method synchronously
            var handle = new ManualResetEvent(false);
            var client = new WebClient();
            bool isCanceled = false;

            client.DownloadFileCompleted += (sender, args) =>
            {
                handle.Close();
                client.Dispose();

                // DownloadFileAsync passes the exception to the DownloadFileCompleted event, if one occurs
                if (args.Error != null && !args.Cancelled)
                {
                    throw args.Error;
                }

                handle.Set();
            };

            client.DownloadProgressChanged += (sender, args) =>
            {
                var progressArgs = new ProgressEventArgs(args.ProgressPercentage);

                // Backwards compatibility
                this.OnProgressChanged(progressArgs);

                if (this.DownloadProgressChanged != null)
                {
                    this.DownloadProgressChanged(this, progressArgs);

                    if (progressArgs.Cancel && !isCanceled)
                    {
                        isCanceled = true;
                        client.CancelAsync();
                    }
                }
            };

            this.OnDownloadStarted(EventArgs.Empty);

            client.DownloadFileAsync(new Uri(this.Video.DownloadUrl), this.SavePath);

            handle.WaitOne();

            this.OnDownloadFinished(EventArgs.Empty);
        }
Example #23
0
        public GuiThread(Type formType)
        {
            if (!formType.IsSubclassOf(typeof(Form)) && formType != typeof(Form))
                throw new ArgumentException("formType must be inherited from System.Windows.Forms.Form.");

            thread = new Thread(new ParameterizedThreadStart(MessagePump));
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Name = "GuiThread";
            windowCreatedEvent = new ManualResetEvent(false);

            thread.Start(formType);
            windowCreatedEvent.WaitOne();
            windowCreatedEvent.Close();
            windowCreatedEvent = null;
        }
Example #24
0
 private void button1_Click(object sender, EventArgs e)
 {
     _prefix = textBox1.Text;
     _actionReady = new ManualResetEvent(false);
     _actionReady.Reset();
     using (Utils.FrameworkDataUpdater updater = new Utils.FrameworkDataUpdater(_core))
     {
         Thread thrd = new Thread(new ThreadStart(this.assignRegionsThreadMethod));
         thrd.Start();
         while (!_actionReady.WaitOne(100))
         {
             System.Windows.Forms.Application.DoEvents();
         }
         thrd.Join();
     }
     _actionReady.Close();
     Close();
 }
 internal override void Open()
 {
     Debug.Print("ListenerAdapter[" + ProtocolName + "]::Open()");
     if (!isOpen)
     {
         lock (ThisLock)
         {
             if (!isOpen)
             {
                 initCompleted = new ManualResetEvent(false);
                 base.Open();
                 initCompleted.WaitOne();
                 initCompleted.Close();
                 initCompleted = null;
                 isOpen = true;
             }
         }
     }
 }
Example #26
0
		public SimulatorBase(PosCommon serviceObject)
		{
			HandleCreated += new EventHandler(SimulatorBase_HandleCreated);
			wr = new WeakReference(serviceObject);

			WindowVisible = new ManualResetEvent(false);
			
			UIThread = new Thread(new ThreadStart(UIThreadMethod));
            UIThread.IsBackground = true;
			UIThread.Start();
			
			WindowVisible.WaitOne();
			WindowVisible.Close();
			WindowVisible = null;

			closed = false;
			stateTimer.Tick +=new EventHandler(stateTimer_Tick);
			stateTimer.Interval = 200;
			stateTimer.Start();
		}
        /// <summary>
        /// Starts the video download.
        /// </summary>
        public override void Execute()
        {
            // We need a handle to keep the method synchronously
            var handle = new ManualResetEvent(false);

            var client = new WebClient();

            client.DownloadFileCompleted += (sender, args) => handle.Set();
            client.DownloadProgressChanged += (sender, args) =>
                this.OnProgressChanged(new ProgressEventArgs(args.ProgressPercentage));

            this.OnDownloadStarted(EventArgs.Empty);

            client.DownloadFileAsync(new Uri(this.Video.DownloadUrl), this.SavePath);

            handle.WaitOne();
            handle.Close();

            this.OnDownloadFinished(EventArgs.Empty);
        }
Example #28
0
        private static void BuildGridForm()
        {
            // Create an event used by the grid form that's being created to signal back to this thread that creation is complete
            ManualResetEvent gridFormIsReadyEvent = new ManualResetEvent(false);

            Thread t = new Thread(
                () =>
                    {
                        _gridForm = new GridForm(gridFormIsReadyEvent);

                        // TODO: When running from within a WinForms app (WPF?), this call's likely to cause issues. Detect and take evasive action.
                        Application.Run(_gridForm);
                    });

            t.SetApartmentState(ApartmentState.STA);

            t.Start();

            // Wait for the grid form to be created.
            gridFormIsReadyEvent.WaitOne();
            gridFormIsReadyEvent.Close();
        }
Example #29
0
        /// <summary>
        /// Starts listening, accepting and reading from the clients.
        /// </summary>
        public void StartListening()
        {
            if (_isListening)
                return;

            Logger.Info("TcpServer is starting...");

            _clientAcceptanceEvent = new ManualResetEvent(false);
            _cancellationTokenSource = new CancellationTokenSource();

            var token = _cancellationTokenSource.Token;
            token.Register(() =>
            {
                _isListening = false;
                _listenerSocket.Close();
                _clientAcceptanceEvent.Close();
            });

            _listenerSocket.Listen(MaxPendingConnections);

            new Task(() =>
            {
                while (true)
                {
                    try
                    {
                        _clientAcceptanceEvent.Reset();
                        _listenerSocket.BeginAccept(AcceptCallback, _listenerSocket);
                        _clientAcceptanceEvent.WaitOne();
                    }
                    catch (Exception)
                    {
                        // *crickets*
                    }
                }
            }, token).Start();

            _isListening = true;
        }
Example #30
0
        /// <summary>
        /// Starts the video download.
        /// </summary>
        /// <exception cref="IOException">The video file could not be saved.</exception>
        /// <exception cref="WebException">An error occured while downloading the video.</exception>
        public override void Execute()
        {
            // We need a handle to keep the method synchronously
            var handle = new ManualResetEvent(false);

            var client = new WebClient();

            client.DownloadFileCompleted += (sender, args) =>
            {
                // DownloadFileAsync passes the exception to the DownloadFileCompleted event, if one occurs
                if (args.Error != null)
                {
                    throw args.Error;
                }

                handle.Set();
            };

            client.DownloadProgressChanged += (sender, args) =>
                this.OnProgressChanged(new ProgressEventArgs(args.ProgressPercentage));

            this.OnDownloadStarted(EventArgs.Empty);

            try
            {
                client.DownloadFileAsync(new Uri(this.Video.DownloadUrl), this.SavePath);

                handle.WaitOne();
            }

            finally
            {
                handle.Close();
            }

            this.OnDownloadFinished(EventArgs.Empty);
        }
Example #31
0
        /// <summary>
        /// Starts the video download.
        /// </summary>
        public override void Execute()
        {
            // We need a handle to keep the method synchronously
            var handle = new ManualResetEvent(false);

            var client = new WebClient();

            client.DownloadFileCompleted += (sender, args) => handle.Set();
            client.DownloadProgressChanged += (sender, args) =>
            {
                double progress = (args.BytesReceived * 1.0 / args.TotalBytesToReceive) * 100;

                this.OnProgressChanged(new ProgressEventArgs(progress));
            };

            this.OnDownloadStarted(EventArgs.Empty);

            client.DownloadFileAsync(new Uri(this.Video.DownloadUrl), this.SavePath);

            handle.WaitOne();
            handle.Close();

            this.OnDownloadFinished(EventArgs.Empty);
        }
        public void EventLoggerLogDebug()
        {
            ManualResetEvent handle = new ManualResetEvent(false);

            try
            {
                EventLogger logger = new EventLogger();

                logger.Log += (sender, args) =>
                {
                    Assert.AreEqual(EventLoggerEventType.Debug, args.EventType);
                    Assert.AreEqual("Debug", args.Message);
                    Assert.IsNull(args.Exception);
                    handle.Set();
                };

                logger.Debug("Debug");
                WaitHandle.WaitAll(new WaitHandle[] { handle });
            }
            finally
            {
                handle.Close();
            }
        }
    IEnumerator RestoreUpdate()
    {
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            Log.LogInfo("connect time out");
            MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
            yield break;
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
        {
            //3G Tip
        }
        //Restore DownLoad From Progress.xml
        System.Net.Sockets.Socket         sClient     = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP);
        System.Net.EndPoint               server      = new System.Net.IPEndPoint(Dns.GetHostAddresses(GameData.Domain)[0], System.Convert.ToInt32(strPort));
        System.Threading.ManualResetEvent connectDone = new System.Threading.ManualResetEvent(false);
        try
        {
            connectDone.Reset();
            sClient.BeginConnect(server, delegate(IAsyncResult ar) {
                try
                {
                    System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;
                    client.EndConnect(ar);
                }
                catch (System.Exception e)
                {
                    Log.LogInfo(e.Message + "|" + e.StackTrace);
                }
                finally
                {
                    connectDone.Set();
                }
            }
                                 , sClient);
            //timeout
            if (!connectDone.WaitOne(2000))
            {
                Log.LogInfo("connect time out");
                MainLoader.ChangeStep(LoadStep.CannotConnect);
                yield break;
            }
            else
            {
                if (!sClient.Connected)
                {
                    Log.LogInfo("connect disabled by server");
                    MainLoader.ChangeStep(LoadStep.CannotConnect);
                    yield break;
                }
            }
        }
        catch
        {
            sClient.Close();
            MainLoader.ChangeStep(LoadStep.CannotConnect);
            yield break;
        }
        finally
        {
            connectDone.Close();
        }
        //Log.LogInfo("download:" + string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName));
        using (WWW vFile = new WWW(string.Format(strVFile, strHost, strPort, strProjectUrl, strPlatform, strVFileName)))
        {
            //Log.LogInfo("error:" + vFile.error);
            yield return(vFile);

            if (vFile.error != null && vFile.error.Length != 0)
            {
                //Log.LogInfo("error " + vFile.error);
                vFile.Dispose();
                //not have new version file
                //can continue game
                MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
                yield break;
            }
            if (vFile.bytes != null && vFile.bytes.Length != 0)
            {
                File.WriteAllBytes(strUpdatePath + "/" + "v.zip", vFile.bytes);
                DeCompressFile(strUpdatePath + "/" + "v.zip", strUpdatePath + "/" + "v.xml");
                vFile.Dispose();
            }
            else
            {
                MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
                yield break;
            }
        }

        XmlDocument xmlVer = new XmlDocument();

        xmlVer.Load(strUpdatePath + "/" + "v.xml");
        XmlElement ServerVer = xmlVer.DocumentElement;

        if (ServerVer != null)
        {
            string strServer = ServerVer.GetAttribute("ServerV");
            UpdateClient = HttpManager.AllocClient(string.Format(strDirectoryBase, strHost, strPort, strProjectUrl, strPlatform, strServer, ""));
            //if (strServer != null && GameData.Version().CompareTo(strServer) == -1)
            //{
            //	strServerVer = strServer;
            //	foreach (XmlElement item in ServerVer)
            //	{
            //		string strClientV = item.GetAttribute("ClientV");
            //		if (strClientV == GameData.Version())
            //		{
            //			strUpdateFile = item.GetAttribute("File");
            //			break;
            //		}
            //	}

            //	if (strUpdateFile != null && strUpdateFile.Length != 0)
            //		StartCoroutine("DownloadNecessaryData");
            //}
            //else
            //{
            //	Log.LogInfo("not need update");
            //             MainLoader.ChangeStep(LoadStep.NotNeedUpdate);
            //}
        }
    }
Example #34
0
        /// <summary>
        /// Sends STARTTLS command to SMTP server.
        /// </summary>
        /// <param name="certCallback">SSL server certificate validation callback. Value null means any certificate is accepted.</param>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="InvalidOperationException">Is raised when SMTP client is not connected or is already secure connection.</exception>
        /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception>
        /// <remarks>After successful STARTTLS all SMTP session data(EHLO,MAIL FROM, ....) will be reset.
        /// If unknwon(not SMTP error) error happens during STARTTLS negotiation, SMTP client should disconnect.</remarks>
        public void StartTLS(RemoteCertificateValidationCallback certCallback)
        {
            if(this.IsDisposed){
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if(!this.IsConnected){
				throw new InvalidOperationException("You must connect first.");
			}
            if(this.IsSecureConnection){
                throw new InvalidOperationException("Connection is already secure.");
            }

            ManualResetEvent wait = new ManualResetEvent(false);
            using(StartTlsAsyncOP op = new StartTlsAsyncOP(certCallback)){
                op.CompletedAsync += delegate(object s1,EventArgs<StartTlsAsyncOP> e1){
                    wait.Set();
                };
                if(!this.StartTlsAsync(op)){
                    wait.Set();
                }
                wait.WaitOne();
                wait.Close();

                if(op.Error != null){
                    throw op.Error;
                }
            }
        }