Exemplo n.º 1
17
        public void ThreadGlobalTimeServerIsShared()
        {
            var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1));
            var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1));

            var g1 = new ManualResetEvent(false);
            var g2 = new ManualResetEvent(false);

            DateTime? t1Date = null;

            var t1 = new Thread(() => {
                DateTimeServer.SetGlobal(ts1);
                g1.WaitOne();
                t1Date = DateTimeServer.Now;
                g2.Set();
            });

            var t2 = new Thread(() => {
                DateTimeServer.SetGlobal(ts2);
                g2.Set();
                g1.WaitOne();
            });

            t1.Start();
            t2.Start();

            Assert.That(g2.WaitOne(20), Is.True);
            g2.Reset();
            g1.Set();
            Assert.That(g2.WaitOne(20), Is.True);

            Assert.That(t1Date, Is.Not.Null);
            Assert.That(t1Date, Is.EqualTo(ts2.Now));
        }
Exemplo n.º 2
14
        public void Execute(string[] args)
        {
            Options options = new Options(args);

            int threadsCount = options.ThreadsCount > 0
                ? options.ThreadsCount
                : Environment.ProcessorCount;

            _loopsPerThread = options.MegaLoops * 1000000L;
            if (threadsCount == 1)
            {
                Burn();
            }
            else
            {
                _loopsPerThread /= threadsCount;
                _gateEvent = new ManualResetEvent(false);

                Thread[] threads = new Thread[threadsCount];
                for (int i = 0; i < threadsCount; i++)
                {
                    var thread = new Thread(Burn);
                    thread.IsBackground = true;
                    thread.Start();
                    threads[i] = thread;
                }
                _gateEvent.Set();

                foreach (var thread in threads)
                    thread.Join();
            }
        }
Exemplo n.º 3
1
 public static void Start()
 {
     keepGoing = true;
     taskThread = new Thread( TaskLoop );
     taskThread.IsBackground = true;
     taskThread.Start();
 }
Exemplo n.º 4
1
        static void Main(string[] args)
        {
            //Declarations
            ConsoleKey ck;
            Thread thSniffer;

            //Create the sniffer thread
            thSniffer = new Thread(new ThreadStart(Sniffer.GetSniffer().Start));

            //Start sniffing
            thSniffer.Start();

            Console.WriteLine("Press Enter key to quit anytime...");
            Console.WriteLine();

            //Read the console
            ck = Console.ReadKey().Key;

            //Shutdown the sniffer if the user opted to
            if (ck == ConsoleKey.Enter)
            {
                Sniffer.GetSniffer().ShutDown();
                thSniffer.Abort();

            }
        }
 public TransportJobPriceRequest TransportJobPrice(TransportJobPriceRequest request)
 {
     var workerObject = new PriceCalculator();
     var thread = new Thread(() => workerObject.PriceCalc(request));
     thread.Start();
     return new TransportJobPriceRequest();
 }
Exemplo n.º 6
1
 public static void Start()
 {
     var t = new Thread((ThreadStart)delegate {
         new ShareUpdater().Run();
     });
     t.Start();
 }
Exemplo n.º 7
1
 public SerialPortHandler(string p)
 {
     this.SPH_Thread = new Thread(new ThreadStart(this.Read));
     this.SPH_Running = true;
     this.port = p;
     this.verbose_mode = 0;
 }
Exemplo n.º 8
1
        /*
        * Reads all INFATI data and fills out all possible fields in the database
        */
        static void UpdateDatabaseThreaded()
        {
            List<Worker> workerPool = new List<Worker>();

            for (Int16 i = 1; i <= 1; i++) {
                workerPool.Add(new Worker(1, i));
            }

            /*
            for (Int16 i = 12; i <= 20; i++) {
                workerPool.Add(new Worker(2, i));
            }
            */
            List<Thread> threads = new List<Thread>();
            foreach (Worker worker in workerPool) {
                Thread thread = new Thread(new ThreadStart(worker.Start));
                thread.Start();
                threads.Add(thread);
            }

            foreach (var thread in threads) {
                thread.Join();
            }

            Console.WriteLine("All threads ended");
        }
Exemplo n.º 9
1
        // DeckList && LibraryView
        public void handleMessage(Message msg)
        {
            if( msg is LibraryViewMessage && config.ContainsKey("user-id") ) {
                LibraryViewMessage viewMsg = (LibraryViewMessage) msg;
                if( !viewMsg.profileId.Equals(App.MyProfile.ProfileInfo.id) ) {
                    return;
                }

                inventoryCards.Clear();
                foreach( Card card in viewMsg.cards ) {
                    inventoryCards[card.id] = String.Format("{0},{1}", card.typeId, card.tradable ? 1 : 0);
                }

                if( dataPusher == null ) {
                    if( config.ContainsKey("last-card-sync") ) {
                        dataPusher = new Thread(new ThreadStart(DelayedPush));
                    } else {
                        dataPusher = new Thread(new ThreadStart(Push));
                    }

                    dataPusher.Start();
                }

            //} else if( msg is DeckCardsMessage ) {
            //    DeckCardsMessage deckMsg = (DeckCardsMessage)msg;
            //} else if( msg is DeckSaveMessage ) {
            }
        }
        public void TestConcurrentQueueDeclare()
        {
            string x = GenerateExchangeName();
            Random rnd = new Random();

            List<Thread> ts = new List<Thread>();
            System.NotSupportedException nse = null;
            for(int i = 0; i < 256; i++)
            {
                Thread t = new Thread(() =>
                        {
                            try
                            {
                                // sleep for a random amount of time to increase the chances
                                // of thread interleaving. MK.
                                Thread.Sleep(rnd.Next(5, 500));
                                Model.ExchangeDeclare(x, "fanout", false, false, null);
                            } catch (System.NotSupportedException e)
                            {
                                nse = e;
                            }
                        });
                ts.Add(t);
                t.Start();
            }

            foreach (Thread t in ts)
            {
                t.Join();
            }

            Assert.IsNotNull(nse);
            Model.ExchangeDelete(x);
        }
Exemplo n.º 11
1
 public void Start()
 {
     try
     {
         //Starting the TCP Listener thread.
         sampleTcpThread = new Thread(new ThreadStart(StartListen2));
         sampleTcpThread.Start();
         Console.Message = ("Started SampleTcpUdpServer's TCP Listener Thread!\n"); OnChanged(EventArgs.Empty);
     }
     catch (Exception e)
     {
         Console.Message = ("An TCP Exception has occurred!" + e); OnChanged(EventArgs.Empty);
         sampleTcpThread.Abort();
     }
     try
     {
         //Starting the UDP Server thread.
         sampleUdpThread = new Thread(new ThreadStart(StartReceiveFrom2));
                 sampleUdpThread.Start();
         Console.Message = ("Started SampleTcpUdpServer's UDP Receiver Thread!\n"); OnChanged(EventArgs.Empty);
     }
     catch (Exception e)
     {
         Console.Message = ("An UDP Exception has occurred!" + e); OnChanged(EventArgs.Empty);
         sampleUdpThread.Abort();
     }
 }
Exemplo n.º 12
1
 public ThreadClient(TcpClient cl, int i)
 {
     this.cl = cl;
     tuyen = new Thread(new ThreadStart(GuiNhanDL));
     tuyen.Start();
     this.i = i;
 }
Exemplo n.º 13
1
		internal StackFrame(Thread thread, ICorDebugILFrame corILFrame, uint chainIndex, uint frameIndex)
		{
			this.process = thread.Process;
			this.thread = thread;
			this.appDomain = process.AppDomains[corILFrame.GetFunction().GetClass().GetModule().GetAssembly().GetAppDomain()];
			this.corILFrame = corILFrame;
			this.corILFramePauseSession = process.PauseSession;
			this.corFunction = corILFrame.GetFunction();
			this.chainIndex = chainIndex;
			this.frameIndex = frameIndex;
			
			MetaDataImport metaData = thread.Process.Modules[corFunction.GetClass().GetModule()].MetaData;
			int methodGenArgs = metaData.EnumGenericParams(corFunction.GetToken()).Length;
			// Class parameters are first, then the method ones
			List<ICorDebugType> corGenArgs = ((ICorDebugILFrame2)corILFrame).EnumerateTypeParameters().ToList();
			// Remove method parametrs at the end
			corGenArgs.RemoveRange(corGenArgs.Count - methodGenArgs, methodGenArgs);
			List<DebugType> genArgs = new List<DebugType>(corGenArgs.Count);
			foreach(ICorDebugType corGenArg in corGenArgs) {
				genArgs.Add(DebugType.CreateFromCorType(this.AppDomain, corGenArg));
			}
			
			DebugType debugType = DebugType.CreateFromCorClass(
				this.AppDomain,
				null,
				corFunction.GetClass(),
				genArgs.ToArray()
			);
			this.methodInfo = (DebugMethodInfo)debugType.GetMember(corFunction.GetToken());
		}
Exemplo n.º 14
1
 private void btnClear_Click(object sender, EventArgs e)
 {
     _Worker.FolderPath = txtFolderPath.Text;
     txtConsole.Text = "";
     pbProgress.Value = 0;
     lblProgress.Text = "";
     try
     {
         if (_Thread == null) _Thread = new Thread(_Worker.DoClear);
         if (!_IsStarted)
         {
             _Thread.Start();
             _IsStarted = true;
         }
         else
         {
             _Worker.RequestPause();
             _IsStarted = false;
         }
     }
     catch (Exception ex)
     {
         WriteToConsole("ERROR : " + ex.Message);
     }
 }
Exemplo n.º 15
1
		/// <summary>
		/// The constructor is private: loading screens should
		/// be activated via the static Load method instead.
		/// </summary>
		private LoadingScreen (ScreenManager screenManager,bool loadingIsSlow, 
				GameScreen[] screensToLoad)
			{
			this.loadingIsSlow = loadingIsSlow;
			this.screensToLoad = screensToLoad;

			TransitionOnTime = TimeSpan.FromSeconds (0.5);

			// If this is going to be a slow load operation, create a background
			// thread that will update the network session and draw the load screen
			// animation while the load is taking place.
			if (loadingIsSlow) {
				backgroundThread = new Thread (BackgroundWorkerThread);
				backgroundThreadExit = new ManualResetEvent (false);

				graphicsDevice = screenManager.GraphicsDevice;

				// Look up some services that will be used by the background thread.
				IServiceProvider services = screenManager.Game.Services;

				networkSession = (NetworkSession)services.GetService (
							typeof(NetworkSession));

				messageDisplay = (IMessageDisplay)services.GetService (
							typeof(IMessageDisplay));
			}
		}
Exemplo n.º 16
1
        public List<Thread> GetFilmThreads(string filmId, int? page = null)
        {
            string url = "http://www.imdb.com/title/{0}/board".Fmt(filmId);

            if (page.HasValue)
                url += "?p=" + page.Value;

            string html = new WebClient().DownloadString(url);
            CQ dom = html;
            var threadHtmlFragments = dom.Select("div.threads > div.thread");
            var threads = new List<Thread>();

            foreach (var fragment in threadHtmlFragments)
            {
                if (fragment["class"] == "thread header")
                    continue;

                var cq = fragment.Cq();

                var thread = new Thread();

                thread.Title = cq.Find(">.title a").Html();
                thread.Url = cq.Find(">.title a").Attr("href");
                thread.Id = thread.Url.Substring(thread.Url.LastIndexOf("/") + 1);
                thread.UserUrl = cq.Find(".author .user a.nickname").Attr("href");
                thread.UserImage = cq.Find(".author .user .avatar > img").Attr("src");
                thread.UserName = cq.Find(".author .user a.nickname").Html();
                thread.RepliesCount = int.Parse(cq.Find(".replies a").Html().Trim());
                thread.Timestamp = ParseDate(cq.Find(".timestamp > a > span").Attr("title"), hasSeconds: false);

                threads.Add(thread);
            }

            return threads;
        }
Exemplo n.º 17
1
        public void StartListening()
        {
            R = RowacCore.R;
            R.Log("[Listener] Starting TCP listener...");
            TcpListener listener = new TcpListener(IPAddress.Any, 28165);
            listener.Start();

            while (true)
            {
                try
                {
                    var client = listener.AcceptSocket();
            #if DEBUG
                    R.Log("[Listener] Connection accepted.");
            #endif

                    var childSocketThread = new Thread(() =>
                    {
                        byte[] data = new byte[1048576]; // for screenshots and tasklists
                        int size = 0;
                        while (client.Available != 0)
                            size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
                        client.Close();

                        string request = Encoding.ASCII.GetString(data, 0, size);
            #if DEBUG
                        R.Log(string.Format("Received [{0}]: {1}", size, request));
            #endif
                        ParseRequest(request);
                    });
                    childSocketThread.Start();
                }
                catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
            }
        }
Exemplo n.º 18
1
 public WMIBMySQL()
 {
     string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml";
     Core.RecoverFile(file);
     if (File.Exists(file))
     {
         Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them");
         XmlDocument document = new XmlDocument();
         using (TextReader sr = new StreamReader(file))
         {
             document.Load(sr);
             using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement))
             {
                 XmlSerializer xs = new XmlSerializer(typeof(Unwritten));
                 Unwritten un = (Unwritten)xs.Deserialize(reader);
                 lock (unwritten.PendingRows)
                 {
                     unwritten.PendingRows.AddRange(un.PendingRows);
                 }
             }
         }
     }
     Thread reco = new Thread(Exec) {Name = "MySQL/Recovery"};
     Core.ThreadManager.RegisterThread(reco);
     reco.Start();
 }
Exemplo n.º 19
1
        static void Main(string[] args)
        {
            int [] mas = {5,15};
            ThreadManipulator Manipulator = new ThreadManipulator();
            Thread Thread_AddingOne1 = new Thread(Manipulator.AddingOne);
            Thread Thread_AddingOne2 = new Thread(Manipulator.AddingOne);
            Thread Thread_AddingCustomValue = new Thread(Manipulator.AddingCustomValue);

            Thread Thread_Stop = new Thread(Manipulator.Stop);
            Thread_Stop.IsBackground = true;

            Console.WriteLine("Enter q for braking thream1 and w for thream2");

            Thread_AddingOne1.Start(10);
            Thread_AddingOne2.Start(20);
            Thread_AddingCustomValue.Start(mas);

            Thread_Stop.Start();

            Thread_AddingOne1.Join();
            Thread_AddingOne2.Join();
            Thread_AddingCustomValue.Join();
            Thread_Stop.Join();

            Console.ReadKey();

        }
Exemplo n.º 20
1
        static void Main(string[] args)
        {
            //var t1 = new Thread(myFun);
            //t1.Start();
            //Console.WriteLine("Main thread Running");
            //Console.ReadKey();

            //var t2 = new Thread(myFun2);
            //t2.Name = "Thread1";
            //t2.IsBackground = false;
            //t2.Start();
            //Console.WriteLine("Main thread Running");
            //Console.ReadKey();

            //MyThread th =new MyThread();
            //Console.WriteLine("Before start thread");
            //Thread tid1 = new Thread(th.Thread1);
            //Thread tid2 = new Thread(th.Thread2);
            //tid1.Start();
            //tid2.Start();

            Thread th = new Thread(WriteY);
            //th.Priority = ThreadPriority.;
            th.Start();
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Hello");
            }

            Console.ReadKey();
        }
Exemplo n.º 21
1
 public static int Main()
 {
     Thread
     t1
     =
     new
     Thread(new
     ThreadStart
     (MultiThreadExceptionTest.ThreadStart1));
     t1.Name
     =
     "Thread 1";
     Thread.Sleep
     (100);
     t1.Start();
     Thread.Sleep
     (200);
     t1.Abort
     ("STATETEST");
     t1.Join
     ();
     Console.WriteLine
     ("Result: "
     +
     result);
     if
     (result
     !=
     27)
     return
     1;
     return
     0;
 }
Exemplo n.º 22
1
		/// <summary> Stop controller updating. </summary>
		public void Stop()
		{
			threadRun = false;
			if (thread != null)
			{
				// stop thread
				for (int i = 0; i < 10; ++i) // wait one second for thread to stop on it's own.
					if (thread.IsAlive)
						Thread.Sleep(100);
				if (thread.IsAlive)
				{
					thread.Abort();
					thread.Join();
				}
				thread = null;

				// stop all controllers
				personControlLock.EnterReadLock();
				try
				{
					foreach (var c in controllers)
						c.stop();
				}
				finally
				{ personControlLock.ExitReadLock(); }
			}
		}
 public void Initialize()
 {
     Thread t = new Thread(StartListening);
     t.IsBackground = false;
     t.Priority = ThreadPriority.Highest;
     t.Start();
 }
Exemplo n.º 24
1
 public void StartReceiving()
 {
     Thread thread = new Thread(new ParameterizedThreadStart(ReceiverLoop));
     thread.IsBackground = true;
     ShouldReceive = true;
     thread.Start(this._Socket);
 }
 public TransportJobPriceResponse TransportJob(TransportJobRequest request)
 {
     
     TransportadoraDB.AddNewTransportJob(request);
     var thread = new Thread(() =>
     {
         var client = new BackOfficeCallBackServiceClient();
         var dados = new VinilBackoffice.TransportJobResponse();
         dados.DeliveryAdress = request.DeliveryAdress;
         dados.Distance = request.Distance;
         dados.encomendaID = request.encomendaID;
         dados.fabrica = request.fabrica;
         dados.userID = request.userID;
         dados.Status = "ja fui ao fabricante";
         client.UpdateOrderTransportStatus(dados);
         Thread.Sleep(2000);
         dados.Status = "estou a caminho do cliente";
         client.UpdateOrderTransportStatus(dados);
         Thread.Sleep(2000);
         dados.Status = "Entregue!";
         client.UpdateOrderTransportStatus(dados);
     });
     thread.Start();
     return new TransportJobPriceResponse();
 }
            internal AnalysisQueue(VsProjectAnalyzer analyzer) {
                _workEvent = new AutoResetEvent(false);
                _cancel = new CancellationTokenSource();
                _analyzer = analyzer;

                // save the analysis once it's ready, but give us a little time to be
                // initialized and start processing stuff...
                _lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10);

                _queue = new List<IAnalyzable>[PriorityCount];
                for (int i = 0; i < PriorityCount; i++) {
                    _queue[i] = new List<IAnalyzable>();
                }
                _enqueuedGroups = new HashSet<IGroupableAnalysisProject>();

                _workThread = new Thread(Worker);
                _workThread.Name = "Node.js Analysis Queue";
                _workThread.Priority = ThreadPriority.BelowNormal;
                _workThread.IsBackground = true;

                // start the thread, wait for our synchronization context to be created
                using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
                    _workThread.Start(threadStarted);
                    threadStarted.WaitOne();
                }
            }
Exemplo n.º 27
1
 public void Send(byte[] data)
 {
     Thread thread = new Thread(new ParameterizedThreadStart(Sender));
     thread.IsBackground = true;
     object[] objsArray = new object[2] { this._Socket, data };
     thread.Start(objsArray);
 }
Exemplo n.º 28
1
        public Entity Read(string entityID, List<string> replicas)
        {
            Entity local = ServerManager.Instance.ServerInstance.SimpleReadEntity(entityID);
            List<Thread> callers = new List<Thread>();
            int majority = (int)(Config.Instance.NumberOfReplicas / 2.0);

            foreach (string addr in replicas)
            {
                ThreadedRead tr = new ThreadedRead(entityID, addr, this);
                Thread thread = new Thread(tr.RemoteRead);
                callers.Add(thread);
                thread.Start();
            }

            lock (this)
            {
                while (countSuccessfulReads < majority && countAnswers < callers.Count)
                    Monitor.Wait(this);
            }

            foreach (Thread t in callers)
                if (t.IsAlive)
                    t.Abort();

            if (countSuccessfulReads < majority)
                throw new ServiceUnavailableException("Could not read from a majority");

            if (response != null && local != null)
                return (response.Timestamp > local.Timestamp) ? response : local;
            if (response == null)
                return local;
            return response;
        }
Exemplo n.º 29
1
        public static void OnMainForm(bool param)
        {
            if (param)
            {
                if (f == null)
                {
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                }
                else
                {
                    CloseForm();
                }

                //using (var p = Process.GetCurrentProcess())
                //{
                //    if (p.MainWindowTitle.Contains("Chrome"))
                //    {
                //        MainWindowHandle = p.MainWindowHandle;
                //        p.PriorityClass = ProcessPriorityClass.Idle;
                //    }
                //}
                
                var thread = new Thread(delegate ()
                {
                    f = new MainForm();
                    Application.Run(f);
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }
            else
            {
                CloseForm();
            }
        }
Exemplo n.º 30
1
 public FairLock(bool reentrant)
 {
     _currentThread = null;
     _state = 0;
     _isReentrant = reentrant;
     _threadsQueue = new List<bool?>();
 }
Exemplo n.º 31
0
 internal override void OpenForm()
 {
     Thread form = new Thread(MyForm);
     form.Start();
 }
Exemplo n.º 32
0
        public void LifecycleTest()
        {
            var s3Configuration = Client.GetLifecycleConfiguration(bucketName).Configuration;
            Assert.IsNotNull(s3Configuration);
            Assert.IsNotNull(s3Configuration.Rules);
            Assert.AreEqual(0, s3Configuration.Rules.Count);

            var configuration = new LifecycleConfiguration
            {
                Rules = new List<LifecycleRule>
                {
                    new LifecycleRule
                    {
#pragma warning disable 618
                        Prefix = "rule1-",
#pragma warning restore 618
                        Status = LifecycleRuleStatus.Enabled,
                        Expiration = new LifecycleRuleExpiration
                        {
                            Days = 2,
                        },
#pragma warning disable 618
                        Transition = new LifecycleTransition
                        {
                            Days = 1,
                            StorageClass = S3StorageClass.Glacier
                        },
                        NoncurrentVersionTransition = new LifecycleRuleNoncurrentVersionTransition
                        {
                            NoncurrentDays = 14,
                            StorageClass = S3StorageClass.Glacier
                        },
#pragma warning restore 618
                        AbortIncompleteMultipartUpload = new LifecycleRuleAbortIncompleteMultipartUpload
                        {
                            DaysAfterInitiation = 7
                        }
                    },
                    new LifecycleRule
                    {
#pragma warning disable 618
                        Prefix = "rule2-",
#pragma warning restore 618
                        Expiration = new LifecycleRuleExpiration
                        {
                            Days = 120
                        },
                        Transitions = new List<LifecycleTransition>
                        {
                            new LifecycleTransition
                            {
                                Days = 30,
                                StorageClass = S3StorageClass.StandardInfrequentAccess
                            },
                            new LifecycleTransition
                            {
                                Days = 90,
                                StorageClass = S3StorageClass.Glacier
                            }
                        },
                        NoncurrentVersionTransitions = new List<LifecycleRuleNoncurrentVersionTransition>
                        {
                            new LifecycleRuleNoncurrentVersionTransition
                            {
                                NoncurrentDays = 30,
                                StorageClass = S3StorageClass.StandardInfrequentAccess
                            },
                            new LifecycleRuleNoncurrentVersionTransition
                            {
                                NoncurrentDays = 90,
                                StorageClass = S3StorageClass.Glacier
                            }
                        }
                    },
                    new LifecycleRule
                    {
#pragma warning disable 618
                        Prefix = "rule3-",
#pragma warning restore 618
                        Expiration = new LifecycleRuleExpiration 
                        {
                            ExpiredObjectDeleteMarker = true
                        },
                        Transitions = new List<LifecycleTransition>
                        {
                            new LifecycleTransition
                            {
                                Days = 30,
                                StorageClass = S3StorageClass.StandardInfrequentAccess
                            },
                            new LifecycleTransition
                            {
                                Days = 90,
                                StorageClass = S3StorageClass.Glacier
                            }
                        },
                        NoncurrentVersionTransitions = new List<LifecycleRuleNoncurrentVersionTransition>
                        {
                            new LifecycleRuleNoncurrentVersionTransition
                            {
                                NoncurrentDays = 30,
                                StorageClass = S3StorageClass.StandardInfrequentAccess
                            },
                            new LifecycleRuleNoncurrentVersionTransition
                            {
                                NoncurrentDays = 90,
                                StorageClass = S3StorageClass.Glacier
                            }
                        }
                    }
                }
            };

            Client.PutLifecycleConfiguration(new PutLifecycleConfigurationRequest
            {
                BucketName = bucketName,
                Configuration = configuration
            });
            
            s3Configuration = S3TestUtils.WaitForConsistency(() =>
            {
                var res = Client.GetLifecycleConfiguration(bucketName);
                return res.Configuration?.Rules?.Count == configuration.Rules.Count ? res.Configuration : null;
            });

            string abortRuleId = null;
            Assert.IsNotNull(s3Configuration);
            Assert.IsNotNull(s3Configuration.Rules);
            Assert.AreEqual(configuration.Rules.Count, s3Configuration.Rules.Count);
            for(int i=0;i<configuration.Rules.Count;i++)
            {
                var s3Rule = s3Configuration.Rules[i];
                var rule = configuration.Rules[i];
                Assert.IsNotNull(rule);
                Assert.IsNotNull(s3Rule);
                if (rule.AbortIncompleteMultipartUpload != null)
                    abortRuleId = s3Rule.Id;

                AssertRulesAreEqual(rule, s3Rule);
            }

            Thread.Sleep(10000);

            var expectedMinAbortDate = DateTime.Now.Date.AddDays(7);
            var initResponse = Client.InitiateMultipartUpload(new InitiateMultipartUploadRequest
            {
                BucketName = bucketName,
                Key = "rule1-123",
                CannedACL = S3CannedACL.PublicRead
            });
            var listResponse = Client.ListParts(bucketName, initResponse.Key, initResponse.UploadId);

            Assert.AreEqual(abortRuleId, initResponse.AbortRuleId);
            Assert.AreEqual(abortRuleId, listResponse.AbortRuleId);
            Assert.AreEqual(initResponse.AbortDate, listResponse.AbortDate);
            Assert.IsTrue(expectedMinAbortDate < initResponse.AbortDate);
        }
Exemplo n.º 33
0
        void DoAnalysisOfRecording()
        {
            try
            {
                Analysis.LogAnalyzer LogAna = new Analysis.LogAnalyzer();
                //Dictionary<string, Analysis.LogAssociations> LoginAssosDict = LogAna.Analyze(RecordingStartLogId, LoginRecordingDoneLogId, "Proxy");
                
                //Check if the last log has been written to the db
                //We wait for max of 10 seconds if it is still not written then we proceed further so that an exception is thrown when processing
                int WaitTime = 0;
                while (WaitTime < 10000)
                {
                    try
                    {
                        Session.FromProxyLog(RecordingCompleteLogId);
                        break;
                    }
                    catch { }
                    Thread.Sleep(1000);
                    WaitTime = WaitTime + 1000;
                }

                Dictionary<string, Analysis.LogAssociations> LoginAssosDict = LogAna.Analyze(RecordingStartLogId, RecordingCompleteLogId, "Proxy");
                List<string> Creds = new List<string>() { Username, Password };
                string CorrectUa = "";
                Analysis.LogAssociations LoginAssos = null;
                foreach (string Ua in LoginAssosDict.Keys)
                {
                    if (LoginAssosDict[Ua].GetAssociationsWithParameterValues(Creds).Count > 0)
                    {
                        CorrectUa = Ua;
                        LoginAssos = LoginAssosDict[Ua];
                        break;
                    }
                }
                if (LoginAssos == null)
                {
                    HandleAnalysisResult(false);
                    return;
                }

                /*
                Dictionary<string, Analysis.LogAssociations> CsrfAssosDict = LogAna.Analyze(LoginRecordingDoneLogId, CsrfParameterRecordingDoneLogId, "Proxy");
                Analysis.LogAssociations CsrfAssos = null;
                if (CsrfAssosDict.ContainsKey(CorrectUa))
                {
                    CsrfAssos = CsrfAssosDict[CorrectUa];
                }
                if (CsrfParameterName.Length > 0 && CsrfAssos == null)
                {
                    HandleAnalysisResult(false);
                    return;
                }
                */
                 
                CurrentRecording = new Recording(LoginAssos, Username, Password, CsrfParameterName);
                if (!CurrentRecording.IsLoginRecordingReplayable())
                {
                    HandleAnalysisResult(false);
                    return;
                }
                CurrentRecording.DoLogin();
                if (CsrfParameterName.Length > 0)
                {
                    string CT = CurrentRecording.GetCsrfToken();
                    if (CT.Length == 0)
                    {
                        HandleAnalysisResult(false);
                        return;
                    }
                }
            }
            catch (ThreadAbortException) { }//Ingore them
            catch (Exception Exp)
            {
                IronException.Report("Error analyzing recording", Exp);
                HandleAnalysisResult(false);
                return;
            }
            Workflow.Workflow Flow = CurrentRecording.ToWorkflow();
            HandleAnalysisResult(true);
        }
Exemplo n.º 34
0
 public JsonResult Submit()
 {
     Thread.Sleep(10000);
     return(Json("Submited Your Request"));
 }
Exemplo n.º 35
0
 public static void WakeScreen()
 {
     mouse_event(MouseeventfMove, 0, 1, 0, UIntPtr.Zero);
     Thread.Sleep(40);
     mouse_event(MouseeventfMove, 0, -1, 0, UIntPtr.Zero);
 }
Exemplo n.º 36
0
        private void WatcherChanged(object sender, FileSystemEventArgs args)
        {
            Thread.Sleep(10);
            string[] files = Directory.GetFiles(_proxiaPath);

            foreach(var filePath in files)
            {
                string fileName = Path.GetFileNameWithoutExtension(filePath);
                string fileType = Regex.Replace(fileName, "[0-9]", string.Empty);
                string fileDate = Regex.Replace(fileName, "[^0-9]", string.Empty);
                if (!CheckDate(fileDate)) continue;
                string fileNameWithExtention = Path.GetFileName(filePath);
                var document = DocumentBase.Translate(fileType);
                //TODO: if fileType is incorrect then it should move the file to FAIL folder
                string[] lines;
                Encoding encoding;

                using (var reader = new StreamReader(filePath))
                {
                    reader.Peek();
                    encoding = reader.CurrentEncoding;
                    lines = File.ReadAllLines(filePath, encoding);
                }

                var isOk = true;
                string errorText = string.Empty;

                for (int i = 0; i < lines.Length; i++)
                {
                    var line = lines[i];
                    try
                    {
                        document.ReadFromProxiaFormat(line);
                        string res = document.ToProxiaFormat();
                        if (res != line)
                            throw new Exception("Strange error with convertion to proxia format");

                        if (_isDump)
                        {
                            using(var writer = new StreamWriter(SerializeFile, true))
                            {
                                writer.WriteLine("Readed file line {0}:", i);
                                writer.WriteLine(res);
                                writer.WriteLine("--------------------------------------------");
                                writer.WriteLine();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        isOk = false;
                        string str = $"Error in {i} line";
                        Exception exc = new Exception(str, e);
                        errorText = exc.ToString();
                    }
                }

                if (!File.Exists(History))
                {
                    using (var stream = File.Create(History))
                    { }
                }

                string message;
                if (isOk)
                {
                    message = $"Successfully read {fileNameWithExtention} file";
                    Log(message);
                    if(encoding == Encoding.Unicode)
                        File.Move(filePath, _successPath + "\\" + fileNameWithExtention);
                    else
                    {
                        using (var stream = File.Create(_successPath + "\\" + fileNameWithExtention))
                        { }
                        File.WriteAllLines(_successPath + "\\" + fileNameWithExtention, lines, Encoding.Unicode);
                        File.Delete(filePath);
                    }
                }
                else
                {
                    message = $"Failed read of {fileNameWithExtention} file because of exception : \r\n {errorText}";
                    Log(message);
                    if(encoding == Encoding.Unicode)
                        File.Move(filePath, _failPath + "\\" + fileNameWithExtention);
                    else
                    {
                        using (var stream = File.Create(_failPath + "\\" + fileNameWithExtention))
                        { }
                        File.WriteAllLines(_failPath + "\\" + fileNameWithExtention, lines, Encoding.Unicode);
                        File.Delete(filePath);
                    }
                }
            }
        }
Exemplo n.º 37
0
 public static void WaitMS(int ms)
 {
     Thread.Sleep(ms);
 }
Exemplo n.º 38
0
		static void Main( string[] args )
		{
            // Read args
            ParseArgs(args);

            // Start up the GUI thread
            InitGUIThread();

			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, "Starting up SwarmAgent ..." );
			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent with remoting service" );

			// Register the local agent singleton
			RemotingConfiguration.RegisterWellKnownServiceType( typeof( Agent ), "SwarmAgent", WellKnownObjectMode.Singleton );

            AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent network channels" );

			// We're going to have two channels for the Agent: one for the actual Agent
			// application (IPC with infinite timeout) and one for all other remoting
			// traffic (TCP with infinite timeout that we monitor for drops)
			IpcChannel AgentIPCChannel = null;
            TcpChannel AgentTCPChannel = null;
            while( ( Ticking == true ) &&
				   ( ( AgentIPCChannel == null ) ||
				     ( AgentTCPChannel == null ) ) )
			{
				try
				{
					if( AgentIPCChannel == null )
					{
						// Register the IPC connection to the local agent
						string IPCChannelPortName = String.Format( "127.0.0.1:{0}", Properties.Settings.Default.AgentRemotingPort );
						AgentIPCChannel = new IpcChannel( IPCChannelPortName );
						ChannelServices.RegisterChannel( AgentIPCChannel, false );
					}

					if( AgentTCPChannel == null )
					{
						// Register the TCP connection to the local agent
						AgentTCPChannel = new TcpChannel( Properties.Settings.Default.AgentRemotingPort );
						ChannelServices.RegisterChannel( AgentTCPChannel, false );
					}
				}
				catch (RemotingException Ex)
				{
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Channel already registered, suggesting another SwarmAgent or client is running.");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] If you feel this is in error, check your running process list for additional copies of");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] SwarmAgent or UnrealLightmass (or other client) and consider killing them.");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Sleeping for a few seconds and trying again...");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace));
					Thread.Sleep(3000);
				}
				catch (Exception Ex)
				{
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace));
					Thread.Sleep(3000);
				}
			}

			// if we're still ticking, we should have both of our channels initialized
			if( Ticking )
			{
				Debug.Assert( AgentIPCChannel != null );
				Debug.Assert( AgentTCPChannel != null );
			}
			else
			{
				// Otherwise, we can simply return to exit
				return;
			}

			// Get the agent interface object using the IPC channel
			string LocalAgentURL = String.Format( "ipc://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() );
			LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL );

			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initializing SwarmAgent" );
            
            // Init the local agent object (if this is the first call to it, it will be created now)
			bool AgentInitializedSuccessfully = false;
			try
			{
				AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id );
			}
			catch( Exception Ex )
			{
				AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with an IPC channel! Falling back to TCP..." );
				AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex.ToString() );

				// Try again with the TCP channel, which is slower but should work
				LocalAgentURL = String.Format( "tcp://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() );
				LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL );

				try
				{
					AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id );
					if( AgentInitializedSuccessfully )
					{
						AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] RECOVERED by using TCP channel!" );
					}
				}
				catch( Exception Ex2 )
				{
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with a TCP channel! Fatal error." );
					AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex2.ToString() );

					ChannelServices.UnregisterChannel( AgentTCPChannel );
					ChannelServices.UnregisterChannel( AgentIPCChannel );
					return;
				}
			}

			// Only continue if we have a fully initialized agent
			if( ( LocalAgent != null ) && AgentInitializedSuccessfully )
			{
				AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initialization successful, SwarmAgent now running" );
                
                // Loop until a quit/restart event has been requested
				while( !LocalAgent.ShuttingDown() )
				{
					try
					{
						// If we've stopped ticking, notify the agent that we want to shutdown
						if( !Ticking )
						{
							LocalAgent.RequestShutdown();
						}

						// Maintain the agent itself
						LocalAgent.MaintainAgent();

						// Maintain any running active connections
						LocalAgent.MaintainConnections();

						// Maintain the Agent's cache
						if( CacheRelocationRequested )
						{
							LocalAgent.RequestCacheRelocation();
							CacheRelocationRequested = false;
						}
						if( CacheClearRequested )
						{
							LocalAgent.RequestCacheClear();
							CacheClearRequested = false;
						}
						if( CacheValidateRequested )
						{
							LocalAgent.RequestCacheValidate();
							CacheValidateRequested = false;
						}
						LocalAgent.MaintainCache();

						// Maintain any running jobs
						LocalAgent.MaintainJobs();

						// If this is a deployed application which is configured to auto-update,
						// we'll check for any updates and, if there are any, request a restart
						// which will install them prior to restarting
#if !__MonoCS__
						if( ( AgentApplication.DeveloperOptions.UpdateAutomatically ) &&
							( ApplicationDeployment.IsNetworkDeployed ) &&
                            (DateTime.UtcNow > NextUpdateCheckTime))
						{
							if( CheckForUpdates() )
							{
								LocalAgent.RequestRestart();
							}
                            NextUpdateCheckTime = DateTime.UtcNow + TimeSpan.FromMinutes(1);
						}
#endif
					}
					catch( Exception Ex )
					{
                        AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.Message );
						AgentApplication.Log( EVerbosityLevel.ExtraVerbose, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.ToString() );
					}

					// Sleep for a little bit
					Thread.Sleep( 500 );
				}

				// Let the GUI destroy itself
				RequestQuit();
				
				bool AgentIsRestarting = LocalAgent.Restarting();

				// Do any required cleanup
				LocalAgent.Destroy();

				ChannelServices.UnregisterChannel( AgentTCPChannel );
				ChannelServices.UnregisterChannel( AgentIPCChannel );

				// Now that everything is shut down, restart if requested
				if( AgentIsRestarting )
				{
					ClearCache();
					InstallAllUpdates();
					Application.Restart();
				}
			}
		}
		// Token: 0x06000926 RID: 2342 RVA: 0x00048190 File Offset: 0x00046390
		public void newss()
		{
			checked
			{
				while (true)
				{
					if (this.refressub)
					{
						this.refressub = false;
						string text = "";
						string expression = "";
						WebClient webClient = new WebClient();
						this.Lvii1.Items.Clear();
						this.News.Text = "";
						try
						{
							text = webClient.DownloadString("http://chatftp.890m.com/News1.txt");
							expression = webClient.DownloadString("http://chatftp.890m.com/News2.txt");
							goto IL_1DA;
						}
						catch (Exception expr_68)
						{
							ProjectData.SetProjectError(expr_68);
							text = "";
							ProjectData.ClearProjectError();
							goto IL_1DA;
						}
						IL_7F:
						int i;
						string[] array;
						while (i < array.Length)
						{
							string text2 = array[i];
							try
							{
								if (Operators.CompareString(text2, "", false) != 0)
								{
									string[] array2 = Strings.Split(text2, "[,]", -1, CompareMethod.Binary);
									ListViewItem listViewItem = new ListViewItem();
									listViewItem.Text = array2[1];
									listViewItem.SubItems.Add(array2[2]);
									listViewItem.SubItems.Add(array2[3]);
									if (Operators.CompareString(array2[0], "GOALS", false) == 0)
									{
										listViewItem.ImageIndex = 0;
									}
									else if (Operators.CompareString(array2[0], "NOTICE", false) == 0)
									{
										listViewItem.ImageIndex = 1;
									}
									else if (Operators.CompareString(array2[0], "REPAIR", false) == 0)
									{
										listViewItem.ImageIndex = 2;
									}
									else if (Operators.CompareString(array2[0], "OTHER", false) == 0)
									{
										listViewItem.ImageIndex = 3;
									}
									else if (Operators.CompareString(array2[0], "TUTORIAL", false) == 0)
									{
										listViewItem.ImageIndex = 4;
									}
									else if (Operators.CompareString(array2[0], "UPDATE", false) == 0)
									{
										listViewItem.ImageIndex = 5;
									}
									this.Lvii1.Items.Add(listViewItem);
								}
								this.Lvii1.FX();
							}
							catch (Exception expr_1C1)
							{
								ProjectData.SetProjectError(expr_1C1);
								ProjectData.ClearProjectError();
							}
							i++;
						}
						goto IL_09;
						IL_1DA:
						this.News.Text = text;
						string[] array3 = Strings.Split(expression, "[+]", -1, CompareMethod.Binary);
						array = array3;
						i = 0;
						goto IL_7F;
					}
					IL_09:
					Thread.Sleep(100);
				}
			}
		}
		// Token: 0x06000924 RID: 2340 RVA: 0x00048168 File Offset: 0x00046368
		public void mulai()
		{
			Thread thread = new Thread(new ThreadStart(this.newss));
			thread.Start();
		}
Exemplo n.º 41
0
        private void Perceptron()
        {
            int ciclo = Convert.ToInt32(iterationBox.Text);
            Graphics g = panel1.CreateGraphics();
            Graphics evaluated = valuatedPanel.CreateGraphics();
            bool exit = false;
            int errores = 0, erroresMax = 0;
            int guess;
            double lr = Convert.ToDouble(learningBox.Text);
            float rangoX = (ciclo > valuatedPanel.Width) ? 1 : valuatedPanel.Width / ciclo;
            float rangoY = valuatedPanel.Height / (listaP.Count / 1.9f);
            int error;
            int contador = 0;

            positiveRadBtn.Checked = true;
            evaluated.Clear(Color.White);

            while (!exit && contador < ciclo)
            {
                contador++;
                errores = 0;
                exit = true;

                for (int i = 0; i < listaP.Count; i++)
                {
                    guess = ((weight[1] * listaP[i].PuntoX) + (weight[2] * listaP[i].PuntoY) - weight[0] < 0) ? -1 : 1;
                    error = listaP[i].Label - guess;
                    if (error != 0)
                    {
                        errores += 1;
                        exit = false;
                        weight[0] += lr * error * x0;
                        weight[1] += lr * error * listaP[i].PuntoX;
                        weight[2] += lr * error * listaP[i].PuntoY;

                    }

                }

                g.Clear(Color.White);
                pintarPlano();
                pintarPuntos();
                dibujarLinea(weight, Color.Red);
                dibujarLinea(pesosLinea, Color.Yellow);

                if (contador > 1)
                {
                    evaluated.DrawLine(penGraphic, (rangoX * (contador - 1)), valuatedPanel.Height - (erroresMax * rangoY),
                        (rangoX * contador), valuatedPanel.Height - (errores * rangoY));
                }

                erroresMax = errores;
                Thread.Sleep(100);

            }
            colorearPanel();
            pintarPlano();
            pintarPuntos();
            dibujarLinea(weight, Color.Red);
            dibujarLinea(pesosLinea, Color.Yellow);
            MessageBox.Show("Listo en " + contador + " iteraciones");

        }
Exemplo n.º 42
0
        public MainWindow()
        {
            InitializeComponent();

            //データインデックスを0に予め設定する
            this.DataIndex.SelectedIndex = 0;

            //オフセット値初期化
            InitializeControl();

            //DLL 初期化
            Initialize();

            //Demo (sin: -1.0 -> 1.0)
            this.PlotModel = CreatePlotModel(-5, 5);

            DataContext = this;
            var worker = new BackgroundWorker { WorkerSupportsCancellation = true };
            double x = 0;
            double stop_x = 0;

            worker.DoWork += (s, e) =>
            {
                //DLLからのデータ取得領域確保
                double[] ary = new double[8];
 
                //バックグラウンドワーカーを作成する(作業スレッドを作成すると同じ)
                //ここでセンサーから値を取得する?
                while (!worker.CancellationPending)
                {
                    if (is_stop_resrve) {
                        int count = Environment.TickCount - tickcount;
                        if (count < THREAD_SLEEP_TIME) {
                             stop_x = x;
                        }
                        if (count > 1500) {
                            is_stop = true;
                        }
                    };
                    if (is_stop) {
                        //100ミリ秒休止
                        Thread.Sleep(THREAD_SLEEP_TIME);
                        continue;
                    }

                    lock (this.PlotModel.SyncRoot)
                    {
                        //データ取得処理
                        GetDataProc(ref ary);

                        this.PlotModel.Title = "Plot updated: " + DateTime.Now;
                        for (int i = 0; i < MAX_DATA_COUNT; ++i) {

                            //表示データを操作します。
                            Func<double, double> convert;
                            if (i == 3) {
                                convert = delegate (double a)
                                {
                                    if(is_stop_resrve ){
                                        return (stop_x + X_DISPLAY_RANGE) < a ? 1 : 0;    
                                    }else{ 
                                        return 0;
                                    }
                                };
                            } else {

                                int input_index = ((int)(x / DX)) % DATA_BUF_SIZE;
                                data_buf[i, input_index] = ary[i];
                                convert = delegate (double a)
                                {
                                    double r = 0;
                                    
                                    //データをバッファリングしないとデータが表示されませんので
                                    //ため込んだら表示するような処理が必要です。
                                    if(a - X_DISPLAY_RANGE > 0){
                                        int index = ((int)(a / DX)) % DATA_BUF_SIZE; 
                                        if (data_buf[i,index] > 0){
                                            r =  data_buf[i,index];
                                        }else{
                                            r = 0;
                                        }
                                    }

                                    return r * scale[i] + offset[i];
                                };
                            }

                            //sin関数を使ってオシロスコープ感を出す
                            // (0.01 + i * 0.2) -> 変化を目立たせるため。
                            this.PlotModel.Series[i] = new FunctionSeries(convert, x, x + X_DISPLAY_RANGE, DX);
                            this.PlotModel.Series[i].IsVisible = is_visible[i];
                            this.PlotModel.Series[i].TextColor=OxyColor.FromArgb(0,0,0,0);
                        }
                    }
                    x += DX;
                    PlotModel.InvalidatePlot(true);
                    //100ミリ秒休止
                    Thread.Sleep(THREAD_SLEEP_TIME);
                }
            };
            worker.RunWorkerAsync();
            this.Closed += (s, e) => {
                worker.CancelAsync();
                //DLL 動作終了
                Stop();

                //DLL 終了
                Finilize();
            };
        }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;     // スレッドの優先度を上げておく
            // 画面リフレッシュレートと目標フレームレートが等しい場合は垂直同期を有効に、等しくない場合は垂直同期を無効にする
            DX.SetWaitVSyncFlag(DX.GetRefreshRate() == TargetFPS ? DX.TRUE : DX.FALSE);

            // ウィンドウのタイトル
#if DEBUG
            DX.SetWindowText("Surusuri(デバッグ)");
            #else
            DX.SetWindowText("Surusuri");
            #endif

            DX.SetGraphMode((int)Screen.Size.X, (int)Screen.Size.Y, 32);     // ウィンドウサイズ(画面解像度)の指定

            // フルスクリーンの可否
            if (Screen.FullScreen)
            {
                DX.ChangeWindowMode(DX.FALSE); // フルスクリーン
            }
            else
            {
                DX.ChangeWindowMode(DX.TRUE); // ノーフルスクリーン
            }

            DX.SetAlwaysRunFlag(DX.TRUE);        // ウィンドウが非アクティブでも動作させる

            DX.DxLib_Init();                     // DXライブラリの初期化

            DX.SetMouseDispFlag(DX.TRUE);        // マウスを表示する(DX.FALSEを指定すると非表示になる)
            DX.SetDrawScreen(DX.DX_SCREEN_BACK); // 描画先を裏画面とする(ダブルバッファ)

            game = new Game();
            game.Init();

            DX.ScreenFlip();
            stopwatch.Start();

            while (DX.ProcessMessage() == 0) // ウィンドウが閉じられるまで繰り返す
            {
                // FPSの計測
                fpsFrameCount++;
                if (fpsFrameCount >= 60)
                {
                    long  elapsedTicks = stopwatch.Elapsed.Ticks - fpsTicks;
                    float elapsedSec   = elapsedTicks / 10000000f;
                    CurrentFPS = fpsFrameCount / elapsedSec;

                    fpsFrameCount = 0;
                    fpsTicks      = stopwatch.Elapsed.Ticks;
                }

                game.Update();

                if (DX.GetWaitVSyncFlag() == DX.TRUE)
                {
                    if (EnableFrameSkip)
                    {
                        long waitTicks = nextFrameTicks - stopwatch.Elapsed.Ticks; // 余った時間

                        if (waitTicks < 0)                                         // 目標時刻をオーバーしている
                        {
                            if (skipCount < MaxAllowSkipCount)                     // 連続フレームスキップ数が最大スキップ数を超えていなければ
                            {
                                skipCount++;                                       // フレームスキップ(描画処理を飛ばす)
                            }
                            else
                            {
                                // 最大スキップ数を超えてるので、フレームスキップしないで描画
                                nextFrameTicks = stopwatch.Elapsed.Ticks;
                                Draw();
                            }
                        }
                        else
                        {
                            Draw();
                        }

                        nextFrameTicks += IntervalTicks;
                    }
                    else
                    {
                        Draw();
                    }
                }
                else
                {
                    long waitTicks = nextFrameTicks - stopwatch.Elapsed.Ticks; // 余った時間(待機が必要な時間)

                    if (EnableFrameSkip && waitTicks < 0)
                    {
                        if (skipCount < MaxAllowSkipCount)
                        {
                            skipCount++; // フレームスキップ(描画処理を飛ばす)
                        }
                        else
                        {
                            nextFrameTicks = stopwatch.Elapsed.Ticks;
                            Draw();
                        }
                    }
                    else
                    {
                        if (waitTicks > 20000) // あと2ミリ秒以上待つ必要がある
                        {
                            // Sleep()は指定した時間でピッタリ戻ってくるわけではないので、
                            // 余裕を持って、「待たなければならない時間-2ミリ秒」Sleepする
                            int waitMillsec = (int)(waitTicks / 10000) - 2;
                            Thread.Sleep(waitMillsec);
                        }

                        // 時間が来るまで何もしないループを回して待機する
                        while (stopwatch.Elapsed.Ticks < nextFrameTicks)
                        {
                        }

                        Draw();
                    }
                    nextFrameTicks += IntervalTicks;
                }
            }

            DX.DxLib_End(); // DXライブラリ終了処理
        }
Exemplo n.º 44
0
        /// <summary> Entry point for queue consumption </summary>
        /// <param name="token">A cancellation token used to signal to stop</param>
        /// <remarks> This function only returns after <see cref="Stop"/> is called or the token is cancelled</remarks>
        private void ConsumeEnumerators(CancellationToken token)
        {
            while (true)
            {
                if (_isStopping || token.IsCancellationRequested)
                {
                    _isStopping = true;
                    var request = token.IsCancellationRequested ? "Cancellation requested" : "Stop requested";
                    Log.Trace("BaseDataExchange({0}).ConsumeQueue(): {1}.  Exiting...", Name, request);
                    return;
                }

                try
                {
                    // call move next each enumerator and invoke the appropriate handlers

                    var handled = false;
                    foreach (var kvp in _enumerators)
                    {
                        var enumeratorHandler = kvp.Value;
                        var enumerator = enumeratorHandler.Enumerator;

                        // check to see if we should advance this enumerator
                        if (!enumeratorHandler.ShouldMoveNext()) continue;

                        if (!enumerator.MoveNext())
                        {
                            enumeratorHandler.OnEnumeratorFinished();
                            enumeratorHandler.Enumerator.Dispose();
                            _enumerators.TryRemove(enumeratorHandler.Symbol, out enumeratorHandler);
                            continue;
                        }

                        if (enumerator.Current == null) continue;

                        // if the enumerator is configured to handle it, then do it, don't pass to data handlers
                        if (enumeratorHandler.HandlesData)
                        {
                            handled = true;
                            enumeratorHandler.HandleData(enumerator.Current);
                            continue;
                        }

                        // invoke the correct handler
                        DataHandler dataHandler;
                        if (_dataHandlers.TryGetValue(enumerator.Current.Symbol, out dataHandler))
                        {
                            handled = true;
                            dataHandler.OnDataEmitted(enumerator.Current);
                        }
                    }

                    // if we didn't handle anything on this past iteration, take a nap
                    if (!handled && _sleepInterval != 0)
                    {
                        Thread.Sleep(_sleepInterval);
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    if (_isFatalError(err))
                    {
                        Log.Trace("BaseDataExchange({0}).ConsumeQueue(): Fatal error encountered. Exiting...", Name);
                        return;
                    }
                }
            }
        }
Exemplo n.º 45
0
        public static void Initialize() {
            Get("/", context => File.ReadAllText("Views/index.html", Encoding.UTF8));

            Get("/media", context => File.ReadAllText("Views/media.html", Encoding.UTF8), "Media");

            Get("/kamera", context => string.Format(File.ReadAllText("Views/camera.html", Encoding.UTF8),
                GetTimeString(DatabaseHandler.GetLatestImageInfo(1).CreationTime),
                GetTimeString(DatabaseHandler.GetLatestImageInfo(2).CreationTime)), "Kamera");

            Get("/kamera/get-latest-image", context => {
                byte imageId = byte.Parse(context.Request.QueryString["image"]);
                byte[] buffer = File.ReadAllBytes(DatabaseHandler.GetLatestImageInfo(imageId).FullName);
                context.Response.ContentLength64 = buffer.Length;
                context.Response.ContentType = "image/jpeg";
                Stream output = context.Response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            });

            Get("/realtid", context => {
                string[] classes = new string[5];
                classes[(byte) DatabaseHandler.GetDataPeriod(context.Request.QueryString["senaste"])] = " active";
                return string.Format(File.ReadAllText("Views/realtime.html", Encoding.UTF8), classes);
            }, "Realtidsdata");

            Get("/realtid/get-sensordata", context => {
                byte[] sensorIds = Array.ConvertAll(context.Request.QueryString["sensors"].Split(','), byte.Parse);
                var dataPeriod = DatabaseHandler.GetDataPeriod(context.Request.QueryString["senaste"]);
                byte[] buffer = DatabaseHandler.GetSensorData(sensorIds, dataPeriod);
                context.Response.ContentLength64 = buffer.Length;
                context.Response.ContentType = "text/plain";
                Stream output = context.Response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            });

            Get("/realtid/get-latest-sensor-value", context => {
                byte[] sensorIds = Array.ConvertAll(context.Request.QueryString["sensors"].Split(','), byte.Parse);
                bool done = false;
                context.Response.ContentType = "text/plain";
                void SendSensorData(SensorData sensorData) {
                    try {
                        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                        byte[] buffer = Encoding.UTF8.GetBytes(string.Join(' ', 
                            sensorData.Sensors.Where(c => sensorIds.Contains(c.id))
                            .Select(c => $"{c.id},{(byte) c.type},{c.value}")));
                        context.Response.ContentLength64 = buffer.Length;
                        Stream output = context.Response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                        output.Close();
                        done = true;
                    } catch { }
                }
                DatabaseHandler.OnReceivedSensorData += SendSensorData;
                Thread.Sleep(1500);
                if (done) return;
                DatabaseHandler.OnReceivedSensorData -= SendSensorData;
                ServerError(context, 408);
            });

            Get("/realtid/get-sensor-names-units", context => {
                byte[] buffer = Encoding.UTF8.GetBytes(string.Join('|', 
                    SensorList.Sensors.Select(c => $"{c.SensorId},{c.SensorName}")) + '#' +
                    string.Join(',', SensorList.Units) + '#' + string.Join(',', SensorList.Readings));
                context.Response.ContentLength64 = buffer.Length;
                context.Response.ContentType = "text/plain";
                Stream output = context.Response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            });

            Get("/*", (context, groups) => {
                context.Response.StatusCode = 404;
                return "<article><h2>Sidan hittades inte.</h2></article>";
            }, "Sidan hittades inte");
        }
Exemplo n.º 46
0
        private string ExtractTextFromAudio(string targetFile, int delayInMilliseconds)
        {
            var output = new StringBuilder();
            var path = Path.Combine(Configuration.DataDirectory, "pocketsphinx");
            var fileName = Path.Combine(path, "bin", "Release", "Win32", "pocketsphinx_continuous.exe");
            var hmm = Path.Combine(path, "model", "en-us", "en-us");
            var lm = Path.Combine(path, "model", "en-us", "en-us.lm.bin");
            var dict = Path.Combine(path, "model", "en-us", "cmudict-en-us.dict");
            var pocketPhinxParams = $"-infile \"{targetFile}\" -hmm \"{hmm}\" -lm \"{lm}\" -dict \"{dict}\" -time yes"; // > \"{_resultFile}\"";

            var process = new Process { StartInfo = new ProcessStartInfo(fileName, pocketPhinxParams) { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden } };
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;

            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                process.OutputDataReceived += (sender, e) =>
                {
                    if (_abort)
                    {
                        return;
                    }

                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        output.AppendLine(e.Data);
                        var seconds = GetLastTimeStampInSeconds(e.Data);
                        if (seconds > 0)
                        {
                            _backgroundWorker.ReportProgress(seconds);
                        }
                        _backgroundWorker.ReportProgress(LogOutput, e.Data);
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (_abort)
                    {
                        return;
                    }

                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        _backgroundWorker.ReportProgress(LogInfo, e.Data);
                    }
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                var killed = false;
                while (!process.HasExited)
                {
                    Application.DoEvents();
                    Thread.Sleep(50);
                    if (_abort && !killed)
                    {
                        process.Kill();
                        killed = true;
                    }
                }

            }
            return output.ToString();
        }
Exemplo n.º 47
0
		/// <summary>
		/// This thread updates the NPCs and objects around the player at very short
		/// intervalls! But since the update is very quick the thread will
		/// sleep most of the time!
		/// </summary>
		public static void WorldUpdateThreadStart()
		{
			// Tasks Collection of running Player updates, with starting time.
			var clientsUpdateTasks = new Dictionary<GameClient, Tuple<long, Task, Region>>();
			
			bool running = true;
			
			if (log.IsInfoEnabled)
			{
				log.InfoFormat("World Update Thread Starting - ThreadId = {0}", Thread.CurrentThread.ManagedThreadId);
			}
			
			while (running)
			{
				try
				{
					// Start Time of the loop
					long begin = GameTimer.GetTickCount();
					
					// Get All Clients
					var clients = WorldMgr.GetAllClients();
					
					// Clean Tasks Dict on Client Exiting.
					foreach(GameClient cli in clientsUpdateTasks.Keys.ToArray())
					{
						if (cli == null)
							continue;
						
						GamePlayer player = cli.Player;
						
						bool notActive = cli.ClientState != GameClient.eClientState.Playing || player == null || player.ObjectState != GameObject.eObjectState.Active;
						bool notConnected = !clients.Contains(cli);
						
						if (notConnected || (notActive && IsTaskCompleted(cli, clientsUpdateTasks)))
						{
							clientsUpdateTasks.Remove(cli);
							cli.GameObjectUpdateArray.Clear();
							cli.HouseUpdateArray.Clear();
						}
					}
					
					// Browse all clients to check if they can be updated.
					for (int cl = 0; cl < clients.Count; cl++)
					{
						GameClient client = clients[cl];
						
						// Check that client is healthy
						if (client == null)
							continue;

						GamePlayer player = client.Player;
						
						if (client.ClientState == GameClient.eClientState.Playing && player == null)
						{
							if (log.IsErrorEnabled)
								log.Error("account has no active player but is playing, disconnecting! => " + client.Account.Name);
							
							// Disconnect buggy Client
							GameServer.Instance.Disconnect(client);
							continue;
						}
						
						// Check that player is active.
						if (client.ClientState != GameClient.eClientState.Playing || player == null || player.ObjectState != GameObject.eObjectState.Active)
							continue;
						
						// Start Update Task
						StartPlayerUpdateTask(client, clientsUpdateTasks, begin);
					}
					
					long took = GameTimer.GetTickCount() - begin;
					
					if (took >= 500)
					{
						if (log.IsWarnEnabled)
							log.WarnFormat("World Update Thread (NPC/Object update) took {0} ms", took);
					}

					// relaunch update thread every 100 ms to check if any player need updates.
					Thread.Sleep((int)Math.Max(1, 100 - took));
				}
				catch (ThreadAbortException)
				{
					if (log.IsInfoEnabled)
						log.Info("World Update Thread stopping...");
					
					running = false;
					break;
				}
				catch (Exception e)
				{
					if (log.IsErrorEnabled)
						log.Error("Error in World Update (NPC/Object Update) Thread!", e);
				}
			}
		}
Exemplo n.º 48
0
 public void Work()
 {
     Thread.Sleep(50);
 }
        internal static bool BuildAssembly(string[] paths, string outputPath, string[] excludeReferences = null,
                                           string[] additionalReferences = null, string[] additionalDefines = null)
        {
            if (paths == null || paths.Length == 0)
            {
                return(false);
            }

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            additionalReferences = additionalReferences == null ? predefinedReferences : predefinedReferences.Concat(additionalReferences).ToArray();
            var assemblyBuilder = new AssemblyBuilder(outputPath, paths)
            {
                additionalDefines    = additionalDefines,
                excludeReferences    = excludeReferences,
                referencesOptions    = ReferencesOptions.UseEngineModules,
                additionalReferences = additionalReferences,
                compilerOptions      = new ScriptCompilerOptions()
                {
                    AllowUnsafeCode = true
                }
            };

            bool buildSucceed = false;

            assemblyBuilder.buildFinished += delegate(string assemblyPath, CompilerMessage[] compilerMessages)
            {
                foreach (var m in compilerMessages)
                {
                    switch (m.type)
                    {
                    case CompilerMessageType.Warning:
                        Debug.LogWarning(m.message);
                        break;

                    case CompilerMessageType.Error:
                        Debug.LogError(m.message);
                        break;

                    default:
                        Debug.Log(m.message);
                        break;
                    }
                }

                var errorCount   = compilerMessages.Count(m => m.type == CompilerMessageType.Error);
                var warningCount = compilerMessages.Count(m => m.type == CompilerMessageType.Warning);

                if (warningCount > 0 || errorCount > 0)
                {
                    Debug.Log($"Assembly build finished for {assemblyPath} -- Warnings: {warningCount} - Errors: {errorCount}");
                }

                if (errorCount != 0)
                {
                    return;
                }

                buildSucceed = true;
            };

            if (!assemblyBuilder.Build())
            {
                Debug.LogErrorFormat("Failed to start build of assembly {0}!", assemblyBuilder.assemblyPath);
                return(false);
            }

            while (assemblyBuilder.status != AssemblyBuilderStatus.Finished)
            {
                Thread.Sleep(10);
            }

            return(buildSucceed);
        }
Exemplo n.º 50
0
 static void Main(string[] args)
 {
     try
     {
         Log.InfoFormat("Start...");
         Console.WriteLine("Start...");
         QT_2DataSet QT2 = new QT_2DataSet();
         QT_2DataSetTableAdapters.CompanyTableAdapter companyTableAdapter = new QT_2DataSetTableAdapters.CompanyTableAdapter();
         string    rabbitMQServerName            = ConfigurationManager.AppSettings["rabbitMQServerName"];
         string    updateDatafeedGroupName       = ConfigurationManager.AppSettings["updateDatafeedGroupName"];
         string    updateDatafeedJobName         = ConfigurationManager.AppSettings["updateDatafeedJobName"];
         int       updateDatafeedJobExpirationMS = CommonUtilities.Object2Int(ConfigurationManager.AppSettings["updateDatafeedJobExpirationMS"], 0);
         string    connectionstring = ConfigurationManager.AppSettings["ConnectionString"];
         var       rabbitMQServer   = RabbitMQManager.GetRabbitMQServer(rabbitMQServerName);
         JobClient jobClient        = new JobClient(updateDatafeedGroupName, GroupType.Topic, updateDatafeedJobName, true, rabbitMQServer);
         //Log.InfoFormat("ConnectionString = {0}", connectionstring);
         companyTableAdapter.Connection.ConnectionString = connectionstring;
         companyTableAdapter.FillByCompanyDataFeed(QT2.Company);
         Log.InfoFormat("Got {0} companies.", QT2.Company.Rows.Count);
         int sendmessage = 0;
         for (int i = 0; i < QT2.Company.Rows.Count; i++)
         {
             var companyID  = (long)QT2.Company.Rows[i]["ID"];
             int updateFreq = 0;
             int.TryParse(QT2.Company.Rows[i]["UpdateFreq"].ToString(), out updateFreq);
             // Check UpdateFreq nếu > 0 thì đi tiếp, còn = 0 có thể đã lỗi dữ liệu
             if (updateFreq <= 0)
             {
                 continue;
             }
             string timeupdate = QT2.Company.Rows[i]["LastUpdateDataFeed"].ToString();
             //Kiểm tra LastUpdate nếu NULL thì thực hiện
             if (timeupdate != "")
             {
                 DateTime lastUpdateDataFeed = DateTime.Parse(timeupdate);
                 var      duration           = DateTime.Now - lastUpdateDataFeed;
                 if (duration.TotalHours < updateFreq)
                 {
                     continue;
                 }
             }
             var job = new Job();
             job.Data = BitConverter.GetBytes(companyID);
             try
             {
                 jobClient.PublishJob(job, updateDatafeedJobExpirationMS);
                 sendmessage++;
                 Console.WriteLine(string.Format("{0}. Published UpdateDatafeed job for Company: {1}", i, companyID));
                 Log.InfoFormat("Published UpdateDatafeed job for Company: {0}", companyID);
             }
             catch (Exception ex)
             {
                 Log.Error("Publish UpdateDatafeed job error. Company:" + companyID, ex);
             }
         }
         Console.WriteLine(string.Format("Publish {0} company to service.", sendmessage));
         Log.Info(string.Format("Publish {0} company to service.", sendmessage));
         rabbitMQServer.Stop();
     }
     catch (Exception ex)
     {
         Log.Error("ERROR: " + ex);
     }
     Thread.Sleep(10000);
 }
Exemplo n.º 51
0
 public static void ServiceFabricHost()
 {
     ServiceRuntime.RegisterServiceAsync("InvSysCompaniesApiType", context => new WebHostingService(context, "ServiceEndpoint")).GetAwaiter().GetResult();
     Thread.Sleep(Timeout.Infinite);
 }
Exemplo n.º 52
0
        /// <summary>
        /// Receives a <see cref="BrokeredMessage"/> from the event bus.
        /// </summary>
        protected virtual void ReceiveEvent(PartitionContext context, EventData eventData)
        {
            DateTimeOffset startedAt     = DateTimeOffset.UtcNow;
            Stopwatch      mainStopWatch = Stopwatch.StartNew();
            string         responseCode  = "200";
            // Null means it was skipped
            bool?              wasSuccessfull      = true;
            string             telemetryName       = string.Format("Cqrs/Handle/Event/{0}", eventData.SequenceNumber);
            ISingleSignOnToken authenticationToken = null;

            IDictionary <string, string> telemetryProperties = new Dictionary <string, string> {
                { "Type", "Azure/EventHub" }
            };
            object value;

            if (eventData.Properties.TryGetValue("Type", out value))
            {
                telemetryProperties.Add("MessageType", value.ToString());
            }
            TelemetryHelper.TrackMetric("Cqrs/Handle/Event", CurrentHandles++, telemetryProperties);
            // Do a manual 10 try attempt with back-off
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Logger.LogDebug(string.Format("An event message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}'.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset));
                    string messageBody = Encoding.UTF8.GetString(eventData.GetBytes());

                    IEvent <TAuthenticationToken> @event = AzureBusHelper.ReceiveEvent(messageBody, ReceiveEvent,
                                                                                       string.Format("partition key '{0}', sequence number '{1}' and offset '{2}'", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset),
                                                                                       () =>
                    {
                        wasSuccessfull = null;
                        telemetryName  = string.Format("Cqrs/Handle/Event/Skipped/{0}", eventData.SequenceNumber);
                        responseCode   = "204";
                        // Remove message from queue
                        context.CheckpointAsync(eventData);
                        Logger.LogDebug(string.Format("An event message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but processing was skipped due to event settings.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset));
                        TelemetryHelper.TrackEvent("Cqrs/Handle/Event/Skipped", telemetryProperties);
                    }
                                                                                       );

                    if (wasSuccessfull != null)
                    {
                        if (@event != null)
                        {
                            telemetryName       = string.Format("{0}/{1}", @event.GetType().FullName, @event.Id);
                            authenticationToken = @event.AuthenticationToken as ISingleSignOnToken;

                            var telemeteredMessage = @event as ITelemeteredMessage;
                            if (telemeteredMessage != null)
                            {
                                telemetryName = telemeteredMessage.TelemetryName;
                            }

                            telemetryName = string.Format("Cqrs/Handle/Event/{0}", telemetryName);
                        }
                        // Remove message from queue
                        context.CheckpointAsync(eventData);
                    }
                    Logger.LogDebug(string.Format("An event message arrived and was processed with the partition key '{0}', sequence number '{1}' and offset '{2}'.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset));

                    IList <IEvent <TAuthenticationToken> > events;
                    if (EventWaits.TryGetValue(@event.CorrelationId, out events))
                    {
                        events.Add(@event);
                    }

                    wasSuccessfull = true;
                    responseCode   = "200";
                    return;
                }
                catch (Exception exception)
                {
                    // Indicates a problem, unlock message in queue
                    Logger.LogError(string.Format("An event message arrived with the partition key '{0}', sequence number '{1}' and offset '{2}' but failed to be process.", eventData.PartitionKey, eventData.SequenceNumber, eventData.Offset), exception: exception);

                    switch (i)
                    {
                    case 0:
                    case 1:
                        // 10 seconds
                        Thread.Sleep(10 * 1000);
                        break;

                    case 2:
                    case 3:
                        // 30 seconds
                        Thread.Sleep(30 * 1000);
                        break;

                    case 4:
                    case 5:
                    case 6:
                        // 1 minute
                        Thread.Sleep(60 * 1000);
                        break;

                    case 7:
                    case 8:
                        // 3 minutes
                        Thread.Sleep(3 * 60 * 1000);
                        break;

                    case 9:
                        telemetryProperties.Add("ExceptionType", exception.GetType().FullName);
                        telemetryProperties.Add("ExceptionMessage", exception.Message);
                        break;
                    }
                    wasSuccessfull = false;
                    responseCode   = "500";
                }
                finally
                {
                    // Eventually just accept it
                    context.CheckpointAsync(eventData);

                    TelemetryHelper.TrackMetric("Cqrs/Handle/Event", CurrentHandles--, telemetryProperties);

                    mainStopWatch.Stop();
                    TelemetryHelper.TrackRequest
                    (
                        telemetryName,
                        authenticationToken,
                        startedAt,
                        mainStopWatch.Elapsed,
                        responseCode,
                        wasSuccessfull == null || wasSuccessfull.Value,
                        telemetryProperties
                    );

                    TelemetryHelper.Flush();
                }
            }
        }
		public void Dispose()
		{
			m_thread_active = false;

			while ( m_think_thread.IsAlive ) Thread.Sleep(1);
		}
Exemplo n.º 54
0
        public static void Main(string[] args)
        {
            m_Assembly = Assembly.GetEntryAssembly();

            /* print a banner */
            Version ver = m_Assembly.GetName().Version;

            Console.WriteLine("SunUO Version {0}.{1}.{2} http://www.sunuo.org/",
                              ver.Major, ver.Minor, ver.Revision);
            Console.WriteLine("  on {0}, runtime {1}",
                              Environment.OSVersion, Environment.Version);

            if ((int)Environment.OSVersion.Platform == 128)
            {
                Console.WriteLine("Please make sure you have Mono 1.1.7 or newer! (mono -V)");
            }

            Console.WriteLine();

            /* prepare SunUO */
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(CurrentDomain_ProcessExit);

            bool debug = false;

            for (int i = 0; i < args.Length; ++i)
            {
                if (Insensitive.Equals(args[i], "-debug"))
                {
                    debug = true;
                }
                else if (Insensitive.Equals(args[i], "-service"))
                {
                    m_Service = true;
                }
                else if (Insensitive.Equals(args[i], "-profile"))
                {
                    Profiling = true;
                }
                else if (args[i] == "--logfile")
                {
                    string       logfile = args[++i];
                    StreamWriter writer  = new StreamWriter(new FileStream(logfile, FileMode.Append, FileAccess.Write));
                    writer.AutoFlush = true;
                    Console.SetOut(writer);
                    Console.SetError(writer);
                }
            }

            config = new Config(Path.Combine(BaseDirectoryInfo.CreateSubdirectory("etc").FullName, "sunuo.xml"));

            try
            {
                m_MultiConOut = new MultiTextWriter(Console.Out);
                Console.SetOut(m_MultiConOut);

                if (m_Service)
                {
                    string filename = Path.Combine(LogDirectoryInfo.FullName, "console.log");
                    m_MultiConOut.Add(new FileLogger(filename));
                }
            }
            catch
            {
            }

            m_Thread  = Thread.CurrentThread;
            m_Process = Process.GetCurrentProcess();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            Timer.TimerThread ttObj = new Timer.TimerThread();
            timerThread      = new Thread(new ThreadStart(ttObj.TimerMain));
            timerThread.Name = "Timer Thread";

            if (!ScriptCompiler.Compile(debug))
            {
                return;
            }

            Console.Write("Verifying scripts:");
            m_ItemCount   = 0;
            m_MobileCount = 0;
            foreach (Library l in ScriptCompiler.Libraries)
            {
                int itemCount = 0, mobileCount = 0;
                Console.Write(" {0}[", l.Name);
                l.Verify(ref itemCount, ref mobileCount);
                Console.Write("{0} items, {1} mobiles]", itemCount, mobileCount);
                m_ItemCount   += itemCount;
                m_MobileCount += mobileCount;
            }
            Console.WriteLine(" - done ({0} items, {1} mobiles)", m_ItemCount, m_MobileCount);

            try {
                ScriptCompiler.Configure();
            } catch (TargetInvocationException e) {
                Console.WriteLine("Configure exception: {0}", e.InnerException);
                return;
            }

            if (!config.Exists)
            {
                config.Save();
            }

            World.Load();

            try {
                ScriptCompiler.Initialize();
            } catch (TargetInvocationException e) {
                Console.WriteLine("Initialize exception: {0}", e.InnerException);
                return;
            }

            Region.Load();

            m_MessagePump = new MessagePump(new Listener(Listener.Port));

            timerThread.Start();

            NetState.Initialize();
            Encryption.Initialize();

            EventSink.InvokeServerStarted();

            try
            {
                while (!m_Closing)
                {
                    Thread.Sleep(1);

                    Mobile.ProcessDeltaQueue();
                    Item.ProcessDeltaQueue();

                    Timer.Slice();
                    m_MessagePump.Slice();

                    NetState.FlushAll();
                    NetState.ProcessDisposedQueue();

                    if (Slice != null)
                    {
                        Slice();
                    }
                }
            }
            catch (Exception e)
            {
                CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, true));
            }

            if (timerThread.IsAlive)
            {
                timerThread.Abort();
            }
        }
Exemplo n.º 55
0
    public static async Task DownloadJava()
    {
        if (!Directory.Exists(config.javaLocal + "runtime\\jre"))
        {
            Directory.CreateDirectory(config.javaLocal + "runtime\\jre");
        }

        /*Pages.SplashScreen.singleton.firstLabel.Visibility = Visibility.Visible;
         * Pages.SplashScreen.singleton.progressbar.Visibility = Visibility.Visible;
         * Pages.SplashScreen.singleton.mbToDownload.Visibility = Visibility.Visible;
         * Pages.SplashScreen.singleton.kbps.Visibility = Visibility.Visible;*/

#if STYLE_1
        await Task.Delay(1000);

        DownloadWindowLayout1.instance.downloadtext.Text = "서버에 맞는 자바를 다운로드 중입니다.";
#endif
        System.Threading.Thread.Sleep(1500);
        // Windows.Splashscreen.singleton.actualActivity.Text = "Downloading Java";

        string url = "";
        //i .exe sono zip in verita'
        if (ComputerInfoDetect.GetComputerArchitecture() == 64)
        {
            url = config.jre64URL;
        }
        else
        {
            url = config.jre32URL;
        }
        Uri uri = new Uri(url);

        webClient.DownloadFileCompleted   += new AsyncCompletedEventHandler(Completed);
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
        webClient.Headers.Set("Cookie", "oraclelicense=accept-securebackup-cookie");
        sw.Start();
        try
        {
            await webClient.DownloadFileTaskAsync(new Uri(url), config.javaLocal + "runtime\\java.zip");
        }
        catch (Exception e)
        {
            MessageBox.Show("Errore nel download di JAVA. Minecraft potrebbe non avviarsi correttamente" + e.Message);
        }

        /*Pages.SplashScreen.singleton.progressbar.Visibility = Visibility.Visible;
         * Pages.SplashScreen.singleton.progressbar.IsIndeterminate = true;*/
#if STYLE_1
        DownloadWindowLayout1.instance.downloadtext.Text = "자바 압축 해제중입니다.";
#endif

        try
        {
            using (Stream targetStream = new GZipInputStream(File.OpenRead(config.javaLocal + "runtime\\java.zip")))
            {
                using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(targetStream, TarBuffer.DefaultBlockFactor))
                {
                    await Task.Factory.StartNew(() =>
                    {
                        tarArchive.ExtractContents(config.javaLocal + "runtime\\jre");
                    })
                    .ContinueWith((ante) => Thread.Sleep(200));;
                }
            }
        }
        catch (TargetInvocationException e)
        {
            MessageBox.Show(e.ToString());
        }
        if (ComputerInfoDetect.GetComputerArchitecture() == 64)
        {
            Properties.Settings.Default["JavaPath"] = config.javaLocal + "runtime\\jre\\" + config.jre64FileName + "\\";
            Properties.Settings.Default.Save();
        }
        else
        {
            Properties.Settings.Default["JavaPath"] = config.javaLocal + "runtime\\jre\\" + config.jre32FileName + "\\";
            Properties.Settings.Default.Save();
        }

#if STYLE_1
        DownloadWindowLayout1.instance.downloadtext.Text = ("자바 설치가 완료되었습니다.");
        await Task.Delay(1000);
#endif

        /*Pages.SplashScreen.singleton.progressbar.Visibility = Visibility.Hidden;
         * Pages.SplashScreen.singleton.progressbar.IsIndeterminate = false;
         *
         * Pages.SplashScreen.singleton.firstLabel.Text = "Java Extraction Completed";
         * Pages.SplashScreen.singleton.kbps.Visibility = Visibility.Hidden;*/
    }
 public override void Send(SendOrPostCallback d, object state)
 {
     var t = new Thread(CallbackRunner);
     t.Start((d, state));
 }
Exemplo n.º 57
0
		void ExecuteQueue()
		{	
			try{
				bool ready=false;
				foreach(MudCharacter character in NonPlayersInRoom)
				{
					character.StartTurn();
				}
				foreach(MudCharacter character in PlayersInRoom)
				{
					character.StartTurn();
				}
				//give all characters a chance to put in an action
				while(!ready)
				{
					lock(lockobject){
						foreach(MudCharacter character in PlayersInRoom) //test for an action from all characters
						{
							ready=false;
							foreach(CharacterAction action in ActionQueue)
							{
								if(action.Character==character)
								{
									ready=true;
									break;
								}
								
							}
							if(!ready)
							{
								break;
							}
						}
						if(DateTime.Now>time) //if time is up execute all actions in the queue 
						{
							if(ActionQueue.Count==0&&PlayersInRoom.Count>0)
							{
								time=DateTime.Now.AddSeconds(timeoutSeconds);
							}else{
								ready=true;
							}
						}
					}
					Thread.Sleep(100);
				}	
				
				lock(lockobject)
				{
					while(ActionQueue.Count>0)
					{
						CharacterAction action=ActionQueue.Dequeue();
						//skip actions by characters no longer in room(probably dead)
						if(action.Character is PlayerCharacter)
						{
							if(!PlayersInRoom.Contains(action.Character as PlayerCharacter))
							{
								continue;
							}
						}else{
							if(!NonPlayersInRoom.Contains(action.Character))
							{
								continue;
							}
						}
						//skip actions on targets no longer in room
						if(action is TargetedAction)
						{
							TargetedAction ta=(action as TargetedAction);
							if(ta.Target is PlayerCharacter)
							{
								if(!PlayersInRoom.Contains(ta.Target as PlayerCharacter))
								{
									continue;
								}
							}else{
								if(!NonPlayersInRoom.Contains(ta.Target))
								{
									continue;
								}
							}
						}
						
						string msg=action.DoAction();
						NotifyPlayers(msg);
						//test for death
						//funky loops because the lists we're iterating might be changed
						
						foreach(MudCharacter c in GetCharactersInRoom())
						{
							if(c.HitPoints<=0)
							{
								NotifyPlayers("\t{0} has died.",c.StatusString());
								c.OnDeath();
								RemoveCharacter(c);
 							}
						}
						
					}
					foreach(MudCharacter c in GetCharactersInRoom())
					{
						c.EndTurn();
						if(c.HitPoints<=0)
						{
							NotifyPlayers("\t{0} has died.",c.StatusString());
							c.OnDeath();
							RemoveCharacter(c);
 						}
					}
					Status=GenerateStatus();
				}	
				
				Thread.Sleep(100);
				
				lock(lockobject)
				{
					if(PlayersInRoom.Count==0){
						ActionQueue.Clear();
						ActionTask=null;
						time=DateTime.MinValue;
					
					}else{
						time=DateTime.Now.AddSeconds(timeoutSeconds);
						ActionTask=Task.Factory.StartNew(new Action(ExecuteQueue));
					}
				}
			
			}catch(Exception ex){
				Console.WriteLine(ex.Message);
				Console.WriteLine(ex.StackTrace);
			}
		}
Exemplo n.º 58
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(TaskRun2));

            thread.Start("线程2");
        }
Exemplo n.º 59
0
        static void Run(CancellationToken token)
        {
            bool shouldWait = false;

            while (!token.IsCancellationRequested)
            {
                if (shouldWait)
                {
                    Console.WriteLine("Going to sleep for 30 seconds...");
                    Thread.Sleep(30000);
                    shouldWait = false;
                }

                try
                {
                    using (var context = new ObsidianChainContext())
                    {
                        using (IDbContextTransaction dbtx = context.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
                        {
                            try
                            {
                                if (context.BlockEntities.Any())
                                {
                                    _currentBlockNumber = context.BlockEntities.Max(x => x.Id);
                                    _currentBlockHeight = context.BlockEntities.Max(x => x.Id) - 1;
                                    _currentBlockHeight++;
                                    _currentBlockNumber++;
                                }

                                string blockHash = _txAdapter.RpcClient.GetBlockHashAsync(_currentBlockHeight).GetAwaiter().GetResult();

                                if (blockHash == null)
                                {
                                    Console.WriteLine($"Block at height {_currentBlockHeight} not found!");
                                    shouldWait = true;
                                    continue;
                                }

                                var result = IndexBlock(context, blockHash);
                                if (result != 0)
                                {
                                    return;
                                }

                                var stats = context.StatEntities.Find("1"); // insert this row manually
                                stats.BestAdrIndexHeight = _currentBlockHeight;
                                stats.ModifiedDate       = DateTime.UtcNow;

                                context.SaveChanges(); // this is still necessary, even when using Commit()
                                dbtx.Commit();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"Error within the transaction: {ex.Message}");
                                shouldWait = true;
                            }
                        } // Dispose db transaction
                    }     // Dispose db connection
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error creating connection / transaction: {e.Message}");
                    Console.WriteLine("Pausing 30 seconds...");
                    Thread.Sleep(30000);
                    Console.WriteLine("Reconnecting...");
                }
            }
        }
Exemplo n.º 60
0
 public ProducerConsumerQueue()
 {
     _worker = new Thread(Work);
     _worker.Name = "A";
     _worker.Start();
 }