Exemple #1
0
 public void TestDelete()
 {
     FileInfo file = new FileInfo(@"d:\X16-42552VS2010UltimTrial1.txt");
     AutoResetEvent are = new AutoResetEvent(false);
     string key = null;
     HttpCommunicate.Upload(file, (result, warning) =>
     {
         Console.WriteLine("result:" + result);
         key = result + "";
         are.Set();
     }, error =>
     {
         Console.WriteLine("error:" + error);
         are.Set();
     });
     are.WaitOne();
     are.Reset();
     FileDeletePackage package = new FileDeletePackage();
     package.key = key;
     HttpCommunicate.Request(package, (result, warning) =>
     {
         Console.WriteLine("file:" + result);
         are.Set();
     }, error =>
     {
         Console.WriteLine("error:" + error);
         are.Set();
     });
     are.WaitOne();
 }
Exemple #2
0
 void OnScriptThreadPause()
 {
     m_BreakPointLock.Reset();
     IsPaused = true;
     UpdateLayout();
     InvalidateVisual();
 }
Exemple #3
0
        private void CreateMainTask()
        {
            taskSimpleScheduler = new TaskSimpleScheduler();

            autoResetEvent.Reset();

            taskSimpleScheduler.StartNewTask("模拟业务", () =>
            {
                if (!this.IsStartSimulator)
                {
                    return;
                }

                // 心跳
                this.EquDber.Execute("update " + EntityReflectionUtil.GetTableName <EquQZDZYJSignal>() + " set TagValue=@TagValue where TagName=@TagName", new { TagName = GlobalVars.EquHeartbeatName, TagValue = DateTime.Now.ToString() });
                // 更新采样计划
                this.EquDber.Execute("update " + EntityReflectionUtil.GetTableName <EquQZDZYJPlan>() + " set DataFlag=1 where DataFlag=0");

                // 控制命令
                EquQZDZYJCmd pDCYJCmd = this.EquDber.Entity <EquQZDZYJCmd>("where DataFlag=0 order by CreateDate desc");
                if (pDCYJCmd != null)
                {
                    CmdHandle(pDCYJCmd);

                    autoResetEvent.WaitOne();
                }
            }, 3000);
        }
        /// <summary>
        /// 翻车业务逻辑入口
        /// </summary>
        private void CreateMainTask()
        {
            taskSimpleScheduler = new TaskSimpleScheduler();

            autoResetEvent.Reset();

            taskSimpleScheduler.StartNewTask("翻车业务逻辑", () =>
            {
                // 获取待处理的车号识别记录 - 入厂方向
                CmcsTrainCarriagePass inTrainCarriagePass = carriageRecognitionerDAO.GetUnHandleTrainCarriagePass(this.carriageRecognitionerMachineCode, eTrainPassDirection.进厂);
                if (inTrainCarriagePass != null)
                {
                    this.CurrentTrainCarriagePass = inTrainCarriagePass;

                    // 检测采样机系统的状态
                    string samplerSystemStatue = commonDAO.GetSignalDataValue(this.trainBeltSampler.EquipmentCode, eSignalDataName.系统.ToString());
                    if (samplerSystemStatue == eEquInfSamplerSystemStatus.发生故障.ToString() || samplerSystemStatue == eEquInfSamplerSystemStatus.正在卸样.ToString())
                    {
                        MessageBoxEx2Show("禁止翻车, " + this.trainBeltSampler.EquipmentName + "发生故障或正在卸样,已暂停运行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        btnStartTurnover.Enabled = true;

                        // 取消任务
                        this.taskSimpleScheduler.Cancal();

                        return;
                    }

                    StartTippingTask(this.CurrentTrainCarriagePass);

                    autoResetEvent.WaitOne();
                }
            }, 4000);
        }
        public void TestRefreshAmount()
        {
            var mock = new MockRepository();
              var getAmountEventReceived = new AutoResetEvent(false);

              var accountServiceMock = mock.StrictMock<IAccountService>();
              var getAmountResetEventMock = mock.StrictMock<AutoResetEvent>();

              var expectedAccountId = new Random().Next(100);
              var accountInfoToTest = new AccountInfo(expectedAccountId, accountServiceMock, getAmountResetEventMock);

              var expectedReturnAmount = new Random().NextDouble();
              Expect.Call(getAmountResetEventMock.WaitOne(0)).Return(true);
              Expect.Call(getAmountResetEventMock.WaitOne(0)).Return(false);
              Expect.Call(accountServiceMock.GetAccountAmount(expectedAccountId)).Return(expectedReturnAmount);
              Expect.Call(getAmountResetEventMock.Set()).Return(true).WhenCalled(MethodInvocation => getAmountEventReceived.Set());
              mock.ReplayAll();

              getAmountEventReceived.Reset();

              accountInfoToTest.RefreshAmount();
              accountInfoToTest.RefreshAmount();

              Assert.IsTrue(getAmountEventReceived.WaitOne(1000));
              Assert.AreEqual(expectedReturnAmount, accountInfoToTest.Amount);

              mock.VerifyAll();
        }
        public void CanCaptureAudio()
        {
            int n = 0;
            SoundInTests((c) =>
            {
                for (int i = 0; i < 500; i++)
                {
                    var waitHandle = new AutoResetEvent(true);

                    c.DataAvailable += (s, e) =>
                    {
                        waitHandle.Reset();
                    };

                    c.Initialize();
                    c.Start();

                    if (!waitHandle.WaitOne(2000))
                        Assert.Fail("Timeout");
                    else
                    {
                        Debug.WriteLine(n.ToString());
                        n++;
                    }

                    c.Stop();

                    waitHandle.Dispose();
                }
            });
        }
        public void Test_Add_and_Retrieve()
        {
            var testBooking = CreateTestBooking();

            Booking actual = null;
            var waiter = new AutoResetEvent(false);
            _client.AddBookingAsync(testBooking, booking =>
                {
                    actual = booking;
                    waiter.Set();
                });

            Assert.IsTrue(waiter.WaitOne(1000), "Timeout waiting for WCF asynk result");
            Assert.AreNotSame(testBooking, actual, "WCF trip over the wire should have created a new object through serialisation");

            //Test that Get the saved booking works over WCF
            IEnumerable<Booking> actualBookings = null;
            waiter.Reset();
            _client.GetBookingsAsync(DateTime.Now, bookings =>
            {
                actualBookings = bookings;
                waiter.Set();
            });

            Assert.IsTrue(waiter.WaitOne(1000), "Timeout waiting for WCF asynk result");

            var retrievedBooking = actualBookings.FirstOrDefault();
            Assert.IsNotNull(retrievedBooking, "Bookings should contain created booking");
            Assert.AreEqual(testBooking.Id, retrievedBooking.Id, "Id is not persisted corectly");
            Assert.AreEqual(testBooking.ClientName, retrievedBooking.ClientName, "ClientName is not persisted corectly");
            Assert.AreEqual(testBooking.Duration, retrievedBooking.Duration, "Duration is not persisted corectly");
            Assert.AreEqual(testBooking.Slot, retrievedBooking.Slot, "Slot is not persisted corectly");
        }
Exemple #8
0
        static void Main(string[] args)
        {
            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                // Add ChannelManager
                ChannelManagerService channelmgr = new ChannelManagerService();
                workflowRuntime.AddService(channelmgr);
                
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { Console.WriteLine("WorkflowCompleted: " + e.WorkflowInstance.InstanceId.ToString()); waitHandle.Set(); };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) { Console.WriteLine("WorkflowTerminated: " + e.Exception.Message); waitHandle.Set(); };

                while (true)
                {
                    WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(Microsoft.WorkflowServices.Samples.SequentialCalculatorClient));
                    Console.WriteLine("Start SequentialCalculatorClient.");
                    instance.Start();
                    waitHandle.WaitOne();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Do another calculation? (Y)");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Press <enter> to exit.");
                    Console.ResetColor();
                    string input = Console.ReadLine();
                    if (input.Length == 0 || input[0] != 'Y')
                        break;
                    waitHandle.Reset();
                }
            }
        }
        public Repository OpenRepositoryWithRetry(IAbsoluteDirectoryPath path, bool createWhenNotExisting = false,
            Action failAction = null) {
            if (createWhenNotExisting && !path.Exists)
                return new Repository(path, createWhenNotExisting);

            using (var autoResetEvent = new AutoResetEvent(false))
            using (var fileSystemWatcher =
                new FileSystemWatcher(path.ToString(), "*.lock") {
                    EnableRaisingEvents = true
                }) {
                var lockFile = path.GetChildFileWithName(Repository.LockFile);
                var fp = Path.GetFullPath(lockFile.ToString());
                fileSystemWatcher.Deleted +=
                    (o, e) => {
                        if (Path.GetFullPath(e.FullPath) == fp)
                            autoResetEvent.Set();
                    };

                while (true) {
                    using (var timer = UnlockTimer(lockFile, autoResetEvent)) {
                        try {
                            return new Repository(path, createWhenNotExisting);
                        } catch (RepositoryLockException) {
                            if (failAction != null)
                                failAction();
                            timer.Start();
                            autoResetEvent.WaitOne();
                            lock (timer)
                                timer.Stop();
                            autoResetEvent.Reset();
                        }
                    }
                }
            }
        }
Exemple #10
0
        public Pipe(Socket client, ApplicationEntity scp, ApplicationEntity scu, Assembly assembly, bool log)
        {
            this.client   = client;
            this.scp      = scp;
            this.assembly = assembly;
            this.log      = log;

            try
            {
                // connect to the SCP
                server          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                server.Blocking = true;
                server.Connect(new IPEndPoint(scp.Address, scp.Port));

                // get the SCP thread up and running
                scpthread      = new Thread(PipeThread);
                scpthread.Name = "Pipe.Scp.PipeThread";
                scpthread.Start(new Connection(scp.Title, server, client, log));

                if (!threadEvent.WaitOne(timeout, false))
                {
                    string message = "Pipe.Scp.Thread not started.";
                    Logging.Log(message);
                    throw new Exception(message);
                }

                threadEvent.Reset();

                // get the SCU thread up and running
                scuthread      = new Thread(PipeThread);
                scuthread.Name = "Pipe.Scu.PipeThread";
                scuthread.Start(new Connection(scu.Title, client, server, log));

                if (!threadEvent.WaitOne(timeout, false))
                {
                    string message = "Pipe.Scu.Thread not started.";
                    Logging.Log(message);
                    throw new Exception(message);
                }
            }
            catch
            {
                client = server = null;
                throw;
            }
        }
Exemple #11
0
    static void Func1(int counter)
    {
        Console.WriteLine("thread ({0}({1})) entered", "Func1", counter);

        CIMEvent.Reset();
        //CIMEvent.WaitOne();
        WaitOne((WaitHandle)CIMEvent, -1);

        Console.WriteLine("thread ({0}({1})) released", "Func1", counter);
    }
Exemple #12
0
		public PlaybackSurface()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();
			AREObj = new System.Threading.AutoResetEvent(false);
			AREObj.Reset();
			m_PlaybackControlList = new PlaybackControlList();
			m_bControlsVisible = true;
			txtTime.Text = "000000";
		}
Exemple #13
0
        public bool Connect(string host, int port)
        {
            IPEndPoint myEnd = null;

            #region ipformat
            try
            {
                myEnd = new IPEndPoint(IPAddress.Parse(host), port);
            }
            catch (FormatException)
            {
                IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName());

                foreach (IPAddress s in p.AddressList)
                {
                    if (!s.IsIPv6LinkLocal)
                    {
                        myEnd = new IPEndPoint(s, port);
                    }
                }
            }

            #endregion

            SocketAsyncEventArgs e = new SocketAsyncEventArgs()
            {
                RemoteEndPoint = myEnd
            };

            e.Completed += new EventHandler <SocketAsyncEventArgs>(Completed);
            AsynEvent    = e;
            if (!_sock.ConnectAsync(e))
            {
                ECompleted(e);
            }

            if (wait.WaitOne(ConnectTimeOut))
            {
                wait.Reset();

                return(IsConn);
            }
            else
            {
                this.Close();
                return(false);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="server">path to the server, like "http://privatenotes.dyndns-server.com"</param>
        /// <param name="path">path, starting fromt he server root-url, like "/webdav2/username/"</param>
        /// <param name="user">username for login</param>
        /// <param name="pass">pw for login</param>
        /// <param name="checkSSlCertificates">if true, an ssl certificate (if https is used) will be checked,
        /// if false, the ssl check will be ommited (has to be used for self-signed certificates etc)</param>
        public WebDAVInterface(String server, String path, String user, String pass, bool checkSSlCertificates)
        {
            //Logger.Debug("creating server " + server + " path " + path + " user " + user + " pass " + pass);
            client = new WebDAVClient();
            client.Server = server;
            client.BasePath = path;
            client.User = user;
            client.Pass = pass;
            client.SSLCertVerification = checkSSlCertificates;
            autoReset = new AutoResetEvent(false);
            autoReset.Reset();

            client.ListComplete += list;
            client.DownloadComplete += download;
            client.UploadComplete += upload;
            client.DeleteComplete += delete;
        }
        public virtual void ShouldAutomaticallyReleaseDataWhenThreadIsReturnedToThePool()
        {
            try
            {
                ThreadPool.SetMinThreads(1, 1);
                ThreadPool.SetMaxThreads(1, 1);
                var mainEvent = new AutoResetEvent(false);
                int? threadId = null;
                int? otherThreadId = null;
                object data = null;
                ThreadPool.QueueUserWorkItem(
                    delegate(object ev)
                    {
                        LogicContext.SetData("Test4", 100);
                        threadId = Thread.CurrentThread.ManagedThreadId;
                        ((AutoResetEvent)ev).Set();
                    }, 
                    mainEvent);

                mainEvent.WaitOne();

                mainEvent.Reset();

                Assert.IsNotNull(threadId);

                ThreadPool.QueueUserWorkItem(
                    delegate(object ev)
                    {
                        otherThreadId = Thread.CurrentThread.ManagedThreadId;
                        data = LogicContext.FindData("Test4");
                        ((AutoResetEvent)ev).Set();
                    }, 
                    mainEvent);
                mainEvent.WaitOne();

                Assert.IsNotNull(otherThreadId);
                Assert.AreEqual(threadId.Value, otherThreadId.Value);
                Assert.IsNull(data);
            }
            finally
            {
                ThreadPool.SetMinThreads(2, 2);
                ThreadPool.SetMaxThreads(1023, 1000);
            }
        }
        /// <summary>
        /// fire and forget
        /// </summary>
        /// <param name="millisecondsTimeout"></param>
        /// <param name="method"></param>
        public static void ExecuteMethodWithTimeout(int millisecondsTimeout, Action method)
        {
            AutoResetEvent timeoutEvent = new AutoResetEvent(false);
            Thread methodInvoker = new Thread(delegate()
            {
                method();
                timeoutEvent.Set();
            });

            timeoutEvent.Reset();
            methodInvoker.Start();

            if (timeoutEvent.WaitOne(millisecondsTimeout, false) == false)
            {
                methodInvoker.Abort();
                throw new TimeoutException();
            }
        }
        static void NLoopConsumeTest()
        {
            AutoResetEvent autoResetEvent = new AutoResetEvent(false); //声明 false, WaitOne时线程等待
            while (true)
            {
                autoResetEvent.Reset(); //WaitOne时,使线程等待
                //todo:从队列取数据

                //消费者
                Task.Run(() =>
                {
                    //todo:处理数据
                    autoResetEvent.Set(); //消费完成,允许线程继续
                });
                autoResetEvent.WaitOne(); //等待某个消费者空闲,线程等待

            }
        }
        public string ReadLine()
        {
            for (int i = 0; i < 5; i++)
            {
                lock (queue.SyncRoot) {
                    if (queue.Count > 0)
                    {
                        return((string)queue.Dequeue());
                    }

                    wait_event.Reset();
                }

                wait_event.WaitOne(3000, false);
            }

            return(null);
        }
        public lineAndScore findBestMoveWithTimeout(baseBoard boardToMove, int timeout)
        {
            findBestMoveBoard = boardToMove;
            Thread findThread = new Thread(findBestMoveWithTimeoutThread);
            evnt = new AutoResetEvent(false);
            evnt.Reset();
            findThread.Start();
            if (evnt.WaitOne(timeout, false))
            {
                if (ex != null)
                    throw ex;
                return bestLine;
            }

            findThread.Abort();

            throw new Exception("Player timeout");
        }
Exemple #20
0
 public void CopyFolder(InventoryFolder dest, InventoryFolder folder)
 {
     UUID newFolderID = Client.Inventory.CreateFolder(dest.UUID, folder.Name, AssetType.Unknown);
     Thread.Sleep(500);
     var items = Client.Inventory.FolderContents(folder.UUID, folder.OwnerID, true, true, InventorySortOrder.ByDate, 45 * 1000);
     AutoResetEvent copied = new AutoResetEvent(false);
     foreach (var item in items)
     {
         if (item is InventoryItem)
         {
             copied.Reset();
             Client.Inventory.RequestCopyItem(item.UUID, newFolderID, item.Name, folder.OwnerID, (InventoryBase target) =>
             {
                 Instance.TabConsole.DisplayNotificationInChat(string.Format("    * Copied {0} to {1}", item.Name, dest.Name));
                 copied.Set();
             });
             copied.WaitOne(15 * 1000, false);
         }
     }
 }
Exemple #21
0
        /// <summary>
        /// 发送存样柜命令并监听执行结果
        /// </summary>
        /// <returns></returns>
        private void SendCYGCmd(string MakeCode, string machineCode, eCZPLX OperType, string OperUser)
        {
            taskSimpleScheduler = new TaskSimpleScheduler();

            autoResetEvent.Reset();

            taskSimpleScheduler.StartNewTask("存样柜命令", () =>
            {
                this.IsWorking = true;

                // 发送取样命令
                if (autoCupboardDAO.SaveAutoCupboardCmd(MakeCode, machineCode, OperType, OperUser))
                {
                    ShowMessage(string.Format("{0}命令发送成功,等待存样柜执行", OperType), eOutputType.Normal);

                    int waitCount = 0;
                    eEquInfCYGCmdResultCode equInfCmdResultCode = eEquInfCYGCmdResultCode.默认;
                    do
                    {
                        Thread.Sleep(10000);
                        if (waitCount % 5 == 0)
                        {
                            ShowMessage("等待执行...执行结果:" + equInfCmdResultCode.ToString().Replace("默认", "执行中"), eOutputType.Normal);
                        }
                        waitCount++;

                        // 获取卸样命令的执行结果
                        equInfCmdResultCode = autoCupboardDAO.GetAutoCupboardResult(MakeCode);
                    }while (equInfCmdResultCode == eEquInfCYGCmdResultCode.气动执行成功);
                    ShowMessage(equInfCmdResultCode.ToString(), eOutputType.Important);
                }
                else
                {
                    ShowMessage("存样柜命令发送失败", eOutputType.Error);
                }

                autoResetEvent.Set();
            });
        }
Exemple #22
0
        static void Main(string[] args)
        {
            EventWaitHandle waitHandle = new AutoResetEvent(false);

            Worker worker1 = new Worker("Worker1", waitHandle);
            Worker worker2 = new Worker("Worker2", waitHandle);

            Console.WriteLine("press 'g' to start threads");
            Console.WriteLine("Press 'p' to pause threads");
            Console.WriteLine("Press 'q' to quit");

            Thread.Sleep(2000);

            worker1.Start();
            worker2.Start();

            while (true) {
                ConsoleKey key = Console.ReadKey(true).Key;
                switch (key) {
                    case ConsoleKey.G:
                        Console.WriteLine("starting...");
                        waitHandle.Set();
                        break;
                    case ConsoleKey.P:
                        Console.WriteLine("pausing...");
                        waitHandle.Reset();
                        break;
                    case ConsoleKey.Q:
                        Console.WriteLine("quitting...");
                        worker1.Stop();
                        worker2.Stop();
                        return;
                    default:
                        break;
                }
            }
        }
        /// <summary>
        /// wait for end of execution or timeout
        /// </summary>
        /// <param name="millisecondsTimeout"></param>
        /// <param name="method"></param>
        /// <returns>true if method executed in less than timeout</returns>
        public static bool ExecuteMethodWithTimeoutSync(int millisecondsTimeout, Action method)
        {
            AutoResetEvent timeoutEvent = new AutoResetEvent(false);
            var executed = false;
            Thread methodInvoker = new Thread(delegate()
            {
                method();
                timeoutEvent.Set();
                executed = true;
            });

            timeoutEvent.Reset();
            methodInvoker.Start();

            if (timeoutEvent.WaitOne(millisecondsTimeout, false) == false)
            {
                methodInvoker.Abort();
            }
            else
            {
                methodInvoker.Join();
            }
            return executed;
        }
 public bool run()
 {
     AutoResetEvent arEvent = new AutoResetEvent(true);
     arEvent.Reset();
     //
     int counter = this._methodStack.Count;
     //
     foreach (StackItem item in this._methodStack) {
         Worker wrk = new Worker(item);
         wrk.Completed += delegate(Object sender, EventArgs e) {
             counter--;
             if (counter == 0) {
                 arEvent.Set();
             }
         };
         //
         Thread t = new Thread(new ThreadStart(wrk.run));
         t.Start();
         //
         _workers.Add(wrk);
     }
     //
     return arEvent.WaitOne();
 }
        public override CmdResult ExecuteRequest(CmdRequest args)
        {
            if (args.Length != 1)
                return ShowUsage(); // " taskrunning objectID [[scriptName] true|false]";


            List<SimObject> PS;
            if (!args.TryGetValue("targets", out PS) || IsEmpty(PS as ICollection))
            {
                PS = WorldSystem.GetAllSimObjects();
            }

            string matching = args.GetString("match");
            string tf = args.GetString("set").ToLower();
            foreach (var found in PS)
            {
                uint objectLocalID = found.LocalID;
                UUID objectID = found.ID;


                List<InventoryBase> items = Client.Inventory.GetTaskInventory(objectID, objectLocalID, 1000*30);

                //bool wantSet = false;
                bool setTaskTo = false;
                if (items != null)
                {
                    string result = String.Empty;
                    bool setAny = false;
                    if (tf == "true")
                    {
                        setAny = true;
                        setTaskTo = true;
                    }
                    else if (tf == "false")
                    {
                        setAny = true;
                        setTaskTo = false;
                    }
                    bool wasRunning = false;

                    EventHandler<ScriptRunningReplyEventArgs> callback;
                    using (AutoResetEvent OnScriptRunningReset = new AutoResetEvent(false))
                    {
                        callback = ((s, e) =>
                                        {
                                            if (e.ObjectID == objectID)
                                            {
                                                result += String.Format(" IsMono: {0} IsRunning: {1}", e.IsMono,
                                                                        e.IsRunning);
                                                wasRunning = e.IsRunning;
                                                OnScriptRunningReset.Set();
                                            }
                                        });

                        Client.Inventory.ScriptRunningReply += callback;

                        for (int i = 0; i < items.Count; i++)
                        {
                            if (items[i] is InventoryFolder)
                            {
                                // this shouldn't happen this year
                                result += String.Format("[Folder] Name: {0}", items[i].Name) + Environment.NewLine;
                            }
                            else
                            {
                                InventoryItem item = (InventoryItem) items[i];
                                AssetType assetType = item.AssetType;
                                result += String.Format("[Item] Name: {0} Desc: {1} Type: {2}", item.Name,
                                                        item.Description,
                                                        assetType);
                                if (assetType == AssetType.LSLBytecode || assetType == AssetType.LSLText)
                                {
                                    OnScriptRunningReset.Reset();
                                    Client.Inventory.RequestGetScriptRunning(objectID, item.UUID);
                                    if (!OnScriptRunningReset.WaitOne(10000, true))
                                    {
                                        result += " (no script info)";
                                    }
                                    if (setAny && item.Name.Contains(matching))
                                    {
                                        if (wasRunning != setTaskTo)
                                        {
                                            OnScriptRunningReset.Reset();
                                            result += " Setting " + setTaskTo + " => ";
                                            Client.Inventory.RequestSetScriptRunning(objectID, item.UUID, setTaskTo);
                                            if (!OnScriptRunningReset.WaitOne(10000, true))
                                            {
                                                result += " (was not set)";
                                            }
                                        }
                                    }
                                }

                                result += Environment.NewLine;
                            }
                        }
                    }
                    Client.Inventory.ScriptRunningReply -= callback;
                    AddSuccess(result);
                }
                else
                {
                    Failure("failed to download task inventory for " + objectLocalID);
                }
            }
            return SuccessOrFailure();
        }
Exemple #26
0
            public async Task Lock(string path, Func<Task> action) {
                using (var autoResetEvent = new AutoResetEvent(false)) {
                    try {
                        using (var fileSystemWatcher =
                            new FileSystemWatcher(Path.GetDirectoryName(path)) {
                                EnableRaisingEvents = true
                            }) {
                            fileSystemWatcher.Deleted +=
                                (o, e) => {
                                    if (Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
                                        autoResetEvent.Set();
                                };

                            while (true) {
                                try {
                                    using (var file = File.Open(path,
                                        FileMode.OpenOrCreate,
                                        FileAccess.ReadWrite,
                                        FileShare.None)) {
                                        fileSystemWatcher.Dispose();
                                        autoResetEvent.Dispose();
                                        await action().ConfigureAwait(false);
                                        break;
                                    }
                                } catch (IOException) {
                                    autoResetEvent.WaitOne();
                                    autoResetEvent.Reset();
                                }
                            }
                        }
                    } finally {
                        File.Delete(path);
                    }
                }
            }
        /// <summary>
        /// File list has been built, now its time to crack open each file
        /// and count the code
        /// </summary>
        private void ProcessFileList()
        {
            // now we are ready to count the files
            CodeCounterEngine codeCounterEngine = new CodeCounterEngine();
            _eventReset = new AutoResetEvent(false);
            object lockObject = new object();

            // hook up finished even handler (required)
            codeCounterEngine.OnFinish += new CodeCounterFinishedEvent(OnCodeCountingFinished);

            if (0 < _listOfFiles.Count)
                Console.WriteLine(string.Format("counting {0} possible files", _listOfFiles.Count));

            // only add these event handlers if the user wanted output
            if (false == _quiet)
            {
                codeCounterEngine.OnStart += new CodeCounterUpdateEvent(OnCodeCountingStart);
                codeCounterEngine.OnUpdate += new CodeCounterUpdateEvent(OnCodeCountingUpdate);
            }

            // for each file in the array
            foreach (IScanForFilesData file in _listOfFiles)
            {
                try
                {
                    codeCounterEngine.File = file.FileInfo;

                    // clean everything up
                    while (true == Console.KeyAvailable)
                        Console.Read();

                    _spinnerPosition = 0;
                    _erasableTextLengh = 0;
                    _eventReset.Reset();

                    // make erasure execute on a separate thread
                    ThreadStart codeCountThreadStart = new ThreadStart(codeCounterEngine.Count);
                    Thread codeCountThread = new Thread(codeCountThreadStart);
                    codeCountThread.Name = "codeCountingThread worker";
                    codeCountThread.Start();

                    _eventReset.WaitOne();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    Console.WriteLine(ex.Message);
                }
            }
        }
Exemple #28
0
        public void SendUpdates() {
            Dictionary<string, AnalysisProgress> results = null;

            using (var ready = new AutoResetEvent(false))
            using (var listener = new AnalyzerStatusListener(r => { results = r; ready.Set(); })) {
                ready.Reset();
                listener.RequestUpdate();
                ready.WaitOne();
                Assert.IsNotNull(results);
                if (results.Count > 0) {
                    ready.Reset();
                    listener.RequestUpdate();
                    ready.WaitOne();
                    Assert.IsNotNull(results);
                    if (results.Count > 0) {
                        Console.WriteLine("WARNING: {0} results received from a previous test", results.Count);
                        Console.WriteLine("Keys are:");
                        foreach (var key in results.Keys) {
                            Console.WriteLine("    {0}", key);
                        }
                    }
                }

                using (var sender1 = new AnalyzerStatusUpdater("SendUpdates1"))
                using (var sender2 = new AnalyzerStatusUpdater("SendUpdates2")) {
                    // Block until workers have started
                    sender1.WaitForWorkerStarted();
                    sender1.ThrowPendingExceptions();
                    sender2.WaitForWorkerStarted();
                    sender2.ThrowPendingExceptions();

                    ready.Reset();
                    listener.RequestUpdate();
                    ready.WaitOne();
                    Assert.IsNotNull(results);
                    AssertUtil.ContainsAtLeast(results.Keys, "SendUpdates1", "SendUpdates2");
                    Assert.AreEqual(int.MaxValue, results["SendUpdates1"].Progress, "SendUpdates1.Progress not initialized to MaxValue");
                    Assert.AreEqual(0, results["SendUpdates1"].Maximum, "SendUpdates1.Maximum not initialized to 0");
                    Assert.AreEqual(string.Empty, results["SendUpdates1"].Message, "SendUpdates1.Message not initialized to empty");
                    Assert.AreEqual(int.MaxValue, results["SendUpdates2"].Progress, "SendUpdates2.Progress not initialized to MaxValue");
                    Assert.AreEqual(0, results["SendUpdates2"].Maximum, "SendUpdates2.Maximum not initialized to 0");
                    Assert.AreEqual(string.Empty, results["SendUpdates2"].Message, "SendUpdates2.Message not initialized to empty");

                    sender1.UpdateStatus(100, 200, "Message1");
                    sender1.FlushQueue(TimeSpan.FromSeconds(1.0));

                    ready.Reset();
                    listener.RequestUpdate();
                    ready.WaitOne();
                    Assert.AreEqual(100, results["SendUpdates1"].Progress, "SendUpdates1.Progress not set to 100");
                    Assert.AreEqual(200, results["SendUpdates1"].Maximum, "SendUpdates1.Maximum not set to 200");
                    Assert.AreEqual("Message1", results["SendUpdates1"].Message, "SendUpdates1.Message not set");
                    Assert.AreEqual(int.MaxValue, results["SendUpdates2"].Progress, "SendUpdates2.Progress changed from MaxValue");
                    Assert.AreEqual(0, results["SendUpdates2"].Maximum, "SendUpdates2.Maximum changed from 0");
                    Assert.AreEqual(string.Empty, results["SendUpdates2"].Message, "SendUpdates2.Message changed from empty");

                    sender2.UpdateStatus(1000, 2000, "Message2");
                    sender2.FlushQueue(TimeSpan.FromSeconds(1.0));

                    ready.Reset();
                    listener.RequestUpdate();
                    ready.WaitOne();
                    Assert.AreEqual(100, results["SendUpdates1"].Progress, "SendUpdates1.Progress changed from 100");
                    Assert.AreEqual(200, results["SendUpdates1"].Maximum, "SendUpdates1.Maximum changed from 200");
                    Assert.AreEqual("Message1", results["SendUpdates1"].Message, "SendUpdates1.Message changed");
                    Assert.AreEqual(1000, results["SendUpdates2"].Progress, "SendUpdates2.Progress not set to 1000");
                    Assert.AreEqual(2000, results["SendUpdates2"].Maximum, "SendUpdates2.Maximum not set to 2000");
                    Assert.AreEqual("Message2", results["SendUpdates2"].Message, "SendUpdates2.Message not set");
                }

                Thread.Sleep(100); // allow updaters to terminate
                ready.Reset();
                listener.RequestUpdate();
                ready.WaitOne();
                Assert.IsNotNull(results);
                if (results.Count > 0) {
                    Console.WriteLine("WARNING: {0} results exist at end of test", results.Count);
                    Console.WriteLine("Keys are:");
                    foreach (var key in results.Keys) {
                        Console.WriteLine("    {0}", key);
                    }
                }
                Assert.IsFalse(results.ContainsKey("SendUpdates1"), "results were not cleaned up");
                Assert.IsFalse(results.ContainsKey("SendUpdates2"), "results were not cleaned up");
            }
        }
Exemple #29
0
        private void CheckTimerThread()
        {
#if !MONO
            timeBeginPeriod(1);
#endif

            Stopwatch watch = new Stopwatch();
            watch.Start();
            long nNextDueTimeInMs = 0;

#if !WINDOWS_PHONE
            System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
#endif

            while (true)
            {
                int nHandle = WaitHandle.WaitTimeout;

                /// See how long until the next timer is due

                if (nNextDueTimeInMs < 0)
                {
                    nNextDueTimeInMs = 0;
                }
                else if (nNextDueTimeInMs > TimerCheck)
                {
                    nNextDueTimeInMs = TimerCheck;
                }

                //Thread.SpinWait(
                if (nNextDueTimeInMs > (PeriodicTimerWatch.AccuracyAndLag + SystemTimerInaccuracyTimeMs))
                {
#if !WINDOWS_PHONE
                    nHandle = WaitHandle.WaitAny(new WaitHandle[] { EventNewTimer }, (int)(nNextDueTimeInMs - SystemTimerInaccuracyTimeMs), true);
#else
                    nHandle = WaitHandle.WaitAny(new WaitHandle[] { EventNewTimer }, (int)(nNextDueTimeInMs - SystemTimerInaccuracyTimeMs));
#endif
                }
                else if (nNextDueTimeInMs > 0)
                {
                    /// Loop instead of waiting at this point until our next time out
                    while (watch.ElapsedMilliseconds < nNextDueTimeInMs)
                    {
                        /// Do nothing but take up CPU
                        ///
                        /// Changed by B.B. 10-28-2009
                        /// We don't really need this to be super accurate, so we'll sleep a little here and see if it has
                        /// any negative affects
                        ///
                        Thread.Sleep(1);
                    }
                }

                try
                {
                    if (nHandle == WaitHandle.WaitTimeout) // Timer elapsed
                    {
                        List <PeriodicTimerWatch> alTimersFire = new List <PeriodicTimerWatch>();
                        lock (GlobalWatchesLock)
                        {
                            if (GlobalWatchesSorted.Count == 0) /// no timers, no need to check until we get signaled
                            {
                                nNextDueTimeInMs = TimerCheck;
                                watch.Reset();
                                watch.Start();
                                continue;
                            }

                            foreach (PeriodicTimerWatch nextTimer in GlobalWatchesSorted)
                            {
                                if (nextTimer.Expired == true)
                                {
                                    alTimersFire.Add(nextTimer);
                                }
                                else
                                {
                                    nNextDueTimeInMs = nextTimer.GetTimeToNextFireMs();
                                    watch.Reset();
                                    watch.Start();
                                    break;
                                }
                            }

                            if (alTimersFire.Count > 0)
                            {
                                foreach (PeriodicTimerWatch nextTimer in alTimersFire)
                                {
                                    nextTimer.Fire();
                                }

                                lock (GlobalWatchesLock)
                                {
                                    foreach (PeriodicTimerWatch nextwatch in GlobalWatchesSorted)
                                    {
                                        nextwatch.LockTimeForSort();
                                    }
                                    GlobalWatchesSorted.Sort(); /// Resort
                                                                ///
                                    if (GlobalWatchesSorted.Count > 0)
                                    {
                                        nNextDueTimeInMs = GlobalWatchesSorted[0].GetTimeToNextFireMs();
                                        watch.Reset();
                                        watch.Start();
                                    }
                                    EventNewTimer.Reset(); // we are again sorted... ignore added event
                                }
                            }
                        }
                    }
                    else if (nHandle == 0) /// new item added or removed
                    {
                        lock (GlobalWatchesLock)
                        {
                            if (GlobalWatchesSorted.Count > 0)
                            {
                                nNextDueTimeInMs = GlobalWatchesSorted[0].GetTimeToNextFireMs();
                                watch.Reset();
                                watch.Start();
                            }
                            else
                            {
                                nNextDueTimeInMs = TimerCheck;
                                watch.Reset();
                                watch.Start();
                            }
                        }
                    }
                }
                catch (System.Exception)
                {
                }
            }
        }
        public void TestScriptCrossOnSameSimulator()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            UUID userId = TestHelpers.ParseTail(0x1);
            int sceneObjectIdTail = 0x2;

            EntityTransferModule etmA = new EntityTransferModule();
            EntityTransferModule etmB = new EntityTransferModule();
            LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
            XEngine xEngineA = new XEngine();
            XEngine xEngineB = new XEngine();
            xEngineA.DebugLevel = 1;
            xEngineB.DebugLevel = 1;

            IConfigSource configSource = new IniConfigSource();

            IConfig startupConfig = configSource.AddConfig("Startup");
            startupConfig.Set("DefaultScriptEngine", "XEngine");
            startupConfig.Set("TrustBinaries", "true");

            IConfig xEngineConfig = configSource.AddConfig("XEngine");
            xEngineConfig.Set("Enabled", "true");
            xEngineConfig.Set("StartDelay", "0");

            // These tests will not run with AppDomainLoading = true, at least on mono.  For unknown reasons, the call
            // to AssemblyResolver.OnAssemblyResolve fails.
            xEngineConfig.Set("AppDomainLoading", "false");

            IConfig modulesConfig = configSource.AddConfig("Modules");
            modulesConfig.Set("EntityTransferModule", etmA.Name);
            modulesConfig.Set("SimulationServices", lscm.Name);

            SceneHelpers sh = new SceneHelpers();
            TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000, configSource);
            TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999, configSource);

            SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, configSource, lscm);
            SceneHelpers.SetupSceneModules(sceneA, configSource, etmA, xEngineA);
            SceneHelpers.SetupSceneModules(sceneB, configSource, etmB, xEngineB);
            sceneA.StartScripts();
            sceneB.StartScripts();

            SceneObjectGroup soSceneA = SceneHelpers.AddSceneObject(sceneA, 1, userId, "so1-", sceneObjectIdTail);
            soSceneA.AbsolutePosition = new Vector3(128, 10, 20);

            string soSceneAName = soSceneA.Name;
            string scriptItemSceneAName = "script1";

            // CREATE SCRIPT TODO
            InventoryItemBase scriptItemSceneA = new InventoryItemBase();
            //            itemTemplate.ID = itemId;
            scriptItemSceneA.Name = scriptItemSceneAName;
            scriptItemSceneA.Folder = soSceneA.UUID;
            scriptItemSceneA.InvType = (int)InventoryType.LSL;

            AutoResetEvent chatEvent = new AutoResetEvent(false);
            OSChatMessage messageReceived = null;
            sceneA.EventManager.OnChatFromWorld += (s, m) => { messageReceived = m; chatEvent.Set(); };

            sceneA.RezNewScript(userId, scriptItemSceneA, 
@"integer c = 0;

default
{    
    state_entry()
    {
        llSay(0, ""Script running"");
    }

    changed(integer change)
    {
        llSay(0, ""Changed"");
    }

    touch_start(integer n)
    {
        c = c + 1; 
        llSay(0, (string)c);
    }
}");

            chatEvent.WaitOne(60000);

            Assert.That(messageReceived, Is.Not.Null, "No chat message received.");
            Assert.That(messageReceived.Message, Is.EqualTo("Script running"));           

            {
                // XXX: Should not be doing this so directly.  Should call some variant of EventManager.touch() instead.
                DetectParams[] det = new DetectParams[1];
                det[0] = new DetectParams();
                det[0].Key = userId;
                det[0].Populate(sceneA);

                EventParams ep = new EventParams("touch_start", new Object[] { new LSL_Types.LSLInteger(1) }, det);

                messageReceived = null;
                chatEvent.Reset();
                xEngineA.PostObjectEvent(soSceneA.LocalId, ep);
                chatEvent.WaitOne(60000);

                Assert.That(messageReceived.Message, Is.EqualTo("1")); 
            }

            AutoResetEvent chatEventB = new AutoResetEvent(false);
            sceneB.EventManager.OnChatFromWorld += (s, m) => { messageReceived = m; chatEventB.Set(); };

            messageReceived = null;
            chatEventB.Reset();
            // Cross with a negative value
            soSceneA.AbsolutePosition = new Vector3(128, -10, 20);

            chatEventB.WaitOne(60000);
            Assert.That(messageReceived, Is.Not.Null, "No Changed message received.");
            Assert.That(messageReceived.Message, Is.Not.Null, "Changed message without content");
            Assert.That(messageReceived.Message, Is.EqualTo("Changed")); 

            // TEST sending event to moved prim and output
            {
                SceneObjectGroup soSceneB = sceneB.GetSceneObjectGroup(soSceneAName);
                TaskInventoryItem scriptItemSceneB = soSceneB.RootPart.Inventory.GetInventoryItem(scriptItemSceneAName);

                // XXX: Should not be doing this so directly.  Should call some variant of EventManager.touch() instead.
                DetectParams[] det = new DetectParams[1];
                det[0] = new DetectParams();
                det[0].Key = userId;
                det[0].Populate(sceneB);

                EventParams ep = new EventParams("touch_start", new Object[] { new LSL_Types.LSLInteger(1) }, det);

                Thread.Sleep(250); // wait for other change messages to pass
                messageReceived = null;
                chatEventB.Reset();
                xEngineB.PostObjectEvent(soSceneB.LocalId, ep);
                chatEventB.WaitOne(60000);

                Assert.That(messageReceived.Message, Is.EqualTo("2")); 
            }
        }
Exemple #31
0
        public void UserTaskExceptionTest()
        {
            Exception e = null;
            AutoResetEvent even = new AutoResetEvent(false);

            int y = 0;
            int t = 0;
            Arbitr<Message, NOPMessage> a = null;
            a = new Arbitr<Message, NOPMessage>(
                (z) =>
                {
                    y += z.x;
                    if (a != null)
                        a.AddUserTaskToLine(new Task(() =>
                        {
                            t = 1 / t;

                        }));

                },
                (z) =>
                {
                    e = z;
                    even.Set();
                });

            even.Reset();
            a.Send(new Message() { x = 1 });
            bool completed = even.WaitOne();
            Assert.AreEqual(y, 1);

            Assert.IsTrue(completed);
            Assert.AreEqual(t, 0);
            Assert.IsNotNull(e);
        }
        /// <summary>
        /// 监听皮带采样机返回结果
        /// </summary>
        /// <returns></returns>
        private void SendBeltSamplerUnloadCmd()
        {
            taskSimpleScheduler = new TaskSimpleScheduler();

            autoResetEvent.Reset();

            taskSimpleScheduler.StartNewTask("卸样业务逻辑", () =>
            {
                this.IsWorking = true;

                // 发送卸样命令
                if (beltSamplerDAO.SendSampleUnloadCmd(this.CurrentSampler.EquipmentCode, this.CurrentRCSampling.Id, this.currentSampleCode, (eEquInfSamplerUnloadType)Convert.ToInt16(flpanUnloadType.Controls.OfType <RadioButton>().First(a => a.Checked).Tag), out this.currentUnloadCmdId))
                {
                    rTxtOutputer.Output("卸样命令发送成功,等待采样机执行", eOutputType.Normal);

                    int waitCount = 0;
                    eEquInfCmdResultCode equInfCmdResultCode;
                    do
                    {
                        Thread.Sleep(10000);
                        if (waitCount % 5 == 0)
                        {
                            rTxtOutputer.Output("正在等待采样机返回结果", eOutputType.Normal);
                        }

                        waitCount++;

                        // 获取卸样命令的执行结果
                        equInfCmdResultCode = UnloadSamplerDAO.GetInstance().GetBeltUnloadSamplerState(this.currentUnloadCmdId);
                    }while (equInfCmdResultCode == eEquInfCmdResultCode.默认);

                    if (equInfCmdResultCode == eEquInfCmdResultCode.成功)
                    {
                        rTxtOutputer.Output("采样机返回:卸样成功", eOutputType.Normal);

                        // 检测制样机系统状态
                        if (rbtnToMaker.Checked)
                        {
                            string makerSystemStatus = commonDAO.GetSignalDataValue(this.makerMachineCode, eSignalDataName.系统.ToString());
                            if (makerSystemStatus == eEquInfSamplerSystemStatus.就绪待机.ToString())
                            {
                                if (MessageBoxEx.Show("卸样成功,检测到制样机已就绪,立刻开始制样?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                                {
                                    if (SendMakePlan(this.CurrentRCSampling.Id, this.CurrentRCSampling.InFactoryBatchId))
                                    {
                                        rTxtOutputer.Output("制样命令发送成功", eOutputType.Normal);
                                    }
                                    else
                                    {
                                        rTxtOutputer.Output("制样命令发送失败", eOutputType.Error);
                                    }
                                }
                            }
                        }
                    }
                    else if (equInfCmdResultCode == eEquInfCmdResultCode.失败)
                    {
                        rTxtOutputer.Output("采样机返回:卸样失败", eOutputType.Error);
                    }
                }
                else
                {
                    rTxtOutputer.Output("卸样命令发送失败", eOutputType.Error);
                }

                this.IsWorking = false;

                LoadSampleBarrel(superGridControl1, this.CurrentSampler.EquipmentCode);
                LoadLatestSampleUnloadCmd(this.CurrentSampler);

                autoResetEvent.Set();
            });
        }
Exemple #33
0
        /// <summary>
        /// 监听采样机返回结果
        /// </summary>
        /// <returns></returns>
        private void SendSamplerUnloadCmd()
        {
            taskSimpleScheduler = new TaskSimpleScheduler();

            autoResetEvent.Reset();

            taskSimpleScheduler.StartNewTask("卸样业务逻辑", () =>
            {
                this.IsWorking = true;

                if (rbtnToMaker.Checked)
                {
                    #region 启动制样进料皮带
                    if (beltSamplerDAO.SendPDUnLoadCmd(this.CurrentMaker, "开始卸料"))
                    {
                        rTxtOutputer.Output("卸样皮带命令发送成功,等待制样机执行", eOutputType.Normal);

                        int waitCount = 0;
                        eEquInfCmdResultCode equInfCmdResultCode;
                        do
                        {
                            Thread.Sleep(10000);
                            if (waitCount % 5 == 0)
                            {
                                rTxtOutputer.Output("正在等待制样机返回结果", eOutputType.Normal);
                            }

                            waitCount++;

                            // 获取卸样命令的执行结果
                            equInfCmdResultCode = UnloadSamplerDAO.GetInstance().GetPDUnloadState();
                        }while (equInfCmdResultCode == eEquInfCmdResultCode.默认);
                        if (equInfCmdResultCode == eEquInfCmdResultCode.成功)
                        {
                            rTxtOutputer.Output("制样机返回:皮带启动成功", eOutputType.Normal);
                        }
                        else if (equInfCmdResultCode == eEquInfCmdResultCode.失败)
                        {
                            rTxtOutputer.Output("制样机返回:执行失败", eOutputType.Error);
                        }
                    }
                    else
                    {
                        rTxtOutputer.Output("卸样皮带命令发送失败", eOutputType.Error);
                    }
                    #endregion
                }

                #region 发送采样机卸样命令
                // 发送卸样命令
                if (beltSamplerDAO.SendSampleUnloadCmd(this.currentSampler.EquipmentCode, this.CurrentRCSampling.Id, this.currentSampleCode, (eEquInfSamplerUnloadType)Convert.ToInt16(flpanUnloadType.Controls.OfType <RadioButton>().First(a => a.Checked).Tag), out this.currentUnloadCmdId))
                {
                    rTxtOutputer.Output("卸样命令发送成功,等待采样机执行", eOutputType.Normal);

                    int waitCount = 0;
                    eEquInfCmdResultCode equInfCmdResultCode;
                    do
                    {
                        Thread.Sleep(10000);
                        if (waitCount % 5 == 0)
                        {
                            rTxtOutputer.Output("正在等待采样机返回结果", eOutputType.Normal);
                        }

                        waitCount++;

                        // 获取卸样命令的执行结果
                        equInfCmdResultCode = UnloadSamplerDAO.GetInstance().GetUnloadSamplerState(this.currentUnloadCmdId);
                    }while (equInfCmdResultCode == eEquInfCmdResultCode.默认);

                    if (equInfCmdResultCode == eEquInfCmdResultCode.成功)
                    {
                        rTxtOutputer.Output("采样机返回:卸样成功", eOutputType.Normal);
                    }
                    else if (equInfCmdResultCode == eEquInfCmdResultCode.失败)
                    {
                        rTxtOutputer.Output("采样机返回:卸样失败", eOutputType.Error);
                        return;
                    }
                }
                else
                {
                    rTxtOutputer.Output("卸样命令发送失败", eOutputType.Error);
                    return;
                }
                #endregion

                #region 停止制样机进料皮带
                if (beltSamplerDAO.SendPDUnLoadCmd(this.CurrentMaker, "停止卸料"))                //卸样完成后 卸料皮带停止
                {
                    rTxtOutputer.Output("卸样皮带停止命令发送成功,等待制样机执行", eOutputType.Normal);
                    int waitCount = 0;
                    eEquInfCmdResultCode equInfCmdResultCode;
                    do
                    {
                        Thread.Sleep(10000);
                        if (waitCount % 5 == 0)
                        {
                            rTxtOutputer.Output("正在等待制样机返回结果", eOutputType.Normal);
                        }

                        waitCount++;

                        // 获取卸样命令的执行结果
                        equInfCmdResultCode = UnloadSamplerDAO.GetInstance().GetPDUnloadState();
                    }while (equInfCmdResultCode == eEquInfCmdResultCode.默认);
                    if (equInfCmdResultCode == eEquInfCmdResultCode.成功)
                    {
                        rTxtOutputer.Output("制样机返回:皮带停止成功", eOutputType.Normal);
                    }
                    else if (equInfCmdResultCode == eEquInfCmdResultCode.失败)
                    {
                        rTxtOutputer.Output("制样机返回:执行失败", eOutputType.Error);
                        return;
                    }
                }
                else
                {
                    rTxtOutputer.Output("卸样皮带命令发送失败", eOutputType.Error);
                    return;
                }
                #endregion

                #region 检测制样机状态,若已就绪提示发送制样计划
                // 检测制样机系统状态
                if (rbtnToMaker.Checked && this.currentEquInfSampleBarrels != null && this.currentEquInfSampleBarrels[0].BarrelType == "底卸式")
                {
                    string makerSystemStatus = commonDAO.GetSignalDataValue(this.CurrentMaker, eSignalDataName.设备状态.ToString());
                    if (makerSystemStatus == eEquInfSamplerSystemStatus.就绪待机.ToString())
                    {
                        if (MessageBoxEx.Show("卸样成功,检测到制样机已就绪,立刻开始制样?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                        {
                            if (SendMakePlan(this.CurrentRCSampling.SampleCode, this.CurrentRCSampling.InFactoryBatchId))
                            {
                                rTxtOutputer.Output("制样命令发送成功", eOutputType.Normal);
                            }
                            else
                            {
                                rTxtOutputer.Output("制样命令发送失败", eOutputType.Error);
                            }
                        }
                    }
                }
                #endregion

                this.IsWorking = false;

                LoadBeltSampleBarrel(superGridControl1, this.CurrentSampler.EquipmentCode);
                LoadLatestSampleUnloadCmd(this.CurrentSampler.EquipmentCode);

                autoResetEvent.Set();
            });
        }
        /// <summary>
        /// 发送存样柜命令并监听执行结果
        /// </summary>
        /// <returns></returns>
        private void SendCYGCmd(List <String> MakeCodes, String OperType, string OperUser, string machineCode)
        {
            taskSimpleScheduler = new TaskSimpleScheduler();

            autoResetEvent.Reset();

            taskSimpleScheduler.StartNewTask("存样柜命令", () =>
            {
                this.IsWorking = true;

                // 发送取样命令
                if (!string.IsNullOrEmpty(autoCupboardDAO.AddAutoCupboard(MakeCodes, OperType, OperUser, machineCode)))
                {
                    //pneumaticTransferDAO.SaveQDCmd();
                    ShowMessage(string.Format("{0}命令发送成功,等待存样柜执行", OperType), eOutputType.Normal);

                    int waitCount = 0;
                    eEquInfCmdResultCode equInfCmdResultCode;
                    do
                    {
                        Thread.Sleep(10000);
                        if (waitCount % 5 == 0)
                        {
                            ShowMessage("正在等待存样柜返回结果", eOutputType.Normal);
                        }

                        waitCount++;

                        // 获取卸样命令的执行结果
                        equInfCmdResultCode = autoCupboardDAO.GetAutoCupboardResult(MakeCodes[0]);
                    }while (equInfCmdResultCode == eEquInfCmdResultCode.默认);

                    if (equInfCmdResultCode == eEquInfCmdResultCode.成功)
                    {
                        ShowMessage("存样柜返回:执行成功", eOutputType.Normal);
                        if (SendQDCSCmd(MakeCodes[0], machineCode))
                        {
                            do
                            {
                                Thread.Sleep(10000);
                                if (waitCount % 5 == 0)
                                {
                                    ShowMessage("正在等待气动传输返回结果", eOutputType.Normal);
                                }

                                waitCount++;

                                // 获取卸样命令的执行结果
                                equInfCmdResultCode = pneumaticTransferDAO.GetQDCSResult(MakeCodes[0]);
                            }while (equInfCmdResultCode == eEquInfCmdResultCode.默认);
                        }
                        if (equInfCmdResultCode == eEquInfCmdResultCode.成功)
                        {
                            ShowMessage("气动传输返回:执行成功", eOutputType.Normal);
                        }
                    }
                }
                else
                {
                    ShowMessage("存样柜命令发送失败", eOutputType.Error);
                }

                autoResetEvent.Set();
            });
        }
Exemple #35
0
        public void TestSubDelTaskCountBasic()
        {
            var opts = utils.DefaultTestOptions;

            Assert.Throws<ArgumentOutOfRangeException>(
                () => { opts.SubscriberDeliveryTaskCount = -1; });

            opts.SubscriberDeliveryTaskCount = 2;

            using (new NATSServer())
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    int s1Count = 0;
                    int s2Count = 0;
                    int COUNT = 10;

                    AutoResetEvent ev1 = new AutoResetEvent(false);
                    AutoResetEvent ev2 = new AutoResetEvent(false);

                    IAsyncSubscription s1 = c.SubscribeAsync("foo", (obj, args) =>
                    {
                        s1Count++;
                        if (s1Count == COUNT)
                        {
                            ev1.Set();
                        }
                    });

                    IAsyncSubscription s2 = c.SubscribeAsync("bar", (obj, args) =>
                    {
                        s2Count++;
                        if (s2Count >= COUNT)
                        {
                            ev2.Set();
                        }
                    });

                    for (int i = 0; i < 10; i++)
                    {
                        c.Publish("foo", null);
                        c.Publish("bar", null);
                    }
                    c.Flush();

                    Assert.True(ev1.WaitOne(10000));
                    Assert.True(ev2.WaitOne(10000));
                    s1.Unsubscribe();

                    Assert.True(s1Count == COUNT);
                    Assert.True(s2Count == COUNT);

                    ev2.Reset();

                    c.Publish("bar", null);
                    c.Flush();

                    Assert.True(ev2.WaitOne(10000));
                    Assert.True(s2Count == COUNT + 1);

                    s2.Unsubscribe();
                }
            }
        }
Exemple #36
0
        public void TestEncodedObjectSerization()
        {
            using (new NATSServer())
            {
                using (IEncodedConnection c = DefaultEncodedConnection)
                {
                    c.OnDeserialize = jsonDeserializer;
                    c.OnSerialize = jsonSerializer;

                    AutoResetEvent ev = new AutoResetEvent(false);
                    JsonObject jo = new JsonObject("bar");

                    EventHandler<EncodedMessageEventArgs> eh = (sender, args) =>
                    {
                        Assert.True(args.ReceivedObject.Equals(jo));
                        ev.Set();
                    };

                    using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                    {
                        for (int i = 0; i < 10; i++)
                            c.Publish("foo", jo);

                        c.Flush();

                        Assert.True(ev.WaitOne(1000));
                    }

                    ev.Reset();
                    using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                    {
                        c.Publish("foo", "bar", jo);
                        c.Flush();

                        Assert.True(ev.WaitOne(1000));
                    }
                }
            }
        }
Exemple #37
0
		public void CanBroadcastTransaction()
		{
			using(NodeServerTester servers = new NodeServerTester(Network.TestNet))
			{
				var notifiedTransactions = new List<WalletTransaction>();
				var chainBuilder = new BlockchainBuilder();
				SetupSPVBehavior(servers, chainBuilder);
				var tx = new Transaction();
				Wallet wallet = new Wallet(new WalletCreation()
				{
					Network = Network.TestNet,
					RootKeys = new[] { new ExtKey().Neuter() },
					UseP2SH = false
				}, keyPoolSize: 11);
				NodesGroup connected = CreateGroup(servers, 2);
				wallet.Configure(connected);
				wallet.Connect();

				AutoResetEvent evt = new AutoResetEvent(false);
				bool passed = false;
				bool rejected = false;
				var broadcasting = wallet.BroadcastTransactionAsync(tx);
				wallet.TransactionBroadcasted += (t) =>
				{
					evt.Set();
					passed = true;
				};
				wallet.TransactionRejected += (t, r) =>
				{
					evt.Set();
					rejected = true;
				};
				BroadcastHub hub = BroadcastHub.GetBroadcastHub(connected.NodeConnectionParameters);
				BroadcastHubBehavior behavior = null;
				while(behavior == null || behavior.AttachedNode.State != NodeState.HandShaked)
				{
					behavior = connected.ConnectedNodes.Select(n => n.Behaviors.Find<BroadcastHubBehavior>()).FirstOrDefault();
					Thread.Sleep(1);
				}
				Assert.Equal(1, behavior.Broadcasts.Count());
				Assert.Equal(1, hub.BroadcastingTransactions.Count());
				Assert.True(evt.WaitOne(20000));
				Assert.True(passed);
				evt.Reset();
				Assert.Equal(0, behavior.Broadcasts.Count());
				Assert.Equal(0, hub.BroadcastingTransactions.Count());
				Assert.Null(broadcasting.Result);

				broadcasting = wallet.BroadcastTransactionAsync(tx);
				Assert.Equal(1, behavior.Broadcasts.Count());
				Assert.True(evt.WaitOne(20000));
				Assert.True(rejected);
				Assert.Equal(0, behavior.Broadcasts.Count());
				Assert.Equal(0, hub.BroadcastingTransactions.Count());
				Assert.NotNull(broadcasting.Result);
			}
		}
Exemple #38
0
        /// <summary>发送并接收消息。主要用于应答式的请求和响应。</summary>
        /// <remarks>如果内部实现是异步模型,则等待指定时间获取异步返回的第一条消息,该消息不再触发消息到达事件<see cref="OnReceived"/>。</remarks>
        /// <param name="message"></param>
        /// <param name="millisecondsTimeout">等待的毫秒数,或为 <see cref="F:System.Threading.Timeout.Infinite" /> (-1),表示无限期等待。默认0表示不等待</param>
        /// <returns></returns>
        public virtual Message SendAndReceive(Message message, Int32 millisecondsTimeout = 0)
        {
            Send(message);

            var _wait = new AutoResetEvent(true);
            _wait.Reset();

            Message msg = null;
            innerOnReceived += (s, e) => { msg = e.Message; _wait.Set(); };

            //if (!_wait.WaitOne(millisecondsTimeout, true)) return null;

            _wait.WaitOne(millisecondsTimeout, false);
            _wait.Close();

            return msg;
        }
Exemple #39
0
        public void MessageMaximumLength() {
            Dictionary<string, AnalysisProgress> results = null;

            using (var ready = new AutoResetEvent(false))
            using (var listener = new AnalyzerStatusListener(r => { results = r; ready.Set(); })) {
                listener.WaitForWorkerStarted();
                listener.ThrowPendingExceptions();

                // Ensure that updates are being received
                listener.RequestUpdate();
                ready.WaitOne();
                Assert.IsNotNull(results);
                if (results.Count > 0) {
                    ready.Reset();
                    listener.RequestUpdate();
                    ready.WaitOne();
                    Assert.IsNotNull(results);
                    if (results.Count > 0) {
                        Console.WriteLine("WARNING: {0} results received from a previous test", results.Count);
                        Console.WriteLine("Keys are:");
                        foreach (var key in results.Keys) {
                            Console.WriteLine("    {0}", key);
                        }
                    }
                }

                using (var sender = new AnalyzerStatusUpdater("MessageMaximumLength")) {
                    sender.WaitForWorkerStarted();
                    sender.ThrowPendingExceptions();

                    // Create a message that is deliberately too long
                    string message = new string('x', AnalyzerStatusUpdater.MAX_MESSAGE_LENGTH * 2);
                    sender.UpdateStatus(0, 0, message);
                    sender.FlushQueue(TimeSpan.FromSeconds(1.0));

                    listener.RequestUpdate();
                    ready.WaitOne();
                    Assert.IsNotNull(results);
                    AssertUtil.Contains(results.Keys, "MessageMaximumLength");
                    var receivedMessage = results["MessageMaximumLength"].Message;
                    Console.WriteLine("Message: <{0}>", receivedMessage);
                    Assert.AreEqual(
                        AnalyzerStatusUpdater.MAX_MESSAGE_LENGTH,
                        receivedMessage.Length,
                        "Message length was not limited"
                    );
                }
            }
        }
Exemple #40
0
        internal void ConnectToOysterServer(string ServerAddress)
        {
            ftpSession = new KCommon.Net.FTP.Session();
            ftpSession.BeginPutFile += new KCommon.Net.FTP.FtpFileEventHandler(FtpSession_BeginPutFile);
            ftpSession.EndPutFile += new KCommon.Net.FTP.FtpFileEventHandler(FtpSession_EndPutFile);
            ftpSession.BeginGetFile += new KCommon.Net.FTP.FtpFileEventHandler(FtpSession_BeginGetFile);
            ftpSession.EndGetFile += new KCommon.Net.FTP.FtpFileEventHandler(FtpSession_EndGetFile);

            ftpSession.FileTransferProgress += new KCommon.Net.FTP.FtpFileEventHandler(FtpSession_FileTransferProgress);

            ftpSession.Server = ServerAddress;
            m_ThreadTransferCompleteEvent = new System.Threading.AutoResetEvent(false);
            m_ThreadTransferCompleteEvent.Reset();
            //ftpSession.Port = CarverLab.Oyster.SystemDefaults.DefaultOysterFileTransferPort;
            ftpSession.Port = 10904;
            try
            {
                ftpSession.Connect("ftp","*****@*****.**");
            }
            catch(Exception Err)
            {
                throw new Exception("Error connecting to server: " + Err.Message);
            }
        }
Exemple #41
0
        static void Main(string[] args)
        {
            // Start the engine.
            using (WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    Console.WriteLine("\nWorkflow Completed");
                    waitHandle.Set();
                };

                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                string anotherOrder = "y";
                while (!anotherOrder.ToLower().StartsWith("n"))
                {
                    // Prompt the user for inputs.
                    Console.Write("\nPlease enter your name: ");
                    string customerName = Console.ReadLine();
                    Console.WriteLine("\nWhat would you like to purchase?");
                    Console.WriteLine("\t(1) Vista Ultimate DVD");
                    Console.WriteLine("\t(2) Vista Ultimate Upgrade DVD");
                    Console.WriteLine("\t(3) Vista Home Premium DVD");
                    Console.WriteLine("\t(4) Vista Home Premium Upgrade DVD");
                    Console.WriteLine("\t(5) Vista Home Basic DVD");
                    Console.WriteLine("\t(6) Vista Home Basic Upgrade DVD");
                    int itemNum = 0;

                    // Make sure an integeral value has been entered for the item number.
                    bool validItemNum = false;
                    while (validItemNum == false)
                    {
                        try
                        {
                            Console.Write("\nPlease enter an item number: ");
                            itemNum = Int32.Parse(Console.ReadLine());  // throw if the input is not an integer
                            validItemNum = true;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine(" => Please enter an integer for the item number!");
                        }
                    }

                    // Make sure an integeral value has been entered for the zip code.
                    string zipCode = "";
                    bool validZip = false;
                    while (validZip == false)
                    {
                        try
                        {
                            Console.Write("\nPlease enter your 5-Digit zip code: ");
                            zipCode = Console.ReadLine();
                            Int32.Parse(zipCode);  // throw if the input is not an integer
                            validZip = true;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine(" => Please enter an integer for the zip code!");
                        }
                    }

                    Console.WriteLine();

                    // Populate the dictionary with the information the user has just entered.
                    Dictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.Add("CustomerName", customerName);
                    parameters.Add("ItemNum", itemNum);
                    parameters.Add("ZipCode", zipCode);

                    // Load the workflow type and create th workflow.
                    WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(Workflow), parameters);
                    waitHandle.Reset();
                    instance.Start();

                    waitHandle.WaitOne();

                    Console.Write("Another Order? (Y/N): ");
                    anotherOrder = Console.ReadLine();
                }
            }
        }
        public void PublishDiscoveryAndRemovalTest()
        {
            DateTime dateTimeWhenToStopWaiting;
            bool found = false;
            AutoResetEvent are = new AutoResetEvent(false);
            SDService foundService = null;

            this.serviceDiscovery.ServiceFound += delegate(SDService service, bool ownService)
            {
                if (ownService)
                {
                    foundService = service;
                    found = true;
                    are.Set();
                }
            };

            this.serviceDiscovery.ServiceLost += delegate(SDService service)
            {
                if (service.Equals(foundService))
                {
                    found = false;
                    are.Set();
                }
            };

            this.serviceDiscovery.SearchForServices(SERVICE_TYPE);
            this.serviceDiscovery.PublishService(SERVICE_TYPE, SERVICE_PORT);

            dateTimeWhenToStopWaiting = DateTime.Now.Add(WAIT_TIME);

            while (!found && DateTime.Now < dateTimeWhenToStopWaiting)
            {
                long ticksToWait = dateTimeWhenToStopWaiting.Subtract(DateTime.Now).Ticks;
                are.WaitOne(new TimeSpan(ticksToWait));
            }

            are.Reset();

            if (!found)
            {
                this.serviceDiscovery.StopSearchingForServices(SERVICE_TYPE);
                this.serviceDiscovery.StopPublishingService(SERVICE_TYPE, SERVICE_PORT);
                Assert.Fail();
            }

            this.serviceDiscovery.StopPublishing();

            dateTimeWhenToStopWaiting = DateTime.Now.Add(WAIT_TIME);
            while (found && DateTime.Now < dateTimeWhenToStopWaiting)
            {
                long ticksToWait = dateTimeWhenToStopWaiting.Subtract(DateTime.Now).Ticks;
                are.WaitOne(new TimeSpan(ticksToWait));
            }

            this.serviceDiscovery.StopSearchingForServices(SERVICE_TYPE);
            this.serviceDiscovery.StopPublishingService(SERVICE_TYPE, SERVICE_PORT);

            if (found)
            {
                Assert.Fail();
            }
        }