Esempio n. 1
0
		public DownloadForm() {
			InitializeComponent();
			objectListViewDownloads.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.DoubleClick;

			comboBoxService.SelectedIndex = 0;
			comboBoxPowerStateWhenDone.SelectedIndex = 0;
			TwitchAPI = new Twixel( "", "", Twixel.APIVersion.v3 );
			JobQueue = new System.Collections.Concurrent.ConcurrentQueue<IVideoJob>();
			RunningJobs = 0;

			if ( !Util.AllowTimedAutoFetch ) {
				labelStatusBar.Hide();
			}

			objectListViewDownloads.SecondarySortColumn = objectListViewDownloads.GetColumn( "Video ID" );
			objectListViewDownloads.SecondarySortOrder = SortOrder.Ascending;

			columnStatus.GroupKeyGetter = delegate ( object rowObject ) {
				return ( (IVideoJob)rowObject ).JobStatus;
			};
			columnIndex.GroupKeyGetter = delegate ( object rowObject ) {
				return 0;
			};

			objectListViewDownloads.FormatRow += ObjectListViewDownloads_FormatRow;

			LoadJobs();

			if ( Util.AllowTimedAutoFetch ) {
				StartTimedAutoFetch();
			}
		}
Esempio n. 2
0
        public void brutalEUSESTest()
        {
            var failures = new System.Collections.Concurrent.ConcurrentQueue<string>();

            var mwb = MockWorkbook.standardMockWorkbook();

            var formulas = System.IO.File.ReadAllLines(@"..\..\TestData\formulas_distinct.txt");

            System.Threading.Tasks.Parallel.ForEach(formulas, f =>
            {
                try
                {
                    Parcel.parseFormula(f, mwb.Path, mwb.WorkbookName, mwb.worksheetName(1));
                }
                catch (Exception e)
                {
                    if (e is AST.IndirectAddressingNotSupportedException)
                    {
                        // OK
                    }
                    else if (e is AST.ParseException)
                    {
                        System.Diagnostics.Debug.WriteLine("Fail: " + f);
                        failures.Enqueue(f);
                    }
                }
            });

            Assert.AreEqual(0, failures.Count());
            if (failures.Count > 0)
            {
                String.Join("\n", failures);
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Initializes the singleton application object.  This is the first line of authored code
 /// executed, and as such is the logical equivalent of main() or WinMain().
 /// </summary>
 public App()
 {
     this.InitializeComponent();
     this.Construct();
     this.Suspending += OnSuspending;
     // Initialize Log Message List
     MessageList = new System.Collections.Concurrent.ConcurrentQueue<string>();
 }
Esempio n. 4
0
              /// <summary>
        /// 主方法
        /// </summary>
        /// <param name="args">参数</param>
        static void Main(string[] args)
        {
            #region test
            //假设有100个请求线程
            int num = 1;

            System.Collections.Concurrent.ConcurrentQueue<Action> queue = new System.Collections.Concurrent.ConcurrentQueue<Action>();
            //使用 MutipleThreadResetEvent
            //ThreadPool.SetMaxThreads(1);
            for (int i = 0; i < num; i++)
            {
                //开启N个线程,传递MutipleThreadResetEvent对象给子线程
                //ThreadPool.QueueUserWorkItem(
                //    new WaitCallback((object state) =>
                //    {
                Task task = Task.Factory.StartNew((object index) =>
                {

                    ISeckillLogProvider itest1 = new SeckillLogProvider();
                    var model = new SeckillLog
                    {
                        Id = Util.GetIdentity(),
                        BId = 879161,
                        CreateDate = DateTime.Now,
                        MemberId = new Random().Next(0, 10000),
                        LogStatus = SeckillLogEnum.Normal,
                        SecKillDate = DateTime.Now,
                        SecKillNum = 1,
                        Status = 0,
                        SeckillId = "a1d06b0ac52146559540d55e804de767"
                    };
                    string msg; int states = 0;
                    itest1.Insert(model, out states, out msg);
                    //MutipleThreadResetEvent cd = state as MutipleThreadResetEvent;
                    ////发送信号量 本线程执行完毕
                    //cd.WaitAll();
                    //cd.SetOne();
                    Console.WriteLine(msg, states);
                }, 1);

                //}), countdown);
            }

            //等待所有线程执行完毕
            Console.WriteLine("线程完毕");
            Console.ReadLine();
            #endregion
            //KNET.NET.Common.AutoMapper.AutoMapperHelper.CreateMap(typeof(Test1));

            //var test = new Test2 { TestValue = "123" };

            //var aaa = test.MapTo<Test1>();
            
            //Console.ReadLine();

        }
Esempio n. 5
0
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            queue = new System.Collections.Concurrent.ConcurrentQueue<IpInfo>();
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
            url = "httsp://www.google.com";
            regex = @"plus\.google\.com";
            find = @"<td>(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})</td>\s+<td>(?<port>\d+)</td>";
            var path = AppDomain.CurrentDomain.BaseDirectory + "config.db";
            if (System.IO.File.Exists(path))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
                {
                    this.setValue(sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
                    sr.Close();
                }
            }

            var list = AppDomain.CurrentDomain.BaseDirectory + "list.db";
            if (System.IO.File.Exists(list))
            {
                button7_Click(null, null);
            }

            var dictPat = AppDomain.CurrentDomain.BaseDirectory + "Url.db";
            if (System.IO.File.Exists(dictPat))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(dictPat))
                {
                    while (!sr.EndOfStream)
                    {
                        dictList.Add(new Dict()
                        {
                            url = sr.ReadLine(),
                            regex = sr.ReadLine()
                        });
                    }
                }
            }
            this.FormClosed += Form1_FormClosed;
            closeTag = true;

            for (var i = 0; i < 20; i++)
            {
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    Check();
                });
            }
        }
Esempio n. 6
0
        public UwaUdpSocket(int localPort, string localIPAddress)
        {
            _DataAvailableSignal = new System.Threading.ManualResetEvent(false);
            _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>();

            this._LocalPort = localPort;

            _Socket = new Windows.Networking.Sockets.DatagramSocket();
            _Socket.MessageReceived += _Socket_MessageReceived;

            BindSocket();
        }
Esempio n. 7
0
        public UwaUdpSocket(int localPort)
        {
            _DataAvailableSignal = new System.Threading.ManualResetEvent(false);
            _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>();

            this.localPort = localPort;

            _Socket = new Windows.Networking.Sockets.DatagramSocket();
            _Socket.MessageReceived += _Socket_MessageReceived;

            var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask();
            t.Wait();
        }
Esempio n. 8
0
 static Log() {
   _useDiagnostic = System.Diagnostics.Debugger.IsAttached;
   try { int window_height = Console.WindowHeight; _useConsole = true; }
   catch { _useConsole = false; }
   if(!Directory.Exists("../log")) {
     Directory.CreateDirectory("../log");
   }
   useFile = true;
   _lfMask = "../log/{0}_" + Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location) + ".log";
   _records = new System.Collections.Concurrent.ConcurrentQueue<LogRecord>();
   _kickEv = new AutoResetEvent(false);
   _wh = ThreadPool.RegisterWaitForSingleObject(_kickEv, Process, null, -1, false);
 }
Esempio n. 9
0
File: Log.cs Progetto: Faham/emophiz
        public Log(string filname = "emotion.Log")
        {
            if (!System.IO.Directory.Exists(m_log_path))
            {
                System.IO.DirectoryInfo info = System.IO.Directory.CreateDirectory(m_log_path);
            }

            m_filename = filname;
            m_logfile = new System.IO.StreamWriter(m_log_path + "\\" + m_filename, false);
            m_logfile.AutoFlush = true;
            m_messages = new System.Collections.Concurrent.ConcurrentQueue<string>();
            m_timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerElapsed);
            m_timer.Start();
        }
Esempio n. 10
0
        public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort)
        {
            _DataAvailableSignal = new System.Threading.ManualResetEvent(false);
            _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>();

            this.ipAddress = ipAddress;
            this.multicastTimeToLive = multicastTimeToLive;
            this.localPort = localPort;

            _Socket = new Windows.Networking.Sockets.DatagramSocket();
            //_Socket.Control.MulticastOnly = true;
            _Socket.MessageReceived += _Socket_MessageReceived;
            var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask();
            t.Wait();
            _Socket.JoinMulticastGroup(new Windows.Networking.HostName(Rssdp.Infrastructure.SsdpConstants.MulticastLocalAdminAddress));
        }
Esempio n. 11
0
        public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort, string localIPAddress)
        {
            _LocalIPAddress = localIPAddress;
            _DataAvailableSignal = new System.Threading.ManualResetEvent(false);
            _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>();

            _LocalIPAddress = ipAddress;
            _MulticastTimeToLive = multicastTimeToLive;
            _LocalPort = localPort;

            _Socket = new Windows.Networking.Sockets.DatagramSocket();
            #if !WINRT
            _Socket.Control.MulticastOnly = true;
            #endif
            _Socket.MessageReceived += _Socket_MessageReceived;

            BindSocket();
            _Socket.JoinMulticastGroup(new Windows.Networking.HostName(Rssdp.Infrastructure.SsdpConstants.MulticastLocalAdminAddress));
        }
Esempio n. 12
0
        public void Bug_ConcurrentMerge()
        {
            const int reps = 1000;
            var source = Enumerable.Range(0, reps).ToObservable();

            var resultQueue = new System.Collections.Concurrent.ConcurrentQueue<int>();
            var r = new Random();

            source.Select(i => Observable.Create<Unit>(o =>
            {
                resultQueue.Enqueue(i);
                System.Threading.Tasks.Task.Factory.StartNew(
                    () =>
                    {
                        Thread.Sleep(r.Next(10));
                        o.OnCompleted();
                    });
                return () => { };
            })).Merge(3).ForEach(_ => { });

            Assert.IsTrue(Enumerable.Range(0, reps).ToList().SequenceEqual(resultQueue.ToList()));
        }
Esempio n. 13
0
 private void button4_Click(object sender, EventArgs e)
 {
     queue = new System.Collections.Concurrent.ConcurrentQueue<IpInfo>();
 }
Esempio n. 14
0
 private void button5_Click(object sender, EventArgs e)
 {
     try
     {
         this.listBox1.Items.Clear();
     }
     catch (Exception)
     {
     }
     try
     {
         this.listBox2.Items.Clear();
     }
     catch (Exception)
     {
     }
     list.Clear();
     queue = new System.Collections.Concurrent.ConcurrentQueue<IpInfo>();
 }
Esempio n. 15
0
 public StreamPair()
 {
     buffer = new System.Collections.Concurrent.ConcurrentQueue<byte[]> ();
     iStream = new IStream (this);
     oStream = new OStream (this);
 }
Esempio n. 16
0
 public void Clear()
 {
     _results = new System.Collections.Concurrent.ConcurrentQueue <ResultForTypeSpec>();
 }
Esempio n. 17
0
        /// <summary>
        /// Display Message on the application page
        /// </summary>
        /// <param name="Message">String to display</param>
        async void LogMessage(string Message)
        {
            if (MessageList == null)
                MessageList = new System.Collections.Concurrent.ConcurrentQueue<string>();
            string Text = string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " " + Message + "\n";
            MessageList.Enqueue(Text);
            System.Diagnostics.Debug.WriteLine(Text);
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                () =>
                {

                    string result;
                    //  double h = logs.ActualHeight;
                    while (MessageList.TryDequeue(out result))
                    {
                        logs.Text += result;
                        if (logs.Text.Length > 16000)
                        {
                            string LocalString = logs.Text;
                            while (LocalString.Length > 12000)
                            {
                                int pos = LocalString.IndexOf('\n');
                                if ((pos > 0) && (pos < LocalString.Length))
                                {
                                    LocalString = LocalString.Substring(pos + 1);
                                }
                            }
                            logs.Text = LocalString;
                        }
                    }
                    //if (logs.ActualHeight > h)
                    //  logs.Height = h;

                }
            );
        }
Esempio n. 18
0
 public PersistentStorage() {
   _tr=new Dictionary<Topic, Record>();
   _freeBlocks=new SortedSet<ulong>();
   _ch=new System.Collections.Concurrent.ConcurrentQueue<Topic>();
 }
Esempio n. 19
0
        static StackObject *get_Count_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Collections.Concurrent.ConcurrentQueue <ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Concurrent.ConcurrentQueue <ILRuntime.Runtime.Intepreter.ILTypeInstance>) typeof(System.Collections.Concurrent.ConcurrentQueue <ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.Count;

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method;
            return(__ret + 1);
        }
Esempio n. 20
0
 /// <summary>
 /// Display Message on the application page
 /// </summary>
 /// <param name="Message">String to display</param>
 void LogMessage(string Message)
 {
     if (MessageList == null)
         MessageList = new System.Collections.Concurrent.ConcurrentQueue<string>();
     string Text = string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " " + Message + "\n";
     MessageList.Enqueue(Text);
     System.Diagnostics.Debug.WriteLine(Text);
 }
Esempio n. 21
0
        public RegionData LoadBackup(string file)
        {
            if (!File.Exists(file))
                return null;

            var stream = ArchiveHelpers.GetStream(file);
            if (stream == null)
                return null;

            GZipStream m_loadStream = new GZipStream(stream, CompressionMode.Decompress);
            TarArchiveReader reader = new TarArchiveReader(m_loadStream);
            List<uint> foundLocalIDs = new List<uint>();
            RegionData regiondata = new RegionData();
            regiondata.Init();

            byte[] data;
            string filePath;
            TarArchiveReader.TarEntryType entryType;
            System.Collections.Concurrent.ConcurrentQueue<byte[]> groups =
                new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
            //Load the archive data that we need
            while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
            {
                if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
                    continue;

                if (filePath.StartsWith("parcels/"))
                {
                    //Only use if we are not merging
                    LandData parcel = new LandData();
                    OSD parcelData = OSDParser.DeserializeLLSDBinary(data);
                    parcel.FromOSD((OSDMap) parcelData);
                    if (parcel.OwnerID != UUID.Parse("05948863-b678-433e-87a4-e44d17678d1d"))
                        //The default owner of the 'default' region
                        regiondata.Parcels.Add(parcel);
                }
                else if (filePath.StartsWith("newstyleterrain/"))
                {
                    regiondata.Terrain = data;
                }
                else if (filePath.StartsWith("newstylerevertterrain/"))
                {
                    regiondata.RevertTerrain = data;
                }
                else if (filePath.StartsWith("newstylewater/"))
                {
                    regiondata.Water = data;
                }
                else if (filePath.StartsWith("newstylerevertwater/"))
                {
                    regiondata.RevertWater = data;
                }
                else if (filePath.StartsWith("entities/"))
                {
                    groups.Enqueue(data);
                }
                else if (filePath.StartsWith("regioninfo/"))
                {
                    RegionInfo info = new RegionInfo();
                    info.FromOSD((OSDMap) OSDParser.DeserializeLLSDBinary(data));
                    regiondata.RegionInfo = info;
                }
                data = null;
            }
            m_loadStream.Close();
            m_loadStream = null;

            int threadCount = groups.Count > 16 ? 16 : groups.Count;
            System.Threading.Thread[] threads = new System.Threading.Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                threads[i] = new System.Threading.Thread(() =>
                                                             {
                                                                 byte[] groupData;
                                                                 while (groups.TryDequeue(out groupData))
                                                                 {
                                                                     MemoryStream ms = new MemoryStream(groupData);
                                                                     ISceneEntity sceneObject =
                                                                         SceneEntitySerializer.SceneObjectSerializer
                                                                                              .FromXml2Format(ref ms,
                                                                                                              null);
                                                                     ms.Close();
                                                                     ms = null;
                                                                     data = null;
                                                                     if (sceneObject != null)
                                                                     {
                                                                         foreach (
                                                                             ISceneChildEntity part in
                                                                                 sceneObject.ChildrenEntities())
                                                                         {
                                                                             lock (foundLocalIDs)
                                                                             {
                                                                                 if (
                                                                                     !foundLocalIDs.Contains(
                                                                                         part.LocalId))
                                                                                     foundLocalIDs.Add(part.LocalId);
                                                                                 else
                                                                                     part.LocalId = 0;
                                                                                         //Reset it! Only use it once!
                                                                             }
                                                                         }
                                                                         regiondata.Groups.Add(
                                                                             sceneObject as SceneObjectGroup);
                                                                     }
                                                                 }
                                                             });
                threads[i].Start();
            }
            for (int i = 0; i < threadCount; i++)
                threads[i].Join();

            foundLocalIDs.Clear();

            return regiondata;
        }
Esempio n. 22
0
        static StackObject *Enqueue_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            ILRuntime.Runtime.Intepreter.ILTypeInstance @item = (ILRuntime.Runtime.Intepreter.ILTypeInstance) typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Collections.Concurrent.ConcurrentQueue <ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Concurrent.ConcurrentQueue <ILRuntime.Runtime.Intepreter.ILTypeInstance>) typeof(System.Collections.Concurrent.ConcurrentQueue <ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.Enqueue(@item);

            return(__ret);
        }
Esempio n. 23
0
        public void TransformStream(Stream a_stream, long a_length = -1)
        {
            Debug.Assert((a_length == -1 || a_length > 0));

            if (a_stream.CanSeek)
            {
                if (a_length > -1)
                {
                    if (a_stream.Position + a_length > a_stream.Length)
                        throw new IndexOutOfRangeException();
                }

                if (a_stream.Position >= a_stream.Length)
                    return;
            }

            System.Collections.Concurrent.ConcurrentQueue<byte[]> queue =
                new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
            System.Threading.AutoResetEvent data_ready = new System.Threading.AutoResetEvent(false);
            System.Threading.AutoResetEvent prepare_data = new System.Threading.AutoResetEvent(false);

            Task reader = Task.Factory.StartNew(() =>
            {
                long total = 0;

                for (; ; )
                {
                    byte[] data = new byte[BUFFER_SIZE];
                    int readed = a_stream.Read(data, 0, data.Length);

                    if ((a_length == -1) && (readed != BUFFER_SIZE))
                        data = data.SubArray(0, readed);
                    else if ((a_length != -1) && (total + readed >= a_length))
                        data = data.SubArray(0, (int)(a_length - total));

                    total += data.Length;

                    queue.Enqueue(data);
                    data_ready.Set();

                    if (a_length == -1)
                    {
                        if (readed != BUFFER_SIZE)
                            break;
                    }
                    else if (a_length == total)
                        break;
                    else if (readed != BUFFER_SIZE)
                        throw new EndOfStreamException();

                    prepare_data.WaitOne();
                }
            });

            Task hasher = Task.Factory.StartNew((obj) =>
            {
                IHash h = (IHash)obj;
                long total = 0;

                for (; ; )
                {
                    data_ready.WaitOne();

                    byte[] data;
                    queue.TryDequeue(out data);

                    prepare_data.Set();

                    total += data.Length;

                    if ((a_length == -1) || (total < a_length))
                    {
                        h.TransformBytes(data, 0, data.Length);
                    }
                    else
                    {
                        int readed = data.Length;
                        readed = readed - (int)(total - a_length);
                        h.TransformBytes(data, 0, data.Length);
                    }

                    if (a_length == -1)
                    {
                        if (data.Length != BUFFER_SIZE)
                            break;
                    }
                    else if (a_length == total)
                        break;
                    else if (data.Length != BUFFER_SIZE)
                        throw new EndOfStreamException();
                }
            }, this);

            reader.Wait();
            hasher.Wait();
        }
Esempio n. 24
0
        public static void ExecuteMain(string nick, IndexArgumentSetup setup, Action prepare_db)
        {
            var dbname = String.Format ("DB.{0}", Path.GetFileName(setup.DATABASE));
            setup.BINARY_DATABASE = dbname;

            prepare_db ();

            SpaceGenericIO.Load (setup.BINARY_DATABASE);
            var arglist = new System.Collections.Concurrent.ConcurrentQueue<String> ();
            arglist.Enqueue ("--save");
            arglist.Enqueue (String.Format ("Tab.ExactIndexes.{0}.{1}.qarg={2}.json", nick, Path.GetFileName (setup.QUERIES), setup.QARG));

            arglist.Enqueue (Indexes.ExecuteSeq (setup, nick));
            var actionlist = new List<Action> ();

            if (setup.ExecuteNANNI) {
                actionlist.Add (() => {
                    foreach (var resname in Indexes.ExecuteNANNI(setup, nick)) {
                        arglist.Enqueue(resname);
                    }
                });
            }
            if (setup.ExecuteTNANNI) {
                actionlist.Add (() => {
                    arglist.Enqueue(Indexes.ExecuteTNANNI(setup, nick));
                });
            }
            if (setup.ExecuteDNANNI) {
                actionlist.Add (() => {
                    arglist.Enqueue(Indexes.ExecuteDNANNI(setup, nick));
                });
            }

            if (setup.ExecuteSAT) {
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteSAT (setup, nick);
                    arglist.Enqueue (resname);
                });
            }
            if (setup.ExecuteSATDistal) {
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteSATDistal (setup, nick);
                    arglist.Enqueue (resname);
                });
            }
            if (setup.ExecuteSATRandom) {
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteSATRandom (setup, nick);
                    arglist.Enqueue(resname);
                });
            }

            if (setup.ExecuteVPT) {
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteVPT (setup, nick);
                    arglist.Enqueue (resname);
                });
            }

            // arglist.Add (Indexes.ExecuteVPTX (setup, nick));
            //arglist.Add (Indexes.ExecuteMILCv3 (setup, nick));

            foreach (var bsize in setup.LC) {
                var _bsize = bsize;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteLC (setup, nick, _bsize);
                    arglist.Enqueue(resname);
                });
            }

            foreach (var numGroups in setup.MANNI) {
                var _numGroups = numGroups;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteMANNI (setup, nick, _numGroups);
                    arglist.Enqueue(resname);
                });
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteTMANNI (setup, nick, _numGroups);
                    arglist.Enqueue(resname);
                });
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteDMANNI (setup, nick, _numGroups);
                    arglist.Enqueue(resname);
                });
                //arglist.Add (Indexes.ExecuteMILCv2 (setup, nick, numGroups));
            }

            foreach (var numGroups in setup.EPT) {
                var _numGroups = numGroups;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteEPTA (setup, nick, _numGroups);
                    arglist.Enqueue (resname);
                });
                // arglist.Add (Indexes.ExecuteEPT (setup, nick, numGroups));
            }

            foreach (var numPivs in setup.BNC) {
                var _numPivs = numPivs;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteBNCInc (setup, nick, _numPivs);
                    arglist.Enqueue (resname);
                });
            }

            foreach (var numPivs in setup.KVP) {
                var _numPivs = numPivs;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteKVP (setup, nick, _numPivs, setup.KVP_Available);
                    arglist.Enqueue (resname);
                });
            }

            foreach (var numPivs in setup.SPA) {
                var _numPivs = numPivs;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteSpaghetti (setup, nick, _numPivs);
                    arglist.Enqueue (resname);
                });
            }

            foreach (var numPivs in setup.LAESA) {
                var _numPivs = numPivs;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteLAESA (setup, nick, _numPivs);
                    arglist.Enqueue (resname);
                });
            }

            foreach (var alpha in setup.SSS) {
                var _alpha = alpha;
                actionlist.Add (() => {
                    var resname = Indexes.ExecuteSSS (setup, nick, _alpha, setup.SSS_max);
                    arglist.Enqueue (resname);
                });
            }

            if (setup.SPAWN == 1) {
                foreach (var action in actionlist) {
                    action.Invoke ();
                }
            } else {
                LongParallel.ForEach (actionlist, (a) => a.Invoke (), setup.SPAWN);
            }
            if (setup.ExecuteSearch) {
                Commands.Check (arglist);
            }
        }
Esempio n. 25
0
 internal StreamingInputVertex(int index, Stage <Epoch> stage)
     : base(index, stage)
 {
     this.inputQueue = new System.Collections.Concurrent.ConcurrentQueue <Instruction>();
     this.output     = new VertexOutputBuffer <S, Epoch>(this);
 }
 public IProjectCompiler(GitHub_Repository repository)
 {
     _repository = repository;
     _pending = new System.Collections.Concurrent.ConcurrentQueue<GitHub_Commit> ();
 }
Esempio n. 27
0
 public void Clear()
 {
     _results = new System.Collections.Concurrent.ConcurrentQueue<ResultForTypeSpec>();
 }
Esempio n. 28
0
        public bool Start(HostControl hostControl)
        {
            var devices = new List <Device>();
            var connectionStringhrportal = System.Configuration.ConfigurationManager.ConnectionStrings["HR-Portal"].ConnectionString;
            var connectionString         = System.Configuration.ConfigurationManager.ConnectionStrings["Attendance"].ConnectionString;


            using (var connection = new SqlConnection(connectionString))
            {
                logger.Info("Open Coonection with Database For Get Hardware");
                connection.Open();
                using (var command = new SqlCommand("SELECT [IPAddress], [IPPort], [NID],[place] FROM [dbo].[HardwareKeicoSF3] WITH (NOLOCK)", connection))
                {
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var config = new Device()
                        {
                            IPAddress = reader.GetString(0),
                            Port      = int.Parse(reader.GetString(1)),
                            NID       = int.Parse(reader.GetString(2)),
                            PlaceName = reader.GetString(3),
                            Password  = 0
                        };
                        devices.Add(config);
                        logger.Info("Device ADD Config");
                    }
                }

                connection.Close();
                logger.Info("Connection Close");
            }



            System.Collections.Concurrent.ConcurrentQueue <NetworkDevice> queue = new System.Collections.Concurrent.ConcurrentQueue <NetworkDevice>();
            foreach (var dev in devices)
            {
                queue.Enqueue(new NetworkDevice(dev.NID, dev.NID, dev.PlaceName)
                {
                    IPAddress = dev.IPAddress, Port = dev.Port
                });
            }


            Task.Factory.StartNew(async() =>
            {
                while (true)
                {
                    Task.Factory.StartNew(async() =>
                    {
                        NetworkDevice device;
                        if (queue.TryDequeue(out device))
                        {
                            if (!device.IsConnected)
                            {
                                Console.WriteLine("Connecting " + device.IPAddress);
                                //logger.Info("Connecting " + device.IPAddress);
                                device.Connect();
                            }
                            if (device.IsConnected || !device.IsConnected) //untuk load test
                            //if (device.IsConnected)
                            {
                                Console.WriteLine("Connected " + device.IPAddress);
                                Console.WriteLine("ID : " + device.NID);

                                var root              = AppDomain.CurrentDomain.BaseDirectory;
                                var glogDir           = System.IO.Path.Combine(root, "GLOG");
                                var temporaryFilePath = System.IO.Path.Combine(glogDir, string.Format("~GLOG_{0:000}.txt", device.NID));
                                var today             = DateTime.Today;
                                var path              = System.IO.Path.Combine(glogDir, today.ToString("yyyyMMdd"));
                                if (!System.IO.Directory.Exists(path))
                                {
                                    System.IO.Directory.CreateDirectory(path);
                                }
                                // device connected
                                // get unread attendance data

                                var data = device.GetAttendanceData();
                                if ((data != null && data.Count() > 0) || System.IO.File.Exists(temporaryFilePath))
                                {
                                    if (data == null)                       // true when temporary glog is exists
                                    {
                                        data = new List <AttendanceData>(); // create object instance to avoid object reference not set exception
                                    }
                                    var filePath = System.IO.Path.Combine(path, string.Format("GLOG_{0:000}_{1:yyyy-MM-dd}.txt", device.NID, DateTime.Today));
                                    // read and write from and to temporary ~GLOG file
                                    int firstIndex;
                                    IEnumerable <AttendanceData> existingData = null;
                                    // open ~GLOG file without lock it or create new one if does not exist
                                    using (System.IO.FileStream fs = System.IO.File.Open(temporaryFilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite))
                                    {
                                        // read unsaved data from ~GLOG file if any
                                        using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
                                        {
                                            // parse GLOG file to List of AttendanceData object
                                            var allText = sr.ReadToEnd();
                                            if (!string.IsNullOrEmpty(allText))
                                            {
                                                existingData = (
                                                    from d in
                                                    from c in allText.Split(new char[] { '\n' }) where !string.IsNullOrEmpty(c) select c.Split(new char[] { '\t' })
                                                    select new AttendanceData()
                                                {
                                                    UserID = int.Parse(d[1]), UserType = (UserType)int.Parse(d[3]), SensorType = (SensorType)int.Parse(d[4]), Mode = (Mode)int.Parse(d[5]), DateTime = DateTime.Parse(d[8], System.Globalization.CultureInfo.InvariantCulture)
                                                }
                                                    ).ToList();
                                            }
                                        }
                                        // read line count
                                        firstIndex = existingData != null ? existingData.Count() : 0;
                                    }
                                    // append data to existing ~GLOG file
                                    using (System.IO.FileStream fs = System.IO.File.Open(temporaryFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite))
                                    {
                                        foreach (var line in data.Select((c, index) => string.Format("{0}\t{1}\t\t{2}\t{3}\t{4}\t{5}\t{6}\t{7:yyyy-MM-dd HH:mm:ss}\r\n", firstIndex + index + 1, c.UserID, (int)c.UserType, (int)c.SensorType, (int)c.Mode, ((int)c.FunctionKey * 10) + c.FunctionNumber, 0, c.DateTime)))
                                        {
                                            fs.Write(System.Text.UTF8Encoding.ASCII.GetBytes(line), 0, line.Count());
                                        }
                                        fs.Flush();
                                        fs.Close();
                                    }
                                    // write to GLOG
                                    int lastSequence = 0;
                                    using (System.IO.FileStream fs = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                                    {
                                        using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
                                        {
                                            string line;
                                            while (!string.IsNullOrEmpty(line = sr.ReadLine()))
                                            {
                                                int.TryParse(line.Split(new char[] { '\t' }).FirstOrDefault(), out lastSequence);
                                            }
                                        }
                                    }
                                    using (System.IO.FileStream fs = System.IO.File.Open(filePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite))
                                    {
                                        foreach (var line in data.Select((c, index) => string.Format("{0}\t{1}\t\t{2}\t{3}\t{4}\t{5}\t{6}\t{7:yyyy-MM-dd HH:mm:ss}\r\n", lastSequence + index + 1, c.UserID, (int)c.UserType, (int)c.SensorType, (int)c.Mode, ((int)c.FunctionKey * 10) + c.FunctionNumber, 0, c.DateTime)))
                                        {
                                            fs.Write(System.Text.UTF8Encoding.ASCII.GetBytes(line), 0, line.Count());
                                        }
                                        fs.Flush();
                                        fs.Close();
                                    }


                                    // if there is unsaved data from ~GLOG file, combine unsaved data with new data from machine
                                    var dataTobeSaved = existingData != null && existingData.Count() > 0 ? existingData.Union(data) : data;
                                    foreach (var row in dataTobeSaved)
                                    {
                                        strNameMsn = string.Format("{0:0000}", device.PlaceName);
                                        //save to database
                                        if (row.UserID > 0) //nilai -1 (Access denied tidak diambil)
                                        {
                                            dblGLOG++;
                                            using (var connectionhr = new SqlConnection(connectionStringhrportal))
                                            {
                                                logger.Info("Connection Open DB Portal and save to Table");
                                                connectionhr.Open();
                                                var xuserid = row.UserID > 0 ? row.UserID.ToString("0000000") : row.UserID.ToString();
                                                using (var command = new SqlCommand("INSERT INTO trans_R(seq_no,EL5K_No,Dev_Type,Dev_id,tr_date,tr_time,tr_data,tr_code,extra,tr_user,staff_number) VALUES('0','" + strNameMsn + "','R','" + device.NID.ToString("00") + "','" + String.Format("{0:yyyyMMdd}", row.DateTime.Date) + "','" + string.Format("{0:00}", row.DateTime.Hour) + string.Format("{0:00}", row.DateTime.Minute) + string.Format("{0:00}", row.DateTime.Second) + "','','0','0000','','" + xuserid + "')", connectionhr))
                                                    command.ExecuteNonQuery();
                                                connectionhr.Close();
                                            }
                                        }
                                        //end save db
                                    }
                                    // delete temporary GLOG
                                    if (System.IO.File.Exists(temporaryFilePath))
                                    {
                                        System.IO.File.Delete(temporaryFilePath);
                                    }
                                }
                            }

                            //lakukan simpan status koneksi mesin ke dalam database
                            string strStatusLast = "";
                            string stsKon        = "";
                            //status koneksi
                            if (!device.IsConnected)
                            {
                                stsKon = "OFFLINE";
                            }
                            else
                            {
                                stsKon = "ONLINE";
                            }

                            using (var connection = new SqlConnection(connectionString))
                            {
                                connection.Open();
                                using (var command = new SqlCommand("select top(1) * from status_machine where nid='" + device.NID + "' and CAST(FLOOR(CAST(updated AS float)) AS datetime)='" + string.Format("{0:yyyy-MM-dd}", DateTime.Now) + "' order by updated desc", connection))
                                {
                                    var reader = command.ExecuteReader();
                                    while (reader.Read())
                                    {
                                        strStatusLast = reader.GetString(3);
                                    }
                                    reader.Close();
                                }

                                if (strStatusLast != stsKon)
                                {
                                    SqlCommand myCommand = new SqlCommand("INSERT INTO status_machine(nid,ipaddr,namemch,statusmch,updated) VALUES('" + device.NID + "','" + device.IPAddress + "','" + device.PlaceName + "','" + stsKon + "','" + string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now) + "')", connection);
                                    myCommand.ExecuteNonQuery();
                                }

                                connection.Close();
                            }
                            queue.Enqueue(device);
                            // await Task.Delay(50);
                        }

                        string logdir          = System.Configuration.ConfigurationManager.AppSettings["logDir"];
                        var root1              = AppDomain.CurrentDomain.BaseDirectory;
                        var glogDir1           = System.IO.Path.Combine(root1, "Logger");
                        var temporaryFilePath1 = System.IO.Path.Combine(glogDir1, string.Format("Logger.txt"));
                        var today1             = DateTime.Now;
                        var path1              = System.IO.Path.Combine(glogDir1, today1.ToString("yyyyMMdd"));

                        /* using (System.IO.FileStream fs = new FileStream(temporaryFilePath1, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite))
                         * {
                         *   var sw = new StreamWriter(fs);
                         *   sw.WriteLine("Start Read break_cd in log dir " + logdir + "break_cd.txt "  + today1);
                         *   if (File.Exists(logdir + "break_cd.txt"))
                         *   {
                         *       sw.WriteLine("Filename exist break_cd log dir " + logdir + "break_cd.txt " + today1);
                         *   }
                         *   else
                         *   {
                         *       sw.WriteLine("Filename not exist break_cd log dir " + logdir + "break_cd.txt " + today1);
                         *   }
                         *   sw.Close();
                         *   fs.Close();
                         * }
                         */
                        //pengecekkan jika ada yang meminta untuk berhenti dulu
                        //ini dilakukan jika clent akan melakukan managment user
                        if (File.Exists(logdir + "break_cd.txt"))
                        {
                            using (System.IO.FileStream fs = new FileStream(temporaryFilePath1, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite))
                            {
                                var sw = new StreamWriter(fs);
                                sw.WriteLine("break_cd.txt exist and create break_cd_do.txt" + today1);
                                sw.Close();
                                fs.Close();
                            }

                            using (System.IO.FileStream fs = new FileStream(logdir + "break_cd_do.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite))
                            {
                                var sw = new StreamWriter(fs);
                                sw.WriteLine("do!");
                                sw.Close();
                                fs.Close();
                            }


                            using (System.IO.FileStream fs = new FileStream(temporaryFilePath1, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite))
                            {
                                var sw = new StreamWriter(fs);
                                sw.WriteLine("break_cd.txt exist");
                                sw.Close();
                                fs.Close();
                            }

                            while (File.Exists(logdir + "break_cd_do.txt"))
                            {
                                if (File.Exists(logdir + "break_cd.txt"))//karena terkadang file ini sudah tidak ada tetapi break_cd_do masih ada
                                {
                                    Console.WriteLine("Stop Data Collection");
                                    using (System.IO.FileStream fs = new FileStream(temporaryFilePath1, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite))
                                    {
                                        var sw = new StreamWriter(fs);
                                        sw.WriteLine("Stop data collection " + today1);
                                        sw.Close();
                                        fs.Close();
                                    }
                                }
                            }
                        }
                        //end stop break
                    });
                    Thread.Sleep(20);
                    await Task.Delay(20);
                }
            }, TaskCreationOptions.LongRunning);


            return(true);
        }
Esempio n. 29
0
 public Stream()
 {
     _Sends    = new System.Collections.Concurrent.ConcurrentQueue <MemoryStream>();
     _Receives = new System.Collections.Concurrent.ConcurrentQueue <MemoryStream>();
 }
Esempio n. 30
0
 public MapGC()
 {
     cleanupQueue = new System.Collections.Concurrent.ConcurrentQueue<string>();
     resetEvent = new ManualResetEvent(false);
 }
Esempio n. 31
0
 public SingleThreadDispatcher(Action <T> process)
 {
     Process = process;
     mQueue  = new System.Collections.Concurrent.ConcurrentQueue <T>();
 }
Esempio n. 32
0
        protected virtual void ReadBackup(IScene scene)
        {
            MainConsole.Instance.Debug("[FileBasedSimulationData]: Reading file for " + scene.RegionInfo.RegionName);
            List<uint> foundLocalIDs = new List<uint>();
            var stream = ArchiveHelpers.GetStream((m_loadDirectory == "" || m_loadDirectory == "/")
                                                      ? m_fileName
                                                      : Path.Combine(m_loadDirectory, m_fileName));
            if(stream == null)
                return;

            GZipStream m_loadStream = new GZipStream(stream, CompressionMode.Decompress);
            TarArchiveReader reader = new TarArchiveReader(m_loadStream);

            byte[] data;
            string filePath;
            TarArchiveReader.TarEntryType entryType;
            System.Collections.Concurrent.ConcurrentQueue<byte[]> groups = new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
            //Load the archive data that we need
            while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
            {
                if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
                    continue;

                if (filePath.StartsWith("parcels/"))
                {
                    //Only use if we are not merging
                    LandData parcel = new LandData();
                    OSD parcelData = OSDParser.DeserializeLLSDBinary(data);
                    parcel.FromOSD((OSDMap) parcelData);
                    m_parcels.Add(parcel);
                }
                else if (filePath.StartsWith("terrain/"))
                {
                    m_oldstyleterrain = data;
                }
                else if (filePath.StartsWith("revertterrain/"))
                {
                    m_oldstylerevertTerrain = data;
                }
                else if (filePath.StartsWith("newstyleterrain/"))
                {
                    m_terrain = data;
                }
                else if (filePath.StartsWith("newstylerevertterrain/"))
                {
                    m_revertTerrain = data;
                }
                else if (filePath.StartsWith("newstylewater/"))
                {
                    m_water = data;
                }
                else if (filePath.StartsWith("newstylerevertwater/"))
                {
                    m_revertWater = data;
                }
                else if (filePath.StartsWith("entities/"))
                {
                    groups.Enqueue(data);
                }
                data = null;
            }
            m_loadStream.Close();
            m_loadStream = null;

            int threadCount = groups.Count > 16 ? 16 : groups.Count;
            System.Threading.Thread[] threads = new System.Threading.Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                threads[i] = new System.Threading.Thread(() =>
                    {
                        byte[] groupData;
                        while(groups.TryDequeue(out groupData))
                        {
                            MemoryStream ms = new MemoryStream(groupData);
                            SceneObjectGroup sceneObject = SceneObjectSerializer.FromXml2Format(ref ms, scene);
                            ms.Close();
                            ms = null;
                            data = null;
                            if (sceneObject != null)
                            {
                                foreach (ISceneChildEntity part in sceneObject.ChildrenEntities())
                                {
                                    lock (foundLocalIDs)
                                    {
                                        if (!foundLocalIDs.Contains(part.LocalId))
                                            foundLocalIDs.Add(part.LocalId);
                                        else
                                            part.LocalId = 0; //Reset it! Only use it once!
                                    }
                                }
                                m_groups.Add(sceneObject);
                            }
                        }
                    });
                threads[i].Start();
            }
            for (int i = 0; i < threadCount; i++)
                threads[i].Join();


            foundLocalIDs.Clear();
            GC.Collect();
        }
Esempio n. 33
0
        ///  <summary>
        ///  Reads data from the ADS1298 device and produces data frames to be sent live to clients.
        ///  </summary>
        internal void ReadDataLive()
        {
            const UInt32 maxBufferSize = 62208;				// Optimal buffer value
            const UInt32 maxBufferDelay = 15;               // Maximum buffer delay in milliseconds

            UInt32 bufferSize;
            UInt32 bytesRead = 0;
            UInt32 sampleFreq;

            UInt32 frameCounter = 0;                      // frame sequence number relative to the beginning of the data acquisition
            UInt32 frameDiff;                             // Difference to calculate the frames in the current package
            UInt32 nPackets = 0;                          //Debug variable to show the numbers of frames generated

            Byte[] readBuffer;
            Byte[] writeBuffer = new Byte[USB_PACKET_SIZE];
            Boolean success = false, sendSuccess = true;

            // Select a optimal buffer size (not extending the consts above)
            WinUsbDevice myWinUsb = new WinUsbDevice();
            Stopwatch myStopwatch = new Stopwatch();
            long ticksBegin, ticksEnd;
            double timeStamp, timeDelta;

            sampleFreq = (UInt32)(HR ? DR_VALUE_HR : DR_VALUE_LP);

            //bufferSize = (UInt32)((sampleFreq * DATALENGTH * (UInt32)((myWinUsb.pipeTimeout<maxBufferDelay) ? myWinUsb.pipeTimeout : maxBufferDelay )* 0.75) / 1000);

            //The buffer size is solely determined by the maximum buffer delay that we choose to allow.
            bufferSize = (UInt32) (DATALENGTH * sampleFreq * maxBufferDelay / 1000);
            bufferSize = bufferSize > maxBufferSize ? maxBufferSize : bufferSize;

            readBuffer = new Byte[bufferSize];
            _packetQueue = new System.Collections.Concurrent.ConcurrentQueue<RawDataPacket>();
            RawDataPacket finalPacket;

            try
            {
                winUsbDev.FlushPipe(PIPE_DATA_IN);

                // Send start-command to ADS device.
                writeBuffer[0] = CMD_START;
                success = winUsbDev.SendBulkData(PIPE_COMMAND_OUT, ref writeBuffer, (UInt32)writeBuffer.Length);       // Send start-command to ADS device.

                if (success)
                {
                    myStopwatch.Reset();
                    myStopwatch.Start();
                    do
                    {
                        // Read some data.
                        ticksBegin = myStopwatch.ElapsedTicks;
                        winUsbDev.ReadBulkData(PIPE_DATA_IN, bufferSize, ref readBuffer, ref bytesRead, ref success);
                        ticksEnd = myStopwatch.ElapsedTicks;

                        timeStamp = (double)ticksBegin / (double)Stopwatch.Frequency;
                        timeDelta = (double)(ticksEnd - ticksBegin) / (double)Stopwatch.Frequency;

                        // Get a proper frame index for our newly read frames
                        // This frame index is 24-bit wide, so at 2000 samples/sec it will
                        // overflow and get back to 0 every 8388 seconds

                        frameDiff=0;

                        for (UInt32 i = 0; i < bytesRead; i += DATALENGTH)
                        {
                            frameCounter = frameCounter & 0x00ffffff;
                            readBuffer[i] = (Byte) ((frameCounter & 0x00ff0000) >> 16);
                            readBuffer[i+1] = (Byte) ((frameCounter & 0x0000ff00) >> 8);
                            readBuffer[i+2] = (Byte) (frameCounter & 0x000000ff);
                            frameCounter++;
                            frameDiff++;
                        }

                            //Here we can create a packet and add it to the frame collection
                            _packetQueue.Enqueue(new RawDataPacket(readBuffer, (Int32)bytesRead, sampleFreq, NumberOfChannels, DATALENGTH, frameDiff, timeStamp, timeDelta));

                        nPackets++;

                        //We have read a new packet, so we make our listeners aware of it
                        OnNewPacket(EventArgs.Empty);

                        sendSuccess &= success;
                    }
                    while (processingData && bytesRead != 0);

                    //Now we send a special duplicate packet indicating there will be no more packets coming
                    finalPacket=new RawDataPacket(readBuffer, (Int32)bytesRead, sampleFreq, NumberOfChannels, DATALENGTH, frameDiff,timeStamp,timeDelta);
                    finalPacket.lastPacket = true;
                    _packetQueue.Enqueue(finalPacket);

                    OnNewPacket(EventArgs.Empty);

                    //DEBUG
                    Console.Out.WriteLine("{0} packets processed.", nPackets);
                    //DEBUG/
                }
                if (sendSuccess)
                {
                    writeBuffer[0] = CMD_STOP;
                    success = winUsbDev.SendBulkData(PIPE_COMMAND_OUT, ref writeBuffer, (UInt32)writeBuffer.Length);   // Send stop-command to ADS device.
                }
            }
            catch (ThreadAbortException)
            {
                throw;
            }

            finally
            {
                writeBuffer[0] = CMD_STOP;
                winUsbDev.SendBulkData(PIPE_COMMAND_OUT, ref writeBuffer, (UInt32)writeBuffer.Length);					// Send stop-command to ADS device.
                winUsbDev.ReadBulkData(PIPE_DATA_IN, bufferSize, ref readBuffer, ref bytesRead, ref success);		// Read the samples after we stopped the reading process.
            }
        }
Esempio n. 34
0
 /// <summary>
 /// Connect to server, returns true if connected succesfully
 /// </summary>
 /// <param name="host"></param>
 /// <param name="port"></param>
 public bool Connect(string host, int port)
 {
     zMessages = new System.Collections.Concurrent.ConcurrentQueue<Message>();
     ReceivedWelcomeMessage = false;
     State = ClientState.Disconnected;
     zSocket = new TcpClient();
     try
     {
         zSocket.Connect(host, port);
         zReceiveThread = new Thread(new ThreadStart(Receive));
         zReceiveThread.IsBackground = true;
         zReceiveThread.Start();
     }
     catch (SocketException e)
     {
         //10061 usually means that server is not running or not accepting
         if (e.ErrorCode == 10061)
             return false;
         //no response (timeout)
         if (e.ErrorCode == 10060)
             return false;
         //server unknown
         if (e.ErrorCode == 11001)
             return false;
         else
             throw e;
     }
     Debug.Write("Client connected");
     State = ClientState.Connected;
     //wait for welcome message
     //its needed because in some cases client will report connected even
     //if it's not
     if (!GetWelcomeMsg())
     {
         Disconnect(false);
         return false;
     }
     return true;
 }
Esempio n. 35
0
 public ServerClient(TcpClient client)
 {
     BufferSize = 0;
     Room = null;
     zMessages = new System.Collections.Concurrent.ConcurrentQueue<Message>();
     zSocket = client;
     if (client != null)
     {
         zIP = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
         Hero = new ClientHero();
         zReceiveThread = new Thread(new ThreadStart(Receive));
         zReceiveThread.IsBackground = true;
     }
     else
     {
         zId = 0;
         zIP = string.Empty;
         Hero = null;
         zReceiveThread = null;
     }
 }
Esempio n. 36
0
 private DWorkspace() {
   _msgs = new System.Collections.Concurrent.ConcurrentQueue<INotMsg>();
   _clients = new SortedList<string, A04Client>();
   _files = new ObservableCollection<UIDocument>();
   _activeDocument = null;
 }
 public StatusMachine()
 {
     _StandBys = new System.Collections.Concurrent.ConcurrentQueue <IStatus>();
 }