Пример #1
0
            public void createBB()
            {
                try {
                    MemoryStream          ms     = new MemoryStream();
                    BigEndianBinaryWriter writer = new BigEndianBinaryWriter(ms);
                    BinaryOutputArchive   boa    = BinaryOutputArchive.getArchive(writer);

                    boa.writeInt(-1, "len"); // We'll fill this in later
                    if (requestHeader != null)
                    {
                        ((Record)requestHeader).serialize(boa, "header");
                    }
                    if (request is ConnectRequest)
                    {
                        request.serialize(boa, "connect");
                        // append "am-I-allowed-to-be-readonly" flag
                        boa.writeBool(readOnly, "readOnly");
                    }
                    else if (request != null)
                    {
                        request.serialize(boa, "request");
                    }
                    ms.Position = 0;
                    bb          = new ByteBuffer(ms);
                    boa.writeInt(bb.limit() - 4, "len");
                    ms.Position = 0;
                } catch (Exception e) {
                    LOG.warn("Ignoring unexpected exception", e);
                }
            }
Пример #2
0
    public byte[] ToByteArray()
    {
        MemoryStream          rawDataStream = new MemoryStream(84);
        BigEndianBinaryWriter dataWriter    = new BigEndianBinaryWriter(rawDataStream);

        try {
            dataWriter.Write(headPosition.x);
            dataWriter.Write(headPosition.y);
            dataWriter.Write(headPosition.z);
            dataWriter.Write(headPose.x);
            dataWriter.Write(headPose.y);
            dataWriter.Write(headPose.z);
            dataWriter.Write(headPose.w);

            dataWriter.Write(leftHandPosition.x);
            dataWriter.Write(leftHandPosition.y);
            dataWriter.Write(leftHandPosition.z);
            dataWriter.Write(leftHandPose.x);
            dataWriter.Write(leftHandPose.y);
            dataWriter.Write(leftHandPose.z);
            dataWriter.Write(leftHandPose.w);

            dataWriter.Write(rightHandPosition.x);
            dataWriter.Write(rightHandPosition.y);
            dataWriter.Write(rightHandPosition.z);
            dataWriter.Write(rightHandPose.x);
            dataWriter.Write(rightHandPose.y);
            dataWriter.Write(rightHandPose.z);
            dataWriter.Write(rightHandPose.w);
        }
        catch (Exception e) {
            Debug.Log(e.StackTrace);
        }
        return(rawDataStream.ToArray());
    }
Пример #3
0
        public void Write(BigEndianBinaryWriter bw)
        {
            /*
             * foreach (var entry in _entries)
             * {
             *  entry.Write(bw);
             * }
             * byte[] stringData = Encoding.ASCII.GetBytes(_nameStringTable);
             * bw.Write(stringData);
             */

            MemoryStream          ms     = new MemoryStream();
            BigEndianBinaryWriter tempbw = new BigEndianBinaryWriter(ms);

            foreach (var entry in _entries)
            {
                entry.Write(tempbw);
            }
            BigEndianBinaryReader tempbr = new BigEndianBinaryReader(ms);

            ms.Position = 0;
            //bw.Write(DataUtil.Encrypt(tempbr.ReadBytes((int)tempbr.BaseStream.Length)));
            bw.Write(tempbr.ReadBytes((int)tempbr.BaseStream.Length));
            byte[] stringData = Encoding.ASCII.GetBytes(_nameStringTable);
            //bw.Write(DataUtil.Encrypt(stringData));
            bw.Write(stringData);
        }
Пример #4
0
        private static Byte[] CreatePayload(Int64 offset, Byte magicByte, Byte attributes, Byte[] key, Byte[] payload)
        {
            var crcContentStream = new MemoryStream();
            var crcContentWriter = new BigEndianBinaryWriter(crcContentStream);

            crcContentWriter.Write(magicByte);
            crcContentWriter.Write(attributes);
            crcContentWriter.Write((Int32)key.Length);
            crcContentWriter.Write(key);
            crcContentWriter.Write(payload.Length);
            crcContentWriter.Write(payload);
            var crcContentBytes = crcContentStream.ToArray();

            var crc = Crc32.Compute(crcContentBytes);

            var messageStream = new MemoryStream();
            var messageWriter = new BigEndianBinaryWriter(messageStream);

            messageWriter.Write(crc);
            messageWriter.Write(crcContentBytes);
            var messageBytes = messageStream.ToArray();

            var messageSetStream = new MemoryStream();
            var messageSetWriter = new BigEndianBinaryWriter(messageSetStream);
            var messageSize      = messageBytes.Length;

            messageSetWriter.Write(offset);
            messageSetWriter.Write(messageSize);
            messageSetWriter.Write(messageBytes);
            return(messageSetStream.ToArray());
        }
Пример #5
0
        public override void Write(BigEndianBinaryWriter bw)
        {
            bw.Write(NameOffset);
            bw.Write(SizeInArchive);
            if (IsResourceFile)
            {
                bw.Write((int)((Offset / 8) | (byte)ResourceType));
            }
            else
            {
                bw.Write((int)(Offset / 8));
            }
            var temp = DecompressedSize;

            if (IsCompressed)
            {
                temp |= 0x40000000;
            }
            if (IsResourceFile)
            {
                temp = (int)(temp | 0x80000000);
                temp = Flags1;
            }
            bw.Write(temp);
            bw.Write(Flags2);
        }
        public byte[] GetBytes()
        {
            var memoryStream = new MemoryStream();
            var writer       = new BigEndianBinaryWriter(memoryStream);

            writer.Write(Token);
            return(memoryStream.ToArray());
        }
Пример #7
0
        public void StringNotSupportedTest()
        {
            // arrange
            var memoryStream = new MemoryStream();
            var binaryWriter = new BigEndianBinaryWriter(memoryStream);

            binaryWriter.Write("test");
        }
Пример #8
0
 public void Write(BigEndianBinaryWriter writer)
 {
     writer.Write(_internalValue);
     foreach (var frame in Frames)
     {
         frame.Write(writer);
     }
 }
        protected override byte[] SerializePayload()
        {
            byte[] payload = new byte[sizeof(int)];
            var    writer  = new BigEndianBinaryWriter(new MemoryStream(payload));

            writer.Write(ChunkLength);
            return(payload);
        }
Пример #10
0
        public void Write(Stream outputStream)
        {
            BinaryWriter headerWriter = new BinaryWriter(outputStream, Encoding.UTF8, true);
            BinaryWriter writer;

            switch (Endianess)
            {
            case Endianess.LittleEndian:
                writer = headerWriter;
                break;

            case Endianess.BigEndian:
                writer = new BigEndianBinaryWriter(outputStream, Encoding.UTF8, true);
                break;

            default:
                throw new Exception("Unknown endianess " + Endianess);
            }

            long headerPosition = outputStream.Position;

            outputStream.Position += 24;

            int valuesPosition = (int)outputStream.Position;

            foreach (var entry in Entries)
            {
                entry.UpdateKey();
                entry.Offset = (int)outputStream.Position - valuesPosition;
                headerWriter.Write(entry.Color);
                writer.WriteNullTerminatedString(entry.Value);
            }

            writer.AlignWrite(4, 0x00);

            int keysPosition = (int)outputStream.Position;

            foreach (var entry in Entries.OrderBy(e => e.Key).ThenByDescending(e => e.Offset))
            {
                writer.Write(entry.Key);
                writer.Write(entry.Offset);
            }

            long endPosition = outputStream.Position;

            outputStream.Position = headerPosition;

            headerWriter.Write(0x474e414c); // LANG
            writer.Write(0x0000003);
            headerWriter.Write(Endianess == Endianess.LittleEndian ? LittleEndianConstant : BigEndianConstant);

            writer.Write(Entries.Count);
            writer.Write(valuesPosition);
            writer.Write(keysPosition);

            outputStream.Position = endPosition;
        }
        public void ShouldReturnNullWhenTableCouldNotBeFound()
        {
            var writer = new BigEndianBinaryWriter();

            writer.WriteTrueTypeFileHeader();

            using MemoryStream stream = writer.GetStream();
            Assert.Null(VerticalHeadTable.Load(new FontReader(stream)));
        }
Пример #12
0
        public void ToStream(Stream streamTo)
        {
            var writer = new BigEndianBinaryWriter(streamTo);

            writer.Write(DestinationAddress.GetAddressBytes());
            writer.Write(SourceAddress.GetAddressBytes());
            writer.Write((ushort)Type);
            PayloadPacket.ToStream(streamTo);
        }
Пример #13
0
 public void SendMessage(IPeerMessage message)
 {
     using (var ms = new MemoryStream())
     {
         BinaryWriter w = new BigEndianBinaryWriter(ms);
         message.Send(w);
         Send(ms.ToArray());
     }
 }
Пример #14
0
 public void Save(Swatch swatch, Stream stream)
 {
     using (var writer = new BigEndianBinaryWriter(stream))
     {
         var colors = swatch.Colors.Union(swatch.Categories.SelectMany(c => c.Colors)).ToList();
         WriteColors(writer, colors, 1);
         WriteColors(writer, colors, 2);
     }
 }
Пример #15
0
        public void Save()
        {
            BigEndianBinaryWriter TROPUSRWriter =
                new BigEndianBinaryWriter(new FileStream(path + "TROPUSR.DAT", FileMode.Open));

            TROPUSRWriter.Write(header.StructToBytes());
            TypeRecord account_id_Record = typeRecordTable[2];

            TROPUSRWriter.BaseStream.Position = account_id_Record.Offset + 32; // 空行
            TROPUSRWriter.Write(account_id.ToCharArray());                     // 帳號


            TypeRecord trophy_id_Record = typeRecordTable[3];

            TROPUSRWriter.BaseStream.Position = trophy_id_Record.Offset + 16;
            TROPUSRWriter.Write(trophy_id.ToCharArray()); // 獎杯ID
            TROPUSRWriter.BaseStream.Position = trophy_id_Record.Offset + 80;
            //TROPUSRWriter.Write(AchievementRate[0]); // 完成度
            //TROPUSRWriter.Write(AchievementRate[1]); // 完成度
            //TROPUSRWriter.Write(AchievementRate[2]); // 完成度
            //TROPUSRWriter.Write(AchievementRate[3]); // 完成度



            TypeRecord TrophyType_Record = typeRecordTable[4];

            TROPUSRWriter.BaseStream.Position = TrophyType_Record.Offset;
            foreach (TrophyType type in trophyTypeTable)
            {
                TROPUSRWriter.BaseStream.Position += 16;
                TROPUSRWriter.Write(type.StructToBytes());
            }

            TypeRecord trophyListInfo_Record = typeRecordTable[5];

            TROPUSRWriter.BaseStream.Position = trophyListInfo_Record.Offset + 16;
            TROPUSRWriter.Write(trophyListInfo.StructToBytes());


            TypeRecord TrophyTimeInfo_Record = typeRecordTable[6];

            TROPUSRWriter.BaseStream.Position = TrophyTimeInfo_Record.Offset;
            foreach (TrophyTimeInfo time in trophyTimeInfoTable)
            {
                TROPUSRWriter.BaseStream.Position += 16;
                TROPUSRWriter.Write(time.StructToBytes());
            }

            TypeRecord unknowType7_Record = typeRecordTable[7];

            TROPUSRWriter.BaseStream.Position = unknowType7_Record.Offset + 16;
            TROPUSRWriter.Write(unknowType7.StructToBytes());

            TROPUSRWriter.Flush();
            TROPUSRWriter.Close();
        }
        public void BigEndianBinaryWriterConstructorEncodingTest()
        {
            Stream   output   = new MemoryStream();
            Encoding encoding = Encoding.UTF7;
            BigEndianBinaryWriter          target   = new BigEndianBinaryWriter(new StreamAdapter(output), encoding);
            PrivateObject                  po       = new PrivateObject(target);
            BigEndianBinaryWriter_Accessor accessor = new BigEndianBinaryWriter_Accessor(po);

            Assert.AreSame(accessor.Encoding, encoding);
        }
        public void WriteByteArrayTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));

            byte[] expected = new byte[] { 1, 2, 3 };
            target.Write(expected);
            byte[] actual = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
Пример #18
0
        public override void Write(BigEndianBinaryWriter bw)
        {
            bw.Write(Flags);
            bw.Write(NameOffset);

            uint temp = (uint)ContentEntryIndex | 0x80000000;

            bw.Write(temp);
            bw.Write(ContentEntryCount);
        }
Пример #19
0
 private void SendMessage(IPeerContext peerContext, Action <BinaryWriter> constructMessage)
 {
     using (var ms = new MemoryStream())
     {
         BinaryWriter writer = new BigEndianBinaryWriter(ms);
         constructMessage(writer);
         writer.Flush();
         peerContext.SendMessage(ExtensionProtocolMessageId, ms.ToArray());
     }
 }
Пример #20
0
        protected Task Send(UdpTrackerRequestMessage message)
        {
            var ms     = new MemoryStream();
            var writer = new BigEndianBinaryWriter(ms);

            message.WriteTo(writer);
            writer.Flush();

            return(client.SendAsync(ms.ToArray(), (int)ms.Length, trackerUri.Host, trackerUri.Port));
        }
Пример #21
0
        public void ToStream(Stream streamTo)
        {
            var writer = new BigEndianBinaryWriter(streamTo);

            writer.Write(SourcePort);
            writer.Write(DestinationPort);
            writer.Write(Length);
            writer.Write(checksum);
            PayloadPacket.ToStream(streamTo);
        }
        public void WriteFloatTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            float data = 1.23f;

            target.Write(data);
            byte[] expected = new byte[] { 0x3F, 0x9D, 0x70, 0xA4 }; // 1.23 in IEEE Float in Big endian representation with single precision (32 bit)
            byte[] actual   = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
        public void WriteLongTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            long data = 1234567890123456789;

            target.Write(data);
            byte[] expected = new byte[] { 0x11, 0x22, 0x10, 0xF4, 0x7D, 0xE9, 0x81, 0x15 };
            byte[] actual   = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
        public void WriteDateTimeTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            DateTime data = new DateTime(1970, 1, 1, 0, 0, 1, DateTimeKind.Utc).ToLocalTime(); // 01.01.1970 00:00:01 UTC

            target.Write(data);
            byte[] expected = new byte[] { 0, 0, 0, 1 }; // 1 sec from Unix epoch
            byte[] actual   = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
        public void WriteStringTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            string data = "abc";

            target.Write(data);
            byte[] expected = new byte[] { 0, 0, 0, 3, 97, 98, 99 }; // 'abc' string in utf-8 + prefix int with string length
            byte[] actual   = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
        public void WriteIntTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            int data = 16776960;

            byte[] expected = new byte[] { 0x00, 0xFF, 0xFF, 0x00 }; // 16776960 in Big endian representation
            target.Write(data);
            byte[] actual = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
        public void WriteByteTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            byte expected = 255;

            target.Write(expected);
            byte actual = output.ToArray()[0];

            Assert.AreEqual(expected, actual);
        }
        public void WriteDoubleTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            double data = 1.23123456789000002231659891549E2;

            target.Write(data);
            byte[] expected = new byte[] { 0x40, 0x5E, 0xC7, 0xE6, 0xB7, 0x4D, 0xCE, 0x59 }; // 1.23123456789000002231659891549E2 in IEEE Double in Big endian representation with double precision (64 bit)
            byte[] actual   = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
        public void WriteShortTest()
        {
            MemoryStream          output = new MemoryStream();
            BigEndianBinaryWriter target = new BigEndianBinaryWriter(new StreamAdapter(output));
            short data = 12345;

            byte[] expected = new byte[] { 0x30, 0x39 }; // 12345 in Big endian representation
            target.Write(data);
            byte[] actual = output.ToArray();
            MyAssert.AreEqual(expected, actual);
        }
Пример #30
0
        public void Write(BigEndianBinaryWriter writer)
        {
            writer.Write(LayerWidth);
            writer.Write(LayerHeight);
            writer.Write((byte)SubLayers.Length);

            foreach (var sublayer in SubLayers)
            {
                sublayer.Write(writer);
            }
        }
Пример #31
0
        public void Save()
        {
            BigEndianBinaryWriter TROPTRNSWriter = new BigEndianBinaryWriter(new FileStream(path + "TROPTRNS.DAT", FileMode.Open));
            TROPTRNSWriter.Write(header.StructToBytes());
            TypeRecord account_id_Record = typeRecordTable[2];
            TROPTRNSWriter.BaseStream.Position = account_id_Record.Offset + 32; // 空行
            TROPTRNSWriter.Write(account_id.ToCharArray());

            TypeRecord trophy_id_Record = typeRecordTable[3];
            TROPTRNSWriter.BaseStream.Position = trophy_id_Record.Offset + 16; // 空行
            TROPTRNSWriter.Write(trophy_id.ToCharArray());
            TROPTRNSWriter.BaseStream.Position = trophy_id_Record.Offset + 32; // 字串長度不定,直接跳過
            TROPTRNSWriter.Write(u1);
            Console.WriteLine(trophyInfoTable.Count);
            TROPTRNSWriter.Write(trophyInfoTable.Count+1); // AllGetTrophysCount
            AllSyncPSNTrophyCount = 0;
            for (int i = 0; i < trophyInfoTable.Count; i++) {
                if (trophyInfoTable[i].IsSync) {
                    AllSyncPSNTrophyCount++;
                }
            }
            // AllSyncPSNTrophyCount++;
            TROPTRNSWriter.Write(AllSyncPSNTrophyCount+1);

            // Type 4
            TypeRecord TrophyType_Record = typeRecordTable[4];
            TROPTRNSWriter.BaseStream.Position = TrophyType_Record.Offset;
            TROPTRNSWriter.BaseStream.Position += 16;
            TROPTRNSWriter.Write(trophyInitTime.StructToBytes());

            for (int i = 0; i < trophyInfoTable.Count; i++) {
                TROPTRNSWriter.BaseStream.Position += 16;
                TrophyInfo ti = trophyInfoTable[i];
                ti.SequenceNumber = i+1; // 整理順序
                //if (i == 0) {
                //    ti._unknowInt2 = 0x100000;
                //} else {
                //    ti._unknowInt2 = 0x100000;
                //}
                ti._unknowInt3 = 0;

                trophyInfoTable[i] = ti;
                TROPTRNSWriter.Write(trophyInfoTable[i].StructToBytes());
            }

            byte[] emptyStruct = new byte[Marshal.SizeOf(typeof(TrophyInfo))];
            Array.Clear(emptyStruct, 0, emptyStruct.Length);
            TrophyInfo emptyTrophyInfo = emptyStruct.ToStruct<TrophyInfo>();
            for (int i = trophyInfoTable.Count; i < TrophyType_Record.Size; i++) {
                TROPTRNSWriter.BaseStream.Position += 16;
                emptyTrophyInfo.SequenceNumber = i + 1;
                TROPTRNSWriter.Write(emptyTrophyInfo.StructToBytes());
            }

            TROPTRNSWriter.Flush();
            TROPTRNSWriter.Close();
        }
Пример #32
0
        public void Save()
        {
            BigEndianBinaryWriter TROPUSRWriter = new BigEndianBinaryWriter(new FileStream(path + "TROPUSR.DAT", FileMode.Open));
            TROPUSRWriter.Write(header.StructToBytes());
            TypeRecord account_id_Record = typeRecordTable[2];
            TROPUSRWriter.BaseStream.Position = account_id_Record.Offset + 32; // 空行
            TROPUSRWriter.Write(account_id.ToCharArray()); // 帳號

            TypeRecord trophy_id_Record = typeRecordTable[3];
            TROPUSRWriter.BaseStream.Position = trophy_id_Record.Offset + 16;
            TROPUSRWriter.Write(trophy_id.ToCharArray()); // 獎杯ID
            TROPUSRWriter.BaseStream.Position = trophy_id_Record.Offset + 80;
            //TROPUSRWriter.Write(AchievementRate[0]); // 完成度
            //TROPUSRWriter.Write(AchievementRate[1]); // 完成度
            //TROPUSRWriter.Write(AchievementRate[2]); // 完成度
            //TROPUSRWriter.Write(AchievementRate[3]); // 完成度

            TypeRecord TrophyType_Record = typeRecordTable[4];
            TROPUSRWriter.BaseStream.Position = TrophyType_Record.Offset;
            foreach (TrophyType type in trophyTypeTable) {
                TROPUSRWriter.BaseStream.Position += 16;
                TROPUSRWriter.Write(type.StructToBytes());
            }

            TypeRecord trophyListInfo_Record = typeRecordTable[5];
            TROPUSRWriter.BaseStream.Position = trophyListInfo_Record.Offset + 16;
            TROPUSRWriter.Write(trophyListInfo.StructToBytes());

            TypeRecord TrophyTimeInfo_Record = typeRecordTable[6];
            TROPUSRWriter.BaseStream.Position = TrophyTimeInfo_Record.Offset;
            foreach (TrophyTimeInfo time in trophyTimeInfoTable) {
                TROPUSRWriter.BaseStream.Position += 16;
                TROPUSRWriter.Write(time.StructToBytes());
            }

            TypeRecord unknowType7_Record = typeRecordTable[7];
            TROPUSRWriter.BaseStream.Position = unknowType7_Record.Offset + 16;
            TROPUSRWriter.Write(unknowType7.StructToBytes());

            TROPUSRWriter.Flush();
            TROPUSRWriter.Close();
        }
        public static void SendMessage(Socket udp, byte id, params byte[] payload)
        {
            byte[] msg = new byte[payload.Length + 4];

            uint innerLen = (uint)payload.Length;

            // bridge message format (all numbers big endian)
            //  bridge command - UINT8 (0 = transmit)
            // --start payload--
            //  inner command - UINT8
            //  inner payload length - UINT16
            //  payload
            msg[0] = BRIDGE_CMD_TX;
            msg[1] = id;
            msg[2] = (byte)((innerLen >> 8) & 0xff);
            msg[3] = (byte)(innerLen & 0xff);

            // copy over the payload
            Buffer.BlockCopy(payload, 0, msg, 4, payload.Length);

            // send that ish out
            udp.SendTo(msg, ControllerEP);
            if (payload.Length == 8) {
                msg = new byte[payload.Length + 9];

                BigEndianBinaryWriter writer = new BigEndianBinaryWriter(msg);
                // write a slot for the timestamp (zero as we don't have any timestamp)
                writer.WriteUInt16(0);
                writer.WriteInt32(0);

                // write message type
                writer.WriteByte(ACT_FEEDBACK_CMDRECEIVED);

                // write the length as bullstuff
                writer.WriteInt16(0);

                // only send for all message
                // change the message ID, only send a subset of the stuffs
                writer.WriteBytes(payload);

                // set the stuff stuff
                udp.SendTo(msg, MulticastEP);
            }
        }
Пример #34
0
        /// <summary>
        /// Writes the geometry information from the specified IFeatureLayer to the file
        /// </summary>
        /// <param name="filename">A filename</param>
        /// <param name="Layer">An IFeatureLayer to save</param>
        public virtual void Write(string filename, IFeatureSet Layer)
        {
            if (Layer == null) return;
            if (Layer.Features == null) return;
            if (Layer.Features.Count == 0) return;
            string rootname, shpFile, shxFile;
            
            rootname = System.IO.Path.GetDirectoryName(filename) + "\\" + System.IO.Path.GetFileNameWithoutExtension(filename);
            shpFile = rootname + ".shp";
            shxFile = rootname + ".shx";
            
            System.IO.FileStream shpStream = new System.IO.FileStream(shpFile, System.IO.FileMode.Create);
            System.IO.FileStream shxStream = new System.IO.FileStream(shxFile, System.IO.FileMode.Create);
            BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream);
            BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream);

            // assumes
           // ShapeHandler handler = Shapefile.GetShapeHandler(Shapefile.GetShapeType(geometryCollection.Geometries[0]));

            ShapeHandler handler = null;

            switch (Layer.Features[0].FeatureType)
            {
                case FeatureTypes.Unspecified: return;
                case FeatureTypes.Line: handler = new MultiLineHandler();
                    break;
                case FeatureTypes.Point: handler = new PointHandler();
                    break;
                case FeatureTypes.Polygon: handler = new PolygonHandler();
                    break;
            }

            IBasicGeometry body;
            int numShapes = Layer.Features.Count;
            // calc the length of the shp file, so it can put in the header.
            int shpLength = 50;
            for (int i = 0; i < numShapes; i++)
            {
                body = Layer.Features[i].BasicGeometry;
                shpLength += 4; // length of header in WORDS
                shpLength += handler.GetLength(body); // length of shape in WORDS
            }

            int shxLength = 50 + (4 * numShapes);

            // write the .shp header
            ShapefileHeader ShapeHeader = new ShapefileHeader();
            ShapeHeader.FileLength = shpLength;

            // get envelope in external coordinates
            IEnvelope env = Layer.Envelope;
            //IEnvelope bounds = ShapeHandler.GetEnvelopeExternal(new PrecisionModel(geometryFactory.PrecisionModel), env);
            ShapeHeader.Bounds = env;

            // write the .shx header
            ShapefileHeader shxHeader = new ShapefileHeader();
            shxHeader.FileLength = shxLength;
            shxHeader.Bounds = ShapeHeader.Bounds;

            // assumes Geometry type of the first item will the same for all other items
            // in the collection.
            switch(Layer.FeatureType)
            {
                case FeatureTypes.Polygon:
                    ShapeHeader.ShapeType = ShapeGeometryTypes.Polygon;
                    shxHeader.ShapeType = ShapeGeometryTypes.Polygon;
                    break;
                case FeatureTypes.Point:
                    ShapeHeader.ShapeType = ShapeGeometryTypes.Point;
                    shxHeader.ShapeType = ShapeGeometryTypes.Point;
                    break;
                case FeatureTypes.Line:
                    ShapeHeader.ShapeType = ShapeGeometryTypes.LineString;
                    shxHeader.ShapeType = ShapeGeometryTypes.LineString;
                    break;
            }
            
            ShapeHeader.Write(shpBinaryWriter);

            // assumes Geometry type of the first item will the same for all other items in the collection.
            
            shxHeader.Write(shxBinaryWriter);

            // write the individual records.
            int _pos = 50; // header length in WORDS
            for (int i = 0; i < numShapes; i++)
            {
                body = Layer.Features[i].BasicGeometry;
                int recordLength = handler.GetLength(body);
                shpBinaryWriter.WriteIntBE(i + 1);
                shpBinaryWriter.WriteIntBE(recordLength);

                shxBinaryWriter.WriteIntBE(_pos);
                shxBinaryWriter.WriteIntBE(recordLength);

                _pos += 4; // length of header in WORDS
                handler.Write(body, shpBinaryWriter, geometryFactory);
                _pos += recordLength; // length of shape in WORDS
            }

            shxBinaryWriter.Flush();
            shxBinaryWriter.Close();
            shpBinaryWriter.Flush();
            shpBinaryWriter.Close();

        }
Пример #35
0
        /// <summary>
        /// Writes an entire shapefile to disk in one call using a geometryCollection.
        /// </summary>
        /// <remarks>
        /// Assumes the type given for the first geometry is the same for all subsequent geometries.
        /// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are
        /// Muli-polygon/ polygon and not lines or points.
        /// The dbase file for the corresponding shapefile contains one column called row. It contains 
        /// the row number.
        /// </remarks>
        /// <param name="filename">The filename to write to (minus the .shp extension).</param>
        /// <param name="geometryCollection">The GeometryCollection to write.</param>		
        public virtual void Write(string filename, GeometryCollection geometryCollection)
        {
            System.IO.FileStream shpStream = new System.IO.FileStream(filename + ".shp", System.IO.FileMode.Create);
            System.IO.FileStream shxStream = new System.IO.FileStream(filename + ".shx", System.IO.FileMode.Create);
            BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream);
            BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream);

            // assumes
            ShapeHandler handler = Shapefile.GetShapeHandler(Shapefile.GetShapeType(geometryCollection.Geometries[0]));

            IGeometry body;
            int numShapes = geometryCollection.NumGeometries;
            // calc the length of the shp file, so it can put in the header.
            int shpLength = 50;
            for (int i = 0; i < numShapes; i++)
            {
                body = geometryCollection.Geometries[i];
                shpLength += 4; // length of header in WORDS
                shpLength += handler.GetLength(body); // length of shape in WORDS
            }

            int shxLength = 50 + (4 * numShapes);

            // write the .shp header
            ShapefileHeader ShapeHeader = new ShapefileHeader();
            ShapeHeader.FileLength = shpLength;

            // get envelope in external coordinates
            IEnvelope env = geometryCollection.EnvelopeInternal;
            IEnvelope bounds = ShapeHandler.GetEnvelopeExternal(new PrecisionModel(geometryFactory.PrecisionModel), env);
            ShapeHeader.Bounds = bounds;

            // assumes Geometry type of the first item will the same for all other items
            // in the collection.
            ShapeHeader.ShapeType = Shapefile.GetShapeType(geometryCollection.Geometries[0]);
            ShapeHeader.Write(shpBinaryWriter);

            // write the .shx header
            ShapefileHeader shxHeader = new ShapefileHeader();
            shxHeader.FileLength = shxLength;
            shxHeader.Bounds = ShapeHeader.Bounds;

            // assumes Geometry type of the first item will the same for all other items in the collection.
            shxHeader.ShapeType = Shapefile.GetShapeType(geometryCollection.Geometries[0]);
            shxHeader.Write(shxBinaryWriter);

            // write the individual records.
            int _pos = 50; // header length in WORDS
            for (int i = 0; i < numShapes; i++)
            {
                body = geometryCollection.Geometries[i];
                int recordLength = handler.GetLength(body);
                shpBinaryWriter.WriteIntBE(i + 1);
                shpBinaryWriter.WriteIntBE(recordLength);

                shxBinaryWriter.WriteIntBE(_pos);
                shxBinaryWriter.WriteIntBE(recordLength);

                _pos += 4; // length of header in WORDS
                handler.Write(body, shpBinaryWriter, geometryFactory);
                _pos += recordLength; // length of shape in WORDS
            }

            shxBinaryWriter.Flush();
            shxBinaryWriter.Close();
            shpBinaryWriter.Flush();
            shpBinaryWriter.Close();

            // WriteDummyDbf(filename + ".dbf", numShapes);	
        }