Esempio n. 1
0
    //-------------------------------------------------------------------------
    public override void update(float elapsed_tm)
    {
        if (LogicScene != null)
        {
            LogicScene.update(elapsed_tm);
        }

        // 更新座位上所有玩家
        foreach (var i in AllSeat)
        {
            if (i.et_playermirror != null)
            {
                i.et_playermirror.update(elapsed_tm);
            }
        }

        while (QueAoIEvent.Count > 0)
        {
            var ev_aoi = QueAoIEvent.Dequeue();

            DesktopNotify desktop_notify;
            desktop_notify.id   = DesktopNotifyId.PlayerSceneAoIUpdate;
            desktop_notify.data = EbTool.protobufSerialize <_tAoIEvent>(ev_aoi);

            StreamData sd = new StreamData();
            sd.event_id = StreamEventId.DesktopStreamEvent;
            sd.param1   = desktop_notify;
            var grain_desktop = Entity.getUserData <GrainCellDesktop>();
            grain_desktop.AsyncStream.OnNextAsync(sd);
        }
    }
Esempio n. 2
0
 protected override void WriteObject(AssetsWriter writer)
 {
     writer.Write(Name);
     //writer.Write(MeshData);
     writer.WriteArrayOf(SubMeshes, (o, w) => o.Write(w));
     BlendShapeData.Write(writer);
     writer.WriteArrayOf(BindPose, (o, w) => w.Write(o));
     writer.WriteArrayOf(BoneNameHashes, (o, w) => w.Write(o));
     writer.Write(RootBoneNameHash);
     writer.Write(MeshCompression);
     writer.Write(IsReadable);
     writer.Write(KeepVerticies);
     writer.Write(KeepIndicies);
     writer.AlignTo(4);
     writer.Write(IndexFormat);
     writer.WriteArray(IndexBuffer);
     writer.AlignTo(4);
     VertexData.Write(writer);
     CompressedMesh.Write(writer);
     LocalAABB.Write(writer);
     writer.Write(MeshUsageFlags);
     writer.WriteArray(BakedConvexCollisionMesh);
     writer.AlignTo(4);
     writer.WriteArray(BakedTriangleCollisionMesh);
     writer.AlignTo(4);
     writer.Write(MeshMetrics1);
     writer.Write(MeshMetrics2);
     StreamData.Write(writer);
 }
Esempio n. 3
0
        public bool IsNewStream(StreamData data)
        {
            if (data == null)
            {
                throw new ArgumentException($"{nameof(data)} is null");
            }

            var config = GetConfig();

            var result = _repository.Get(data.StreamerName);

            if (result == null)
            {
                _logger.LogInformation($"New Streamer {data.StreamerName} Added to the cache");

                _repository.AddOrUpdate(data.StreamerName, data);
                return(true);
            }

            if (result.StreamName != data.StreamName || IsOldStream(result.Updated, config.TimeBetweenNewStreams))
            {
                _logger.LogInformation($"Streamer {data.StreamerName} started a new stream: {data.StreamName}");

                _repository.AddOrUpdate(data.StreamerName, data);
                return(true);
            }

            _repository.UpdateTime(data.StreamerName);

            _logger.LogInformation($"Already streaming: {data.StreamerName}; StreamName: {data.StreamName}");

            return(false);
        }
        void OnStreamReceived(StreamData streamData)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                bool isMyChannel = streamData.Channel == CHANNEL;
                //Console.WriteLine($"ImageData received {CHANNEL} ===> token : {receivedToken}, isChannel : {isThisToken}");

                if (streamData != null && streamData.Image.Length > 0 && canStream && isMyChannel)
                {
                    var bitmapimg = new BitmapImage();
                    using (var mem = new MemoryStream(streamData.Image.ToByteArray()))
                    {
                        mem.Position = 0;
                        bitmapimg.BeginInit();
                        bitmapimg.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                        bitmapimg.CacheOption   = BitmapCacheOption.OnLoad;

                        bitmapimg.UriSource    = null;
                        bitmapimg.StreamSource = mem;
                        bitmapimg.EndInit();
                    }
                    bitmapimg.Freeze();
                    if (bitmapimg != null)
                    {
                        Console.WriteLine($"     ===> received {CHANNEL} : len : {streamData.Image.Length},  width : {bitmapimg.PixelWidth}, hegith : {bitmapimg.PixelHeight}");
                        StreamImage.Source = bitmapimg;
                    }
                    else
                    {
                        Console.WriteLine("Iamge received NULL");
                    }
                }
            }));
        }
Esempio n. 5
0
        public void CreateTest()
        {
            Type        t        = typeof(int);
            SuperStream ms       = new SuperStream(Endianess.Little);
            var         expected = new StreamDataTestData
            {
                A = -15,
                B = "Test one!",
                C = "Test two!",
                D = new List <int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }),
                E = ByteEnum.Hello,
                F = LongEnum.Max
            };

            ms.WriteInt32(expected.A);
            ms.WriteString(expected.B);
            ms.WriteCString(expected.C);
            ms.WriteUInt32((uint)expected.D.Count);
            foreach (var i in expected.D)
            {
                ms.WriteInt32(i);
            }

            ms.WriteByte((byte)ByteEnum.Hello);
            ms.WriteInt64((Int64)LongEnum.Max);

            ms.Position = 0;

            StreamDataTestData actual;

            actual = StreamData.Create <StreamDataTestData>(ms);
            Assert.AreEqual(expected, actual);
        }
        public void CreateStream(string streamPath, bool overwrite, byte[] data, int byteCount)
        {
            if (overwrite)
            {
                _streams[streamPath] = new StreamData(streamPath);
            }
            else
            {
                if (StreamExists(streamPath))
                {
                    throw new Exception("stream exists");
                }
                _streams.Add(streamPath, new StreamData(streamPath));
            }

            // if there is data passed in, we should do the same operation as in append
            if (data != null)
            {
                if (byteCount > data.Length)
                {
                    throw new Exception("invalid byteCount");
                }

                var stream = _streams[streamPath];

                //always make a copy of the original buffer since it is reused
                byte[] toAppend = new byte[byteCount];
                Array.Copy(data, toAppend, byteCount);

                stream.Append(toAppend);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Take an existing byte[] frame and map it to this data type
        /// </summary>
        /// <param name="frame">The existing frame data</param>
        /// <param name="payloadStart">The index that the payload starts at in the frame byte[]</param>
        protected virtual void ReadFrame(byte[] frame, int payloadStart, byte receivers)
        {
            // The end of the frame payload is just before the unique id
            int  end      = frame.Length - (sizeof(ulong) * 2);
            bool isStream = receivers == 255;

            // If the receivers is invalid, pull it from the data
            if (isStream)
            {
                end      -= 1;
                Receivers = (Receivers)frame[end];
                //end--;
            }
            else
            {
                Receivers = (Receivers)receivers;
            }

            // If an empty frame was sent, do not copy it to data as data is already empty
            if (frame.Length - payloadStart > end)
            {
                StreamData.BlockCopy(frame, payloadStart, end - payloadStart);
            }

            if (isStream)
            {
                end += 1;
            }

            // Pull the time step for this frame
            TimeStep = BitConverter.ToUInt64(frame, end);

            // Pull the unique id for this frame
            UniqueId = BitConverter.ToUInt64(frame, end + sizeof(ulong));
        }
Esempio n. 8
0
        public void OnNext(StreamData <FixationData> fixation)
        {
            var fixationBeginTime = 0d;
            var fixationPointX    = fixation.Data.X;
            var fixationPointY    = fixation.Data.Y;

            switch (fixation.Data.EventType)
            {
            case FixationDataEventType.Begin:
                fixationBeginTime = fixation.Data.Timestamp;
                Console.WriteLine(@"Begin fixation at X: {0}, Y: {1}", fixationPointX, fixationPointY);
                break;

            case FixationDataEventType.Data:
                OnFixation?.Invoke(this, new ReceivedDataEventArgs(new Point(fixationPointX, fixationPointY)));
                break;

            case FixationDataEventType.End:
                OnFixationEnd?.Invoke(this,
                                      new ReceivedDataEventArgs(new Point(fixationPointX, fixationPointY),
                                                                TimeSpan.FromMilliseconds(fixation.Data.Timestamp - fixationBeginTime)));
                Console.WriteLine(@"End fixation at X: {0}, Y: {1}", fixationPointX, fixationPointY);
                Console.WriteLine(@"Fixation duration: {0} ",
                                  fixationBeginTime > 0
                            ? TimeSpan.FromMilliseconds(fixation.Data.Timestamp - fixationBeginTime)
                            : TimeSpan.Zero);
                break;

            default:
                throw new InvalidOperationException(
                          "Unknown fixation event type, which doesn't have explicit handling.");
            }
        }
Esempio n. 9
0
        public void I2CStreamTest()
        {
            Console.WriteLine("Starting I2C data stream test...");

            I2CPreamble pre = new I2CPreamble();

            pre.DeviceAddress = 0xA0;
            pre.PreambleData.Add(0);
            pre.PreambleData.Add(0);
            pre.PreambleData.Add(0xA1);
            pre.StartMask = 4;

            TestI2CFunctionality();

            byte[] StreamData, InitialRead;

            for (int trial = 0; trial < 5; trial++)
            {
                Console.WriteLine("Starting stream...");
                FX3.StartI2CStream(pre, 64, 1000);
                FX3.WaitForStreamCompletion(10000);
                Console.WriteLine("Stream complete. Checking data...");
                InitialRead = FX3.GetI2CBuffer();
                for (int i = 1; i < 1000; i++)
                {
                    StreamData = FX3.GetI2CBuffer();
                    for (int j = 0; j < StreamData.Count(); j++)
                    {
                        Assert.AreEqual(InitialRead[j], StreamData[j], "ERROR: Invalid I2C read back data on buffer " + i.ToString());
                    }
                }
                TestI2CFunctionality();
            }
        }
        private void OnFixationData(object sender, StreamData <FixationData> streamData)
        {
            switch (streamData.Data.EventType)
            {
            case Tobii.Interaction.Framework.FixationDataEventType.Begin:
                _Fixations.Clear();
                _Fixations.Add(new System.Windows.Point(streamData.Data.X, streamData.Data.Y));
                OnFixation(this, new FixationEventArgs(true, new System.Windows.Point(0, 0)));
                break;

            case Tobii.Interaction.Framework.FixationDataEventType.Data:
                _Fixations.Add(new System.Windows.Point(streamData.Data.X, streamData.Data.Y));
                break;

            case Tobii.Interaction.Framework.FixationDataEventType.End:
                _Fixations.Add(new System.Windows.Point(streamData.Data.X, streamData.Data.Y));
                double avgX = _Fixations.Average(f => f.X);
                double avgY = _Fixations.Average(f => f.Y);
                if (avgX > 0 && avgY > 0)
                {
                    OnFixation(this, new FixationEventArgs(false, new System.Windows.Point(avgX, avgY)));
                }
                _Fixations.Clear();
                break;

            default:
                break;
            }
        }
        private void OnEyePositionData(object sender, StreamData <EyePositionData> streamData)
        {
            _TobiiTrackStatus.Dispatcher.BeginInvoke((Action) delegate()
            {
                if (streamData.Data.HasLeftEyePosition)
                {
                    _LeftEye.Visibility = System.Windows.Visibility.Visible;
                    Canvas.SetLeft(_LeftEye, (1 - streamData.Data.LeftEyeNormalized.X) * _TobiiTrackStatus.ActualWidth);
                    Canvas.SetTop(_LeftEye, streamData.Data.LeftEyeNormalized.Y * _TobiiTrackStatus.ActualHeight);
                }
                else
                {
                    _LeftEye.Visibility = System.Windows.Visibility.Hidden;
                }

                if (streamData.Data.HasRightEyePosition)
                {
                    _RightEye.Visibility = System.Windows.Visibility.Visible;
                    Canvas.SetLeft(_RightEye, (1 - streamData.Data.RightEyeNormalized.X) * _TobiiTrackStatus.ActualWidth);
                    Canvas.SetTop(_RightEye, streamData.Data.RightEyeNormalized.Y * _TobiiTrackStatus.ActualHeight);
                }
                else
                {
                    _RightEye.Visibility = System.Windows.Visibility.Hidden;
                }
            });
        }
Esempio n. 12
0
            public async override Task GetStreaming(AuthToken request, IServerStreamWriter <StreamData> responseStream, ServerCallContext context)
            {
                var projectPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")));

                int index = 0;

                while (true)
                {
                    string path = Path.Combine(projectPath, "img", $"car{index++}.png");
                    if (index > 5)
                    {
                        index = 0;
                    }
                    var imgData = await File.ReadAllBytesAsync(path);

                    var data = new StreamData();
                    data.Authtoken = new AuthToken {
                        Token = "servertoken1"
                    };
                    data.Filetype = new FileType {
                        Type = 1
                    };
                    data.Image = Google.Protobuf.ByteString.CopyFrom(imgData);

                    await responseStream.WriteAsync(data);

                    Console.WriteLine($"Server sent => {path}");
                    Thread.Sleep(1000);
                }
            }
        private static void OnNextHeadPose(object sender, StreamData <HeadPoseData> headPose)
        {
            var timestamp       = headPose.Data.Timestamp;
            var hasHeadPosition = headPose.Data.HasHeadPosition;
            var headPosition    = headPose.Data.HeadPosition;
            var hasRotation     = headPose.Data.HasRotation;
            var headRotation    = headPose.Data.HeadRotation;

            Console.WriteLine($"Head pose timestamp  : {timestamp}");
            Console.WriteLine($"Has head position    : {hasHeadPosition}");
            Console.WriteLine($"Has rotation  (X,Y,Z): ({hasRotation.HasRotationX},{hasRotation.HasRotationY},{hasRotation.HasRotationZ})");
            if (headPosition.X <= -40)
            {
                Console.WriteLine("HEAD POSITION LEFT");
            }
            if (headPosition.X >= 40)
            {
                Console.WriteLine("HEAD POSITION RIGHT");
            }
            Console.WriteLine($"Head position (X,Y,Z): ({headPosition.X},{headPosition.Y},{headPosition.Z})");
            if (headRotation.Y <= -0.2)
            {
                Console.WriteLine("HEAD ROTATION RIGHT");
            }
            if (headRotation.Y >= 0.2)
            {
                Console.WriteLine("HEAD ROTATION LEFT");
            }
            Console.WriteLine($"Head rotation (X,Y,Z): ({headRotation.X},{headRotation.Y},{headRotation.Z})");
            Console.WriteLine("-----------------------------------------------------------------");
        }
Esempio n. 14
0
        static IntPtr AddStream(Stream stream, OpenMedia openMedia, ReadMedia readMedia, SeekMedia seekMedia, CloseMedia closeMedia)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            IntPtr handle;

            lock (DicStreams)
            {
                _streamIndex++;

                handle             = new IntPtr(_streamIndex);
                DicStreams[handle] = new StreamData
                {
                    Buffer     = new byte[0x4000],
                    Handle     = handle,
                    Stream     = stream,
                    OpenMedia  = openMedia,
                    ReadMedia  = readMedia,
                    SeekMedia  = seekMedia,
                    CloseMedia = closeMedia
                };
            }
            return(handle);
        }
Esempio n. 15
0
        StreamData ParseToJson(string fileText)
        {
            //string substring = fileText.Substring(1, fileText.Length-2);
            StreamData streamData = JsonConvert.DeserializeObject <StreamData>(fileText);

            return(streamData);
        }
Esempio n. 16
0
        private static void OnNextFixation(object sender, StreamData <FixationData> fixation)
        {
            switch (fixation.Data.EventType)
            {
            case FixationDataEventType.Begin:
                Console.WriteLine("\n" +
                                  "Fixation started at X: {0}, Y: {1}", fixation.Data.X, fixation.Data.Y);
                _fixationBeginTimestamp = fixation.Data.Timestamp;
                break;

            case FixationDataEventType.Data:
                Console.WriteLine("During fixation, currently at: X: {0}, Y: {1}", fixation.Data.X, fixation.Data.Y);
                break;

            case FixationDataEventType.End:
                Console.WriteLine("Fixation ended at X: {0}, Y: {1}", fixation.Data.X, fixation.Data.Y);
                if (!Double.IsNaN(_fixationBeginTimestamp))
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Fixation duration: {0}", TimeSpan.FromMilliseconds(fixation.Data.Timestamp - _fixationBeginTimestamp));
                    Console.ForegroundColor = _defaultForegroundColor;
                }
                break;
            }
        }
Esempio n. 17
0
        private void GazeDataStreamOnNext(object sender, StreamData <GazePointData> gazePositionStream)
        {
            GazePointData data = gazePositionStream.Data;

            LastGazePointData = data;

            var gazePointX = data.X;
            var gazePointY = data.Y;


            var screenWidth  = DisplaySize.Width;
            var screenHeight = DisplaySize.Height;


            var normalizedGazePointX = (float)Math.Min(Math.Max((gazePointX / screenWidth), 0.0), 1.0);
            var normalizedGazePointY = (float)Math.Min(Math.Max((gazePointY / screenHeight), 0.0), 1.0);

            NormalizedGazePoint = new Vector2(normalizedGazePointX, normalizedGazePointY);

            var normalizedDistanceFromCenterX = (normalizedGazePointX - 0.5f) * 2.0f;
            var normalizedDistanceFromCenterY = (normalizedGazePointY - 0.5f) * 2.0f;

            NormalizedCenterDelta = new Vector2(normalizedDistanceFromCenterX, normalizedDistanceFromCenterY);

            UpdateReason = UpdateReason.GazeDataChanged;
            //OnUpdate();
        }
Esempio n. 18
0
        public static List <streamList> GetStreamForModule(string moduleName) //给定模块名,返回模块名对应的所有业务流List
        {
            List <streamList> stream         = new List <streamList>();
            StreamData        streamData     = LoadStreamInfo();
            List <DataRow>    streamNameList = streamData.Tables[StreamData.STREAM_TABLE].Select(StreamData.MODULES_NAME_FIELD + " = '" + moduleName + "'").Distinct().ToList();

            for (int i = 0; i < streamNameList.Count; i++)
            {
                DataRow row = streamNameList[i];
                if (i > 0 && row[StreamData.NAME_FIELD].Equals(streamNameList[i - 1][StreamData.NAME_FIELD]))
                {
                    continue;
                }
                streamList oneStream = new streamList();
                oneStream.modulesList = new List <string>();
                oneStream.streamName  = row[StreamData.NAME_FIELD].ToString();
                DataRow[] oneStreamTable = streamData.Tables[StreamData.STREAM_TABLE].Select(StreamData.NAME_FIELD + "= '" + oneStream.streamName + "'");
                foreach (DataRow streamRow in oneStreamTable)
                {
                    string mod = streamRow[StreamData.MODULES_NAME_FIELD].ToString();
                    oneStream.modulesList.Add(mod);
                }
                stream.Add(oneStream);
            }
            return(stream);
        }
Esempio n. 19
0
 /// <summary>
 /// Selects the stream for sending messages.
 /// </summary>
 /// <param name="streamData">The stream data.</param>
 public void SelectStream(StreamData streamData)
 {
     if (GetStreamData() != null && GetStreamData().Contains(streamData))
     {
         this.SelectedStream = GetStreamData().IndexOf(streamData);
     }
 }
Esempio n. 20
0
        public void CreateStream(string streamPath, bool overwrite, byte[] data, int byteCount)
        {
            if (overwrite)
            {
                _streams[streamPath] = new StreamData(streamPath);
            }
            else
            {
                if (StreamExists(streamPath))
                {
                    throw new Exception("stream exists");
                }
                _streams.Add(streamPath, new StreamData(streamPath));
            }

            // if there is data passed in, we should do the same operation as in append
            if (data != null)
            {
                if (byteCount > data.Length)
                {
                    throw new Exception("invalid byteCount");
                }

                var stream = _streams[streamPath];

                //always make a copy of the original buffer since it is reused
                byte[] toAppend = new byte[byteCount];
                Array.Copy(data, toAppend, byteCount);

                stream.Append(toAppend);
            }
        }
Esempio n. 21
0
 protected override void WriteObject(AssetsWriter writer)
 {
     base.WriteBase(writer);
     writer.Write(Name);
     writer.Write(ForcedFallbackFormat);
     writer.Write(DownscaleFallback);
     writer.AlignTo(4);
     writer.Write(Width);
     writer.Write(Height);
     writer.Write(CompleteImageSize);
     writer.Write((int)TextureFormat);
     writer.Write(MipCount);
     writer.Write(IsReadable);
     writer.Write(StreamingMipmaps);
     writer.AlignTo(4);
     writer.Write(StreamingMipmapsPriority);
     writer.Write(ImageCount);
     writer.Write(TextureDimension);
     TextureSettings.Write(writer);
     writer.Write(LightmapFormat);
     writer.Write(ColorSpace);
     writer.Write(ImageData.Length);
     writer.Write(ImageData);
     writer.AlignTo(4);
     StreamData.Write(writer);
 }
Esempio n. 22
0
        public void Setup()
        {
            _arrayOfData = new StreamItemCollection[_totalCount];

            for (int i = 0; i < _totalCount; i++)
            {
                _arrayOfData[i] = new StreamItemCollection(new []
                {
                    new StreamItem()
                    {
                        StreamItemId = i
                    }
                });
            }

            var loggerFactory = new LoggerFactory();

            _streamService = new StreamServiceExample(loggerFactory.CreateLogger("StreamServiceBenchmark"), false);
            var cts = new CancellationTokenSource();
            var serverStreamWriter = new ServerStreamWriterFake();
            var streamInfo         = new StreamInfo <StreamItemCollection>()
            {
                CancelationToken = cts.Token,
                Keys             = new[] { "tenantId" },
                Peer             = "127.0.0.1:5000",
                Stream           = serverStreamWriter
            };

            _streamData = _streamService.RegisterStream(streamInfo, new Filter()).GetAwaiter().GetResult();
            _streamService.SwitchToReady(_streamData);
        }
Esempio n. 23
0
        public void SerializeTest()
        {
            SuperStream expectedStream = new SuperStream(Endianess.Little);
            var         expectedObject = new StreamDataTestData
            {
                A = -15,
                B = "Test one!",
                C = "Test two!",
                D = new List <int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }),
                E = ByteEnum.Hello,
                F = LongEnum.Max
            };

            expectedStream.WriteInt32(expectedObject.A);
            expectedStream.WriteString(expectedObject.B);
            expectedStream.WriteCString(expectedObject.C);
            expectedStream.WriteUInt32((uint)expectedObject.D.Count);
            foreach (var i in expectedObject.D)
            {
                expectedStream.WriteInt32(i);
            }
            expectedStream.WriteByte((byte)ByteEnum.Hello);
            expectedStream.WriteInt64((Int64)LongEnum.Max);

            var expected = ((MemoryStream)expectedStream.BaseStream).ToArray();

            var actualStream = new SuperStream(Endianess.Little);

            StreamData.Serialize(expectedObject, actualStream);

            var actual = ((MemoryStream)actualStream.BaseStream).ToArray();

            Assert.IsTrue(actual.SequenceEqual(expected));
        }
Esempio n. 24
0
        private void OnNextHeadPose(object sender, StreamData <HeadPoseData> headPose)
        {
            if (headPose.Data.HasHeadPosition)
            {
                var axisData = new[] { headPose.Data.HeadPosition.X, headPose.Data.HeadPosition.Y, headPose.Data.HeadPosition.Z, headPose.Data.HeadRotation.X, headPose.Data.HeadRotation.Y, headPose.Data.HeadRotation.Z };

                for (int i = 0; i < 2; i++)
                {
                    if (!AxisMonitors.Keys.Contains(i))
                    {
                        continue;
                    }
                    int value = (int)(axisData[i] * 163.84);
                    if (value > 32768)
                    {
                        value = 32768;
                    }
                    else if (value < -32767)
                    {
                        value = -32767;
                    }
                    AxisMonitors[i].Poll(value);
                }
            }
        }
Esempio n. 25
0
        private StreamData OpenFile(string filePath, Encoding encoding, FileAccess access, bool isNew = false)
        {
            string destinationDirectory = Path.GetDirectoryName(filePath);

            if (access.HasFlag(FileAccess.Write) && !Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            FileMode mode;

            if (access.HasFlag(FileAccess.Write))
            {
                mode = isNew ? FileMode.Create : FileMode.OpenOrCreate;
            }
            else
            {
                mode = FileMode.Open;
            }

            StreamData streamData = new StreamData
            {
                FileStreamData = File.Open(filePath, mode, access)
            };

            streamData.BufferedStreamData = new BufferedStream(streamData.FileStreamData);
            streamData.StreamReaderData   = access.HasFlag(FileAccess.Read) ? new StreamReader(streamData.BufferedStreamData) : null;
            streamData.StreamWriterData   = access.HasFlag(FileAccess.Write) ? new StreamWriter(streamData.BufferedStreamData, encoding) : null;

            return(streamData);
        }
Esempio n. 26
0
        /// <summary>
        /// Determines whether the sorting is valid.
        /// </summary>
        /// <param name="fileName">Name of the input file.</param>
        /// <returns>
        ///   <c>true</c> if the sorting is valid; otherwise, <c>false</c>.
        /// </returns>
        public async Task <bool> IsSotringValid(string fileName)
        {
            StreamData stream = _fileProvider.OpenFileForReading(fileName, AppConstants.TextEncoding);

            bool   isValid = true;
            string line;

            string previousLine = null;

            while ((line = await _fileProvider.ReadNextLineAsync(stream)) != null)
            {
                line = line.Trim(AppConstants.BomSymbol);

                if (line != string.Empty && string.Compare(previousLine, line, StringComparison.InvariantCultureIgnoreCase) > 0)
                {
                    isValid = false;
                    break;
                }

                previousLine = line;
            }

            stream.Dispose();

            return(isValid);
        }
Esempio n. 27
0
        private void GazePointDataStream_Next(object sender, StreamData <GazePointData> data)
        {
            var gazePoint = data.Data;

            _lastGazePoint = new GazePoint(gazePoint.X, gazePoint.Y);
            _signal.Set();
        }
Esempio n. 28
0
        private async Task SortFileEntriesAsync(string inputFileName, string outputFileName)
        {
            List <string> entries = new List <string>();

            using (StreamData inputStream = _fileProvider.OpenFileForReading(inputFileName, AppConstants.TextEncoding))
            {
                string line;

                while ((line = await _fileProvider.ReadNextLineAsync(inputStream)) != null)
                {
                    entries.Add(line);
                }
            }

            entries.Sort(AppConstants.Comparer);

            using (StreamData outputStream = _fileProvider.OpenFileForWriting(outputFileName, AppConstants.TextEncoding, true))
            {
                foreach (string line in entries)
                {
                    await _fileProvider.WriteLineInFileAsync(line, outputStream);
                }

                await _fileProvider.FlushStreamWriterAsync(outputStream);
            }
        }
Esempio n. 29
0
        private void ProcessStream(StreamData data)
        {
            Debug.Assert(data != null, "The object should be a StreamData instance.");

            try
            {
                m_Diagnostics.Log(
                    LevelToLog.Trace,
                    CommunicationConstants.DefaultLogTextPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Received data from {0}.",
                        data.SendingEndpoint));

                var translatedData = TranslateMessage(data);

                // Raise the event on another thread AFTER we copied the stream so that the
                // WCF auto-dispose doesn't stuff us up.
                Task.Factory.StartNew(() => RaiseOnNewData(translatedData));
            }
            catch (Exception e)
            {
                m_Diagnostics.Log(
                    LevelToLog.Error,
                    CommunicationConstants.DefaultLogTextPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Exception occurred during the handling of a data from {0}. Exception was: {1}",
                        data.SendingEndpoint,
                        e));
            }
        }
Esempio n. 30
0
 // Poll the queue.
 private void PollQueue()
 {
     while (activeStreams.Count > 0)
     {
         queuedItem.WaitOne();
         while (queue.Count > 0)
         {
             StreamData data = (StreamData)queue.Dequeue();
             if (data.end)
             {
                 lock (activeStreams)
                 {
                     activeStreams.Remove(data.handle);
                 }
             }
             if (DataReceived != null)
             {
                 DataReceived(data);
             }
         }
     }
     if (Complete != null)
     {
         Complete();
     }
 }
Esempio n. 31
0
 public bool CheckAssetIntegrity()
 {
     if (IsReadStreamData(File.Version))
     {
         StreamData.CheckIntegrity(File);
     }
     return(true);
 }
Esempio n. 32
0
        public static TwitchUsher FromUser(string user)
        {
            HttpWebRequest req =
                (HttpWebRequest)WebRequest.Create("http://usher.twitch.tv/find/" + user + ".xml?type=live");

            req.Method = "GET";

            var resp = req.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            var str = reader.ReadToEnd();

            var doc = new HtmlDocument();
            doc.LoadHtml(str);

            var ret = new TwitchUsher();

            try
            {
                foreach (var node in doc.DocumentNode.SelectNodes("//live"))
                {
                    var strData = new StreamData();

                    if (node.SelectSingleNode("play") != null)
                        strData.PlayStream = node.SelectSingleNode("play").InnerText;
                    if (node.SelectSingleNode("video_height") != null)
                        strData.VideoHeight = node.SelectSingleNode("video_height").InnerText;
                    if (node.SelectSingleNode("token") != null)
                        strData.Token = node.SelectSingleNode("token").InnerText;
                    if (node.SelectSingleNode("connect") != null)
                        strData.Server = node.SelectSingleNode("connect").InnerText;

                    if (strData.Server.Contains("rtmp://"))
                        strData.Server = strData.Server.Substring(("rtmp://").Length);

                    if (strData.Server.Contains("/app"))
                        strData.Server = strData.Server.Remove(strData.Server.IndexOf("/app"));

                    ret.Streams.Add(strData);
                }
            }
            catch(Exception ex){}
            return ret;
        }
 private bool CheckStreamData(StreamData record)
 {
     VirtualContainer vc = new VirtualContainer(record.VcLevel);
     return OutputCredentials[record.Port].SetVirtualContainer(record.VcLevel, record.HigherPath, record.LowerPath, vc);
 }
 // Handle stream read notification.
 private void HandleRead(StreamData streamData)
 {
     queue.Enqueue(streamData);
     queuedItem.Set();
 }
            /// <summary>
            /// Delegate method which can be attached to AsyncStreamReader.DataReceived to
            /// aggregate data until a new line is found before calling LineHandler.
            /// </summary>
            public void AggregateLine(Process process, StreamWriter stdin, StreamData data)
            {
                if (DataHandler != null) DataHandler(process, stdin, data);
                bool linesProcessed = false;

                if (data.data != null)
                {
                    // Simplify line tracking by converting linefeeds to newlines.
                    data.text = data.text.Replace("\r\n", "\n").Replace("\r", "\n");

                    List<StreamData> aggregateList = GetBufferedData(data.handle);
                    aggregateList.Add(data);
                    bool complete = false;
                    while (!complete)
                    {
                        List<StreamData> newAggregateList = new List<StreamData>();
                        int textDataIndex = 0;
                        int aggregateListSize = aggregateList.Count;
                        complete = true;

                        foreach (StreamData textData in aggregateList)
                        {
                            bool end = data.end && (++textDataIndex == aggregateListSize);
                            newAggregateList.Add(textData);
                            int newlineOffset = textData.text.Length;
                            if (!end)
                            {
                                newlineOffset = textData.text.IndexOf("\n");
                                if (newlineOffset < 0) continue;
                                newAggregateList.Remove(textData);
                            }

                            StreamData concatenated = Aggregate(newAggregateList);

                            // Flush the aggregation list and store the overflow.
                            newAggregateList.Clear();
                            if (!end)
                            {
                                // Add the remaining line to the concatenated data.
                                concatenated.text += textData.text.Substring(0, newlineOffset + 1);
                                // Save the line after the newline in the buffer.
                                newAggregateList.Add(new StreamData(
                                    data.handle, textData.text.Substring(newlineOffset + 1),
                                    textData.data, false));
                                complete = false;
                            }

                            // Report the data.
                            if (LineHandler != null) LineHandler(process, stdin, concatenated);
                            linesProcessed = true;
                        }
                        aggregateList = newAggregateList;
                    }
                    streamDataByHandle[data.handle] = aggregateList;
                }
                // If no lines were processed call the handle to allow it to look ahead.
                if (!linesProcessed && LineHandler != null)
                {
                    LineHandler(process, stdin, StreamData.Empty);
                }
            }
Esempio n. 36
0
        private void AddNewlyStartedStreams(TwitchRootObject obj)
        {
            if (obj == null || obj.Streams == null || obj.Streams.Count == 0)
                return;

            foreach(var stream in obj.Streams)
            {
                bool globalancounce = false;
                if(_streamData.Keys.Contains(stream.Channel.Name))
                {
                    globalancounce = true;
                }
                bool bTryAddresult = _streamData.TryAdd(stream.Channel.Name, new TwitchStreamData { Started = DateTime.Now, Stream = stream });

                if(bTryAddresult)
                {
                    // Probably helps differentiate between different Game Titles from Response
                    string oldgame = xmlprovider.StreamInfo(stream.Channel.Name, "game");
                    string _game = "";
                    if (oldgame != stream.Channel.Game)
                    {
                        _game = stream.Channel.Game;
                    }
                    if (oldgame != stream.Game)
                    {
                        _game = stream.Game;
                    }
                    var _stream = new DeathmicChatbot.StreamInfo.Stream
                    {
                        Channel = stream.Channel.Name,
                        Game = _game,
                        Message = stream.Channel.Status
                    };
                    var _streamdata = new StreamData
                    {
                        Stream = _stream,
                        Started = DateTime.Now,
                        StreamProvider = this
                    };
                    TwitchStreamData _tstreamdata = new TwitchStreamData();
                    _tstreamdata.Started = DateTime.Now;
                    _tstreamdata.Stream = new DeathmicChatbot.StreamInfo.Twitch.Stream();
                    _tstreamdata.Stream.Channel = new DeathmicChatbot.StreamInfo.Twitch.Channel();
                    _tstreamdata.Stream.Channel.Name = stream.Channel.Name;
                    _tstreamdata.Stream.Channel.Mature = stream.Channel.Mature;
                    _tstreamdata.Stream.Channel.ID = stream.Channel.ID;
                    _tstreamdata.Stream.Channel.Delay = stream.Channel.Delay;
                    _tstreamdata.Stream.Channel.Created_At = stream.Channel.Created_At;
                    _tstreamdata.Stream.Channel.Display_Name = stream.Channel.Display_Name;
                    _tstreamdata.Stream.Channel.Links = stream.Channel.Links;
                    _tstreamdata.Stream.Channel.Profile_Banner = stream.Channel.Profile_Banner;
                    _tstreamdata.Stream.Channel.Url = stream.Channel.Url;
                    _tstreamdata.Stream.Channel.Updated_At = stream.Channel.Updated_At;
                    _tstreamdata.Stream.Game = _game;
                    _tstreamdata.Stream.Channel.Game = _game;

                    AddStreamdatatoXML(_tstreamdata);
                    StreamEventArgs streamEventArgs = new StreamEventArgs(_streamdata);
                    StreamStarted(this, streamEventArgs);
                }
                if(!bTryAddresult && globalancounce)
                {
                    string oldgame = xmlprovider.StreamInfo(stream.Channel.Name, "game");
                    string _game = "";
                    if (oldgame != stream.Channel.Game)
                    {
                        _game = stream.Channel.Game;
                    }
                    if (oldgame != stream.Game)
                    {
                        _game = stream.Game;
                    }

                    var _stream = new DeathmicChatbot.StreamInfo.Stream
                    {
                        Channel = stream.Channel.Name,
                        Game = _game,
                        Message = stream.Channel.Status
                    };
                    var _streamdata = new StreamData
                    {
                        Stream = _stream,
                        Started = DateTime.Now,
                        StreamProvider = this
                    };
                    StreamEventArgs streamEventArgs = new StreamEventArgs(_streamdata);
                    StreamGlobalNotification(this, streamEventArgs);
                }

            }
        }
Esempio n. 37
0
        private void RemoveStoppedStreams(TwitchRootObject obj)
        {
            foreach (var pair in from pair in _streamData where StreamStopped != null select pair)
            {
                bool bFound = obj.Streams.Any(stream => pair.Key == stream.Channel.Name);
                if(!bFound)
                {
                    TwitchStreamData sd;
                    _streamStopCounter.StreamTriesToStop(pair.Key);
                    if(_streamStopCounter.StreamHasTriedStoppingEnoughTimes(pair.Key) || !_streamData.TryRemove(pair.Key,out sd))
                    {
                        continue;
                    }
                    _streamStopCounter.StreamHasStopped(pair.Key);
                    var stream = new DeathmicChatbot.StreamInfo.Stream
                    {
                        Channel = pair.Value.Stream.Channel.Name,
                        Game = pair.Value.Stream.Game,
                        Message = pair.Value.Stream.Channel.Status
                    };
                    var streamData = new StreamData
                    {
                        Started = DateTime.Now,
                        Stream = stream,
                        StreamProvider = this
                    };
                    var streamEventArgs = new StreamEventArgs(streamData);
                    StreamStopped(this, streamEventArgs);

                }
            }
        }
 public StreamCreatedArgs(StreamData streamData)
 {
     StreamData = streamData;
 }
 public bool RemoveStreamData(StreamData record)
 {
     if (Streams.Contains(record))
     {
         Streams.Remove(record);
         ClearCredentials(record);
         return true;
     }
     return false;
 }
Esempio n. 40
0
        /// <summary>
        /// Initializes a new instance of the CompareStreamData class and sets all properties based on the StreamData provided
        /// </summary>
        /// <param name="leftStream">First StreamData object to use for comparison</param>
        /// <param name="rightStream">Second StreamData object to use for comparison</param>
        public CompareStreamData(StreamData leftStream, StreamData rightStream)
        {
            if (leftStream == null && rightStream == null)
            {
                throw new InvalidOperationException(Strings.ErrorNoStreams);
            }

            this.StreamName = Strings.Unknown;
            this.LeftPublicMetadataCount = 0;
            this.RightPublicMetadataCount = 0;
            this.LeftPersonalMetadataCount = 0;
            this.RightPersonalMetadataCount = 0;
            string dataTypeIdKey = Strings.DataTypeIdHeader;
            string semanticIdKey = Strings.SemanticIdHeader;
            string eventCountKey = Strings.EventCountHeader;
            string startTimeKey = Strings.StreamStartTimeHeader;
            string endTimeKey = Strings.StreamEndTimeHeader;
            string leftSemanticId = string.Empty;
            string rightSemanticId = string.Empty;
            string leftEventCount = string.Empty;
            string rightEventCount = string.Empty;
            string leftStartTime = string.Empty;
            string rightStartTime = string.Empty;
            string leftEndTime = string.Empty;
            string rightEndTime = string.Empty;
            string leftDataTypeId = string.Empty;
            string rightDataTypeId = string.Empty;
            KStudioMetadata leftPublicMetadata = null;
            KStudioMetadata rightPublicMetadata = null;
            KStudioMetadata leftPersonalMetadata = null;
            KStudioMetadata rightPersonalMetadata = null;

            if (leftStream != null)
            {
                this.StreamName = leftStream.EventStream.DataTypeName;
                leftSemanticId = leftStream.EventStream.SemanticId.ToString();
                leftEventCount = leftStream.EventHeaders.Count.ToString();
                leftStartTime = leftStream.StartTime.ToString();
                leftEndTime = leftStream.EndTime.ToString();
                leftDataTypeId = leftStream.EventStream.DataTypeId.ToString();
                leftPublicMetadata = leftStream.PublicMetadata;
                leftPersonalMetadata = leftStream.PersonalMetadata;
                this.LeftPublicMetadataCount = leftStream.PublicMetadata.Count;
                this.LeftPersonalMetadataCount = leftStream.PersonalMetadata.Count;
            }

            if (rightStream != null)
            {
                if (leftStream == null)
                {
                    this.StreamName = rightStream.EventStream.DataTypeName;
                }

                rightSemanticId = rightStream.EventStream.SemanticId.ToString();
                rightEventCount = rightStream.EventHeaders.Count.ToString();
                rightStartTime = rightStream.StartTime.ToString();
                rightEndTime = rightStream.EndTime.ToString();
                rightDataTypeId = rightStream.EventStream.DataTypeId.ToString();
                rightPublicMetadata = rightStream.PublicMetadata;
                rightPersonalMetadata = rightStream.PersonalMetadata;
                this.RightPublicMetadataCount = rightStream.PublicMetadata.Count;
                this.RightPersonalMetadataCount = rightStream.PersonalMetadata.Count;
            }

            // compare stream metadata
            bool samePublicMetadata = true;
            bool samePersonalMetadata = true;
            this.PublicMetadata = CompareFileData.CompareMetadata(leftPublicMetadata, rightPublicMetadata, out samePublicMetadata);
            this.PersonalMetadata = CompareFileData.CompareMetadata(leftPersonalMetadata, rightPersonalMetadata, out samePersonalMetadata);

            if (this.LeftPublicMetadataCount == 0 && this.RightPublicMetadataCount == 0)
            {
                this.StreamPublicMetadataCompareText = string.Format(Strings.PublicMetadataHeader, Strings.None);
            }
            else
            {
                this.StreamPublicMetadataCompareText = string.Format(Strings.PublicMetadataHeader, samePublicMetadata ? Strings.Same : Strings.Different);
            }

            if (this.LeftPersonalMetadataCount == 0 && this.RightPersonalMetadataCount == 0)
            {
                this.StreamPersonalMetadataCompareText = string.Format(Strings.PersonalMetadataHeader, Strings.None);
            }
            else
            {
                this.StreamPersonalMetadataCompareText = string.Format(Strings.PersonalMetadataHeader, samePersonalMetadata ? Strings.Same : Strings.Different);
            }

            // compare stream details
            this.StreamDetails = new ObservableCollection<CompareData>();
            this.StreamDetails.Add(new CompareData(dataTypeIdKey, leftDataTypeId, rightDataTypeId));
            this.StreamDetails.Add(new CompareData(semanticIdKey, leftSemanticId, rightSemanticId));
            this.StreamDetails.Add(new CompareData(eventCountKey, leftEventCount, rightEventCount));
            this.StreamDetails.Add(new CompareData(startTimeKey, leftStartTime, rightStartTime));
            this.StreamDetails.Add(new CompareData(endTimeKey, leftEndTime, rightEndTime));

            bool sameDetails = this.StreamDetails.All(data => data.Same);

            this.StreamDetailsCompareText = string.Format(Strings.StreamDetailsHeader, sameDetails ? Strings.Same : Strings.Different);

            this.Same = (samePublicMetadata && samePersonalMetadata && sameDetails) ? true : false;
        }
 /// <summary>
 /// Selects the stream for sending messages.
 /// </summary>
 /// <param name="streamData">The stream data.</param>
 public void SelectStream(StreamData streamData)
 {
     if (GetStreamData() != null && GetStreamData().Contains(streamData))
     {
         this.SelectedStream = GetStreamData().IndexOf(streamData);
     }
 }
 public bool RemoveStreamData(StreamData stream)
 {
     if (Adaptation.RemoveStreamData(stream))
     {
         if (StreamRemoved != null)
         {
             List<StreamData> streams = new List<StreamData>();
             streams.Add(stream);
             StreamRemoved(new StreamChangedArgs(streams));
         }
         return true;
     }
     else return false;
 }
 private bool ClearCredentials(StreamData record)
 {
     Frame outputCredential = (Frame)OutputCredentials[record.Port];
     return outputCredential.ClearVirtualContainer(record.VcLevel, record.HigherPath, record.LowerPath);
 }
        private StreamData CreateRecord(List<string> literalRecord)
        {
            int outPort = int.Parse(literalRecord[0]);
            int? lowerPath = literalRecord[4].Equals("") ? null : (int?)int.Parse(literalRecord[4]);
            int higherPath = int.Parse(literalRecord[3]);

            VirtualContainerLevel level = VirtualContainerLevelExt.GetContainer(literalRecord[2]);
            StmLevel stm = StmLevelExt.GetContainer(literalRecord[1]);

            StreamData record = new StreamData(outPort, stm, level, higherPath, lowerPath);

            return record;
        }