private void btnChooseFile_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".data";
            dlg.Filter = "Frame data (*.data)|*.data";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                frameList.Clear();
                // Open document
                string filename = dlg.FileName;
                using (System.IO.BinaryReader br =
                    new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open)))
                {
                    while (br.BaseStream.Position < br.BaseStream.Length)
                    {
                        //deserialises and reads the binary file
                        DateTime date = new DateTime();
                        date = DateTime.FromBinary(br.ReadInt64());
                        // Console.WriteLine(date.ToString());

                        Int32 stimCode = br.ReadInt32();

                        Int32 nextBlock = br.ReadInt32();
                        byte[] frameData = br.ReadBytes(nextBlock);
                        Leap.Frame newFrame = new Leap.Frame();
                        newFrame.Deserialize(frameData);

                        if (stimCode == 5443)
                        {
                            Debug.WriteLine("5443 detected: " + newFrame.Id);
                        }
                        frameList.Add(newFrame);
                        //Console.WriteLine(newFrame.CurrentFramesPerSecond);

                    }
                    br.Close();
                    br.Dispose();
                }
                /* WRITE CODE HERE TO EXTRACT DATA FROM FILE
                foreach (Leap.Frame frame in frameList)
                {
                    //Console.WriteLine(frame.Id);
                }
                */

            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Unpack Deserializes Node from Stream
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="reader"></param>
        public void Unpack(IInternalPersistent parent,
                           System.IO.BinaryReader reader)
        {
            Count          = reader.ReadInt16();
            HintSizeOnDisk = reader.ReadInt32();
            ParentAddress  = reader.ReadInt64();
            if (Slots == null)
            {
                Slots = new BTreeItemOnDisk[((BTreeAlgorithm)parent).SlotLength];
            }
            if (ChildrenAddresses == null)
            {
                ChildrenAddresses = new long[Slots.Length + 1];
                ResetArray(ChildrenAddresses, -1);
            }
            short newCount = 0;

            for (int i = 0; i <= Slots.Length; i++)
            {
                ChildrenAddresses[i] = reader.ReadInt64();
                if (ChildrenAddresses[i] != -1)
                {
                    newCount++;
                }
            }
            if (ChildrenAddresses[0] == -1L)
            {
                ChildrenAddresses = null;
            }
            else if (newCount > 0 && Count != newCount - 1)
            {
                Count = (short)(newCount - 1);
            }
            for (int i = 0; i < Count; i++)
            {
                Slots[i] = new BTreeItemOnDisk();
                object key = null;

                int vn = reader.ReadInt32();
                Slots[i].VersionNumber = vn;
                if (Slots[i].Key is IPersistentVersioned)
                {
                    ((IPersistentVersioned)Slots[i].Key).VersionNumber = Slots[i].VersionNumber;
                }
                // read key from disk
                CollectionOnDisk.ReadPersistentData(parent, reader, ref key);

                if (key == null)
                {
                    if (((BTreeAlgorithm)parent).onKeyUnpack != null)
                    {
                        key = ((BTreeAlgorithm)parent).onKeyUnpack(reader);
                    }
                    if (key == null)
                    {
                        if (i == 0)
                        {
                            ((BTreeAlgorithm)parent).RootNeedsReload = true;
                            return;
                        }
                        throw new InvalidOperationException(
                                  "Can't DeSerialize Key, ensure there is a TypeStore Entry for this data type.");
                    }
                }

                Slots[i].Key   = key;
                Slots[i].Value = new ItemOnDisk();
                if (((BTreeAlgorithm)parent).IsDataInKeySegment)
                {
                    if (((BTreeAlgorithm)parent).IsDataLongInt)
                    {
                        long l = reader.ReadInt64();
                        Slots[i].Value.Data = l;
                    }
                    else
                    {
                        if (((BTreeAlgorithm)parent).PersistenceType == PersistenceType.Unknown)
                        {
                            throw new InvalidOperationException("Parent BTreeAlgorithm PersistenceType is unknown.");
                        }
                        // write the value and keep track of its data size and location in the disk buffer.
                        long startPos = reader.BaseStream.Position;
                        if (CollectionOnDisk.ReadPersistentData(parent, reader, ref Slots[i].Value.Data, ItemType.Value) == null)
                        {
                            ((BTreeAlgorithm)parent).ValueUnpack(reader, Slots[i]);
                        }
                        Slots[i].HintSizeOnDisk = (int)(reader.BaseStream.Position - startPos);
                    }
                    Slots[i].ValueLoaded   = true;
                    Slots[i].Value.IsDirty = false;
                }
                else
                {
                    // read Address of Value in Data Segment
                    long l = reader.ReadInt64();
                    Slots[i].Value.DiskBuffer = ((BTreeAlgorithm)parent).CreateBlock();
                    // new Sop.DataBlock((DataBlockSize) parent.DiskBuffer.Length);
                    ((CollectionOnDisk)parent).SetIsDirty(Slots[i].Value.DiskBuffer, false);
                    Slots[i].ValueLoaded = false;
                    ((BTreeAlgorithm)parent).DataBlockDriver.SetId(Slots[i].Value.DiskBuffer, l);
                    Slots[i].Value.DiskBuffer.contiguousBlockCount = reader.ReadUInt16();
                }
            }
        }
Ejemplo n.º 3
0
 public override void Unpack(System.IO.BinaryReader reader)
 {
     Key       = reader.ReadString();
     TimeStamp = reader.ReadInt64();
 }
Ejemplo n.º 4
0
        //  Converts an array of eight bytes to a 64-bit integer

        public static long To_LI(byte [] bytes)
        {
            in_bytes.reset();
            in_bytes.set_stream_bytes(bytes);
            return(in_stream.ReadInt64());
        }
Ejemplo n.º 5
0
        public void LoadParsing( string _corpus_path )
        {
            corpus_path = _corpus_path;
               sent2pos = new List<long>();

               // Читаем файл filepath построчно, запоминая позиции узлов <sentence ...> в особом
               // индексном файле

               index_path = System.IO.Path.Combine( System.IO.Path.GetTempPath(), System.IO.Path.GetFileNameWithoutExtension( corpus_path ) + ".XMLINDEX" );

               // проверить, если такой файл уже существует и создан после файла парсинга, то можно просто загрузить его содержимое.
               if( System.IO.File.Exists( index_path ) && System.IO.File.GetLastWriteTime( corpus_path ) < System.IO.File.GetLastWriteTime( index_path ) )
               {
            using( System.IO.BinaryReader rdr = new System.IO.BinaryReader( System.IO.File.Open( index_path, System.IO.FileMode.Open ) ) )
            {
             long filesize = rdr.BaseStream.Length;
             long nrec = filesize / sizeof( long );
             long[] recs = new long[nrec];

             for( long i = 0; i < nrec; ++i )
             {
              sent2pos.Add( rdr.ReadInt64() );
             }
            }
               }
               else
               {
            using( System.IO.BinaryWriter index_wrt = new System.IO.BinaryWriter( System.IO.File.Open( index_path, System.IO.FileMode.Create ) ) )
            {
             using( System.IO.FileStream rdr = new System.IO.FileStream( corpus_path, System.IO.FileMode.Open ) )
             {
              while( true )
              {
               long pos = rdr.Position;
               string line = ReadLine( rdr );
               if( string.IsNullOrEmpty( line ) )
               {
            continue;
               }

               if( line == "</parsing>" )
            break;

               if( line.StartsWith( "<sentence" ) )
               {
            index_wrt.Write( pos );
            sent2pos.Add( pos );
               }
              }
             }
            }
               }

               return;
        }
Ejemplo n.º 6
0
 public bool Read(ref long val, string name = null)
 {
     val = _reader.ReadInt64();
     return(true);
 }
Ejemplo n.º 7
0
 public static ChunkHeaderv1 Deserialzie(byte[] buffer)
 {
     if (buffer == null)
         throw new ArgumentNullException ("buffer");
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             return new ChunkHeaderv1 (DateTime.FromBinary (BR.ReadInt64 ()), BR.ReadString ());
         }
     }
 }
Ejemplo n.º 8
0
 public long getLong()
 {
     return(reader.ReadInt64());
 }
Ejemplo n.º 9
0
        public override void Read(System.IO.BinaryReader reader)
        {
            long int64 = reader.ReadInt64();

            _key = new DateTime(int64);
        }
Ejemplo n.º 10
0
Archivo: Column.cs Proyecto: vebin/BD2
 public static Column Deserialize(Frontend fb, byte[] chunkID, byte[] buffer)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             return new Column (fb, chunkID, BR.ReadString (), fb.ValueSerializer.IDToType (BR.ReadByte ()), BR.ReadBoolean (), BR.ReadInt64 ());
         }
     }
 }
        /// <summary>
        /// 从指定的网络流中获取数据并写入到输出流中。支持断点续传。
        /// </summary>
        /// <param name="networkStream">与客户端连接的网络流。</param>
        /// <param name="outputStream">数据输出流。</param>
        /// <param name="bufferSize">设置允许使用的缓冲区最大大小。</param>
        /// <param name="transferSizeChanged">已经传输的数据大小更改时引发此事件。设置为 null 则忽略此参数。</param>
        /// <returns>指示数据传输是否成功。</returns>
        /// <remarks>
        /// 断点续传的前提条件为数据输出流参数 <paramref name="outputStream"/> 提供读写支持。
        /// </remarks>
        public static bool ReadDataFromNetworkBreakPoint(System.Net.Sockets.NetworkStream networkStream, System.IO.Stream outputStream, int bufferSize, TransferPositionChangedHandler transferSizeChanged)
        {
            if (outputStream.CanRead == false || outputStream.CanWrite == false || outputStream.CanSeek == false)
            {
                throw new System.IO.IOException("无效的数据输出流参数“outputStream”,必须允许读取数据,写入数据和支持查找功能。");
            }
            //System.Int32 EnableBreakLength = 1024 * 500; //指示断点上传启用条件。当待上传的数据总大小大于或等于此值时启用断点上传功能。断点检测是需要耗费时间的,所以此值不应该设置过小。
            //System.Int32 BreakCheckLength = 1024 * 32; //指示断点识别数据块大小,为 0 时表示忽略断点检测。默认设置为32Kbyte。如果设置的值太小将造成识别错误,太大又将影响效率首次传输效率。
            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(networkStream, System.Text.Encoding.UTF8);
            System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(networkStream, System.Text.Encoding.UTF8);

            System.Int64 dataLength      = binaryReader.ReadInt64();           //读取待上传数据总长度。
            System.Int32 sha1Length      = binaryReader.ReadInt32();           //读取SHA1码的长度。
            byte[]       clientSha1Datas = binaryReader.ReadBytes(sha1Length); //读取SHA1码。

            #region 加载断点数据或生成新的断点数据。
            if (dataLength == outputStream.Length)                        //如果存盘数据大小与待上传数据大小相同,则先确认文件上传是否已经完成。
            {
                byte[] sha1 = Thinksea.General.GetSHA1(outputStream, 0);  //获取SHA1码。
                if (Thinksea.General.CompareArray(sha1, clientSha1Datas)) //如果 SHA1 码相同,则认为文件已经传输完成。
                {
                    binaryWriter.Write(dataLength);                       //写入发送数据的起始位置。
                    binaryWriter.Write(true);                             //告诉客户端文件传输已经完成。
                    return(true);
                }
            }
            BreakPoint breakPoint = LoadBreakPoint(outputStream);
            if (!(breakPoint != null && dataLength == breakPoint.TotalSize && Thinksea.General.CompareArray(breakPoint.SHA1, clientSha1Datas))) //只有文件大小相同,并且校验码相同,才启用断点续传。
            {
                breakPoint                      = new BreakPoint();
                breakPoint.TotalSize            = dataLength;
                breakPoint.SHA1                 = clientSha1Datas;
                breakPoint.LastTransferPosition = 0;
                SaveBreakPoint(outputStream, breakPoint);
            }
            #endregion

            //System.Int64 BreakCheckPosition = 0; //断点识别数据块起始位置。
            //if (dataLength >= outputStream.Length && dataLength > EnableBreakLength && outputStream.Length > 0) //如果需要断点续传。
            //{
            //    if (outputStream.Length < BreakCheckLength) BreakCheckLength = System.Convert.ToInt32(outputStream.Length); //根据已经传送的数据的长度调整校验数据块的大小。
            //    BreakCheckPosition = outputStream.Seek(0 - BreakCheckLength, System.IO.SeekOrigin.End); //定位断点检测起始位置。
            //    byte[] BreakCheckDatas = new byte[BreakCheckLength]; //断点识别数据块。
            //    outputStream.Read(BreakCheckDatas, 0, BreakCheckDatas.Length); //读取待校验的断点数据。

            //    binaryWriter.Write(BreakCheckPosition); //写入断点识别数据块起始位置。
            //    binaryWriter.Write(BreakCheckLength); //写入断点识别数据块大小。
            //    System.Int32 clientBreakDatasLength = binaryReader.ReadInt32(); //获取客户端将上传的断点识别数据块大小。
            //    byte[] clientBreakDatas = binaryReader.ReadBytes(clientBreakDatasLength); //获取客户端上传的断点识别数据块。
            //    if (Thinksea.General.CompareArray(BreakCheckDatas, clientBreakDatas)) //如果校验码相同,则启用断点续传。
            //    {
            //        outputStream.Seek(0, System.IO.SeekOrigin.End);
            //    }
            //    else //如果校验码不同,则重新传送数据。
            //    {
            //        outputStream.SetLength(0); //截断文件长度。
            //        outputStream.Seek(0, System.IO.SeekOrigin.Begin);
            //    }
            //}
            //else
            //{
            //    BreakCheckPosition = 0;
            //    BreakCheckLength = 0;
            //    binaryWriter.Write(BreakCheckPosition); //写入断点识别数据块起始位置。
            //    binaryWriter.Write(BreakCheckLength); //写入断点识别数据块大小。

            //    outputStream.SetLength(0); //截断文件长度。
            //    outputStream.Seek(0, System.IO.SeekOrigin.Begin);
            //}
            binaryWriter.Write(breakPoint.LastTransferPosition); //通知客户端上传数据的起始位置。
            if (breakPoint.LastTransferPosition < breakPoint.TotalSize)
            {
                outputStream.Seek(breakPoint.LastTransferPosition, System.IO.SeekOrigin.Begin); //设置写入数据起始位置。
                int saveBreakPointSize = 1024 * 500;                                            //保存断点信息的条件。
                //Thinksea.FileTransfer.Lib.FileSystem.ReadDataFromNetwork(networkStream, (dataLength - outputStream.Position), outputStream, bufferSize, transferSizeChanged); //读取数据。
                Thinksea.Net.DataTransfer.ReadDataFromNetwork(networkStream, (dataLength - outputStream.Position), outputStream, bufferSize, delegate(TransferPositionChangedEventArgs e)
                {
                    if ((e.TransferPosition - breakPoint.LastTransferPosition) > saveBreakPointSize) //记录断点传输信息。
                    {
                        breakPoint.LastTransferPosition = e.TransferPosition;
                        SaveBreakPoint(outputStream, breakPoint);
                    }
                    if (transferSizeChanged != null)
                    {
                        transferSizeChanged(e);
                    }
                }); //读取数据。
            }
            bool success = false;
            if (outputStream.Position == breakPoint.TotalSize)
            {
                outputStream.SetLength(breakPoint.TotalSize); //清除断点数据。

                #region 校验文件SHA1码是否相同。
                byte[] serverSha1Datas = Thinksea.General.GetSHA1(outputStream, 0); //获取SHA1码。
                if (Thinksea.General.CompareArray(clientSha1Datas, serverSha1Datas))
                {
                    success = true;
                }
                else
                {
                    success = false;
                }
                #endregion
            }
            binaryWriter.Write(success);
            return(success);
        }
Ejemplo n.º 12
0
        protected override void DecodeContent(System.IO.BinaryReader r)
        {
            //25
            Id = Encoding.UTF8.GetString(r.ReadBytes(25)).Trim();                      //车辆信息Id
            //6
            StationId = Encoding.UTF8.GetString(r.ReadBytes(6)).Trim();                //r.ReadUInt32();  //站点Id
            //8
            EvtTime = ConvertToDateTime(r.ReadUInt64());                               //事件发生时间
            //8
            MsgTime = ConvertToDateTime(r.ReadUInt64());                               //消息接收时间
            //1
            LaneNo = r.ReadByte();                                                     //车道序号
            //8
            EvtNo = r.ReadInt64();                                                     //设备序号
            //4
            r.ReadUInt32();                                                            //备用
            //2
            r.ReadUInt16();                                                            //备用
            //1
            r.ReadByte();                                                              //备用
            //1
            ValidityCode = r.ReadByte();                                               //有效性号
            //15
            Plate = Encoding.UTF8.GetString(r.ReadBytes(15)).Trim("\0".ToCharArray()); //车牌号码
            //Plate = Encoding.GetEncoding("gb2312").GetString(r.ReadBytes(15)).Trim("\0".ToCharArray());
            //1
            PlateColor = r.ReadByte();    //车牌颜色
            //4
            r.ReadUInt32();               //备用
            //1
            ClassIndex = r.ReadByte();    //DictDataModel.ClassIndexs(r.ReadByte()); //r.ReadByte();         //车型
            //1
            AxlesCount = r.ReadByte();    //axles count         //轴数
            //4
            TotalWeight = r.ReadUInt32(); //weight
            //20
            AxleWeights = new ushort[10];
            for (var idx = 0; idx < 10; idx++)
            {
                AxleWeights[idx] = r.ReadUInt16();//axle_x weight
            }
            //18
            axleSpaces = new ushort[9];
            for (var idx = 0; idx < 9; idx++)
            {
                axleSpaces[idx] = r.ReadUInt16();//axle_x weight
            }
            //1
            Direction = r.ReadByte();                           // == 1 ? "逆行" : "正常行驶";//direction   //DictDataModel.dictDemo(r.ReadByte());
            //2
            Speed = r.ReadInt16();                              //speed
            //2
            Length = r.ReadUInt16();                            //length
            //2
            Width = r.ReadUInt16();                             //width
            //2
            Height = r.ReadUInt16();                            //height
            //2
            Wheelbase = r.ReadUInt16();                         //总轴距 cm
            //1
            Temperature = r.ReadByte() - 100;                   //温度
            //1
            IsStraddle = r.ReadByte();                          // ? "跨道" : "未跨道";//isStraddle

            //2
            OverLength = r.ReadUInt16();                        //over width, height, length, speed, weight
            //2
            OverWidth = r.ReadUInt16();
            //2
            OverHeight = r.ReadUInt16();
            //4
            OverWeight = r.ReadUInt32();
            //2
            OverSpeed = r.ReadUInt16();       //是否超速:0否,1是
            //2
            OverLengthRatio = r.ReadUInt16(); //over ratio : width, height, length, speed, weight
            //2
            OverWidthRatio = r.ReadUInt16();
            //2
            OverHeightRatio = r.ReadUInt16();
            //2
            OverWeightRatio = r.ReadUInt16();
            //2
            OverSpeedRatio = r.ReadUInt16();    //超速比率,百分比

            //2
            //r.ReadUInt16();
            //5
            //r.ReadBytes(4);//???????????????????
            var imgSize = r.ReadInt32();//img size

            ImgData = r.ReadBytes(imgSize);

            var plateImgSize = r.ReadInt32();//img size

            PlateImgData = r.ReadBytes(plateImgSize);

            var laserImgSize = r.ReadInt32();         //laser img size   //激光3D图片大小

            LaserImgData = r.ReadBytes(laserImgSize); //laser img data

            //r.ReadBytes(6);//备用
            Gap     = r.ReadUInt16();                          //车间距,单位:50cm
            TimeGap = r.ReadUInt16();                          //车时间距,单位:毫秒
            Headway = r.ReadUInt16();                          //车头时距,单位:100毫秒

            WIM_Id = Encoding.UTF8.GetString(r.ReadBytes(25)); //wim    //动态称重记录Id
            LPR_Id = Encoding.UTF8.GetString(r.ReadBytes(25)); //lpr    //车牌识别记录Id
            DMS_Id = Encoding.UTF8.GetString(r.ReadBytes(25)); //dms    //激光扫描记录Id

            OverWeightCalculate();
            if (this.AxlesCount > 10 || this.Length > 2500 || this.Length < 0 || this.Axle1_T > 9500 || this.TotalWeight > 100000)
            {
                OverWeightDataState = -1;
            }
            else
            {
                if (OverWeight > 0 && (this.Speed > 110 || this.Speed < 20 || (this.Plate.Equals("无车牌") && !(Program.port.Equals("10015") || Program.port.Equals("10016")))))
                //if (OverWeight > 0 && (this.Speed > 110 || this.Speed < 20 || (this.Plate.Equals("无车牌"))))
                {
                    OverWeightDataState = -1;
                }
                else
                {
                    //G15沈海苏沪省界2车道全部超重数据放入异常数据库
                    //2020.10.30改
                    //start
                    if (Program.port.Equals("10017") && this.LaneNo == 2)
                    {
                        OverWeight           = 0;
                        this.OverWeightRatio = 0;
                        OverWeightDataState  = -1;
                    }
                    else
                    {
                        //end
                        OverWeightDataState = 1;
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public static Row Deserialize(byte[] bytes)
        {
            using (System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes, false)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader(MS)) {
                    byte[]    columnSet  = BR.ReadBytes(32);
                    int       FieldCount = BR.ReadInt32();
                    object[]  fields     = new object[FieldCount];
                    ColumnSet cs         = css [columnSet];
                    if (cs.Columns.Length != fields.Length)
                    {
                        throw new Exception();
                    }
                    for (int n = 0; n != fields.Length; n++)
                    {
                        bool Null = BR.ReadBoolean();
                        if (Null)
                        {
                            fields [n] = null;
                            continue;
                        }
                        switch (cs.Columns [n].TFQN)
                        {
                        case "System.Byte[]":
                            fields [n] = BR.ReadBytes(BR.ReadInt32());
                            break;

                        case "System.Byte":
                            fields [n] = BR.ReadByte();
                            break;

                        case "System.SByte":
                            fields [n] = BR.ReadSByte();
                            break;

                        case "System.Int16":
                            fields [n] = BR.ReadInt16();
                            break;

                        case "System.UInt16":
                            fields [n] = BR.ReadUInt16();
                            break;

                        case "System.Int32":
                            fields [n] = BR.ReadInt32();
                            break;

                        case "System.UInt32":
                            fields [n] = BR.ReadUInt32();
                            break;

                        case "System.Int64":
                            fields [n] = BR.ReadInt64();
                            break;

                        case "System.UInt64":
                            fields [n] = BR.ReadUInt64();
                            break;

                        case "System.Single":
                            fields [n] = BR.ReadSingle();
                            break;

                        case "System.Double":
                            fields [n] = BR.ReadDouble();
                            break;

                        case "System.String":
                            fields [n] = BR.ReadString();
                            break;

                        case "System.Char":
                            fields [n] = BR.ReadChar();
                            break;

                        case "System.Boolean":
                            fields [n] = BR.ReadBoolean();
                            break;

                        case "System.DateTime":
                            fields [n] = new DateTime(BR.ReadInt64());
                            break;

                        case "System.Guid":
                            fields [n] = new Guid(BR.ReadBytes(16));
                            break;
                        }
                    }
                    return(new Row(cs, fields));
                }
            }
        }
Ejemplo n.º 14
0
Archivo: Row.cs Proyecto: vebin/BD2
 public static Row Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             byte[] columnSet = BR.ReadBytes (32);
             int FieldCount = BR.ReadInt32 ();
             object[] fields = new object[FieldCount];
             ColumnSet cs = css [columnSet];
             if (cs.Columns.Length != fields.Length)
                 throw new Exception ();
             for (int n = 0; n != fields.Length; n++) {
                 bool Null = BR.ReadBoolean ();
                 if (Null) {
                     fields [n] = null;
                     continue;
                 }
                 switch (cs.Columns [n].TFQN) {
                 case "System.Byte[]":
                     fields [n] = BR.ReadBytes (BR.ReadInt32 ());
                     break;
                 case "System.Byte":
                     fields [n] = BR.ReadByte ();
                     break;
                 case "System.SByte":
                     fields [n] = BR.ReadSByte ();
                     break;
                 case "System.Int16":
                     fields [n] = BR.ReadInt16 ();
                     break;
                 case "System.UInt16":
                     fields [n] = BR.ReadUInt16 ();
                     break;
                 case "System.Int32":
                     fields [n] = BR.ReadInt32 ();
                     break;
                 case "System.UInt32":
                     fields [n] = BR.ReadUInt32 ();
                     break;
                 case "System.Int64":
                     fields [n] = BR.ReadInt64 ();
                     break;
                 case "System.UInt64":
                     fields [n] = BR.ReadUInt64 ();
                     break;
                 case "System.Single":
                     fields [n] = BR.ReadSingle ();
                     break;
                 case "System.Double":
                     fields [n] = BR.ReadDouble ();
                     break;
                 case "System.String":
                     fields [n] = BR.ReadString ();
                     break;
                 case "System.Char":
                     fields [n] = BR.ReadChar ();
                     break;
                 case "System.Boolean":
                     fields [n] = BR.ReadBoolean ();
                     break;
                 case "System.DateTime":
                     fields [n] = new DateTime (BR.ReadInt64 ());
                     break;
                 case "System.Guid":
                     fields [n] = new Guid (BR.ReadBytes (16));
                     break;
                 }
             }
             return new Row (cs, fields);
         }
     }
 }
        public static TransparentStreamSeekRequestMessage Deserialize(byte[] buffer)
        {
            if (buffer == null)
                throw new ArgumentNullException ("buffer");
            Guid id;
            Guid streamID;
            long offset;
            System.IO.SeekOrigin seekOrigin;

            using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
                    id = new Guid (BR.ReadBytes (16));
                    streamID = new Guid (BR.ReadBytes (16));
                    offset = BR.ReadInt64 ();
                    seekOrigin = (System.IO.SeekOrigin)BR.ReadInt32 ();
                }
            }
            return new TransparentStreamSeekRequestMessage (id, streamID, offset, seekOrigin);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Load the Container from the Stream
        /// </summary>
        /// <param name="reader">the Stream Reader</param>
        internal void Load(System.IO.BinaryReader reader)
        {
            valid = ContainerValid.FileNotFound;
            items.Clear();
            int offset = reader.ReadInt32();

            version = reader.ReadByte();
            type    = (ContainerType)reader.ReadByte();
            int count = reader.ReadInt32();

            long pos = reader.BaseStream.Position;

            try
            {
                if (version <= VERSION)
                {
                    reader.BaseStream.Seek(offset, System.IO.SeekOrigin.Begin);
                    added    = DateTime.FromFileTime(reader.ReadInt64());
                    filename = reader.ReadString();

                    if (System.IO.File.Exists(filename))
                    {
                        DateTime mod = System.IO.File.GetLastWriteTime(filename);
                        if (mod <= added)
                        {
                            valid = ContainerValid.Yes;
                        }
                        else
                        {
                            valid = ContainerValid.Modified;
                        }
                    }

                    if (valid == ContainerValid.Yes)
                    {
                        switch (type)
                        {
                        case ContainerType.Object:
                        {
                            for (int i = 0; i < count; i++)
                            {
                                ObjectCacheItem oci = new ObjectCacheItem();
                                oci.Load(reader);
                                items.Add(oci);
                            }

                            break;
                        }

                        case ContainerType.MaterialOverride:
                        {
                            for (int i = 0; i < count; i++)
                            {
                                MMATCacheItem oci = new MMATCacheItem();
                                oci.Load(reader);
                                items.Add(oci);
                            }

                            break;
                        }

                        case ContainerType.Rcol:
                        {
                            for (int i = 0; i < count; i++)
                            {
                                RcolCacheItem oci = new RcolCacheItem();
                                oci.Load(reader);
                                items.Add(oci);
                            }

                            break;
                        }

                        case ContainerType.Want:
                        {
                            for (int i = 0; i < count; i++)
                            {
                                WantCacheItem oci = new WantCacheItem();
                                oci.Load(reader);
                                items.Add(oci);
                            }

                            break;
                        }

                        case ContainerType.Memory:
                        {
                            for (int i = 0; i < count; i++)
                            {
                                MemoryCacheItem oci = new MemoryCacheItem();
                                oci.Load(reader);
                                oci.ParentCacheContainer = this;
                                if (oci.Version >= MemoryCacheItem.DISCARD_VERSIONS_SMALLER_THAN)
                                {
                                    items.Add(oci);
                                }
                            }

                            break;
                        }

                        case ContainerType.Package:
                        {
                            for (int i = 0; i < count; i++)
                            {
                                PackageCacheItem oci = new PackageCacheItem();
                                oci.Load(reader);
                                items.Add(oci);
                            }

                            break;
                        }
                        }         //switch
                    }             // if valid
                }                 //if VERSION
                else
                {
                    valid = ContainerValid.UnknownVersion;
                }
            }
            finally
            {
                reader.BaseStream.Seek(pos, System.IO.SeekOrigin.Begin);
            }
        }
Ejemplo n.º 17
0
        public override void PrepareProcessing()
        {
            _reader?.Dispose();
            try {
                _reader = new System.IO.BinaryReader(System.IO.File.OpenRead(_attrFilePath.TypedGet()));
            } catch (Exception ex) {
                Parent.Context.Notify(new GraphNotification(GraphNotification.NotificationType.Error, ex.ToString()));
                throw;
            }

            if (_reader != null)
            {
                _reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                _portOut.PrepareProcessing();
                _portTrigger.PrepareProcessing();
                _buffer      = new TimeLocatedBuffer1D <double>(_portOut.Buffer.Capacity, _portOut.Samplerate);
                _endOfStream = false;

                if (_portTrigger.Connection == null)
                {
                    _startTime = new TimeStamp(0);
                }
            }
            else
            {
                throw new Exception("File node: did not specify input");
            }

            _lastStatePosition = 0;

            _sampleSize = _dataTypeSizes[_attrDataType.TypedGet()];

            _sampleGetterFunc = () => {
                throw new System.IO.EndOfStreamException();
            };

            switch (_attrDataType.TypedGet())
            {
            case DataType.Float32:
                _sampleGetterFunc = () => _reader.ReadSingle();
                break;

            case DataType.Float64:
                _sampleGetterFunc = () => _reader.ReadDouble();
                break;

            case DataType.Int16:
                _sampleGetterFunc = () => _reader.ReadInt16();
                break;

            case DataType.Int32:
                _sampleGetterFunc = () => _reader.ReadInt32();
                break;

            case DataType.Int64:
                _sampleGetterFunc = () => _reader.ReadInt64();
                break;

            default:
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 18
0
        private bool TryLoadCachedGroup(byte[] data, DateTime lastWriteTime)
        {
            var timer = System.Diagnostics.Stopwatch.StartNew();

            var reader = new BinaryReader(new MemoryStream(data), Encoding.UTF8);

            DateTime cacheTime = new DateTime(reader.ReadInt64(), DateTimeKind.Utc);
            if (cacheTime != lastWriteTime)
                return false;

            Dictionary<int, object> objects = new Dictionary<int, object>();
            objects.Add(0, null);

            // first pass constructs objects
            long objectTableOffset = reader.BaseStream.Position;
            int objectCount = reader.ReadInt32();
            for (int i = 0; i < objectCount; i++)
            {
                int key = reader.ReadInt32();
                object obj = CreateGroupObject(reader, key, objects);
                objects.Add(key, obj);
            }

            reader.BaseStream.Seek(objectTableOffset + 4, SeekOrigin.Begin);
            for (int i = 0; i < objectCount; i++)
            {
                int key = reader.ReadInt32();
                LoadGroupObject(reader, key, objects);
            }

            List<TemplateGroup> importsToClearOnUnload = new List<TemplateGroup>();
            Dictionary<string, CompiledTemplate> templates = new Dictionary<string, CompiledTemplate>();
            Dictionary<string, IDictionary<string, object>> dictionaries = new Dictionary<string, IDictionary<string, object>>();

            // imported groups
            int importCount = reader.ReadInt32();
            for (int i = 0; i < importCount; i++)
                importsToClearOnUnload.Add((TemplateGroup)objects[reader.ReadInt32()]);

            // delimiters
            char delimiterStartChar = reader.ReadChar();
            char delimiterStopChar = reader.ReadChar();

            // templates & aliases
            int templateCount = reader.ReadInt32();
            for (int i = 0; i < templateCount; i++)
            {
                string key = reader.ReadString();
                CompiledTemplate value = (CompiledTemplate)objects[reader.ReadInt32()];
                templates[key] = value;
            }

            // dictionaries
            int dictionaryCount = reader.ReadInt32();
            for (int i = 0; i < dictionaryCount; i++)
            {
                string name = reader.ReadString();
                IDictionary<string, object> dictionary = new Dictionary<string, object>();
                dictionaries[name] = dictionary;
                int valueCount = reader.ReadInt32();
                for (int j = 0; j < valueCount; j++)
                {
                    string key = reader.ReadString();
                    object value = objects[reader.ReadInt32()];
                    dictionary[key] = value;
                }
            }

            this._importsToClearOnUnload.AddRange(importsToClearOnUnload);
            this.delimiterStartChar = delimiterStartChar;
            this.delimiterStopChar = delimiterStopChar;

            foreach (var pair in templates)
                this.templates[pair.Key] = pair.Value;

            foreach (var pair in dictionaries)
                this.dictionaries[pair.Key] = pair.Value;

            System.Diagnostics.Debug.WriteLine(string.Format("Successfully loaded the cached group {0} in {1}ms.", Name, timer.ElapsedMilliseconds));
            return true;
        }
Ejemplo n.º 19
0
        public static void readSeparateIndex(System.IO.Stream index, System.IO.Stream XMLBytes, int XMLSize, VTDGen vg)
        {
            if (index == null || vg == null || XMLBytes == null)
            {
                throw new System.ArgumentException("Invalid argument(s) for readIndex()");
            }
            //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' 
            //which has a different behavior. 
            //"ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
            System.IO.BinaryReader dis = new System.IO.BinaryReader(index);
            byte b = dis.ReadByte(); // first byte
            // no check on version number for now
            // second byte
            vg.encoding = dis.ReadByte();
            int intLongSwitch;
            int endian;
            // third byte
            b = dis.ReadByte();
            if ((b & 0x80) != 0)
                intLongSwitch = 1;
            //use ints
            else
                intLongSwitch = 0;
            if ((b & 0x40) != 0)
                vg.ns = true;
            else
                vg.ns = false;
            if ((b & 0x20) != 0)
                endian = 1;
            else
                endian = 0;
            if ((b & 0x1f) != 0)
                throw new IndexReadException("Last 5 bits of the third byte should be zero");

            // fourth byte
            vg.VTDDepth = dis.ReadByte();

            // 5th and 6th byte
            int LCLevel = (((int)dis.ReadByte()) << 8) | dis.ReadByte();
            if (LCLevel != 4 && LCLevel != 6)
            {
                throw new IndexReadException("LC levels must be at least 3");
            }
            // 7th and 8th byte
            vg.rootIndex = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            long l = dis.ReadInt64();

            int size;
            // read XML size
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
                size = (int)l;
            else
                size = (int)reverseLong(l);


            // read XML bytes
            byte[] XMLDoc = new byte[size];
            XMLBytes.Read(XMLDoc, 0, size);

            //dis.Read(XMLDoc, 0, size);
            /*if ((size & 0x7) != 0)
            {
                int t = (((size >> 3) + 1) << 3) - size;
                while (t > 0)
                {
                    dis.ReadByte();
                    t--;
                }
            }*/

            vg.setDoc(XMLDoc);
            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
            {
                // read vtd records
                int vtdSize = (int)dis.ReadInt64();
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(dis.ReadInt64());
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)dis.ReadInt64();
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(dis.ReadInt64());
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)dis.ReadInt64();
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(dis.ReadInt64());
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)dis.ReadInt64();
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(dis.ReadInt32());
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append((int)(dis.ReadInt64() >> 32));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(dis.ReadInt64());
                        l3Size--;
                    }

                    int l4Size = (int)dis.ReadInt64();
                    while (l4Size > 0)
                    {
                        vg._l4Buffer.append(dis.ReadInt64());
                        l4Size--;
                    }

                    int l5Size = (int)dis.ReadInt64();
                    if (intLongSwitch == 1)
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(dis.ReadInt32());
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append((int)(dis.ReadInt64() >> 32));
                            l5Size--;
                        }
                    }
                }
            }
            else
            {
                // read vtd records
                int vtdSize = (int)reverseLong(dis.ReadInt64());
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(reverseLong(dis.ReadInt64()));
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)reverseLong(dis.ReadInt64());
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(reverseLong(dis.ReadInt64()));
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)reverseLong(dis.ReadInt64());
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(reverseLong(dis.ReadInt64()));
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)reverseLong(dis.ReadInt64());
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt(dis.ReadInt32()));
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(reverseLong(dis.ReadInt64()));
                        l3Size--;
                    }

                    int l4Size = (int)reverseLong(dis.ReadInt64());
                    {
                        vg._l4Buffer.append(reverseLong(dis.ReadInt64()));
                        l4Size--;
                    }

                    int l5Size = (int)reverseLong(dis.ReadInt64());
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt(dis.ReadInt32()));
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l5Size--;
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Читает P-объект из бинарного ридера, начиная с текущего места
        /// </summary>
        /// <param name="typ"></param>
        /// <param name="br"></param>
        /// <returns></returns>
        public static object GetPO(PType typ, System.IO.BinaryReader br)
        {
            switch (typ.Vid)
            {
            case PTypeEnumeration.none: return(null);

            case PTypeEnumeration.boolean: return(br.ReadBoolean());

            case PTypeEnumeration.integer: return(br.ReadInt32());

            case PTypeEnumeration.longinteger: return(br.ReadInt64());

            case PTypeEnumeration.real: return(br.ReadDouble());

            case PTypeEnumeration.@byte: return(br.ReadByte());

            case PTypeEnumeration.fstring:
            {
                //int len = ((PTypeFString)typ).Length;
                int    size = ((PTypeFString)typ).Size;
                byte[] arr  = new byte[size];
                arr = br.ReadBytes(size);
                string s = System.Text.Encoding.Unicode.GetString(arr);
                return(s);
            }

            case PTypeEnumeration.sstring:
            {
                //int len = br.ReadInt32();
                //char[] chrs = br.ReadChars(len);
                //return new string(chrs);
                return(br.ReadString());
            }

            case PTypeEnumeration.record:
            {
                PTypeRecord r_tp   = (PTypeRecord)typ;
                object[]    fields = new object[r_tp.Fields.Length];
                for (int i = 0; i < r_tp.Fields.Length; i++)
                {
                    fields[i] = GetPO(r_tp.Fields[i].Type, br);
                }
                return(fields);
            }

            case PTypeEnumeration.sequence:
            {
                PTypeSequence mts  = (PTypeSequence)typ;
                PType         tel  = mts.ElementType;
                long          llen = br.ReadInt64();
                object[]      els  = new object[llen];
                for (long ii = 0; ii < llen; ii++)
                {
                    els[ii] = GetPO(tel, br);
                }
                return(els);
            }

            case PTypeEnumeration.union:
            {
                PTypeUnion mtu = (PTypeUnion)typ;
                int        v   = br.ReadByte();
                PType      mt  = mtu.Variants[v].Type;
                return(new object[] { v, GetPO(mt, br) });
            }

            default: throw new Exception("Err in TPath Get(): type is not implemented " + typ.Vid);
            }
        }
Ejemplo n.º 21
0
 private void btnLoadOverlay_Click(object sender, EventArgs e)
 {
     dlgLoadOverlay.InitialDirectory = m_DefaultDirectory;
     if (dlgLoadOverlay.ShowDialog() == DialogResult.OK)
     {
         System.IO.BinaryReader r  = null;
         System.IO.FileStream   fr = null;
         try
         {
             if (dlgLoadOverlay.FileName.ToLower().EndsWith(".x3l"))
             {
                 m_OverlayScene = (GDI3D.Scene)xmlscene.Deserialize(new System.IO.StringReader(System.IO.File.ReadAllText(dlgLoadOverlay.FileName)));
             }
             else if (dlgLoadOverlay.FileName.ToLower().EndsWith(".rwd") || rx_RWD.Match(dlgLoadOverlay.FileName.ToLower()).Success)
             {
                 fr = new System.IO.FileStream(dlgLoadOverlay.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                 SySal.Scanning.Plate.IO.OPERA.RawData.Fragment frag = new Scanning.Plate.IO.OPERA.RawData.Fragment(fr);
                 fr.Close();
                 fr = null;
                 GDI3D.Scene scene = new GDI3D.Scene();
                 int         total = 0;
                 int         v;
                 for (v = 0; v < frag.Length; v++)
                 {
                     total += frag[v].Top.Length + frag[v].Bottom.Length;
                 }
                 scene.Lines           = new GDI3D.Line[2 * total];
                 scene.Points          = new GDI3D.Point[0];
                 scene.OwnerSignatures = new string[total];
                 total = 0;
                 for (v = 0; v < frag.Length; v++)
                 {
                     int i;
                     for (i = 0; i < frag[v].Top.Length; i++)
                     {
                         SySal.Tracking.MIPEmulsionTrackInfo info = frag[v].Top[i].Info;
                         info.Intercept = frag[v].Top.MapPoint(info.Intercept);
                         info.Slope     = frag[v].Top.MapVector(info.Slope);
                         scene.OwnerSignatures[total / 2] = v + "T" + i + ": " + info.Count + " " + info.AreaSum + " " + info.Intercept.X.ToString("F1") + " " + info.Intercept.Y.ToString("F1") + " " + info.Slope.X.ToString("F4") + " " + info.Slope.Y.ToString("F4") + " " + info.Sigma.ToString("F3");
                         scene.Lines[total++]             = new GDI3D.Line(info.Intercept.X, info.Intercept.Y, 0, info.Intercept.X + EmulThickness * info.Slope.X, info.Intercept.Y + EmulThickness * info.Slope.Y, EmulThickness, i, 224, 0, 0);
                         scene.Lines[total++]             = new GDI3D.Line(info.Intercept.X, info.Intercept.Y, 0, info.Intercept.X - BaseThickness * info.Slope.X, info.Intercept.Y - BaseThickness * info.Slope.Y, -BaseThickness, i, 0, 224, 0);
                     }
                     for (i = 0; i < frag[v].Bottom.Length; i++)
                     {
                         SySal.Tracking.MIPEmulsionTrackInfo info = frag[v].Bottom[i].Info;
                         info.Intercept = frag[v].Bottom.MapPoint(info.Intercept);
                         info.Slope     = frag[v].Bottom.MapVector(info.Slope);
                         scene.OwnerSignatures[total / 2] = v + "B" + i + ": " + info.Count + " " + info.AreaSum + " " + info.Intercept.X.ToString("F1") + " " + info.Intercept.Y.ToString("F1") + " " + info.Slope.X.ToString("F4") + " " + info.Slope.Y.ToString("F4") + " " + info.Sigma.ToString("F3");
                         scene.Lines[total++]             = new GDI3D.Line(info.Intercept.X, info.Intercept.Y, -BaseThickness, info.Intercept.X - EmulThickness * info.Slope.X, info.Intercept.Y - EmulThickness * info.Slope.Y, -BaseThickness - EmulThickness, i, 0, 0, 224);
                         scene.Lines[total++]             = new GDI3D.Line(info.Intercept.X, info.Intercept.Y, -BaseThickness, info.Intercept.X + BaseThickness * info.Slope.X, info.Intercept.Y + BaseThickness * info.Slope.Y, 0, i, 0, 224, 0);
                     }
                 }
                 m_OverlayScene = scene;
             }
             else if (dlgLoadOverlay.FileName.ToLower().EndsWith(".reader"))
             {
                 r = new System.IO.BinaryReader(new System.IO.FileStream(dlgLoadOverlay.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read));
                 int         total = r.ReadInt32();
                 GDI3D.Scene scene = new GDI3D.Scene();
                 scene.Lines           = new GDI3D.Line[2 * total];
                 scene.Points          = new GDI3D.Point[0];
                 scene.OwnerSignatures = new string[total];
                 r.ReadDouble(); r.ReadDouble(); r.ReadDouble(); r.ReadDouble();
                 int i;
                 for (i = 0; i < total; i++)
                 {
                     Int64  zone    = r.ReadInt64();
                     short  side    = r.ReadInt16();
                     int    id      = r.ReadInt32();
                     short  count   = r.ReadInt16();
                     int    areasum = r.ReadInt32();
                     double x       = r.ReadDouble();
                     double y       = r.ReadDouble();
                     double z       = (side == 1) ? 0 : -BaseThickness;
                     double sx      = r.ReadDouble();
                     double sy      = r.ReadDouble();
                     double sigma   = r.ReadDouble();
                     int    view    = r.ReadInt32();
                     double vx      = r.ReadDouble();
                     double vy      = r.ReadDouble();
                     scene.OwnerSignatures[i] = zone + " " + side + " " + id + ": " + count + " " + areasum + " " + x.ToString("F1") + " " + y.ToString("F1") + " " + sx.ToString("F4") + " " + sy.ToString("F4") + " " + sigma.ToString("F3") + " in " + view + ": " + vx.ToString("F1") + " " + vy.ToString("F1");
                     double dz     = ((side == 1) ? EmulThickness : -EmulThickness);
                     double dzbase = ((side == 1) ? -BaseThickness : BaseThickness);
                     scene.Lines[2 * i]     = new GDI3D.Line(x, y, z, x + dz * sx, y + dz * sy, z + dz, i, (side == 1) ? 255 : 0, 0, (side == 2) ? 255 : 0);
                     scene.Lines[2 * i + 1] = new GDI3D.Line(x, y, z, x + dzbase * sx, y + dzbase * sy, z + dzbase, i, (side == 1) ? 255 : 0, 192, (side == 2) ? 255 : 0);
                 }
                 r.Close();
                 r = null;
                 m_OverlayScene = scene;
             }
             else if (dlgLoadOverlay.FileName.ToLower().EndsWith(".tlg"))
             {
                 SySal.DataStreams.OPERALinkedZone lzd = new DataStreams.OPERALinkedZone(dlgLoadOverlay.FileName);
                 int         total = lzd.Length;
                 GDI3D.Scene scene = new GDI3D.Scene();
                 scene.Lines           = new GDI3D.Line[3 * total];
                 scene.Points          = new GDI3D.Point[0];
                 scene.OwnerSignatures = new string[total];
                 int i;
                 for (i = 0; i < total; i++)
                 {
                     SySal.Tracking.MIPEmulsionTrackInfo info = lzd[i].Info;
                     scene.OwnerSignatures[i] = i + ": " + info.Count + " " + info.AreaSum + " " + info.Intercept.X.ToString("F1") + " " + info.Intercept.Y.ToString("F1") + " " + info.Slope.X.ToString("F4") + " " + info.Slope.Y.ToString("F4") + " " + info.Sigma.ToString("F3");
                     scene.Lines[3 * i]       = new GDI3D.Line(info.Intercept.X, info.Intercept.Y, 0, info.Intercept.X + EmulThickness * info.Slope.X, info.Intercept.Y + EmulThickness * info.Slope.Y, EmulThickness, i, 224, 0, 0);
                     scene.Lines[3 * i + 1]   = new GDI3D.Line(info.Intercept.X, info.Intercept.Y, 0, info.Intercept.X - BaseThickness * info.Slope.X, info.Intercept.Y - BaseThickness * info.Slope.Y, -BaseThickness, i, 0, 224, 0);
                     scene.Lines[3 * i + 2]   = new GDI3D.Line(info.Intercept.X - BaseThickness * info.Slope.X, info.Intercept.Y - BaseThickness * info.Slope.Y, -BaseThickness, info.Intercept.X - (BaseThickness + EmulThickness) * info.Slope.X, info.Intercept.Y - (BaseThickness + EmulThickness) * info.Slope.Y, -BaseThickness - EmulThickness, i, 0, 0, 224);
                 }
                 lzd.Dispose();
                 m_OverlayScene = scene;
             }
             else
             {
                 MessageBox.Show("Unsupported format", "File error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
         catch (Exception x)
         {
             MessageBox.Show(x.ToString(), "File error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         finally
         {
             if (r != null)
             {
                 r.Close();
                 r = null;
             }
             if (fr != null)
             {
                 fr.Close();
                 fr = null;
             }
             m_OverlayBmp = null;
         }
     }
 }
Ejemplo n.º 22
0
Archivo: Column.cs Proyecto: vebin/BD2
 public static Column Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             return new Column (new Guid (BR.ReadBytes (16)), BR.ReadString (), BR.ReadBoolean (), BR.ReadInt64 (), BR.ReadString ());
         }
     }
 }
Ejemplo n.º 23
0
        protected internal async void GetFile(string sFullPathToFolder, int intFileGetPort) //Using GetFile(int iPort)
        {
            try
            {
                System.Net.Sockets.TcpListener listener = System.Net.Sockets.TcpListener.Create(intFileGetPort);
                Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " +
                                                 Form1.myForm.LocalHost.UserName + ": Готов принять файл");

                listener.Start();
                System.Net.Sockets.TcpClient client = await listener.AcceptTcpClientAsync();

                using (System.Net.Sockets.NetworkStream inputStream = client.GetStream())
                {
                    using (var cancellationTokenSource = new System.Threading.CancellationTokenSource(3000))
                    {
                        using (cancellationTokenSource.Token.Register(() => inputStream.Close()))
                        {
                            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(inputStream))
                            {
                                sActionFile            = reader.ReadString();
                                Form1.myForm.sFilePath = System.IO.Path.Combine(sFullPathToFolder, sActionFile);
                                long lenght = reader.ReadInt64();
                                using (System.IO.FileStream outputStream = System.IO.File.Open(Form1.myForm.sFilePath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                                {
                                    long totalBytes = 0;
                                    int  readBytes  = 0;

                                    try
                                    {
                                        byte[] buffer = new byte[1024];

                                        do
                                        {
                                            readBytes = await inputStream.ReadAsync(buffer, 0, buffer.Length, cancellationTokenSource.Token); //cancellationtoken

                                            outputStream.Write(buffer, 0, readBytes);
                                            totalBytes += readBytes;
                                        } while (client.Connected && totalBytes < lenght);

                                        string sizeReceivedFile = "";
                                        if (totalBytes < 1024)
                                        {
                                            sizeReceivedFile = totalBytes + " B";
                                        }
                                        else if (1024 < totalBytes && totalBytes < 1048576)
                                        {
                                            sizeReceivedFile = Math.Round((Convert.ToDouble(totalBytes) / 1024), 1).ToString() + " kB";
                                        }
                                        else if (1048576 < totalBytes && totalBytes < 1073741824)
                                        {
                                            sizeReceivedFile = Math.Round((Convert.ToDouble(totalBytes) / 1024 / 1024), 1).ToString() + " MB";
                                        }
                                        else
                                        {
                                            sizeReceivedFile = Math.Round((Convert.ToDouble(totalBytes) / 1024 / 1024 / 1024), 1).ToString() + " GB";
                                        }

                                        Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " +
                                                                         Form1.myForm.LocalHost.UserName + ": Принят файл - " + Form1.myForm.sFilePath + " Размер - " + sizeReceivedFile);
                                    }
                                    catch (TimeoutException e)
                                    {
                                        readBytes = -1;
                                    }
                                }
                            }
                        }
                    }
                }

                if (System.IO.Path.GetFileName(Form1.myForm.sFilePath).ToLower() != System.IO.Path.GetFileName(System.Windows.Forms.Application.ExecutablePath).ToLower())
                {
                    if (!System.IO.Path.GetExtension(Form1.myForm.sFilePath).ToLower().Contains("top") &&
                        !System.IO.Path.GetExtension(Form1.myForm.sFilePath).ToLower().Contains("jpg") &&
                        !System.IO.Path.GetExtension(Form1.myForm.sFilePath).ToLower().Contains("png"))
                    {
                        Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " +
                                                         Form1.myForm.LocalHost.UserName + "copy from " + Form1.myForm.sFilePath + " to " + System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, System.IO.Path.GetFileName(Form1.myForm.sFilePath)));
                        System.IO.File.Copy(
                            Form1.myForm.sFilePath,
                            System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, System.IO.Path.GetFileName(Form1.myForm.sFilePath)), true
                            );
                    }
                    //    else { System.IO.File.Delete(Form1.myForm.sFilePath); }
                }
                else
                {
                    Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " +
                                                     Form1.myForm.LocalHost.UserName + "get " + Form1.myForm.sFilePath);
                }

                //  aResEvntGotFile.Set();
                //close chanel after got updates
                client.Close();  //test
                listener.Stop(); //test
                listener.Server.Dispose();
            }
            catch (Exception expt)
            {
                Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Can't get file... " + expt.Message);
            }
        }
 public override TimeSpan BinaryReadValue(System.IO.BinaryReader reader)
 {
     return(new TimeSpan(reader.ReadInt64()));
 }
Ejemplo n.º 25
0
 public static Column Deserialize(FrontendInstanceBase fib, byte[] chunkID, byte[] buffer)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream(buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader(MS)) {
             return(new Column(fib, BR.ReadBytes(32), chunkID, BR.ReadString(), ((Frontend)fib.Frontend).ValueDeserializer.IDToType(BR.ReadByte()), BR.ReadBoolean(), BR.ReadInt64()));
         }
     }
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Reads summary information from a stream, preparing the LinkedZone and its Sides for coming access requests.
        /// </summary>
        /// <param name="str">the stream from which data have to be retrieved.</param>
        protected void Read(System.IO.Stream str)
        {
            r = new System.IO.BinaryReader(m_Stream = str);
            byte   infotype     = r.ReadByte();
            ushort headerformat = r.ReadUInt16();

            if (infotype == ((byte)0x41))
            {
                switch (headerformat)
                {
                case (ushort)0x07: break;

                default: throw new SystemException("Unsupported format");
                }
            }
            ;

            if (r.ReadByte() != SectionTag)
            {
                throw new Exception("The first section in a TLG file must contain tracks!");
            }
            r.ReadInt64();

            m_Transform.MXX = m_Transform.MYY = 1.0;
            m_Transform.MXY = m_Transform.MYX = 0.0;
            m_Transform.TX  = m_Transform.TY = 0.0;
            m_Transform.RX  = m_Transform.RY = 0.0;

            m_Id.Part0 = r.ReadInt32();
            m_Id.Part1 = r.ReadInt32();
            m_Id.Part2 = r.ReadInt32();
            m_Id.Part3 = r.ReadInt32();

            m_Center.X      = r.ReadDouble();
            m_Center.Y      = r.ReadDouble();
            m_Extents.MinX  = r.ReadDouble();
            m_Extents.MaxX  = r.ReadDouble();
            m_Extents.MinY  = r.ReadDouble();
            m_Extents.MaxY  = r.ReadDouble();
            m_Transform.MXX = r.ReadDouble();
            m_Transform.MXY = r.ReadDouble();
            m_Transform.MYX = r.ReadDouble();
            m_Transform.MYY = r.ReadDouble();
            m_Transform.TX  = r.ReadDouble();
            m_Transform.TY  = r.ReadDouble();
            m_Transform.RX  = r.ReadDouble();
            m_Transform.RY  = r.ReadDouble();

            int    ntopviews    = r.ReadInt32();
            int    nbottomviews = r.ReadInt32();
            double toptz        = r.ReadDouble();
            double topbz        = r.ReadDouble();
            double bottomtz     = r.ReadDouble();
            double bottombz     = r.ReadDouble();
            long   topviews_sp  = str.Position;

            str.Seek(ntopviews * View.Size, System.IO.SeekOrigin.Current);
            long bottomviews_sp = str.Position;

            str.Seek(nbottomviews * View.Size, System.IO.SeekOrigin.Current);
            uint ntoptracks    = r.ReadUInt32();
            uint nbottomtracks = r.ReadUInt32();

            N_Tracks = r.ReadUInt32();
            long toptracks_sp    = str.Position;
            long bottomtracks_sp = toptracks_sp + MIPIndexedEmulsionTrack.Size * ntoptracks;

            Tracks_SP = bottomtracks_sp + MIPIndexedEmulsionTrack.Size * nbottomtracks;
            long toptrackindices_sp    = Tracks_SP + MIPBaseTrack.Size * N_Tracks;
            long bottomtrackindices_sp = toptrackindices_sp + MIPIndexedEmulsionTrack.IndexSize * ntoptracks;

            m_Top    = new Side(toptz, topbz, (int)ntopviews, topviews_sp, (int)ntoptracks, toptracks_sp, toptrackindices_sp, str);
            m_Bottom = new Side(bottomtz, bottombz, (int)nbottomviews, bottomviews_sp, (int)nbottomtracks, bottomtracks_sp, bottomtrackindices_sp, str);
        }
Ejemplo n.º 27
0
 public override void Unpack(System.IO.BinaryReader reader)
 {
     ExpirationTime    = reader.ReadInt64();
     SlidingExpiration = reader.ReadInt64();
     Priority          = (CacheItemPriority)reader.ReadByte();
 }
Ejemplo n.º 28
0
        private static OperationInfo ReadOperationInfo(System.IO.BinaryReader reader)
        {
            // Read the operation id
            var id = new OperationId(reader.ReadUInt32());

            // Read the operation title
            var title = ReadString(reader);

            // Read the command working directory
            var workingDirectory = ReadString(reader);

            // Read the command executable
            var executable = ReadString(reader);

            // Read the command arguments
            var arguments = ReadString(reader);

            // Read the declared input files
            var declaredInput = ReadFileIdList(reader);

            // Read the declared output files
            var declaredOutput = ReadFileIdList(reader);

            // Read the read access list
            var readAccess = ReadFileIdList(reader);

            // Read the write access list
            var writeAccess = ReadFileIdList(reader);

            // Read the child operation ids
            var children = ReadOperationIdList(reader);

            // Read the dependency count
            var dependecyCount = reader.ReadUInt32();

            // Read the value indicating if there was a successful run
            var wasSuccessfulRun = ReadBoolean(reader);

            // Read the utc tick since January 1, 0001 at 00:00:00.000 in the Gregorian calendar
            var evaluateTime = new DateTime(reader.ReadInt64(), DateTimeKind.Utc);

            // Read the observed input files
            var observedInput = ReadFileIdList(reader);

            // Read the observed output files
            var observedOutput = ReadFileIdList(reader);

            return(new OperationInfo(
                       id,
                       title,
                       new CommandInfo(
                           new Path(workingDirectory),
                           new Path(executable),
                           arguments),
                       declaredInput,
                       declaredOutput,
                       readAccess,
                       writeAccess,
                       children,
                       dependecyCount,
                       wasSuccessfulRun,
                       evaluateTime,
                       observedInput,
                       observedOutput));
        }
Ejemplo n.º 29
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.LongValue:
            {
                return(new JSONData(aReader.ReadInt64()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
Ejemplo n.º 30
0
 public override DateTime BinaryReadValue(System.IO.BinaryReader reader)
 {
     return(DateTime.FromFileTime(reader.ReadInt64()));
 }
Ejemplo n.º 31
0
 public override void Unpack(IInternalPersistent parent, System.IO.BinaryReader reader)
 {
     base.Unpack(parent, reader);
     Address = reader.ReadInt64();
 }
Ejemplo n.º 32
0
 public long ReadInt64()
 {
     return(Reader.ReadInt64());
 }
Ejemplo n.º 33
0
        public void Load(System.IO.BinaryReader reader)
        {
            long ticks = reader.ReadInt64();

            DTime = new DateTime(ticks);
        }
Ejemplo n.º 34
0
        public static void readSeparateIndex(System.IO.Stream index, System.IO.Stream XMLBytes, int XMLSize, VTDGen vg)
        {
            if (index == null || vg == null || XMLBytes == null)
            {
                throw new System.ArgumentException("Invalid argument(s) for readIndex()");
            }
            //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader'
            //which has a different behavior.
            //"ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
            System.IO.BinaryReader dis = new System.IO.BinaryReader(index);
            byte b = dis.ReadByte(); // first byte

            // no check on version number for now
            // second byte
            vg.encoding = dis.ReadByte();
            int intLongSwitch;
            int endian;

            // third byte
            b = dis.ReadByte();
            if ((b & 0x80) != 0)
            {
                intLongSwitch = 1;
            }
            //use ints
            else
            {
                intLongSwitch = 0;
            }
            if ((b & 0x40) != 0)
            {
                vg.ns = true;
            }
            else
            {
                vg.ns = false;
            }
            if ((b & 0x20) != 0)
            {
                endian = 1;
            }
            else
            {
                endian = 0;
            }
            if ((b & 0x1f) != 0)
            {
                throw new IndexReadException("Last 5 bits of the third byte should be zero");
            }

            // fourth byte
            vg.VTDDepth = dis.ReadByte();

            // 5th and 6th byte
            int LCLevel = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            if (LCLevel != 4 && LCLevel != 6)
            {
                throw new IndexReadException("LC levels must be at least 3");
            }
            // 7th and 8th byte
            vg.rootIndex = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            long l = dis.ReadInt64();

            int size;

            // read XML size
            if (BitConverter.IsLittleEndian && endian == 0 ||
                BitConverter.IsLittleEndian == false && endian == 1)
            {
                size = (int)l;
            }
            else
            {
                size = (int)reverseLong(l);
            }


            // read XML bytes
            byte[] XMLDoc = new byte[size];
            XMLBytes.Read(XMLDoc, 0, size);

            //dis.Read(XMLDoc, 0, size);

            /*if ((size & 0x7) != 0)
             * {
             *  int t = (((size >> 3) + 1) << 3) - size;
             *  while (t > 0)
             *  {
             *      dis.ReadByte();
             *      t--;
             *  }
             * }*/

            vg.setDoc(XMLDoc);
            // skip a long
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            if (BitConverter.IsLittleEndian && endian == 0 ||
                BitConverter.IsLittleEndian == false && endian == 1)
            {
                // read vtd records
                int vtdSize = (int)dis.ReadInt64();
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(dis.ReadInt64());
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)dis.ReadInt64();
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(dis.ReadInt64());
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)dis.ReadInt64();
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(dis.ReadInt64());
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)dis.ReadInt64();
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(dis.ReadInt32());
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append((int)(dis.ReadInt64() >> 32));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(dis.ReadInt64());
                        l3Size--;
                    }

                    int l4Size = (int)dis.ReadInt64();
                    while (l4Size > 0)
                    {
                        vg._l4Buffer.append(dis.ReadInt64());
                        l4Size--;
                    }

                    int l5Size = (int)dis.ReadInt64();
                    if (intLongSwitch == 1)
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(dis.ReadInt32());
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append((int)(dis.ReadInt64() >> 32));
                            l5Size--;
                        }
                    }
                }
            }
            else
            {
                // read vtd records
                int vtdSize = (int)reverseLong(dis.ReadInt64());
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(reverseLong(dis.ReadInt64()));
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)reverseLong(dis.ReadInt64());
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(reverseLong(dis.ReadInt64()));
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)reverseLong(dis.ReadInt64());
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(reverseLong(dis.ReadInt64()));
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)reverseLong(dis.ReadInt64());
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt(dis.ReadInt32()));
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(reverseLong(dis.ReadInt64()));
                        l3Size--;
                    }

                    int l4Size = (int)reverseLong(dis.ReadInt64());
                    {
                        vg._l4Buffer.append(reverseLong(dis.ReadInt64()));
                        l4Size--;
                    }

                    int l5Size = (int)reverseLong(dis.ReadInt64());
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt(dis.ReadInt32()));
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l5Size--;
                        }
                    }
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>Loads the black-box logs from the previous simulation run</summary>
        internal static void LoadLogs()
        {
            string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");

            try
            {
                using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
                    {
                        byte[]      Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
                        const short Version    = 1;
                        byte[]      Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        short Number = Reader.ReadInt16();
                        if (Version != Number)
                        {
                            throw new System.IO.InvalidDataException();
                        }
                        Game.LogRouteName = Reader.ReadString();
                        Game.LogTrainName = Reader.ReadString();
                        Game.LogDateTime  = DateTime.FromBinary(Reader.ReadInt64());
                        Interface.CurrentOptions.GameMode = (GameMode)Reader.ReadInt16();
                        Game.BlackBoxEntryCount           = Reader.ReadInt32();
                        Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
                        for (int i = 0; i < Game.BlackBoxEntryCount; i++)
                        {
                            Game.BlackBoxEntries[i].Time           = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Position       = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Speed          = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].Acceleration   = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerDriver    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerSafety    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeDriver    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeSafety    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].EventToken     = (Game.BlackBoxEventToken)Reader.ReadInt16();
                        }
                        Game.ScoreLogCount             = Reader.ReadInt32();
                        Game.ScoreLogs                 = new Game.ScoreLog[Game.ScoreLogCount];
                        Game.CurrentScore.CurrentValue = 0;
                        for (int i = 0; i < Game.ScoreLogCount; i++)
                        {
                            Game.ScoreLogs[i].Time          = Reader.ReadDouble();
                            Game.ScoreLogs[i].Position      = Reader.ReadDouble();
                            Game.ScoreLogs[i].Value         = Reader.ReadInt32();
                            Game.ScoreLogs[i].TextToken     = (Game.ScoreTextToken)Reader.ReadInt16();
                            Game.CurrentScore.CurrentValue += Game.ScoreLogs[i].Value;
                        }
                        Game.CurrentScore.Maximum = Reader.ReadInt32();
                        Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
                        Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        Reader.Close();
                    } Stream.Close();
                }
            }
            catch
            {
                Game.LogRouteName       = "";
                Game.LogTrainName       = "";
                Game.LogDateTime        = DateTime.Now;
                Game.BlackBoxEntries    = new Game.BlackBoxEntry[256];
                Game.BlackBoxEntryCount = 0;
                Game.ScoreLogs          = new Game.ScoreLog[64];
                Game.ScoreLogCount      = 0;
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// データ読み込み
        /// </summary>
        public static void LoadData()
        {
            // ここではファイルに保存したデータを読み込み、Parametersのプロパティに設定します

            // コイン枚数初期値を設定
            TotalCoinCount = INIT_COIN;

            // 投入コイン初期値を設定
            InsertCoinCount = 0;

            // 最終コイン補充時間初期値を設定
            LastRefillCoinTime = DateTime.Now;

            // 最終更新時間初期値を設定
            LastUpdateTime = DateTime.Now;

            // ファイル存在チェック
            if(System.IO.File.Exists(@SAVE_FILE))
            {
                // ファイルが存在する場合
                using(var fs = System.IO.File.Open(@SAVE_FILE, System.IO.FileMode.Open))
                {
                    // バイナリリーダー作成
                    var br = new System.IO.BinaryReader(fs);

                    // データ読み込み
                    LastUpdateTime = new DateTime(br.ReadInt64());		// 最終更新時間
                    LastRefillCoinTime = new DateTime(br.ReadInt64());	// 最終コイン補充時間
                    TotalCoinCount = br.ReadInt64();					// 残コイン数
                    InsertCoinCount = br.ReadInt32();					// 投入コイン数

                    // 各種クローズ処理
                    br.Close();
                    fs.Close();
                }
            }
        }
 public static TransparentStreamSetPositionRequestMessage Deserialize(byte[] buffer)
 {
     if (buffer == null)
         throw new ArgumentNullException ("buffer");
     Guid id;
     Guid streamID;
     long position;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             id = new Guid (BR.ReadBytes (16));
             streamID = new Guid (BR.ReadBytes (16));
             position = BR.ReadInt64 ();
         }
     }
     return new TransparentStreamSetPositionRequestMessage (id, streamID, position);
 }
Ejemplo n.º 38
0
        public override object Deserialize(System.IO.BinaryReader binaryReader)
        {
            bool hasValue = binaryReader.ReadBoolean();

            if (!hasValue)
            {
                return(null);
            }
            int typeID = binaryReader.ReadByte();

            switch (typeID)
            {
            case 1:
                return(binaryReader.ReadBoolean());

            case 2:
                return(binaryReader.ReadByte());

            case 128:
                return(binaryReader.ReadSByte());

            case 3:
                return(binaryReader.ReadInt16());

            case 129:
                return(binaryReader.ReadUInt16());

            case 4:
                return(binaryReader.ReadInt32());

            case 130:
                return(binaryReader.ReadUInt32());

            case 5:
                return(binaryReader.ReadInt64());

            case 131:
                return(binaryReader.ReadUInt64());

            case 9:
                return(binaryReader.ReadDouble());

            case 16:
                return(binaryReader.ReadString());

            case 144:
                return(binaryReader.ReadChar());

            case 24:
                return(new DateTime(binaryReader.ReadInt64()));

            case 32:
                return(new Guid(binaryReader.ReadBytes(16)));

            case 36:
                return(binaryReader.ReadBytes(binaryReader.ReadInt32()));

            default:
                throw new Exception(string.Format("Serialization for type <{0}> is not supported", typeID));
            }
        }
Ejemplo n.º 39
0
		/// <summary>Loads the black-box logs from the previous simulation run</summary>
		internal static void LoadLogs()
		{
			string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");
			try
			{
				using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
				{
					using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
					{
						byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
						const short Version = 1;
						byte[] Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						short Number = Reader.ReadInt16();
						if (Version != Number) throw new System.IO.InvalidDataException();
						Game.LogRouteName = Reader.ReadString();
						Game.LogTrainName = Reader.ReadString();
						Game.LogDateTime = DateTime.FromBinary(Reader.ReadInt64());
						Interface.CurrentOptions.GameMode = (Interface.GameMode)Reader.ReadInt16();
						Game.BlackBoxEntryCount = Reader.ReadInt32();
						Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
						for (int i = 0; i < Game.BlackBoxEntryCount; i++)
						{
							Game.BlackBoxEntries[i].Time = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Position = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Speed = Reader.ReadSingle();
							Game.BlackBoxEntries[i].Acceleration = Reader.ReadSingle();
							Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
							Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerDriver = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerSafety = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeDriver = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeSafety = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].EventToken = (Game.BlackBoxEventToken)Reader.ReadInt16();
						}
						Game.ScoreLogCount = Reader.ReadInt32();
						Game.ScoreLogs = new Game.ScoreLog[Game.ScoreLogCount];
						Game.CurrentScore.Value = 0;
						for (int i = 0; i < Game.ScoreLogCount; i++)
						{
							Game.ScoreLogs[i].Time = Reader.ReadDouble();
							Game.ScoreLogs[i].Position = Reader.ReadDouble();
							Game.ScoreLogs[i].Value = Reader.ReadInt32();
							Game.ScoreLogs[i].TextToken = (Game.ScoreTextToken)Reader.ReadInt16();
							Game.CurrentScore.Value += Game.ScoreLogs[i].Value;
						}
						Game.CurrentScore.Maximum = Reader.ReadInt32();
						Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
						Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						Reader.Close();
					} Stream.Close();
				}
			}
			catch
			{
				Game.LogRouteName = "";
				Game.LogTrainName = "";
				Game.LogDateTime = DateTime.Now;
				Game.BlackBoxEntries = new Game.BlackBoxEntry[256];
				Game.BlackBoxEntryCount = 0;
				Game.ScoreLogs = new Game.ScoreLog[64];
				Game.ScoreLogCount = 0;
			}
		}
 /// <summary>
 /// Deserialize Dss TimeSpan
 /// </summary>
 public virtual object Deserialize(System.IO.BinaryReader reader)
 {
     this.Ticks = reader.ReadInt64();
     return(this);
 }
 public static TransparentStreamGetLengthResponseMessage Deserialize(byte[] buffer)
 {
     if (buffer == null)
         throw new ArgumentNullException ("buffer");
     Guid streamID;
     Guid requestID;
     long length;
     Exception exception;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             streamID = new Guid (BR.ReadBytes (16));
             requestID = new Guid (BR.ReadBytes (16));
             length = BR.ReadInt64 ();
             if (MS.ReadByte () == 1) {
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 object deserializedObject = BF.Deserialize (MS);
                 if (deserializedObject is Exception) {
                     exception = (Exception)deserializedObject;
                 } else {
                     throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                 }
             } else
                 exception = null;
         }
     }
     return new TransparentStreamGetLengthResponseMessage (streamID, requestID, length, exception);
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Process a PCAP Next Generation section header block
        /// </summary>
        /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param>
        /// <param name="thePacketPayloadLength">The payload length of the packet read from the packet capture</param>
        /// <returns>Boolean flag that indicates whether the PCAP Next Generation section header block could be processed</returns>
        private bool ProcessSectionHeaderBlock(System.IO.BinaryReader theBinaryReader, out long thePacketPayloadLength)
        {
            bool theResult = true;

            // We have got a PCAP Next Generation section header block

            // The PCAP Next Generation section header block does not contain an Ethernet frame
            // Set up the output parameter for the length of the PCAP Next Generation packet capture packet payload
            // Set this output parameter to a value of zero to prevent any attempt to process an Ethernet frame from the PCAP Next Generation packet capture packet payload
            thePacketPayloadLength = 0;

            // Read off and store the block type for the PCAP Next Generation section header block for use below
            uint theBlockType =
                theBinaryReader.ReadUInt32();

            // Read off and store the block total length for the PCAP Next Generation section header block, adjusting it up to the next even four byte boundary, for use below
            uint theBlockTotalLength =
                AdjustBlockTotalLength(theBinaryReader.ReadUInt32());

            // Read off and store the magic number of the PCAP Next Generation section header block for use below
            uint theByteOrderMagic =
                theBinaryReader.ReadUInt32();

            // The endianism of the remainder of the values in the PCAP Next Generation section header block will be corrected to little endian if the magic number indicates big endian representation
            if (theByteOrderMagic == Constants.LittleEndianByteOrderMagic)
            {
                this.TheDebugInformation.WriteInformationEvent(
                    "The PCAP Next Generation packet capture contains the little endian byte-order magic");

                this.isTheSectionHeaderBlockLittleEndian = true;
            }
            else if (theByteOrderMagic == Constants.BigEndianByteOrderMagic)
            {
                this.TheDebugInformation.WriteInformationEvent(
                    "The PCAP Next Generation packet capture contains the big endian byte-order magic");

                this.isTheSectionHeaderBlockLittleEndian = false;
            }

            ushort theMajorVersion = 0;
            ushort theMinorVersion = 0;

            // Just read off the remainder of the PCAP Next Generation section header block from the packet capture so we can move on
            // Some of the data will be stored for use below
            if (this.isTheSectionHeaderBlockLittleEndian)
            {
                theMajorVersion = theBinaryReader.ReadUInt16();
                theMinorVersion = theBinaryReader.ReadUInt16();
                theBinaryReader.ReadUInt64(); // Section length
            }
            else
            {
                theMajorVersion = (ushort)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt16());
                theMinorVersion = (ushort)System.Net.IPAddress.NetworkToHostOrder(theBinaryReader.ReadInt16());
                theBinaryReader.ReadInt64(); // Section length
            }

            // The PCAP Next Generation section header block does not contain an Ethernet frame
            // Just read the bytes off the remaining bytes from the PCAP Next Generation section header block so we can continue
            theBinaryReader.ReadBytes(
                (int)(theBlockTotalLength -
                      (uint)Constants.BlockTotalLength.SectionHeaderBlock));

            // Validate fields from the PCAP Next Generation section header block
            theResult = this.ValidateSectionHeaderBlock(
                theBlockType,
                theByteOrderMagic,
                theMajorVersion,
                theMinorVersion);

            return(theResult);
        }