Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
 public Connection(ref System.Net.Sockets.TcpClient TCPClient, System.Threading.ManualResetEvent eventChannelConnectionComplete, ref CarverLab.Utility.Logger logger)
 {
     log = logger;
     log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
     m_TCPClient = TCPClient;
     m_bConnected = false;
     m_iBufferMaxLength = 2048;
     m_iBufferLength = 0;
     m_bytesIncomingBuffer = new byte[m_iBufferMaxLength];
     m_bDone = false;
     m_ThreadReceiveDataAndEnqueue = new System.Threading.Thread(new System.Threading.ThreadStart(this.ReceiveDataAndEnqueue));
     m_ThreadAutomaticDequeue = new System.Threading.Thread(new System.Threading.ThreadStart(this.DequeCommands));
     m_ThreadIsConnectionAlive = new System.Threading.Thread(new System.Threading.ThreadStart(this.IsConnectionAlive));
     m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue());
     m_EventChannelConnectionComplete = eventChannelConnectionComplete;
     m_EventChannelConnectionComplete.Reset();
     m_EventMessageAvailable = new System.Threading.AutoResetEvent(false);
     m_EventThreadComplete = new System.Threading.ManualResetEvent(false);
     m_bIsRunning = false;
     m_bAutomaticDequeueingSuspended = false;
     m_EventAutomaticQueueing = new System.Threading.ManualResetEvent(true);
 }
Exemplo n.º 3
0
        private void DialogMessageForOverWrite(int FileType, string FilePath)
        {
            if (decryption.TempOverWriteOption == 2)
            {                   // Overwrite all
                return;
            }

            if (!bkg.IsBusy)
            {
                bkg.RunWorkerAsync();
                // Unblock the worker
                _busy.Set();
            }

            // 問い合わせ
            // 以下のファイルはすでに存在しています。上書きして保存しますか?
            //
            // Question
            // The following file already exists. Do you overwrite the files to save?
            //
            string DialogTitleQuestion         = "Question";
            string labelComfirmToOverwriteFile = "The following file already exists. Do you overwrite the files to save?";

            if (CurrentCultureName == "ja")
            {
                DialogTitleQuestion         = "問い合わせ";
                labelComfirmToOverwriteFile = "以下のファイルはすでに存在しています。上書きして保存しますか?";
            }
            if (MessageBox.Show(labelComfirmToOverwriteFile + "\n" + FilePath,
                                DialogTitleQuestion, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                decryption.TempOverWriteOption = 2;                     //Overwrite all
            }

            _busy.Reset();
        }
Exemplo n.º 4
0
        private void ReceiveThread()
        {
            var errorTimes = 0;

            while (!_mainCancelSource.IsCancellationRequested)
            {
                try
                {
                    Initialize();
                    Receive();
                    errorTimes = 0;
                    // 判断线程是否暂停
                    if (!IsSuspend)
                    {
                        continue;
                    }
                    _blockWait.Reset();
                    // 无限等待
                    _blockWait.WaitOne(System.Threading.Timeout.Infinite);
                }
                catch (Exception ex)
                {
                    errorTimes++;
                    if (ExcptionCallback != null)
                    {
                        ExcptionCallback(this, ex,
                                         string.Format("MQ 数据接收线程异常,异常次数:{0},超过3次则自动重连", errorTimes));
                    }
                }
                // 异常超过3次,将清空连接,重新连接
                if (errorTimes > 3)
                {
                    ClearConnection();
                }
            }
        }
Exemplo n.º 5
0
        //Nút bắt đầu
        private async void Nut_bat_dau(object sender, EventArgs e)
        {
            for (int i = 0; i < spt; i++)
            {
                try
                {
                    array[i] = Convert.ToInt32(value[i].Text);
                }
                catch
                {
                    MessageBox.Show("Vui lòng nhập giá trị vào mảng");
                    return;
                }
            }
            checkBox1.AutoCheck = false;
            button11.Enabled    = true;
            button5.Enabled     = false;
            button8.Enabled     = false;
            button10.Enabled    = false;
            button6.Enabled     = false;
            button7.Enabled     = false;
            button9.Enabled     = false;
            if (ytuong.Text == y_tuong_tuyen_tinh)
            {
                for (int i = 0; i < spt; i++)
                {
                    value[i].BackColor = SystemColors.Highlight;
                    value[i].Refresh();
                }
                key = Convert.ToInt32(textBox1.Text);
                int c = 0;
                for (int i = 0; i < spt; i++)
                {
                    label9.Text = "";
                    label6.Text = "";
                    label7.Text = "i = " + i;
                    label7.Refresh();
                    label9.Refresh();
                    label6.Refresh();
                    // dịch chuyển textbox lên
                    while (value[i].Top > 400)
                    {
                        value[i].Top -= 1;
                        System.Threading.Thread.Sleep(5);
                    }

                    //Nhấn nút tiếp tục để tiếp tục chương trình

                    await Task.Run(() =>
                    {
                        mre.WaitOne();
                        mre.Reset();
                    });                    // đưa textbox về vị trí ban đầu

                    // đưa textbox về vị trí ban đầu
                    while (value[i].Top < 450)
                    {
                        value[i].Top += 1;
                        System.Threading.Thread.Sleep(5);
                    }

                    if (array[i] == key)
                    {
                        c++;
                        value[i].BackColor = Color.Red;
                    }
                    else
                    {
                        value[i].BackColor = SystemColors.Highlight;
                    }
                }

                // c là biến đếm nếu có phần tử trong mảng thì sẽ thêm 1 giá trị
                if (c != 0)
                {
                    MessageBox.Show("Tìm thấy phần tử trong mảng");
                }
                else
                {
                    MessageBox.Show("Không tìm thấy phần tử trong mảng");
                }
                MessageBox.Show("Đã Thực hiện xong");
            }
            else if (ytuong.Text == y_tuong_nhi_phan)
            {
                key = Convert.ToInt32(textBox1.Text);
                for (int i = 0; i < spt; i++)
                {
                    value[i].BackColor = SystemColors.Highlight;
                    value[i].Refresh();
                }
                if (kiem_tra(array) == false)
                {
                    button11.Enabled = false;
                    button10.Enabled = true;
                    button9.Enabled  = true;
                    return;
                }
                int c     = 0;
                int left  = 0;
                int right = spt - 1;
                label7.Text = "mid = " + (left + right) / 2;
                label9.Text = "left = 0";
                label6.Text = "right = " + (spt);
                label7.Refresh();
                label9.Refresh();
                label6.Refresh();
                while (left <= right)
                {
                    int mid = (left + right) / 2;
                    while (value[mid].Top > 400)
                    {
                        value[mid].Top -= 1;
                        System.Threading.Thread.Sleep(5);
                    }

                    //Nhấn nút tiếp tục để tiếp tục chương trình

                    await Task.Run(() =>
                    {
                        mre.WaitOne();
                        mre.Reset();
                    });                    // đưa textbox về vị trí ban đầu

                    // đưa textbox về vị trí ban đầu
                    while (value[mid].Top < 450)
                    {
                        value[mid].Top += 1;
                        System.Threading.Thread.Sleep(5);
                    }
                    if (array[mid] == key)
                    {
                        c++;
                        value[mid].BackColor = Color.Red;
                        break;
                    }
                    else if (array[mid] > key)
                    {
                        right = mid - 1;
                        value[mid].BackColor = SystemColors.Highlight;
                    }
                    else
                    {
                        left = mid + 1;
                        value[mid].BackColor = SystemColors.Highlight;
                    }
                    label7.Text = "mid = " + (left + right) / 2;
                    label9.Text = "left = " + left;
                    label6.Text = "right = " + right;
                    label7.Refresh();
                    label9.Refresh();
                    label6.Refresh();
                }
                if (c != 0)
                {
                    MessageBox.Show("Tìm thấy phần tử trong mảng");
                }
                else
                {
                    MessageBox.Show("Không tìm thấy phần tử trong mảng");
                }
                MessageBox.Show("Đã Thực hiện xong");
            }
            else if (ytuong.Text == y_tuong_noi_suy)
            {
                key = Convert.ToInt32(textBox1.Text);
                for (int i = 0; i < spt; i++)
                {
                    value[i].BackColor = SystemColors.Highlight;
                    value[i].Refresh();
                }
                if (kiem_tra(array) == false)
                {
                    button11.Enabled = false;
                    button10.Enabled = true;
                    button9.Enabled  = true;
                    return;
                }
                int c = 0;
                int left = 0, right = spt - 1;
                label9.Text = "left = 0";
                label6.Text = "right = " + (spt - 1);
                label7.Text = "pos = " + (left + ((key - array[left]) * (right - left) / (array[right] - array[left])));

                label7.Refresh();
                label9.Refresh();
                label6.Refresh();

                while (array[left] != array[right] && key >= array[left] && key <= array[right])
                {
                    int pos = left + ((key - array[left]) * (right - left) / (array[right] - array[left]));

                    while (value[pos].Top > 400)
                    {
                        value[pos].Top -= 1;
                        System.Threading.Thread.Sleep(5);
                    }

                    //Nhấn nút tiếp tục để tiếp tục chương trình

                    await Task.Run(() =>
                    {
                        mre.WaitOne();
                        mre.Reset();
                    });

                    while (value[pos].Top < 450)
                    {
                        value[pos].Top += 1;
                        System.Threading.Thread.Sleep(5);
                    }
                    if (array[pos] == key)
                    {
                        label7.Text = "pos = " + pos;
                        label9.Text = "left = " + left;
                        label6.Text = "right = " + right;
                        label7.Refresh();
                        label9.Refresh();
                        label6.Refresh();
                        c++;
                        value[pos].BackColor = Color.Red;
                        break;
                    }
                    else if (array[pos] < key)
                    {
                        left = pos + 1;
                        value[pos].BackColor = SystemColors.Highlight;
                    }
                    else
                    {
                        right = pos - 1;
                        value[pos].BackColor = SystemColors.Highlight;
                    }
                    label7.Text = "pos = " + pos;
                    label9.Text = "left = " + left;
                    label6.Text = "right = " + right;
                    label7.Refresh();
                    label9.Refresh();
                    label6.Refresh();
                }
                if (c != 0)
                {
                    MessageBox.Show("Tìm thấy phần tử trong mảng");
                }
                else
                {
                    MessageBox.Show("Không tìm thấy phần tử trong mảng");
                }
                MessageBox.Show("Đã Thực hiện xong");
            }
            button5.Enabled     = true;
            button8.Enabled     = true;
            button10.Enabled    = true;
            button6.Enabled     = true;
            button7.Enabled     = true;
            button11.Enabled    = false;
            checkBox1.AutoCheck = true;

            return;
        }
Exemplo n.º 6
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 (LinkedStack.TryPush(ref LastInputOutput))
                    {
                        System.Console.WriteLine("pushThread: " + LastInputOutput);

                        ++countIn;

                        mre.Set();

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

                if (LinkedStack.IsEmpty)
                {
                    System.Console.WriteLine("pushThread Empty");
                }

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

            int countOut = 0;

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

                    if (LinkedStack.TryPop(out dequeue))
                    {
                        ++countOut;

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

                        mre.Set();

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

                //if (false == LinkedStack.IsEmpty) throw new System.Exception("popThread");

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

            enqueueThread.Start();

            dequeueThread.Start();

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

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

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

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

                        long peek = 0;

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

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

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

                mre.WaitOne(0);
            }

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

            if (false == LinkedStack.IsEmpty)
            {
                throw new System.Exception("IsEmpty," + LinkedStack.Count);
            }

            System.Console.WriteLine("Count: " + LinkedStack.Count);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            bstuff = new BotStuff();
            Donify = bstuff.OnyVariables.Donify;
            logger = bstuff.OnyVariables.logger;
            nstruct = bstuff.OnyVariables.nstruct;
            if (!File.Exists("funcpersistence.xml"))
                bstuff.OnyVariables.persistence.save();
            bstuff.OnyVariables.persistence.load();
            LoadPlugins();
            bstuff.OnyEvents.InComingMessage += new BotStuff.BotEvents.IncomingMessageHook(OnyEvents_InComingMessage);
            if (!socketfunctions.trybindsocket(mainsock, ref port, true, 50, IPAddress.Any))
            { logger.log("FAILED TO BIND TO ANY PORT. EXITTING", Logging.Priority.Critical); return; }
            logger.log("Initialized main function", Logging.Priority.Info);
            logger.log("Loading variables..",Logging.Priority.Notice);

            try
            { bstuff.OnyFunctions.PrivFunctions.loadnow(new OnyLib.SpecialClasses.BotFunctionData(nstruct)); }
            catch (Exception ex)
            { logger.logerror(ex); }
            logger.log("Trying to load playback file..", Logging.Priority.Notice);
            try { nstruct.loadplayback(); }
            catch (Exception ex) { logger.logerror(ex); }

            while (bstuff.OnyVariables.run)
            {
                if ((bstuff.OnyVariables.amountloops % 10) == 0) { nstruct.saveplayback(); bstuff.OnyVariables.amountloops = 0; bstuff.OnyVariables.persistence.save(); }
                logger.log("Waiting for incoming commands", Logging.Priority.Info);
                Donify.Reset();
                mainsock.BeginAccept(new AsyncCallback(acceptIncomingConnection), mainsock);
                Donify.WaitOne();
            }
            nstruct.saveplayback();
            bstuff.OnyVariables.persistence.save();
            Console.WriteLine("Going down!");
            logger.log("Shutting down bot.", Logging.Priority.Notice);
            logger.log("Uptime: " + (DateTime.Now - bstuff.OnyVariables.starttime).ToString(), Logging.Priority.Info);
            Environment.Exit(0);
        }
		public void CancelPendingRequests ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var mre = new ManualResetEvent (false);

			mh.OnSendFull = (l, c) => {
				mre.Set ();
				Assert.IsTrue (c.WaitHandle.WaitOne (1000), "#20");
				Assert.IsTrue (c.IsCancellationRequested, "#21");
				mre.Set ();
				return CompletedTask.FromResult (new HttpResponseMessage ());
			};

			var t = Task.Factory.StartNew (() => {
				client.SendAsync (request).Wait (WaitTimeout);
			});

			Assert.IsTrue (mre.WaitOne (500), "#1");
			mre.Reset ();
			client.CancelPendingRequests ();
			Assert.IsTrue (t.Wait (500), "#2");

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return CompletedTask.FromResult (new HttpResponseMessage ());
			};

			client.SendAsync (request).Wait (WaitTimeout);
		}
Exemplo n.º 9
0
 private void ResetWatchDog() => _watchDogWaitHandle.Reset();
Exemplo n.º 10
0
        void StartRenderLoop()
        {
            // If the render loop is already running then do not start another thread.
            if (_renderLoopWorker != null)
            {
                return;
            }

            // Create a task for rendering that will be run on a background thread.
            var workItemHandler = new Windows.System.Threading.WorkItemHandler((Windows.Foundation.IAsyncAction action) => {
                int oldPanelWidth  = -1;
                int oldPanelHeight = -1;
                while (action.Status == Windows.Foundation.AsyncStatus.Started)
                {
                    int panelWidth  = 0;
                    int panelHeight = 0;
                    GetSwapChainPanelSize(out panelWidth, out panelHeight);

                    bool swapResult = false;
                    lock (_renderSurfaceLock) {
                        if (_renderSurface == IntPtr.Zero)
                        {
                            continue;
                        }
                        _eglContext.MakeCurrent(_renderSurface);

                        // Signal 'surface changed' when needed
                        if (panelWidth != oldPanelWidth || panelHeight != oldPanelHeight)
                        {
                            _baseMapView.OnSurfaceChanged(panelWidth, panelHeight);
                            oldPanelWidth  = panelWidth;
                            oldPanelHeight = panelHeight;
                        }

                        // Do actual rendering
                        _baseMapView.OnDrawFrame();

                        // Display rendered image
                        swapResult = _eglContext.SwapBuffers(_renderSurface);
                    }

                    // The call to eglSwapBuffers might not be successful (i.e. due to Device Lost)
                    // If the call fails, then we must reinitialize EGL and the GL resources.
                    if (!swapResult)
                    {
                        // XAML objects like the SwapChainPanel must only be manipulated on the UI thread.
                        var recoveryWorker = _swapChainPanel.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => {
                            RecoverFromLostDevice();
                        }));
                        recoveryWorker.Close();
                        return;
                    }

                    // Wait for the next 'redraw' signal
                    _swapChainEvent.WaitOne();
                    _swapChainEvent.Reset();
                }
            });

            // Run task on a dedicated high priority background thread.
            _renderLoopWorker = Windows.System.Threading.ThreadPool.RunAsync(workItemHandler, Windows.System.Threading.WorkItemPriority.Normal, Windows.System.Threading.WorkItemOptions.TimeSliced);
        }
Exemplo n.º 11
0
        public bool connect(string host, UInt16 port)
        {
            if (isConnected)
            {
                disconnect();
            }

            _state = State.Connecting;
            string errorMessage = string.Empty;
            var    mrEvent      = new System.Threading.ManualResetEvent(false);

            try {
                IPAddress[] addresses = Dns.GetHostAddresses(host);
                for (int i = 0; i < addresses.Length; ++i)
                {
                    try {
                        var address = addresses[i];
                        if ((address.AddressFamily != AddressFamily.InterNetwork) &&
                            (address.AddressFamily != AddressFamily.InterNetworkV6))
                        {
                            continue;
                        }

                        mrEvent.Reset();

                        var endPoint = new IPEndPoint(address, port);
                        createSocket(address.AddressFamily);
                        IAsyncResult result = _socket.BeginConnect(endPoint, (res) => {
                            mrEvent.Set();
                        }, null);
                        bool isActive = mrEvent.WaitOne(connectionTimeout);
                        if (isActive)
                        {
                            _socket.EndConnect(result);
                            connected();
                            return(true);
                        }
                        errorMessage = "Connection timeout!";
                    }
                    catch (SocketException e) {
                        if (i >= (addresses.Length - 1))
                        {
                            errorMessage = e.Message;
                            break;
                        }
                    }
                }

                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = "Address not available";
                }
            }
            catch (Exception e) {
                errorMessage = e.Message;
            }

            error(errorMessage);
            close();
            return(false);
        }
Exemplo n.º 12
0
 private void Browser_FrameLoadStart(object sender, FrameLoadStartEventArgs e)
 {
     System.Diagnostics.Debug.WriteLine("Browser_FrameLoadStart " + e.Url);
     _frameLoadEvent.Reset();
 }
Exemplo n.º 13
0
 public void Waite()
 {
     _Mre.Reset();
 }
Exemplo n.º 14
0
        public void ImportProjectServiceWithMigrationTest()
        {
            SampleData.ClearDatabaseThenImportDefaultProject();

            var importData = PrepareImport();

            var service = new ImportExportService();

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

            KProcess.Ksmed.Business.Dtos.Export.ProjectImport projectImport = null;
            Exception e = null;

            int newProjectId = -1;

            service.PredictMergedReferentialsProject(importData, pi =>
            {
                projectImport = pi;

                service.ImportProject(pi, false, TestContext.DeploymentDirectory, p =>
                {
                    newProjectId = p.ProjectId;
                    mre.Set();
                }, ex =>
                {
                    e = ex;
                    mre.Set();
                });
            }, ex =>
            {
                e = ex;
                mre.Set();
            });

            mre.WaitOne();
            AssertExt.IsExceptionNull(e);
            Assert.IsNotNull(projectImport);

            Assert.IsTrue(projectImport.ExportedProject.Project.Label.EndsWith(" migré"));

            // Récupérer le projet depuis la base et tester
            var prepareService = new PrepareService();

            mre.Reset();
            ProjectsData data = null;

            prepareService.GetProjects(d =>
            {
                data = d;
                mre.Set();
            }, ex =>
            {
                e = ex;
                mre.Set();
            });

            mre.WaitOne();
            AssertExt.IsExceptionNull(e);

            var project = data.Projects.First(p => p.ProjectId == newProjectId);

            Assert.IsTrue(project.Label.EndsWith(" migré"));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Exporte le projet spécifié.
        /// </summary>
        private void ExportVideoDecomposition(int projectId, int scenarioId, int videoId, int targetProjectId, bool merge)
        {
            var service = new ImportExportService();

            string fileName = string.Format("out{0}.xml", fileNumber++);

            KProcess.Ksmed.Business.Dtos.Export.VideoDecompositionExport oldVideoExport;
            using (var context = KProcess.Ksmed.Data.ContextFactory.GetNewContext())
            {
                oldVideoExport = new VideoDecompositionExporter(context, projectId, scenarioId, videoId).CreateExport();
            }

            var       mre    = new System.Threading.ManualResetEvent(false);
            Stream    stream = null;
            Exception e      = null;

            service.ExportVideoDecomposition(projectId, scenarioId, videoId, d =>
            {
                stream = d;
                mre.Set();
            }, ex =>
            {
                e = ex;
                mre.Set();
            });

            mre.WaitOne();
            AssertExt.IsExceptionNull(e);
            Assert.IsNotNull(stream);

            using (var reader = new StreamReader(stream))
            {
                string xml = reader.ReadToEnd();
                File.WriteAllText(fileName, xml);

                Assert.IsNotNull(xml);
            }
            stream.Close();

            Initialization.SetCurrentUser("paula");

            // Ouvrir le fichier
            mre.Reset();
            service.PredictMergedReferentialsVideoDecomposition(targetProjectId, File.OpenRead(fileName), vdi =>
            {
                service.ImportVideoDecomposition(vdi, merge, TestContext.DeploymentDirectory, targetProjectId, success =>
                {
                    Assert.IsTrue(success);
                    mre.Set();
                }, ex =>
                {
                    e = ex;
                    mre.Set();
                });
            }, ex =>
            {
                e = ex;
                mre.Set();
            });

            mre.WaitOne();
            AssertExt.IsExceptionNull(e);

            // Récupérer le numéro de scénario initial du projet
            Scenario targetScenario;
            int      newVideoId;

            using (var context = KProcess.Ksmed.Data.ContextFactory.GetNewContext())
            {
                targetScenario = context.Scenarios.Single(s => s.ProjectId == targetProjectId && s.StateCode == KnownScenarioStates.Draft && s.NatureCode == KnownScenarioNatures.Initial);
                var oldVideoName = context.Videos.Single(v => v.VideoId == videoId).Name;
                newVideoId = context.Videos.Where(v => v.ProjectId == targetProjectId && v.Name == oldVideoName)
                             .AsEnumerable().Last().VideoId;
            }

            //Réexporter la décompo
            KProcess.Ksmed.Business.Dtos.Export.VideoDecompositionExport newVideoExport;
            using (var context = KProcess.Ksmed.Data.ContextFactory.GetNewContext())
            {
                newVideoExport = new VideoDecompositionExporter(context, targetScenario.ProjectId, targetScenario.ScenarioId, newVideoId).CreateExport();
            }

            // Comparer les valeurs

            // Vidéo
            var oldVideo = oldVideoExport.Video;
            var newVideo = newVideoExport.Video;

            AssertVideo(oldVideo, newVideo);

            // Référentiels
            var p1RerentialsProject  = ReferentialsHelper.GetAllReferentialsProject(oldVideoExport.Actions).ToArray();
            var p1RerentialsStandard = ReferentialsHelper.GetAllReferentialsStandardUsed(oldVideoExport.Actions).ToArray();

            var p2RerentialsProject  = ReferentialsHelper.GetAllReferentialsProject(newVideoExport.Actions).ToArray();
            var p2RerentialsStandard = ReferentialsHelper.GetAllReferentialsStandardUsed(newVideoExport.Actions).ToArray();

            Assert.IsTrue(p1RerentialsProject.Length <= p2RerentialsProject.Length);
            Assert.AreEqual(p1RerentialsProject.Length + p1RerentialsStandard.Length, p2RerentialsProject.Length);
            Assert.AreEqual(0, p2RerentialsStandard.Length);

            // Vérifier que toutes les actions de l'ancien export soient également maintenant dans le projet de destination
            var oldActions = oldVideoExport.Actions.OrderBy(a => WBSHelper.GetParts(a.WBS), new WBSHelper.WBSComparer()).ToArray();
            var newActions = newVideoExport.Actions.OrderBy(a => WBSHelper.GetParts(a.WBS), new WBSHelper.WBSComparer()).ToArray();

            Assert.AreEqual(oldActions.Length, newActions.Length);

            // Actions
            for (int j = 0; j < oldActions.Length; j++)
            {
                var oldAction = oldActions[j];
                var newAction = newActions[j];

                AssertAction(oldAction, newAction);

                // Actions réduites
                AssertActionReduced(oldAction.Reduced, newAction.Reduced);
            }

            ServicesDiagnosticsDebug.CheckReferentialsState();
        }
Exemplo n.º 16
0
        public Train()
        {
            //일정 시간에 모델 저장
            System.Timers.Timer saveTimer = new System.Timers.Timer(10 /*분*/ * 60 * 1000);
            saveTimer.Elapsed += saveTimer_Elapsed;
            saveTimer.Start();

            Console.WriteLine("Connected!");

            ////////////////////////////////////////////////////

            //학습
            //CPU를 최대로 활용하기 위해 여러 단계로 프로세스를 나눔

            //generation
            Task.Run(() =>
            {
                int makingTurn = 0;
                while (running)
                {
                    //자료가 한 쪽이라도 남아있으면 쉰다.
                    if (dataPolicy.Count > 5000 || dataValue.Count > 5000)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                    else
                    {
                        genGibo();
                        //genReinforce();
                        signal.Set();                        //만들었으니 학습을 시도하시오 파란불 반짝
                    }

                    makingTurn++;
                }
            });

            //Augmentation
            Task.Run(() =>
            {
                while (running)
                {
                    while (bufferPolicy.Count < setCount * 20 && dataPolicy.Count >= 5000)
                    {
                        List <Tuple <Board, Move> > sub;
                        lock (dataPolicy)
                        {
                            sub = dataPolicy.GetRange(0, 5000);
                            dataPolicy.RemoveRange(0, 5000);
                        }

                        var sub2 = from e in sub select new Tuple <Board, Move>(e.Item1.GetFlip(), e.Item2.GetFlip());

                        lock (bufferPolicy)
                        {
                            bufferPolicy.AddRange(sub);
                            bufferPolicy.AddRange(sub2);
                            signal.Set();                            //만들었으니 학습을 시도하시오 파란불 반짝
                        }
                    }

                    while (bufferValue.Count < 10000 && dataValue.Count >= 5000)
                    {
                        List <Tuple <Board, float> > sub;
                        lock (dataValue)
                        {
                            sub = dataValue.GetRange(0, 5000);
                            dataValue.RemoveRange(0, 5000);
                        }

                        var subFlip = from e in sub select new Tuple <Board, float>(e.Item1.GetFlip(), e.Item2);

                        lock (bufferValue)
                        {
                            bufferValue.AddRange(sub);
                            bufferValue.AddRange(subFlip);
                            signal.Set();                            //만들었으니 학습을 시도하시오 파란불 반짝
                        }
                    }

                    lock (bufferPolicy)
                    {
                        Shuffle(bufferPolicy);
                    }

                    lock (bufferValue)
                    {
                        Shuffle(bufferValue);
                    }



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


            //학습 프로세스
            running = true;
            while (running)
            {
                while (bufferPolicy.Count < setCount && bufferValue.Count < setCount)
                {
                    signal.Reset();
                    signal.WaitOne();
                }

                if (bufferPolicy.Count > setCount)
                {
                    Console.WriteLine("train policy ... " + DateTime.Now.ToString());
                    List <Tuple <Board, Move> > sub;
                    lock (bufferPolicy)
                    {
                        sub = bufferPolicy.GetRange(0, setCount);
                        bufferPolicy.RemoveRange(0, setCount);
                    }

                    tcpCommClient.TrainPolicy(sub);
                }

                if (bufferValue.Count > setCount)
                {
                    Console.WriteLine("train value ... " + DateTime.Now.ToString());
                    List <Tuple <Board, float> > sub;
                    lock (bufferValue)
                    {
                        sub = bufferValue.GetRange(0, setCount);
                        if (sub[0] == null)
                        {
                            throw new Exception("???");
                        }

                        bufferValue.RemoveRange(0, setCount);
                        if (sub[0] == null)
                        {
                            throw new Exception("???");
                        }
                    }

                    if (sub[0] == null)
                    {
                        throw new Exception("???");
                    }
                    tcpCommClient.TrainValue(sub);
                }
            }

            tcpCommClient.Disconnect();
        }
Exemplo n.º 17
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;
            });
        }
Exemplo n.º 18
0
 /// <summary>
 /// Closes the <see cref="Gate">Gate</see>.
 /// </summary>
 public void Close()
 {
     cgEvent.Reset();
 }
Exemplo n.º 19
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);
            }
        }
Exemplo n.º 20
0
        void preauth_fed_workplacejoined_asProxy_success(object px)
        {
            preauth_fed_asProxy_success_signal.Reset();
            WebProxy proxy = px as WebProxy;

            authTokenPresent   = false;
            accessToWebApp     = false;
            backendTlsCaptured = false;
            lock (managedThreads)
            {
                System.Threading.Thread t = new System.Threading.Thread(AsyncInstallAndPublishApp1AndAccess);
                t.Start();
                managedThreads.Add(t);
            }

            DateTime start   = DateTime.Now;
            int      timeout = 10;

            while ((DateTime.Now - start).TotalMinutes < timeout)
            {
                lock (resourceLocker)
                {
                    if (first != null)
                    {
                        first.Text = Encoding.UTF8.GetString(first.Data);
                        if (first.ParsedHttpRequest != null)
                        {
                            if (first.ParsedHttpRequest.Method == HttpRequest.HttpMethod.POST)
                            {
                            }
                            if (first.ParsedHttpRequest.RequestUrl.Path.ToLower() == Constraints.EstablishTrustUrl.ToLower())
                            {
                                if (proxyCert == null)
                                {
                                    if (first.ParsedHttpRequest.Body == null)
                                    {
                                        requestIs100Continue = true;
                                    }
                                    establishTrustRequest = first.ParsedHttpRequest;
                                    if (!requestIs100Continue)
                                    {
                                        //already full request
                                        retriveProxyCert();
                                        proxy.SetClientCertificate(proxyCert);
                                    }
                                }
                            }
                            else if (first.ParsedHttpRequest.RequestUrl.Path.ToLower() == Constraints.RenewTrustUrl.ToLower())
                            {
                                first.Ignore = true;
                            }
                            else if (first.ParsedHttpRequest.RequestUrl.Path.ToLower().Contains(Constraints.BackEndProxyTLSUrl.ToLower()))
                            {
                                backendTlsCaptured = true;
                            }
                            else if (first.ParsedHttpRequest.RequestUrl.Path.ToLower().Contains(EnvironmentConfig.App1Name.ToLower()))
                            {
                                accessToWebApp = true;
                                break;
                            }
                        }
                        else if (first.Sender == SenderType.Target)
                        {
                            if (first.ParsedHttpResponse == null)
                            {
                                first.ParsedHttpResponse = new HttpResponse();
                                first.ParsedHttpResponse.Parse(Encoding.UTF8.GetString(first.Data));
                            }
                            HttpResponse res = first.ParsedHttpResponse;

                            if (res.StatusCode == System.Net.HttpStatusCode.TemporaryRedirect)
                            {
                                string loc = res.GetHeaderFieldValue(System.Net.HttpResponseHeader.Location);
                                BaseTestSite.Assert.IsNotNull(loc, "location cannot be null for HTTP 307");
                                Url u = new Url(loc);
                                List <KeyValuePair <string, string> > pairs = u.GetQueryPairs();

                                foreach (KeyValuePair <string, string> p in pairs)
                                {
                                    if (p.Key.ToLower() == "authtoken")
                                    {
                                        authTokenPresent = true;
                                    }
                                }
                            }
                        }
                        else if (proxyCert == null && requestIs100Continue && first.ParsedHttpRequest == null)
                        {
                            establishTrustRequest.Body += first.Text;
                            retriveProxyCert();
                            proxy.SetClientCertificate(proxyCert);
                        }
                        second = first;
                        first  = null;
                    }
                }
                System.Threading.Thread.Sleep(150);
            }

            preauth_fed_asProxy_success_signal.Set();
        }
Exemplo n.º 21
0
 public void Reset()
 {
     _currentObject.Reset();
 }
Exemplo n.º 22
0
        public EditorWorkProgressShowerInConsole()
        {
#if UNITY_EDITOR_WIN
            var pipeName = System.DateTime.Now.ToString("yyMMddHHmmss");
            var pipeout  = new System.IO.Pipes.NamedPipeServerStream("ProgressShowerInConsole" + pipeName, System.IO.Pipes.PipeDirection.Out);
            var pipein   = new System.IO.Pipes.NamedPipeServerStream("ProgressShowerInConsoleControl" + pipeName, System.IO.Pipes.PipeDirection.In);
            var arout    = pipeout.BeginWaitForConnection(null, null);
            var arin     = pipein.BeginWaitForConnection(null, null);

            var dir     = Application.dataPath + "/../";
            var tooldir = CapsModEditor.GetPackageOrModRoot(CapsEditorUtils.__MOD__) + "/~Tools~/";
            System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(tooldir + "ProgressShowerInConsole.exe", pipeName);
            si.WorkingDirectory = tooldir;
            _ExProc             = System.Diagnostics.Process.Start(si);

            var thd_Write = new System.Threading.Thread(() =>
            {
                try
                {
                    pipeout.EndWaitForConnection(arout);
                    var sw = new System.IO.StreamWriter(pipeout);
                    while (_MessageReady.WaitOne())
                    {
                        _MessageReady.Reset();
                        lock (_MessageQueue)
                        {
                            foreach (var line in _MessageQueue)
                            {
                                sw.WriteLine(line);
                            }
                            sw.Flush();
                            _MessageQueue.Clear();
                        }
                    }
                }
                finally
                {
                    pipeout.Dispose();
                }
            });
            thd_Write.Start();

            var thd_Read = new System.Threading.Thread(() =>
            {
                try
                {
                    pipein.EndWaitForConnection(arin);
                    var sr = new System.IO.StreamReader(pipein);
                    while (!_ExProc.HasExited)
                    {
                        var line = sr.ReadLine();
                        if (line != null)
                        {
                            if (line == "\uEE05Quit")
                            {
                                break;
                            }
                        }
                    }
                }
                finally
                {
                    _ShouldQuit = true;
                    thd_Write.Abort();
                    _MessageReady.Set();
                    pipein.Dispose();
                }
            });
            thd_Read.Start();
#endif
        }
Exemplo n.º 23
0
        private void Work()
        {
            string         text     = string.Empty;
            TargetLanguage language = TargetLanguage.VB;;

            System.Threading.ManualResetEvent[] events2 = { doCancel, doConvert };
            while (true)
            {
                var evIndex = System.Threading.WaitHandle.WaitAny(events2);
                switch (evIndex)
                {
                case 0:
                    return;

                case 1:
                    #region
                {
                    doConvert.Reset();
                    evIndex = System.Threading.WaitHandle.WaitAny(events2, _ConvertStartDelay);
                    if (evIndex == 0)
                    {
                        return;
                    }
                    if (evIndex == 1)
                    {
                        continue;
                    }

                    text            = this.InputText;
                    this.OutputText = "";
                    language        = this.InputLanguage;
                    changed         = false;
                    doConvert.Reset();
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        Result = null;
                        continue;
                    }
                    this.root = null;
                    try
                    {
                        Item item;
                        if (this.InputLanguage == TargetLanguage.VB)
                        {
                            var vbTree = VB.VisualBasicSyntaxTree.ParseText(text);
                            var vbRoot = (VB.VisualBasicSyntaxNode)vbTree.GetRoot();

                            var vbRoot2 = vbRoot.NormalizeWhitespace();

                            this.OutputText = vbRoot2.ToFullString();


                            item      = Item.Create(vbRoot);
                            this.root = vbRoot;
                        }
                        else
                        {
                            var csTree = CS.CSharpSyntaxTree.ParseText(this.InputText);
                            var csRoot = (CS.CSharpSyntaxNode)csTree.GetRoot();

                            Gekka.Roslyn.Translator.CS2VB.ResetCounter();
                            var vbRoot = Gekka.Roslyn.Translator.CS2VB.Translate(text).NormalizeWhitespace();
                            this.OutputText = vbRoot.ToFullString();


                            item      = Item.Create(csRoot);
                            this.root = csRoot;
                        }

                        this.Result = item;
                        this.doSelect.Set();
                        GenerateItems(item);
                        canSetSelection = true;
                    }
                    catch (Exception ex)
                    {
                        OutputText = ex.Message;
                    }
                }
                    #endregion
                    break;

                case 2:
                    #region
                {
                    this.doSelect.Reset();

                    //var sel = this.InputSelection;
                    //var result = this.Result;
                    //var root = this.root;
                    //if (result != null && root != null && sel != null)
                    //{
                    //	var item = Find(result.Items, sel);
                    //	if (item != null)
                    //	{

                    //	}
                    //}
                }
                    #endregion
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 24
0
 public override void Pause(string prompt)
 {
     m_pause.Reset();
     ShowPause(true, prompt);
     bool x = m_pause.WaitOne();
 }
Exemplo n.º 25
0
 public void Stop()
 {
     block.Reset();
     active = false;
 }
Exemplo n.º 26
0
 private void programPauseButton_Click(object sender, RoutedEventArgs e)
 {
     cpu.Running = CPUStatus.Pause;
     pauseEvent.Reset();
 }
Exemplo n.º 27
0
 public bool CloseGate()
 {
     return(gate.Reset());
 }
Exemplo n.º 28
0
 public void Pause()
 {
     paused = true;
     //StopRead();
     resumeEvent.Reset();
 }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
0
 // semaphore stuff
 public static void Block(this System.Threading.ManualResetEvent semaphore)
 {
     semaphore.Reset();
 }
Exemplo n.º 31
0
        public void BulkScenarioCloneTests()
        {
            SampleData.ClearDatabaseThenImportDefaultProject();
            var service = new PrepareService();

            int[] projectIds;
            using (var context = KProcess.Ksmed.Data.ContextFactory.GetNewContext())
            {
                projectIds = context.Projects.Select(p => p.ProjectId).ToArray();
            }

            foreach (var pid in projectIds)
            {
                var mre = new System.Threading.ManualResetEvent(false);

                Exception     e    = null;
                ScenariosData data = null;

                service.GetScenarios(pid, d =>
                {
                    data = d;
                    mre.Set();
                }, ex =>
                {
                    e = ex;
                    mre.Set();
                });

                mre.WaitOne();
                AssertExt.IsExceptionNull(e);
                Assert.IsNotNull(data);

                foreach (var scenario in data.Scenarios.Where(s => s.NatureCode != KnownScenarioNatures.Realized))
                {
                    if (scenario.NatureCode == KnownScenarioNatures.Target && scenario.Actions.Any(a => !a.IsReduced))
                    {
                        // Il s'agit d'un vieux projet. Tous les actions d'un scénario cible doivent aujourd'hui avoir une partie réduite
                        continue;
                    }

                    mre.Reset();

                    Scenario newScenario = null;

                    service.CreateScenario(pid, scenario, true, s =>
                    {
                        newScenario = s;
                        mre.Set();
                    }, ex =>
                    {
                        e = ex;
                        mre.Set();
                    });

                    mre.WaitOne();
                    AssertExt.IsExceptionNull(e);
                    Assert.IsNotNull(newScenario);

                    // Vérification de l'intégrité du scénario
                    ActionsTimingsMoveManagement.DebugCheckAllWBS(EnumerableExt.Concat(newScenario));

                    // Vérifier qu'il n'y ai pas de tâche avec un temps process nul
                    if (scenario.NatureCode != KnownScenarioNatures.Initial && newScenario.Actions.Any(a => a.BuildDuration <= 0))
                    {
                        Assert.Fail("Une action a un temps invalide");
                    }
                }
            }
        }
Exemplo n.º 32
0
        public bool StartPhosphorescenceMeasurement(long delay, uint count, double shutterTimeMs, double gain,
                                                    Callback whenMeasurementEnds, out string error)
        {
            bool result = false;

            error = "";

            try
            {
                if (!_cameraConnected)
                {
                    throw new Exception("Camera not connected");
                }

                Ready = false;


                //stop streaming camera
                _ptGreyCamera.StopVideo();

                if (!_ptGreyCamera.SetBinning(true))
                {
                    throw new Exception("Could not enable binning");
                }

                if (!SetShutterTime(shutterTimeMs))
                {
                    throw new Exception("Could not change shutter");
                }

                if (!SetGain(gain))
                {
                    throw new Exception("Could not change gain");
                }

                //increase frame buffer count
                if (!_ptGreyCamera.SetStreamBufferCount(50))
                {
                    throw new Exception("Could not set frame buffer count");
                }

                //do this before we change trigger mode
                _phosStartTimestamp = _ptGreyCamera.GetImageTimeStamp();

                //empty phos image buffer
                _phosImages.Clear();

                //enable external trigger with count + delay
                if (!_ptGreyCamera.PhosTriggerMode(true, count, delay))
                {
                    throw new Exception("Could not set trigger mode");
                }

                //set phos count
                _phosImagesToCollect = count;

                //start video
                _ptGreyCamera.StartVideo();

                //start backgroundworker to wait for completion
                BWArgument arg;
                arg.measurementEnd = whenMeasurementEnds;
                arg.waitTime       = (int)(5000 + (count * Shutter + delay));


                _phosMeasureCompletionEvent.Reset();
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork             += WaitForPhosCompletion;
                bw.RunWorkerCompleted += PhosMeasurementComplete;
                bw.RunWorkerAsync(arg);

                result = true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                Ready = true;
                _ptGreyCamera.StopVideo();
                _phosImagesToCollect = 0;
                _phosMeasureCompletionEvent.Set();
                _ptGreyCamera.PhosTriggerMode(false, 0, 0);
                _ptGreyCamera.SetStreamBufferCount(1);
                _ptGreyCamera.SetBinning(false);
                SetShutterTime(Properties.Settings.Default.ShutterDefault);
                SetGain(Properties.Settings.Default.GainDefault);
                _ptGreyCamera.StartVideo();
            }

            return(result);
        }
Exemplo n.º 33
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[] pushThreads = new System.Threading.Thread[ThreadCount];

            System.Threading.Thread[] popThreads = 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 (LinkedStack.TryPeek(ref peek))
                        {
                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> TryPeek: " + peek);

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

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Last = " + System.Threading.Thread.VolatileRead(ref LinkedStack.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)
            {
                pushThreads[t] = new System.Threading.Thread(() =>
                {
                    int threadLocalCountIn = 0;

                    while (threadLocalCountIn < MultiThreadAmount)
                    {
                        ++LastInputOutput;

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

                            ++threadLocalCountIn;

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

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                        else
                        {
                            LinkedStack.Push(LastInputOutput);

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

                            ++threadLocalCountIn;

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

                            sharedResetEvent.Set();

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

                    if (LinkedStack.IsEmpty)
                    {
                        System.Console.WriteLine("pushThread Empty");
                    }

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

                    Priority = System.Threading.ThreadPriority.Normal,

                    Name = "pushThreads_" + t
                };

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

                    while (threadLocalCountOut < MultiThreadAmount)
                    {
                        long pop;

                        if (LinkedStack.TryPop(out pop))
                        {
                            ++threadLocalCountOut;

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

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

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

                            sharedResetEvent.Set();

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

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

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

                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Name = "popThreads_" + t
                };

                enumerateThreads[t] = createEnumerateThread();
            }

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

            System.Linq.ParallelEnumerable.ForAll(popThreads.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: " + LinkedStack.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:" + statLevelCountIn + "," + stackLevelCountOut);
            }

            if (false == LinkedStack.IsEmpty)
            {
                throw new System.Exception("IsEmpty," + LinkedStack.Count);
            }

            System.Console.WriteLine("Count: " + LinkedStack.Count);
        }
Exemplo n.º 34
0
        public void Run(EasyHook.RemoteHooking.IContext context, String channelName, ConfigDll config)
        {
            //Если не использовать GAC, могут возникать проблемы с правильной организацией удаленных сборок.
            //Это обходной путь, который гарантирует, что текущая сборка правильно связана
            AppDomain currentDomain = AppDomain.CurrentDomain;

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

            var curProcess = Process.GetCurrentProcess();

            NativeMethods.MessageBox(curProcess.MainWindowHandle.ToString());
            //NativeMethods.SendMessage(handle, NativeMethods.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);

            // NOTE: This is running in the target process
            _interface.Message("Injected into process Id: " + RemoteHooking.GetCurrentProcessId().ToString());

            _runWait = new System.Threading.ManualResetEvent(false);
            _runWait.Reset();

            try
            {
                // point to Initialise the Hook
                // Initialise the Hook
                if (!InitialiseDirectXHook(config))
                {
                    return;
                }

                _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler;

                _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();


                // point of disposin all threads
                //NativeMethods.MessageBox("Disposing");
            }
            catch (Exception e)
            {
                _interface.Message("Method \"Run\". An unexpected error occured: " + e.ToString());
            }
            finally
            {
                try
                {
                    _interface.Message("Disconnecting from process " + EasyHook.RemoteHooking.GetCurrentProcessId());
                }
                catch
                {
                }

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

                // Always sleep long enough for any remaining messages to complete sending
                System.Threading.Thread.Sleep(100);
            }
        }
Exemplo n.º 35
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);
            }
        }
Exemplo n.º 36
0
        bool LoadTexture(UUID textureID, ref Image texture, bool removeAlpha)
        {
            var gotImage = new System.Threading.ManualResetEvent(false);
            Image img = null;

            try
            {
                gotImage.Reset();
                byte[] tgaData;
                Client.Assets.RequestImage(textureID, (TextureRequestState state, AssetTexture assetTexture) =>
                {
                    ManagedImage mi;
                    if (state == TextureRequestState.Finished && OpenJPEG.DecodeToImage(assetTexture.AssetData, out mi))
                    {

                        if (removeAlpha)
                        {
                            if ((mi.Channels & ManagedImage.ImageChannels.Alpha) != 0)
                            {
                                mi.ConvertChannels(mi.Channels & ~ManagedImage.ImageChannels.Alpha);
                            }
                        }
                        tgaData = mi.ExportTGA();
                        img = LoadTGAClass.LoadTGA(new MemoryStream(tgaData));
                    }
                    gotImage.Set();
                });
                gotImage.WaitOne(30 * 1000, false);

                if (img != null)
                {
                    texture = img;
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
                return false;
            }
        }
Exemplo n.º 37
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;
            });
        }
Exemplo n.º 38
0
        /// <summary>
        /// Gets the next ordered packet from our buffer, or null if none are available
        /// </summary>
        /// <returns></returns>
        protected RTPPacket GetPacketInternal()
        {
            RTPPacket packetret = null;
            int       nNewSize  = 0;

            lock (PacketLock)
            {
                NewPacketEvent.Reset();

                if (Packets.Count <= 0)
                {
                    return(null);
                }

                if (IsQueueLargeEnough() == false) ///we may be growing our queue because of unavailable packets, take the audio hit all at once
                {
                    return(null);
                }

                if ((m_nCorrectOrientedPackets > 500) && (this.CurrentPacketQueueMinimumSize > InitialPacketQueueMinimumSize) && (Packets.Count > 1))
                {
                    // we can move our packet queue buffer back down because we've received enough packets in the correct order to have faith in the network connnection
                    // do this to decrease audio latency
                    m_nCorrectOrientedPackets = 0;
                    CurrentPacketQueueMinimumSize--;
                    System.Diagnostics.Debug.WriteLine("**********Decreasing jitter buffer size to {0}=>{1}", CurrentPacketQueueMinimumSize, CurrentMaxQueueSize);

                    Packets.RemoveAt(0);
                    m_nNextExpectedSequence = Packets[0].SequenceNumber;
                }


                packetret = Packets[0];
                int nSequenceCompare = CompareSequence(packetret.SequenceNumber, m_nNextExpectedSequence);


                if (nSequenceCompare > 0) //(packetret.SequenceNumber > m_nNextExpectedSequence)
                {
                    m_nCorrectOrientedPackets = 0;
                    Packets.RemoveAt(0);
                    m_nNextExpectedSequence = RTPPacket.GetNextSequence(packetret.SequenceNumber);

                    /// Increase our minimum size because our buffer is not big enough to handle the jitter if we can't find the right packet within it
                    ///
                    if (CurrentPacketQueueMinimumSize < (this.InitialPacketQueueMinimumSize + this.PacketSizeShiftMax))
                    {
                        CurrentPacketQueueMinimumSize++;
                        System.Diagnostics.Debug.WriteLine("**********Increasing jitter buffer size to {0}=>{1}", CurrentPacketQueueMinimumSize, CurrentMaxQueueSize);
                        m_bWaitingForQueueToGrow = true;
                    }
                }
                else if (nSequenceCompare == 0) //(packetret.SequenceNumber == m_nNextExpectedSequence)
                {
                    m_nCorrectOrientedPackets++;
                    Packets.RemoveAt(0);
                    m_nNextExpectedSequence = RTPPacket.GetNextSequence(packetret.SequenceNumber);
                    //System.Diagnostics.Debug.WriteLine("MATCH - retrieving packet {0}", packetret);
                }
                else
                {
                    /// packet sequence is before the expected value... should never happen
                    ///
                    Packets.RemoveAt(0);
                    System.Diagnostics.Debug.Assert(true);
                    packetret = null;
                }

                //if (packetret.SequenceNumber <= m_nNextExpectedSequence) /// Packet is the expected one, or before the expected one... should never happen since we don't add packets before the next expected one
                //{
                //    Packets.RemoveAt(0);
                //    m_nNextExpectedSequence = (ushort)(packetret.SequenceNumber + 1);
                //}
                //else if (Packets.Count == MaxQueueSize) // May have lost the desired packet.  We've waited all we can, get the lowest packet number
                //{
                //    Packets.RemoveAt(0);
                //    m_nNextExpectedSequence = (ushort)(packetret.SequenceNumber + 1);
                //}

                nNewSize = Packets.Count;
            }
            CurrentQueueSize = nNewSize;
            return(packetret);
        }
Exemplo n.º 39
0
 private void pauseProgramToolStripMenuItem_Click(object sender, EventArgs e)
 {
     resumeProgramToolStripMenuItem.Enabled = true;
     pauseProgramToolStripMenuItem.Enabled  = false;
     PauseEvent.Reset();
 }
Exemplo n.º 40
0
        /// <summary>
        /// Runs a MethodInvoker delegate on the UI thread from whichever thread we are currently calling from and BLOCKS until it is complete
        /// </summary>
        /// <param name="ivk"></param>
        public void UIBlockingInvoke(MethodInvoker ivk)
        {
            bool result;
            System.Threading.ManualResetEvent UIAsyncComplete = new System.Threading.ManualResetEvent(false);
            UIAsyncComplete.Reset();
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    try
                    {
                        ivk();
                    }
                    finally
                    {
                        UIAsyncComplete.Set();
                    }
                }));

                while (AppRunning)
                {
                    //Check AppRunning...
                    //Don't call WaitOne(int32)!!!  It was added in .NET framework 2.0 SERVICE PACK 2!!
                    //Instead call WaitOne(int32, false).  This works in .NET framework 2.0 RTM.
                    result = UIAsyncComplete.WaitOne(500, false);      //timeout after 500mS to check if AppRunning is still true
                    if (result)
                    {
                        break;  //Exit when UIAsyncComplete has been set OR if AppRunning becomes false.
                    }
                }
            }
            else
            {
                ivk();
            }
        }