示例#1
0
        /// <summary>
        /// インスタンスを初期化します。
        /// </summary>
        /// <param name="ecLevel">誤り訂正レベル</param>
        /// <param name="maxVersion">型番の上限</param>
        /// <param name="allowStructuredAppend">複数シンボルへの分割を許可するには true を指定します。</param>
        /// <param name="charsetName">文字セット名</param>
        public Symbols(ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel.M,
                       int maxVersion             = Constants.MAX_VERSION,
                       bool allowStructuredAppend = false,
                       string charsetName         = Charset.SHIFT_JIS)
        {
            if (!(Constants.MIN_VERSION <= maxVersion && maxVersion <= Constants.MAX_VERSION))
            {
                throw new ArgumentOutOfRangeException(nameof(maxVersion));
            }

            _items = new List <Symbol>();

            _minVersion = Constants.MIN_VERSION;

            _maxVersion              = maxVersion;
            _errorCorrectionLevel    = ecLevel;
            _structuredAppendAllowed = allowStructuredAppend;
            _encoding = Encoding.GetEncoding(charsetName);

            _parity = 0;

            _currSymbol = new Symbol(this);
            _items.Add(_currSymbol);

            _encNumeric = new NumericEncoder(_encoding);
            _encAlpha   = new AlphanumericEncoder(_encoding);

            if (Charset.IsJP(charsetName))
            {
                _encKanji = new KanjiEncoder(_encoding);
            }

            _encByte = new ByteEncoder(_encoding);
        }
示例#2
0
        public Stream GetContentWriteStream()
        {
            this.AssertOpen();
            if (this.contentWritten)
            {
                throw new InvalidOperationException(Strings.ContentAlreadyWritten);
            }
            if (this.partContent != null)
            {
                throw new InvalidOperationException(Strings.PartContentIsBeingWritten);
            }
            Stream rawContentWriteStream = this.GetRawContentWriteStream();

            if (this.contentTransferEncoding == ContentTransferEncoding.SevenBit || this.contentTransferEncoding == ContentTransferEncoding.EightBit || this.contentTransferEncoding == ContentTransferEncoding.Binary)
            {
                return(rawContentWriteStream);
            }
            if (this.contentTransferEncoding == ContentTransferEncoding.BinHex)
            {
                throw new NotSupportedException(Strings.BinHexNotSupportedForThisMethod);
            }
            ByteEncoder byteEncoder = MimePart.CreateEncoder(null, this.contentTransferEncoding);

            if (byteEncoder == null)
            {
                throw new NotSupportedException(Strings.UnrecognizedTransferEncodingUsed);
            }
            this.encodedPartContent = new EncoderStream(rawContentWriteStream, byteEncoder, EncoderStreamAccess.Write);
            return(new SuppressCloseStream(this.encodedPartContent));
        }
示例#3
0
        /// <summary>
        /// 符号化モードを設定します。
        /// </summary>
        /// <param name="encMode">符号化モード</param>
        /// <param name="c">符号化する最初の文字。この文字はシンボルに追加されません。</param>
        /// <returns>シンボル容量が不足している場合は false を返します。</returns>
        internal bool TrySetEncodingMode(EncodingMode encMode, char c)
        {
            QRCodeEncoder encoder;
            Encoding      encoding = _parent.Encoding;

            switch (encMode)
            {
            case EncodingMode.NUMERIC:
                encoder = new NumericEncoder(encoding);
                break;

            case EncodingMode.ALPHA_NUMERIC:
                encoder = new AlphanumericEncoder(encoding);
                break;

            case EncodingMode.EIGHT_BIT_BYTE:
                encoder = new ByteEncoder(encoding);
                break;

            case EncodingMode.KANJI:
                if (Charset.IsJP(encoding.WebName))
                {
                    encoder = new KanjiEncoder(encoding);
                }
                else
                {
                    throw new InvalidOperationException();
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(encMode));
            }

            int bitLength = encoder.GetCodewordBitLength(c);

            while (_dataBitCapacity <
                   _dataBitCounter
                   + ModeIndicator.LENGTH
                   + CharCountIndicator.GetLength(_currVersion, encMode)
                   + bitLength)
            {
                if (_currVersion >= _parent.MaxVersion)
                {
                    return(false);
                }

                SelectVersion();
            }

            _dataBitCounter += ModeIndicator.LENGTH
                               + CharCountIndicator.GetLength(_currVersion, encMode);
            _currEncoder = encoder;
            _segments.Add(_currEncoder);
            _segmentCounter[encMode]++;
            _currEncodingMode = encMode;

            return(true);
        }
        public void GetLittleEndianUInt32()
        {
            _log.Debug("Running: GetLittleEndianUInt32");
            const UInt32 anInt   = 12345;
            UInt32       aNewInt = ByteEncoder.GetLittleEndian(anInt);

            Assert.IsTrue(anInt == ByteEncoder.GetLittleEndian(aNewInt));
        }
        public void GetBigEndianlong()
        {
            _log.Debug("Running: GetBigEndianlong");
            const long anInt   = 123456660700770;
            long       aNewInt = ByteEncoder.GetBigEndian(anInt);

            Assert.IsTrue(anInt == ByteEncoder.GetBigEndian(aNewInt));
        }
        public void GetBigEndianUInt16()
        {
            _log.Debug("Running: GetBigEndianUInt16");
            const UInt16 anInt   = 123;
            UInt16       aNewInt = ByteEncoder.GetBigEndian(anInt);

            Assert.IsTrue(anInt == ByteEncoder.GetBigEndian(aNewInt));
        }
示例#7
0
        protected override void EndSize32(int pos)
        {
            int cur = (int)_out.Position;

            _out.Seek(pos, SeekOrigin.Begin);
            _writer.Write(ByteEncoder.GetBigEndian((Int32)cur - pos - 4));
            _out.Seek(cur, SeekOrigin.Begin);
        }
示例#8
0
 private byte[] CreatePacketHeader(int packetSize, MessageType messageType)
 {
     byte[] array = new byte[GetHeaderSize()];
     array[0] = 255;
     ByteEncoder.IntToByteArray(packetSize).CopyTo(array, 1);
     array[5] = (byte)messageType;
     return(array);
 }
        public void GetBigEndianInt32()
        {
            _log.Debug("Running: GetBigEndianInt32");
            const int anInt   = -12345;
            Int32     aNewInt = ByteEncoder.GetBigEndian(anInt);

            Assert.IsTrue(anInt == ByteEncoder.GetBigEndian(aNewInt));
        }
示例#10
0
        private void ProcessIncomingData(byte[] data, EndPoint remoteEndPoint)
        {
            string val = ByteEncoder.ByteArrayToString(data);

            if (DataReceived != null)
            {
                DataReceived(this, new DataReceivedEventArgs(data, null, val, remoteEndPoint));
            }
        }
示例#11
0
        void Tcp_DataReceived(object sender, Tcp.DataReceivedEventArgs e)
        {
            try
            {
                bool compression = false;
                if (e.CustomHeader[0] == 1)
                {
                    compression = true;
                }
                bool encryption = false;
                if (e.CustomHeader[1] == 1)
                {
                    encryption = true;
                }
                byte[] packetBytes = e.ByteData;
                if (compression)
                {
                    packetBytes = packetModifiers.DecompressPacket(packetBytes);
                }
                if (encryption)
                {
                    packetBytes = packetModifiers.DecryptPacket(packetBytes);
                }
                if (e.CustomHeader[2] == 1)
                {
                    // This was a packet list, process it
                    int position = 0;
                    while (position < packetBytes.Length)
                    {
                        int segmentSize = ByteEncoder.ByteArrayToInt(packetBytes, position);
                        position += 4;
#if EVENTTHREAD
                        PlayerEvent playerEvent = new PlayerEvent(ByteEncoder.ByteArrayToString(packetBytes, position, segmentSize));
                        eventThread.AddEvent(playerEvent);
#else
                        MessageProcessor.ProcessData(this, ByteEncoder.ByteArrayToString(packetBytes, position, segmentSize));
#endif
                        position += segmentSize;
                    }
                }
                else
                {
#if EVENTTHREAD
                    PlayerEvent playerEvent = new PlayerEvent(PMDCP.Core.ByteEncoder.ByteArrayToString(packetBytes));
                    eventThread.AddEvent(playerEvent);
#else
                    MessageProcessor.ProcessData(this, PMDCP.Core.ByteEncoder.ByteArrayToString(packetBytes));
#endif
                }
            }
            catch (Exception ex)
            {
                Exceptions.ErrorLogger.WriteToErrorLog(ex, "Tcp_DataRecieved");
            }
        }
示例#12
0
 public void WriteHeader(BinaryWriter writer)
 {
     writer.Seek(0, SeekOrigin.Begin);
     writer.Write(ByteEncoder.GetBigEndian(ShapeFileConstants.HeaderStartCode));
     writer.Write(new Byte[20]);
     writer.Write(ByteEncoder.GetBigEndian(FileLengthInWords));
     writer.Write(ByteEncoder.GetLittleEndian(ShapeFileConstants.VersionCode));
     writer.Write(ByteEncoder.GetLittleEndian((Int32)ShapeType));
     writer.Write(ByteEncoder.GetLittleEndian(Extents.GetMin(Ordinates.X)));
     writer.Write(ByteEncoder.GetLittleEndian(Extents.GetMin(Ordinates.Y)));
     writer.Write(ByteEncoder.GetLittleEndian(Extents.GetMax(Ordinates.X)));
     writer.Write(ByteEncoder.GetLittleEndian(Extents.GetMax(Ordinates.Y)));
     writer.Write(new Byte[32]); // Z-values and M-values
 }
        // Token: 0x06000852 RID: 2130 RVA: 0x0002E1A4 File Offset: 0x0002C3A4
        public void ApplyValueDecoder(ByteEncoder decoder)
        {
            this.CheckDisposed("ApplyValueDecoder");
            char?c   = this.lastChar;
            int? num = (c != null) ? new int?((int)c.GetValueOrDefault()) : null;

            if (num != null)
            {
                throw new InvalidOperationException();
            }
            if (this.decoderStream != null)
            {
                throw new InvalidOperationException();
            }
            this.decoderStream = new EncoderStream(this.GetValueReadStream(null), decoder, EncoderStreamAccess.Read);
        }
示例#14
0
 /// <summary>
 /// Parses the .shx shapefile index file
 /// </summary>
 /// <remarks>
 /// The index file is organized to give a matching offset and content length for each entry in the .shp file.
 ///
 /// From ESRI ShapeFile Technical Description document
 ///
 /// http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
 ///
 /// Byte
 /// Position    Field           Value           Type    Order
 /// ---------------------------------------------------------
 /// Byte 0      Offset          Offset          Integer Big
 /// Byte 4      Content Length  Content Length  Integer Big
 ///
 /// The Integer type corresponds to the CLS Int32 type.
 /// </remarks>
 private void parseIndex()
 {
     using (FileStream indexStream = _indexFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
         using (BinaryReader indexReader = new BinaryReader(indexStream, Encoding.Unicode))
         {
             indexStream.Seek(ShapeFileConstants.HeaderSizeBytes, SeekOrigin.Begin);
             UInt32 recordNumber = 0;
             while (indexStream.Position < indexStream.Length)
             {
                 Int32      offset = ByteEncoder.GetBigEndian(indexReader.ReadInt32());
                 Int32      length = ByteEncoder.GetBigEndian(indexReader.ReadInt32());
                 IndexEntry entry  = new IndexEntry(length, offset);
                 _shapeIndex[recordNumber++] = entry;
             }
         }
 }
示例#15
0
 static void tcpClient_DataReceived(object sender, Tcp.DataReceivedEventArgs e)
 {
     try
     {
         bool compression = false;
         if (e.CustomHeader[0] == 1)
         {
             compression = true;
         }
         bool encryption = false;
         if (e.CustomHeader[1] == 1)
         {
             encryption = true;
         }
         byte[] packetBytes = e.ByteData;
         if (compression)
         {
             packetBytes = packetModifiers.DecompressPacket(packetBytes);
         }
         if (encryption)
         {
             packetBytes = packetModifiers.DecompressPacket(packetBytes);
         }
         if (e.CustomHeader[2] == 1)
         {
             // This was a packet list, process it
             int position = 0;
             while (position < packetBytes.Length)
             {
                 int segmentSize = ByteEncoder.ByteArrayToInt(packetBytes, position);
                 position += 4;
                 MessageProcessor.HandleData(ByteEncoder.ByteArrayToString(packetBytes, position, segmentSize));
                 position += segmentSize;
             }
         }
         else
         {
             MessageProcessor.HandleData(ByteEncoder.ByteArrayToString(packetBytes));
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("Packet:");
         System.Diagnostics.Debug.WriteLine(ex.ToString());
         System.Diagnostics.Debug.WriteLine(ex.StackTrace);
     }
 }
示例#16
0
        public void Send(byte[] data)
        {
            try {
                if (socket.Connected)
                {
                    byte[] buffer = CreatePacketHeader(data.Length, MessageType.Generic);
                    buffer = ByteEncoder.AppendToByteArray(buffer, data);

                    socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), buffer);
                }
            } catch {
                if (ConnectionBroken != null)
                {
                    ConnectionBroken(this, EventArgs.Empty);
                }
            }
        }
示例#17
0
        public void SendFile(string filePath)
        {
            try {
                if (socket.Connected)
                {
                    FileInfo      fileInfo  = new FileInfo(filePath);
                    NetworkStream ns        = new NetworkStream(socket);
                    byte[]        nameBytes = ByteEncoder.StringToByteArray(Path.GetFileName(filePath));
                    ByteArray     header    = new ByteArray(CreatePacketHeader(4 + nameBytes.Length + (int)fileInfo.Length, MessageType.FileTransfer));

                    FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                    int fullHeaderLength = header.Length() + 4 + nameBytes.Length;

                    int    len = (int)fileInfo.Length;
                    byte[] b   = new byte[fullHeaderLength];

                    header.ToArray().CopyTo(b, 0);
                    ByteEncoder.IntToByteArray(nameBytes.Length).CopyTo(b, header.Length());
                    nameBytes.CopyTo(b, header.Length() + 4);

                    int offset    = fullHeaderLength;
                    int bytesRead = 0;
                    ns.Write(b, 0, b.Length);
                    //socket.Send(b, 0, b.Length, SocketFlags.None);
                    b = new Byte[1024];
                    while (bytesRead < len)
                    {
                        bytesRead += file.Read(b, 0, (b.Length + bytesRead < len) ? b.Length : (len - bytesRead));
                        //socket.Send(b, 0, b.Length, SocketFlags.None);
                        //socket.Send(b, 0, b.Length, SocketFlags.None);
                        ns.Write(b, 0, b.Length);
                        if (offset != 0)
                        {
                            offset = 0;
                        }
                        b = new byte[1024];
                        file.Seek(bytesRead, SeekOrigin.Begin);
                    }
                    ns.Close();
                    ns.Dispose();
                }
            } catch {
            }
        }
示例#18
0
        public void Save()
        {
            using (FileStream indexStream = _indexFile.Open(FileMode.Create, FileAccess.Write, FileShare.None))
                using (BinaryWriter indexWriter = new BinaryWriter(indexStream))
                {
                    _header.Extents           = ShapeFile.GetExtents();
                    _header.FileLengthInWords = computeIndexLengthInWords();
                    _header.WriteHeader(indexWriter);

                    foreach (IndexEntry entry in _shapeIndex.Values)
                    {
                        indexWriter.Write(ByteEncoder.GetBigEndian(entry.Offset));
                        indexWriter.Write(ByteEncoder.GetBigEndian(entry.Length));
                    }

                    indexWriter.Flush();
                }
        }
示例#19
0
 private void Frame(byte flags, byte type, byte track, int channel, int size, MemoryStream buf)
 {
     lock (_sendlock)
     {
         _writer.Write(flags);
         _writer.Write(type);
         _writer.Write(ByteEncoder.GetBigEndian((UInt16)(size + network.Frame.HEADER_SIZE)));
         _writer.Write((byte)0);
         _writer.Write(track);
         _writer.Write(ByteEncoder.GetBigEndian((UInt16)(channel)));
         _writer.Write((byte)0);
         _writer.Write((byte)0);
         _writer.Write((byte)0);
         _writer.Write((byte)0);
         _sender.Send(_header);
         _header.Seek(0, SeekOrigin.Begin);
         _sender.Send(buf, size);
     }
 }
示例#20
0
        /// <summary>
        /// Reads and parses the header of the .shp index file
        /// </summary>
        /// <remarks>
        /// From ESRI ShapeFile Technical Description document
        ///
        /// http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
        ///
        /// Byte
        /// Position    Field           Value       Type    Order
        /// -----------------------------------------------------
        /// Byte 0      File Code       9994        Integer Big
        /// Byte 4      Unused          0           Integer Big
        /// Byte 8      Unused          0           Integer Big
        /// Byte 12     Unused          0           Integer Big
        /// Byte 16     Unused          0           Integer Big
        /// Byte 20     Unused          0           Integer Big
        /// Byte 24     File Length     File Length Integer Big
        /// Byte 28     Version         1000        Integer Little
        /// Byte 32     Shape Type      Shape Type  Integer Little
        /// Byte 36     Bounding Box    Xmin        Double  Little
        /// Byte 44     Bounding Box    Ymin        Double  Little
        /// Byte 52     Bounding Box    Xmax        Double  Little
        /// Byte 60     Bounding Box    Ymax        Double  Little
        /// Byte 68*    Bounding Box    Zmin        Double  Little
        /// Byte 76*    Bounding Box    Zmax        Double  Little
        /// Byte 84*    Bounding Box    Mmin        Double  Little
        /// Byte 92*    Bounding Box    Mmax        Double  Little
        ///
        /// * Unused, with value 0.0, if not Measured or Z type
        ///
        /// The "Integer" type corresponds to the CLS Int32 type, and "Double" to CLS Double (IEEE 754).
        /// </remarks>
        private void parseHeader(BinaryReader reader)
        {
            reader.BaseStream.Seek(0, SeekOrigin.Begin);

            // Check file header
            if (ByteEncoder.GetBigEndian(reader.ReadInt32()) != ShapeFileConstants.HeaderStartCode)
            {
                throw new ShapeFileIsInvalidException("Invalid ShapeFile (.shp)");
            }

            // Seek to File Length
            reader.BaseStream.Seek(24, 0);

            // Read filelength as big-endian. The length is number of 16-bit words in file
            FileLengthInWords = ByteEncoder.GetBigEndian(reader.ReadInt32());

            // Seek to ShapeType
            reader.BaseStream.Seek(32, 0);
            ShapeType = (ShapeType)reader.ReadInt32();

            // Seek to bounding box of shapefile
            reader.BaseStream.Seek(36, 0);

            // Read the spatial bounding box of the contents
            Double xMin = ByteEncoder.GetLittleEndian(reader.ReadDouble());
            Double yMin = ByteEncoder.GetLittleEndian(reader.ReadDouble());
            Double xMax = ByteEncoder.GetLittleEndian(reader.ReadDouble());
            Double yMax = ByteEncoder.GetLittleEndian(reader.ReadDouble());

            ICoordinate min = _geoFactory.CoordinateFactory.Create(xMin, yMin);
            ICoordinate max = _geoFactory.CoordinateFactory.Create(xMax, yMax);

            Extents = min.Equals(max) && min.Equals(_geoFactory.CoordinateFactory.Create(0, 0)) //jd: if the shapefile has just been created the box wil be 0,0,0,0 in this case create an empty extents
                ? _geoFactory.CreateExtents()
                : _geoFactory.CreateExtents(min, max);


            //jd:allow exmpty extents
            //if (Extents.IsEmpty)
            //{
            //    Extents = null;
            //}
        }
示例#21
0
        private byte[] CreatePacketHeader(int packetSize, MessageType messageType, byte[] customHeader)
        {
            byte[] array = new byte[GetHeaderSize()];
            array[0] = 255;
            ByteEncoder.IntToByteArray(packetSize).CopyTo(array, 1);
            array[5] = (byte)messageType;
            int n = 6;

            for (int i = 0; i < customHeader.Length; i++)
            {
                if (n + i < array.Length)
                {
                    array[n + i] = customHeader[i];
                }
                else
                {
                    break;
                }
            }
            return(array);
        }
示例#22
0
        public byte[] CombinePackets()
        {
            ByteArray[] packetBytes = new ByteArray[packets.Count];
            int         totalSize   = 0;

            for (int i = 0; i < packets.Count; i++)
            {
                packetBytes[i] = new ByteArray(ByteEncoder.StringToByteArray(packets[i].PacketString));
                totalSize     += packetBytes[i].Length() + GetPacketSegmentHeaderSize();
            }
            byte[] packet   = new byte[totalSize];
            int    position = 0;

            for (int i = 0; i < packetBytes.Length; i++)
            {
                // Add the size of the packet segment
                Array.Copy(ByteArray.IntToByteArray(packetBytes[i].Length()), 0, packet, position, 4);
                position += 4;
                // Add the packet data
                Array.Copy(packetBytes[i].ToArray(), 0, packet, position, packetBytes[i].Length());
                position += packetBytes[i].Length();
            }
            return(packet);
        }
 // Token: 0x060007BC RID: 1980 RVA: 0x0002A803 File Offset: 0x00028A03
 public void ApplyValueOverrides(Encoding charset, ByteEncoder decoder)
 {
     this.reader.ApplyValueOverrides(charset, decoder);
 }
示例#24
0
 public static void SendData(IPacket packet, bool compress, bool encrypt)
 {
     SendData(ByteEncoder.StringToByteArray(packet.PacketString), compress, encrypt, false);
 }
        // Token: 0x06000107 RID: 263 RVA: 0x000041B0 File Offset: 0x000023B0
        public Stream GetAttachmentStream(AttachmentHandler.IAttachmentRetriever attachmentRetriever, AttachmentHandler.IAttachmentPolicyChecker policyChecker, bool asDataUri)
        {
            ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>((long)this.GetHashCode(), "AttachmentHandler.GetAttachmentStream: Getting attachment stream for id={0}", this.id);
            if (string.IsNullOrEmpty(this.id))
            {
                ExTraceGlobals.AttachmentHandlingTracer.TraceDebug((long)this.GetHashCode(), "Attachment id is empty or null. returning null stream.");
                throw new FaultException("Id cannot be null or empty.");
            }
            Stream      stream      = null;
            ByteEncoder byteEncoder = null;
            Stream      stream2     = null;
            Stream      result;

            try
            {
                Attachment            attachment = attachmentRetriever.Attachment;
                AttachmentPolicyLevel policy     = policyChecker.GetPolicy(attachment, this.webOperationContext.IsPublicLogon);
                if (AudioFile.IsProtectedVoiceAttachment(attachment.FileName))
                {
                    attachment.ContentType = Utils.GetUnProtectedVoiceAttachmentContentType(attachment.FileName);
                    stream = DRMUtils.OpenProtectedAttachment(attachment, this.callContext.AccessingADUser.OrganizationId);
                    string fileName;
                    if (AudioFile.TryGetNonDRMFileNameFromDRM(attachment.FileName, out fileName))
                    {
                        attachment.FileName = fileName;
                    }
                }
                string        text          = AttachmentUtilities.GetContentType(attachment);
                string        fileExtension = attachment.FileExtension;
                OleAttachment oleAttachment = attachment as OleAttachment;
                if (oleAttachment != null)
                {
                    stream = oleAttachment.ConvertToImage(ImageFormat.Jpeg);
                    if (stream != null)
                    {
                        text = "image/jpeg";
                    }
                }
                if (this.IsBlocked(policy) && !attachment.IsInline && !this.IsImagePreview)
                {
                    ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>((long)this.GetHashCode(), "Attachment is blocked. Returning null stream. id is {0}", this.id);
                    result = null;
                }
                else
                {
                    this.WriteResponseHeaders(text, policy, attachment);
                    if (stream == null)
                    {
                        StreamAttachment streamAttachment = attachment as StreamAttachment;
                        if (streamAttachment != null)
                        {
                            if (string.Equals(text, "audio/mpeg", StringComparison.OrdinalIgnoreCase))
                            {
                                stream = streamAttachment.GetContentStream(PropertyOpenMode.Modify);
                            }
                            else
                            {
                                stream = streamAttachment.GetContentStream(PropertyOpenMode.ReadOnly);
                            }
                        }
                        else
                        {
                            ItemAttachment itemAttachment = attachment as ItemAttachment;
                            if (itemAttachment != null)
                            {
                                using (Item item = itemAttachment.GetItem(StoreObjectSchema.ContentConversionProperties))
                                {
                                    IRecipientSession         adrecipientSession        = item.Session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid);
                                    OutboundConversionOptions outboundConversionOptions = new OutboundConversionOptions(this.callContext.DefaultDomain.DomainName.Domain);
                                    outboundConversionOptions.ClearCategories = false;
                                    outboundConversionOptions.UserADSession   = adrecipientSession;
                                    outboundConversionOptions.LoadPerOrganizationCharsetDetectionOptions(adrecipientSession.SessionSettings.CurrentOrganizationId);
                                    stream = new MemoryStream();
                                    ItemConversion.ConvertItemToMime(item, stream, outboundConversionOptions);
                                    stream.Seek(0L, SeekOrigin.Begin);
                                }
                            }
                        }
                    }
                    long num  = 0L;
                    long num2 = 0L;
                    if (AttachmentUtilities.NeedToFilterHtml(text, fileExtension, policy, this.configurationContext))
                    {
                        stream = AttachmentUtilities.GetFilteredStream(this.configurationContext, stream, attachment.TextCharset, attachmentRetriever.BlockStatus);
                    }
                    else if (this.NeedToSendPartialContent(stream, out num, out num2))
                    {
                        string value = string.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", new object[]
                        {
                            num,
                            num2,
                            stream.Length
                        });
                        this.webOperationContext.Headers["Accept-Ranges"] = "bytes";
                        this.webOperationContext.Headers["Content-Range"] = value;
                        this.webOperationContext.ETag       = this.id;
                        this.webOperationContext.StatusCode = HttpStatusCode.PartialContent;
                        long num3 = num2 - num + 1L;
                        if (num3 < stream.Length)
                        {
                            ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <long, long, long>((long)this.GetHashCode(), "RangeBytes:{0} - Seek:{1} - SetLength:{2}", num3, num, num2 + 1L);
                            stream.Seek(num, SeekOrigin.Begin);
                            return(new BoundedStream(stream, true, num, num2));
                        }
                    }
                    if (asDataUri)
                    {
                        byteEncoder = new Base64Encoder();
                        stream2     = new EncoderStream(stream, byteEncoder, EncoderStreamAccess.Read);
                        stream      = new DataUriStream(stream2, text);
                    }
                    result = stream;
                }
            }
            catch (Exception ex)
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (stream2 != null)
                {
                    stream2.Dispose();
                }
                if (byteEncoder != null)
                {
                    byteEncoder.Dispose();
                }
                string formatString = string.Empty;
                if (ex is ExchangeDataException)
                {
                    formatString = "Fail to sanitize HTML getting attachment. id is {0}, Exception: {1}";
                }
                else if (ex is StoragePermanentException)
                {
                    formatString = "StoragePermanentException when getting attachment. id is {0}, Exception: {1}";
                }
                else
                {
                    if (!(ex is StorageTransientException))
                    {
                        throw;
                    }
                    formatString = "StorageTransientException when getting attachment. id is {0}, Exception: {1}";
                }
                ExTraceGlobals.AttachmentHandlingTracer.TraceError <string, Exception>((long)this.GetHashCode(), formatString, this.id, ex);
                throw new CannotOpenFileAttachmentException(ex);
            }
            return(result);
        }
示例#26
0
 public override void WriteUint64(long l)
 {
     _writer.Write(ByteEncoder.GetBigEndian(l));
 }
示例#27
0
 public override void WriteUint32(long i)
 {
     Debug.Assert(i < 0x100000000L);
     _writer.Write(ByteEncoder.GetBigEndian((UInt32)i));
 }
示例#28
0
 public override void WriteUint16(int s)
 {
     Debug.Assert(s < 0x10000);
     _writer.Write(ByteEncoder.GetBigEndian((UInt16)s));
 }
示例#29
0
 public override void WriteDouble(double d)
 {
     _writer.Write(ByteEncoder.GetBigEndian(d));
 }
示例#30
0
        private ShapeFileIndex(ShapeFileProvider shapeFile, FileInfo file)
        {
            if (shapeFile == null)
            {
                throw new ArgumentNullException("shapeFile");
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            _shapeFile = shapeFile;

            if (String.Compare(file.Extension, ".shx", StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                throw new ShapeFileIsInvalidException("Shapefile index must end in '.shx'.");
            }

            _indexFile = file;

            if (File.Exists(_indexFile.FullName))
            {
                using (FileStream indexStream = _indexFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (BinaryReader reader = new BinaryReader(indexStream))
                    {
                        _header = new ShapeFileHeader(reader, _shapeFile.GeometryFactory);

                        indexStream.Seek(ShapeFileConstants.HeaderSizeBytes, SeekOrigin.Begin);

                        Int32 featureCount = (Int32)((_indexFile.Length - ShapeFileConstants.HeaderSizeBytes)
                                                     / ShapeFileConstants.IndexRecordByteLength);

                        for (Int32 id = 0; id < featureCount; id++)
                        {
                            Int32 offset = ByteEncoder.GetBigEndian(reader.ReadInt32());
                            Int32 length = ByteEncoder.GetBigEndian(reader.ReadInt32());

                            IndexEntry entry = new IndexEntry(length, offset);
                            // Record numbers begin at 1. (Shapefile: p. 5)
                            _shapeIndex.Add((UInt32)id + 1, entry);
                        }
                    }
            }
            else
            {
                // We need to create the index data from the raw data file
                FileStream dataStream = new FileStream(Path.ChangeExtension(_indexFile.FullName, ".shp"), FileMode.Open,
                                                       FileAccess.Read);
                BinaryReader reader = new BinaryReader(dataStream);
                {
                    _header = new ShapeFileHeader(reader, _shapeFile.GeometryFactory);

                    reader.BaseStream.Seek(ShapeFileConstants.HeaderSizeBytes, SeekOrigin.Begin);
                    long  offset   = ShapeFileConstants.HeaderSizeBytes;
                    long  fileSize = _header.FileLengthInWords * 2;
                    Int32 id       = 0;

                    while (offset < fileSize)
                    {
                        reader.BaseStream.Seek(offset, 0); //Skip content length
                        uint oid_id      = (uint)ByteEncoder.GetBigEndian(reader.ReadInt32());
                        int  data_length = 2 * ByteEncoder.GetBigEndian(reader.ReadInt32());

                        if (_shapeIndex.ContainsKey(oid_id) == false)
                        {
                            IndexEntry entry = new IndexEntry(data_length / 2, (int)(offset / 2));
                            // Record numbers begin at 1. (Shapefile: p. 5)
                            _shapeIndex.Add((UInt32)oid_id, entry);

                            offset += data_length; // Add Record data length
                            offset += 8;           //  Plus add the record header size
                            ++id;
                        }
                        else
                        {
                            offset = fileSize;
                        }
                    }

                    --id;
                    // Correct the header size
                    _header.FileLengthInWords = (id * 4) + ShapeFileConstants.HeaderSizeBytes;
                }
                reader.Close();
                dataStream.Close();
            }
        }