Ejemplo n.º 1
0
		public ProtectedConsoleStream(Stream s)
		{
			if((s.GetType() != Type.GetType("System.IO.__ConsoleStream"))&&
				(s.GetType() != Type.GetType("System.IO.FileStream")))//for mono
			{
				throw new ArgumentException("Not ConsoleStream");
			}
			this.s=s;
		}
Ejemplo n.º 2
0
 public ProtectedConsoleStream(Stream stream)
 {
     if ((stream.GetType() != Type.GetType("System.IO.__ConsoleStream")) &&
         (stream.GetType() != Type.GetType("System.IO.FileStream")))
     {
         throw new ArgumentException("Not ConsoleStream");
     }
     m_stream = stream;
 }
Ejemplo n.º 3
0
		public void Connect()
		{
			Uri uri = new Uri("http://" + settings.Server + ":" + settings.Port + settings.Mount);
			req = (HttpWebRequest)WebRequest.Create(uri);
			//req.Proxy = proxy;
			//req.UserAgent = userAgent;
			req.ProtocolVersion = HttpVersion.Version10; // new Version("ICE/1.0");
			req.Method = "SOURCE";
			req.ContentType = "audio/mpeg";
			req.Headers.Add("ice-name", settings.Name ?? "no name");
			req.Headers.Add("ice-public", "1");
			if ((settings.Url ?? "") != "") req.Headers.Add("ice-url", settings.Url);
			if ((settings.Genre ?? "") != "") req.Headers.Add("ice-genre", settings.Genre);
			if ((settings.Desctiption ?? "") != "") req.Headers.Add("ice-description", settings.Desctiption);
			req.Headers.Add("Authorization", string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("source:{0}", settings.Password)))));
			req.Timeout = System.Threading.Timeout.Infinite;
			req.ReadWriteTimeout = System.Threading.Timeout.Infinite;
			//req.ContentLength = 999999999;
			req.KeepAlive = false;
			req.SendChunked = true;
			req.AllowWriteStreamBuffering = false;
			req.CachePolicy = new System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.BypassCache);

			System.Reflection.PropertyInfo pi = typeof(ServicePoint).GetProperty("HttpBehaviour", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
			pi.SetValue(req.ServicePoint, pi.PropertyType.GetField("Unknown").GetValue(null), null);

			reqStream = req.GetRequestStream();

			System.Reflection.FieldInfo fi = reqStream.GetType().GetField("m_HttpWriteMode", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
			fi.SetValue(reqStream, fi.FieldType.GetField("Buffer").GetValue(null));
			System.Reflection.MethodInfo mi = reqStream.GetType().GetMethod("CallDone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, null, new Type[0], null);
			mi.Invoke(reqStream, null);

			try
			{
				resp = req.GetResponse() as HttpWebResponse;
				if (resp.StatusCode == HttpStatusCode.OK)
				{
					encoder = new CUETools.Codecs.LAME.LAMEEncoderCBR("", reqStream, AudioPCMConfig.RedBook);
					(encoder.Settings as CUETools.Codecs.LAME.LAMEEncoderCBRSettings).StereoMode = settings.JointStereo ? 
						CUETools.Codecs.LAME.Interop.MpegMode.JOINT_STEREO : CUETools.Codecs.LAME.Interop.MpegMode.STEREO;
					(encoder.Settings as CUETools.Codecs.LAME.LAMEEncoderCBRSettings).CustomBitrate = settings.Bitrate;
				}
			}
			catch (WebException ex)
			{
				if (ex.Status == WebExceptionStatus.ProtocolError)
					resp = ex.Response as HttpWebResponse;
				else
					throw ex;
			}
		}
Ejemplo n.º 4
0
		internal byte[] StreamToBuffer (Stream assemblyStream)
		{
			byte [] buffer;

			using (assemblyStream) {
				// avoid extra step for MemoryStream (but not any stream that inherits from it)
				if (assemblyStream.GetType () == MemoryStreamType)
					return (assemblyStream as MemoryStream).ToArray ();

				// it's normally bad to depend on Stream.Length since some stream (e.g. NetworkStream)
				// don't implement them. However it is safe in this case (i.e. SL2 depends on Length too)
				buffer = new byte [assemblyStream.Length];

				int length = buffer.Length;
				int offset = 0;
				while (length > 0) {
					int read = assemblyStream.Read (buffer, offset, length);
					if (read == 0)
						break;

					length -= read;
					offset += read;
				}
			}

			return buffer;
		}
Ejemplo n.º 5
0
 public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
 {
     lock (lockObject) {
         Trace($"{nameof(CopyToAsync)}(destination={destination?.GetType()?.Name}, bufferSize={bufferSize})".ToString(CultureInfo.CurrentCulture));
         return(baseStream.CopyToAsync(destination, bufferSize, cancellationToken));
     }
 }
Ejemplo n.º 6
0
        public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) {
            if (input==null) {
                throw new ArgumentNullException(nameof(input));
            }
            if (encoding==null) {
                throw new ArgumentNullException(nameof(encoding));
            }
            if (!input.CanRead)
                throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
            Contract.EndContractBlock();
            m_stream = input;
            m_decoder = encoding.GetDecoder();
            m_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
            int minBufferSize = encoding.GetMaxByteCount(1);  // max bytes per one char
            if (minBufferSize < 16) 
                minBufferSize = 16;
            m_buffer = new byte[minBufferSize];
            // m_charBuffer and m_charBytes will be left null.

            // For Encodings that always use 2 bytes per char (or more), 
            // special case them here to make Read() & Peek() faster.
            m_2BytesPerChar = encoding is UnicodeEncoding;
            // check if BinaryReader is based on MemoryStream, and keep this for it's life
            // we cannot use "as" operator, since derived classes are not allowed
            m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
            m_leaveOpen = leaveOpen;

            Contract.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
        }
Ejemplo n.º 7
0
        public static string GetStreamSource(Stream stream)
        {
            if (stream is FileStream file)
            {
                return(file.Name);
            }

            return(stream?.GetType( ).Name);
        }
Ejemplo n.º 8
0
        public override void Add(long key, Stream value)
        {
            String name = value.GetType().Name;

            m_NamedMountPoints.Add(key, name);

            logger.Debug(String.Format("Stream Mount: {0} -> {1}", key.ToString("X8"), name));

            base.Add(key, value);
        }
		private static bool ShouldWrapStream( Stream stream )
		{
			return
				( stream != null
				&& !_knownMemoryOrBufferingStreams.Contains( stream.GetType().FullName ) )
#if DEBUG
				|| _alwaysWrap
#endif // DEBUG
				;
		}
Ejemplo n.º 10
0
        /**
         * Save the specified part.
         *
         * @throws OpenXml4NetException
         *             Throws if an internal exception is thrown.
         */
        public bool Marshall(PackagePart part, Stream os)
        {
            if (!(os is ZipOutputStream))
            {
                logger.Log(POILogger.ERROR,"Unexpected class " + os.GetType().Name);
                throw new OpenXml4NetException("ZipOutputStream expected !");
                // Normally should happen only in developement phase, so just throw
                // exception
            }

            ZipOutputStream zos = (ZipOutputStream)os;
            string name = ZipHelper
                    .GetZipItemNameFromOPCName(part.PartName.URI
                            .OriginalString);
            ZipEntry partEntry = new ZipEntry(name);
            try
            {
                // Create next zip entry
                zos.PutNextEntry(partEntry);

                // Saving data in the ZIP file
                Stream ins = part.GetInputStream();
                byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE];
                int totalRead = 0;
                while (true)
                {
                    int resultRead = ins.Read(buff, 0, buff.Length);
                    if (resultRead == 0)
                    {
                        // End of file reached
                        break;
                    }
                    zos.Write(buff, 0, resultRead);
                    totalRead += resultRead;
                }
                zos.CloseEntry();
            }
            catch (IOException ioe)
            {
                logger.Log(POILogger.ERROR, "Cannot write: " + part.PartName + ": in ZIP", ioe);
                return false;
            }

            // Saving relationship part
            if (part.HasRelationships)
            {
                PackagePartName relationshipPartName = PackagingUriHelper
                        .GetRelationshipPartName(part.PartName);

                MarshallRelationshipPart(part.Relationships,
                        relationshipPartName, zos);

            }
            return true;
        }
Ejemplo n.º 11
0
 public FileParameter ParameterToFile(string name, Stream stream)
 {
     if (stream.GetType().Equals(typeof(FileStream)))
     {
         return(FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name)));
     }
     else
     {
         return(FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided"));
     }
 }
Ejemplo n.º 12
0
        internal static bool IsFileStream(Stream stream)
        {
            if (FileStreamType.Value == null)
            {
                return(false);
            }

            var type = stream.GetType();

            return(type == FileStreamType.Value || type.GetTypeInfo().IsSubclassOf(FileStreamType.Value));
        }
        internal static byte[] ToByteArray(this Stream stream)
        {
            if (stream.GetType() == typeof(MemoryStream))
            {
                return(((MemoryStream)stream).ToArray());
            }
            var ms = new MemoryStream();

            stream.CopyTo(ms);
            return(ms.ToArray());
        }
Ejemplo n.º 14
0
        bool CreateStream(HttpWebRequest request)
        {
            try {
                NetworkStream serverStream = new NetworkStream(socket, false);

                if (request.Address.Scheme == Uri.UriSchemeHttps)
                {
                    ssl = true;
                    EnsureSSLStreamAvailable();
                    if (!reused || nstream == null || nstream.GetType() != sslStream)
                    {
                        byte [] buffer = null;
                        if (sPoint.UseConnect)
                        {
                            bool ok = CreateTunnel(request, sPoint.Address, serverStream, out buffer);
                            if (!ok)
                            {
                                return(false);
                            }
                        }

                        object[] args = new object [4] {
                            serverStream,
                            request.ClientCertificates,
                            request, buffer
                        };
                        nstream = (Stream)Activator.CreateInstance(sslStream, args);
#if SECURITY_DEP
                        SslClientStream scs    = (SslClientStream)nstream;
                        var             helper = new ServicePointManager.ChainValidationHelper(request);
                        scs.ServerCertValidation2 += new CertificateValidationCallback2(helper.ValidateChain);
#endif
                        certsAvailable = false;
                    }
                    // we also need to set ServicePoint.Certificate
                    // and ServicePoint.ClientCertificate but this can
                    // only be done later (after handshake - which is
                    // done only after a read operation).
                }
                else
                {
                    ssl     = false;
                    nstream = serverStream;
                }
            } catch (Exception) {
                if (!request.Aborted)
                {
                    status = WebExceptionStatus.ConnectFailure;
                }
                return(false);
            }

            return(true);
        }
Ejemplo n.º 15
0
        private void ExtractExeFS(Stream output, NCCHRegion region, Keyslot secondaryKeyslot, bool close = true)
        {
            if (secondaryKeyslot == Keyslot.NCCH)
            {
                //if the secondary keyslot is also the original 0x2C NCCH Keyslot, don't bother decrypting anything in parts, and just shove the entire ExeFS through a CryptoStream
                Tools.CryptFileStreamPart(this.NCCHMemoryMappedFile, output, new AesCtrCryptoTransform(this.Cryptor.NormalKey[(int)Keyslot.NCCH], region.CTR), region.Offset, region.Size, close);
                return;
            }

            //here we go, i don't like this part

            byte[] header = new byte[0x200];

            using (MemoryMappedViewStream headerViewStream = this.NCCHMemoryMappedFile.CreateViewStream(region.Offset, 0x200))
            {
                header = Tools.CryptBytes(headerViewStream.ReadBytes(0x200), new AesCtrCryptoTransform(this.Cryptor.NormalKey[0x2C], region.CTR));
            }

            output.Write(header);

            //create dummy ExeFS class instance to figure out the locations of each file in the ExeFS
            ExeFS exefs = new ExeFS(header);

            //write decrypted header to output file
            foreach (ExeFSEntry entry in exefs.Entries)
            {
                byte[] CTR = (region.CTRInt + (entry.Offset / 16)).ToCTRBytes();

                AesCtrCryptoTransform transform = (NormalCryptoExeFSFiles.Contains(entry.Name)) ? new AesCtrCryptoTransform(this.Cryptor.NormalKey[(int)Keyslot.NCCH], CTR) : new AesCtrCryptoTransform(this.Cryptor.NormalKey[(int)secondaryKeyslot], CTR);

                using (MemoryMappedViewStream fileViewStream = this.NCCHMemoryMappedFile.CreateViewStream(region.Offset + entry.Offset, entry.Size))
                {
                    CryptoStream cs = new CryptoStream(output, transform, CryptoStreamMode.Write);

                    output.Seek(entry.Offset, SeekOrigin.Begin);

                    fileViewStream.CopyTo(cs);

                    cs.FlushFinalBlock();
                }
            }

            //sneaky way to make it gm9-like

            if (!(output.GetType() == typeof(MemoryMappedViewStream)))
            {
                output.SetLength(Tools.RoundUp(output.Length, 0x200));
            }

            if (close)
            {
                output.Dispose();
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Returns the stream as an array.
 /// </summary>
 public byte[] ToArray()
 {
     if (Stream.GetType() == typeof(FileStream))
     {
         Stream.Position = 0;
         byte[] buffer = new byte[Stream.Length];
         Stream.Read(buffer, 0, buffer.Length);
         return(buffer);
     }
     return(((MemoryStream)Stream).ToArray());
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Codes the data from the input chunk into the output chunk.
 /// </summary>
 /// <param name="input">Input stream (encoded data).</param><param name="output">Output stream (decoded data).</param><param name="args">Variable number of extra arguments.</param>
 /// <returns>
 /// An object that holds data specific to the media format which this codec deal with.
 ///     For example, an image codec might return a structure that has image related details,
 ///     such as height, width, etc.
 /// </returns>
 public override object Decode( Stream input, Stream output, params object[] args )
 {
     byte[] data = new byte[ input.Length ];
     input.Read( data, 0, (int)input.Length );
     output.Write( data, 0, (int)input.Length );
     if ( input.GetType() == typeof( XnaImageCodecStream ) )
     {
         return ( (XnaImageCodecStream)input ).ImageData;
     }
     return null;
 }
Ejemplo n.º 18
0
        public BinaryStreamWriter([NotNull] Stream stream)
        {
            this.stream = stream ?? throw new ArgumentNullException(nameof(stream));

            if (!stream.CanWrite)
            {
                throw new AggregateException($"Output stream of type '{stream.GetType().Name}' was not writable.");
            }

            buffer = new BinaryBufferWriter(BufferSize);
        }
Ejemplo n.º 19
0
 static void TrackGcs(Stream input)
 {
     int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2);
     for (int i = 0; i < ITERS; i++)
     {
         input.Position = 0;
         input.CopyToAsync(Stream.Null).Wait();
     }
     int newGen0 = GC.CollectionCount(0), newGen1 = GC.CollectionCount(1), newGen2 = GC.CollectionCount(2);
     Console.WriteLine("{0}\tGen0:{1}   Gen1:{2}   Gen2:{3}", input.GetType().Name, newGen0 - gen0, newGen1 - gen1, newGen2 - gen2);
 }
 public static bool WriteBeyondEndTest(Stream s)
 {
     Console.WriteLine("Write Beyond End test on "+s.GetType().Name);
     FileStream fs = s as FileStream;
     if (fs != null)
         Console.WriteLine("FileStream type is: "+(fs.IsAsync ? "asynchronous" : "synchronous"));
     long origLength = s.Length;        
     byte[] bytes = new byte[10];
     for(int i=0; i<bytes.Length; i++)
         bytes[i] = (byte) i;
     int spanPastEnd = 5;
     s.Seek(spanPastEnd, SeekOrigin.End);
     if (s.Position != s.Length + spanPastEnd)
         throw new Exception("Position is incorrect!  Seek(5, SeekOrigin.End) should leave us at s.Length + spanPastEnd ("+(s.Length + spanPastEnd)+"), but got: "+s.Position);
     Console.WriteLine("Original Length: "+origLength);
     s.Write(bytes, 0, bytes.Length);
     long pos = s.Position;
     if (pos != origLength + spanPastEnd + bytes.Length)
         throw new Exception(String.Format("After asynchronously writing beyond end of the stream, position is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     if (s.Length != origLength + spanPastEnd + bytes.Length)
         throw new Exception(String.Format("After asynchronously writing beyond end of the stream, Length is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     WritePastEndHelper(s, bytes, origLength, spanPastEnd, false);
     origLength = s.Length;
     s.Position = s.Length + spanPastEnd;
     s.WriteByte(0x42);
     long expected = origLength + spanPastEnd + 1;
     if (s.Position != expected)
     {
         iCountErrors++ ;
         throw new Exception("After WriteByte, Position was wrong!  got: "+s.Position+"  expected: "+expected);
     }
     if (s.Length != expected)
     {
         iCountErrors++ ;
         throw new Exception("After WriteByte, Length was wrong!  got: "+s.Length+"  expected: "+expected);
     }
     origLength = s.Length;
     s.Position = s.Length + spanPastEnd;
     IAsyncResult ar = s.BeginWrite(bytes, 0, bytes.Length, null, null);
     s.EndWrite(ar);
     pos = s.Position;
     if (pos != origLength + spanPastEnd + bytes.Length) 
     {
         iCountErrors++ ;
         throw new Exception(String.Format("After writing beyond end of the stream, position is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     }
     if (s.Length != origLength + spanPastEnd + bytes.Length) 
     {
         iCountErrors++;
         throw new Exception(String.Format("After writing beyond end of the stream, Length is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     }
     WritePastEndHelper(s, bytes, origLength, spanPastEnd, true);
     return true;
 }
Ejemplo n.º 21
0
        // Stream
        #region
        public static bool MarkedToStream(Stream stream)
        {
#if DBG
            string status = "Began saving";
#endif
            try
            {
                var markers = UnityObject.FindObjectsOfType <FSMarker>();
                var data    = new Dictionary <int, string>(markers.Length);

                if (OnBeganSavingMarked != null)
                {
                    OnBeganSavingMarked(data);
                }

                using (var memory = new MemoryStream())
                {
                    for (int i = 0; i < markers.Length; i++)
                    {
                        var marker = markers[i];
#if DBG
                        status = "Saving " + marker.name;
#endif
                        Save.GameObjectToStream(memory, marker.gameObject, marker);

                        string serializedState = memory.ToArray().GetString();
                        int    id = marker.GetPersistentId();
                        data[id] = serializedState;

                        memory.Reset();
                    }
                }
#if DBG
                status = "Saving to stream (" + stream.GetType() + ")";
#endif
                Save.ObjectToStream(stream, data);

                if (OnFinishedSavingMarked != null)
                {
                    OnFinishedSavingMarked(data);
                }

                return(true);
            }
            catch (Exception e)
            {
#if DBG
                Log(string.Format("Error ({0}): {1}", status, e.Message));
#else
                Log("Error saving: " + e.Message);
#endif
                return(false);
            }
        }
Ejemplo n.º 22
0
        public BinaryStreamReader(Stream stream)
        {
            this.stream = stream ?? throw new ArgumentNullException(nameof(stream));

            if (!stream.CanRead)
            {
                throw new AggregateException($"Input stream of type '{stream.GetType().Name}' was not readable.");
            }

            buffer = new BinaryBufferReader(new byte[BufferSize], 0);
        }
Ejemplo n.º 23
0
            /// <summary>
            ///  型'<see cref="ExapisSOP.IO.Settings.CommandLine.Option.Value"/>'の新しいインスタンスを生成します。
            /// </summary>
            /// <param name="stream">応答ファイルを表すストリームです。</param>
            /// <exception cref="System.ArgumentNullException"/>
            public Value(Stream stream)
            {
                if (stream == null)
                {
                    throw new ArgumentNullException(nameof(stream));
                }
                var sr = new StreamReader(stream, true);

                this.Source = stream is FileStream fs ? fs.Name : stream.GetType().FullName ?? string.Empty;
                this.Text   = sr.ReadToEnd();
            }
Ejemplo n.º 24
0
        public WebRequest(ConcurrentDictionary <string, string> headers, Stream body, NetworkStream clientStream)
        {
            Headers = headers;
            Headers.TryGetValue("HTTPType", out this.HTTPType);
            Headers.TryGetValue("HTTPVersion", out this.HTTPVersion);
            Headers.TryGetValue("URL", out this.Uri);
            ResponseTarget = clientStream;

            if (HTTPVersion.EndsWith("\r\n"))
            {
                HTTPVersion = HTTPVersion.Substring(0, HTTPVersion.Length - 2);
            }

            string length = "";

            if (Headers.TryGetValue("content-length", out length))
            {
                long clength = 0;
                long.TryParse(length, out clength);

                if (body.GetType() == typeof(MemoryStream))
                {
                    Body = new ConcatStream(body, clientStream, clength);
                }
                else if (body.GetType() == typeof(NetworkStream))
                {
                    Body = body;
                }
            }
            else
            {
                if (body.GetType() == typeof(MemoryStream))
                {
                    Body = new ConcatStream(body, clientStream);
                }
                else if (body.GetType() == typeof(NetworkStream))
                {
                    Body = body;
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Writes a single field of data to a DBF file using the provided Stream object.  This method assumes the Stream object's write position is located at the position to begin writing.
        /// </summary>
        /// <param name="s">An initialized Stream object of a DBF file with the cursor position set to the beginning of the field to be written.</param>
        /// <param name="fld">A DbfField object detailing the structure of the field to be written to.</param>
        /// <param name="value">A System.Object value whose string representation will be written to the Stream.</param>
        public static void WriteDbfField(Stream s, DbfField fld, object value)
        {
            // Save the Stream's current position and the size of the field.
            long sPos = s.Position, sLen = fld.FieldLength + fld.DecimalLength;

            // Get the string value of the passed Object 'value' to be written.
            string val = string.Empty;

            if (value != null)
            {
                val = (value.GetType().Name == "DateTime") ? ((DateTime)value).ToString("yyyyMMdd") : value.ToString();
            }

            // Create a byte array from the string representation of 'value'.
            byte[] buffer = Encoding.ASCII.GetBytes(val.Substring(0, System.Math.Min(fld.FieldLength, val.Length)).PadRight(fld.FieldLength, ' '));

            // If the passed Stream object is a FileStream object,
            //   then lock the bytes we're about to write to.
            if (s.GetType().FullName == "System.IO.FileStream")
            {
                ((FileStream)s).Lock(sPos, sLen);
            }

            // Write the byte buffer.  If an error occurs, just throw it back
            //   to the calling code, but don't forget to unlock the stream.
            try
            {
                s.Write(buffer, 0, buffer.Length);
                DbfTable.SetLastUpdateTime(s);
            }
            catch
            { throw; }
            finally
            {
                if (s.GetType().FullName == "System.IO.FileStream")
                {
                    ((FileStream)s).Unlock(sPos, sLen);
                }
                s.Position = sPos;
            }
        }
Ejemplo n.º 26
0
        public void CreateTest()
        {
            AbstractFactory <int, Stream> factory = new AbstractFactory <int, Stream>();

            factory.Register(0, new CustomCreator());
            factory.Register(1, null);
            Stream newStream = factory.Create(0);

            Assert.AreNotEqual(newStream, null);
            Assert.AreEqual(newStream.GetType(), typeof(MemoryStream));
            Assert.AreEqual(factory.Create(1), null);
        }
Ejemplo n.º 27
0
        public override Codec.DecodeResult Decode( Stream input )
        {
            var data = new byte[ input.Length ];
            input.Read( data, 0, (int)input.Length );
            var output = new MemoryStream();
            output.Write( data, 0, (int)input.Length );

            if ( input.GetType() == typeof( XnaImageCodecStream ) )
                return new Codec.DecodeResult( output, ( (XnaImageCodecStream)input ).ImageData );

            return null;
        }
Ejemplo n.º 28
0
 public void setInputStream(Stream ins)
 {
     //ConsoleStream low buffer patch
     if (ins != null)
     {
         if (ins.GetType() == Type.GetType("System.IO.__ConsoleStream"))
         {
             ins = new Fireball.Streams.ProtectedConsoleStream(ins);
         }
     }
     this.ins = ins;
 }
Ejemplo n.º 29
0
    public static bool ReadBeyondEndTest(Stream s)
    {
        Console.WriteLine("Read Beyond End test on " + s.GetType().Name);
        byte[] bytes = new byte[10];
        for (int i = 0; i < bytes.Length; i++)
        {
            bytes[i] = (byte)i;
        }
        s.Seek(5, SeekOrigin.End);
        if (s.Position != s.Length + 5)
        {
            iCountErrors++;
            throw new Exception("Position is incorrect!  Seek(5, SeekOrigin.End) should leave us at s.Length + 5, but got: " + s.Position);
        }
        int numRead = s.Read(bytes, 0, bytes.Length);

        if (numRead != 0)
        {
            iCountErrors++;
            throw new Exception("Reading from past end of stream is broken!  Expected 0, got: " + numRead);
        }
        for (int i = 0; i < bytes.Length; i++)
        {
            if (bytes[i] != (byte)i)
            {
                iCountErrors++;
                throw new Exception("Error in byte[] - Read overwrote it!  pos: " + i + "  got: " + bytes[i]);
            }
        }
        numRead = s.ReadByte();
        if (numRead != -1)
        {
            iCountErrors++;
            throw new Exception("ReadByte didn't return -1!  got: " + numRead);
        }
        IAsyncResult ar = s.BeginRead(bytes, 0, bytes.Length, null, null);

        numRead = s.EndRead(ar);
        if (numRead != 0)
        {
            iCountErrors++;
            throw new Exception("Reading from past end of stream with BeginRead is broken!  Expected 0, got: " + numRead);
        }
        for (int i = 0; i < bytes.Length; i++)
        {
            if (bytes[i] != (byte)i)
            {
                iCountErrors++;
                throw new Exception("Error in byte[] - BeginRead overwrote it!  pos: " + i + "  got: " + bytes[i]);
            }
        }
        return(true);
    }
Ejemplo n.º 30
0
        /// <summary>
        /// Limiting a stream, basically it creates a new Stream with the given length
        /// </summary>
        /// <param name="ms"></param>
        /// <param name="newLimit"></param>
        /// <returns></returns>
        static public Stream Limit(this Stream stream, int newLimit)
        {
            Stream newStream = (Stream)Activator.CreateInstance(stream.GetType(), newLimit);

            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                newStream.Write(ms.ToArray(), 0, newLimit);
            }

            return(newStream);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Gets the name from stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>System.String.</returns>
        private static string getNameFromStream(Stream stream)
        {
            var type                   = stream.GetType();
            var namePropertyInfo       = type.GetProperty("Name");
            var name                   = (string)namePropertyInfo.GetValue(stream, null);
            var lastDirectorySeparator = name.LastIndexOf("\\");
            var fileExtensionIndex     = name.LastIndexOf(".");

            return((lastDirectorySeparator < fileExtensionIndex)
                ? name.Substring(lastDirectorySeparator + 1, fileExtensionIndex - lastDirectorySeparator - 1)
                : name.Substring(lastDirectorySeparator + 1, name.Length - lastDirectorySeparator - 1));
        }
Ejemplo n.º 32
0
        private int read(byte[] buffer, int offset, int size)
        {
            var readLen = _innerStream.Read(buffer, offset, size);

            if (readLen < size)
            {
                var msg = String.Format("Data can not be read from {0}.", _innerStream.GetType().Name);
                throw new IOException(msg);
            }

            return(readLen);
        }
            public void ReadAll()
            {
                //定义读取流中所有数据的方法
                Console.WriteLine("Reading stream ofTypeis: " + src.GetType());
                int nextByte;

                //在while循环中以字节方式读出所有数据
                while ((nextByte = src.ReadByte()) != -1)
                {
                    Console.Write((char)nextByte);
                }
            }
        internal static void AllowFilteringInSinkAfterEndRequest(Stream sinkStream)
        {
            // Allows the filter to work in the HTTP response sink, even though
            // the EndRequest event was already raised, and filtering should have
            // been already completed
            PropertyInfo filtering = sinkStream.GetType().GetProperty("Filtering", BindingFlags.Instance | BindingFlags.NonPublic);

            if (filtering.CanWrite)
            {
                filtering.SetValue(sinkStream, true, null);
            }
        }
Ejemplo n.º 35
0
 /// <summary>
 ///     Finish creating the GIF and start flushing
 /// </summary>
 private void Finish()
 {
     if (_stream == null)
     {
         return;
     }
     _stream.WriteByte(0x3B); // Image terminator
     if (_stream.GetType() == typeof(FileStream))
     {
         _stream.Dispose();
     }
 }
Ejemplo n.º 36
0
        public ExcelSpreadsheetWriter(Stream outputStream, CompressionLevel compressionLevel = CompressionLevel.Fastest)
            : base(outputStream ?? new MemoryStream())
        {
            if (outputStream.GetType().FullName == "System.Web.HttpResponseStream")
            {
                outputStream = new WriteStreamWrapper(outputStream);
            }

            _Package = new PackageWriteStream(outputStream);

            _CompressionLevel = compressionLevel;
        }
Ejemplo n.º 37
0
    static void TrackGcs(Stream input)
    {
        int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2);

        for (int i = 0; i < ITERS; i++)
        {
            input.Position = 0;
            input.CopyToAsync(Stream.Null).Wait();
        }
        int newGen0 = GC.CollectionCount(0), newGen1 = GC.CollectionCount(1), newGen2 = GC.CollectionCount(2);

        Console.WriteLine("{0}\tGen0:{1}   Gen1:{2}   Gen2:{3}", input.GetType().Name, newGen0 - gen0, newGen1 - gen1, newGen2 - gen2);
    }
Ejemplo n.º 38
0
        public BaseFile(GameDataManager gameDataManager, string path)
        {
            GameDataManager = gameDataManager;
            Filename        = path;
            InArchive       = false;
            ArchiveFile     = null;
            FileNumber      = -1;

            Stream             = DataCompression.StreamHelper.Decompress(new MemoryStream(File.ReadAllBytes(Filename)));
            OriginalStreamType = Stream.GetType();

            Parse();
        }
Ejemplo n.º 39
0
        /// <summary>
        /// An extension to Stream which clones the Stream object to a MemoryStream
        /// </summary>
        /// <param name="stream">The Stream object to be cloned</param>
        /// <returns>A MemoryStream object copy of the original Stream</returns>
        public static MemoryStream CloneToMemoryStream(this Stream stream)
        {
            long originalStreamPosition = stream.Position;

            stream.Position = 0;
            Type         T            = stream.GetType();
            MemoryStream memoryStream = new MemoryStream();

            stream.CopyTo(memoryStream);
            stream.Position       = originalStreamPosition;
            memoryStream.Position = 0;
            return(memoryStream);
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Process the entire length of the Input Stream
        /// </summary>
        ///
        /// <returns>The Message Authentication Code</returns>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if ComputeMac is called before Initialize(), or Size + Offset is longer than Input stream</exception>
        public byte[] ComputeMac()
        {
            if (!m_isInitialized)
            {
                throw new CryptoProcessingException("MacStream:ComputeMac", "Initialize() must be called before a write operation can be performed!", new InvalidOperationException());
            }
            if (m_inStream.Length < 1)
            {
                throw new CryptoProcessingException("MacStream:ComputeMac", "The Input stream is too short!", new ArgumentOutOfRangeException());
            }

            if (m_inStream.Length < BUFFER_SIZE || !m_inStream.GetType().Equals(typeof(FileStream)))
            {
                m_isConcurrent = false;
            }

            long dataLen = m_inStream.Length - m_inStream.Position;

            CalculateInterval(dataLen);

            return(Compute(dataLen));
        }
Ejemplo n.º 41
0
        public static string FileName(this Stream stream)
        {
            switch (stream)
            {
            case FileStream fstream:
                return(fstream.Name);

            case IHasName hasName:
                return(hasName.Name);

            default:
                return(stream?.GetType().Name);
            }
        }
Ejemplo n.º 42
0
Archivo: IO.cs Proyecto: x893/SharpSSH
 public void setInputStream(Stream ins)
 {
     //ConsoleStream low buffer patch
     if (ins != null)
     {
         if (ins.GetType() == Type.GetType("System.IO.__ConsoleStream"))
             ins = new Streams.ProtectedConsoleStream(ins);
         else if (ins.GetType() == Type.GetType("System.IO.FileStream"))
             ins = new Streams.ProtectedConsoleStream(ins);
         m_ins = new JStream(ins);
     }
     else
         m_ins = null;
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Rewinds the current stream pointer to the beginning of the stream (when supported by the stream)
        /// </summary>
        /// <param name="src">Source stream to rewind</param>
        public static void Rewind(this Stream src)
        {
            if (src is null)
            {
                throw new ArgumentException(nameof(src));
            }

            if (!src.CanSeek)
            {
                throw new ArgumentException($"Cannot seek in stream of type: {src.GetType()}");
            }

            src.Seek(0, SeekOrigin.Begin);
        }
Ejemplo n.º 44
0
 public static void ByteTest(Stream s) 
 {
     Console.WriteLine("  (01)  ByteTest on "+s.GetType( ).Name);
     int		size	= 0x25000;
     int		r;
     for(int i=0;i<size;i++)			s.WriteByte((byte)i);
     s.Position=0;
     for(int i=0;i<size;i++) 
     {
         r=s.ReadByte( );
         if(r!=i%256)
             throw new Exception("Didn't get the correct value for i at: "
                 +i+"  expected: "+(i%256)+"  got: "+r);
     }
 }
Ejemplo n.º 45
0
        private NetworkStream m_NetworkStream;  //optimizing writes

        public StreamFramer(Stream Transport) {
            if (Transport == null || Transport == Stream.Null) {
                throw new ArgumentNullException("Transport");
            }
            m_Transport = Transport;
            if(m_Transport.GetType() == typeof(NetworkStream)){
                m_NetworkStream = Transport as NetworkStream;
            }
            m_ReadHeaderBuffer = new byte[m_CurReadHeader.Size];
            m_WriteHeaderBuffer = new byte[m_WriteHeader.Size];

            m_ReadFrameCallback = new AsyncCallback(ReadFrameCallback);
            m_BeginWriteCallback = new AsyncCallback(BeginWriteCallback);

        }
Ejemplo n.º 46
0
 public static void SpanTest(Stream s) 
 {
     Console.WriteLine("  (02)  SpanTest on "+s.GetType( ).Name);
     //	If a read request spans across two buffers, make sure we get the data
     //	back in one read request, since it would be silly to not do so. This 
     //	caught a bug in BufferedStream, which was missing a case to handle the
     //	second read request.
     //	Here's a legend.  The space is at the 8K buffer boundary.
     //	/-------------------|------- -------|------------------\ 
     //	First for loop 	  Read(bytes)	 Second for loop
     int			max;
     int			r;
     byte[]		bytes;
     int			numBytes;
     const int	bufferSize	= 8*(1<<10);
     for(int i=0;i<bufferSize*2;i++)			s.WriteByte((byte)(i % 256));
     s.Position=0;
     max = bufferSize-(bufferSize>>2);
     for(int i=0;i<max;i++) 
     {
         r=s.ReadByte( );
         if(r!=i%256)
             throw new Exception("Didn't get the correct value for i at: "
                 +i+"  expected: "+(i%256)+"  got: "+r);
     }
     bytes = new byte[bufferSize>>1];
     numBytes=s.Read(bytes,0,bytes.Length);
     if (numBytes!=bytes.Length)
         throw new Exception("While reading into a byte[] spanning a buffer starting at position "
             +max+", didn't get the right number of bytes!  asked for: "
             +bytes.Length+"  got: "+numBytes);
     for(int i=0;i<bytes.Length;i++) 
     {
         if(bytes[i]!=((i+max)%256))
             throw new Exception("When reading in an array that spans across two buffers, "+
                 "got an incorrect value at index: "+i+
                 "  expected: "+((i+max)%256)+"  got: "+bytes[i]);
     }
     //	Read rest of data
     for(int i=0;i<max;i++) 
     {
         r=s.ReadByte( );
         if(r!=(i+max+bytes.Length)%256)
             throw new Exception("While reading the last part of the buffer, "
                 +"didn't get the correct value for i at: "+i
                 +"  expected: "+((i+max+bytes.Length)%256)+"  got: "+r);
     }
 }
Ejemplo n.º 47
0
 public static bool ReadBeyondEndTest(Stream s)
 {
     Console.WriteLine("Read Beyond End test on "+s.GetType().Name);
     byte[] bytes = new byte[10];
     for(int i=0; i<bytes.Length; i++)
         bytes[i] = (byte) i;
     s.Seek(5, SeekOrigin.End);
     if (s.Position != s.Length + 5)
     {
         iCountErrors++;
         throw new Exception("Position is incorrect!  Seek(5, SeekOrigin.End) should leave us at s.Length + 5, but got: "+s.Position);
     }
     int numRead = s.Read(bytes, 0, bytes.Length);
     if (numRead != 0)
     {
         iCountErrors++ ;
         throw new Exception("Reading from past end of stream is broken!  Expected 0, got: "+numRead);
     }
     for(int i=0; i<bytes.Length; i++)
     {
         if (bytes[i] != (byte) i)
         {
             iCountErrors++ ;
             throw new Exception("Error in byte[] - Read overwrote it!  pos: "+i+"  got: "+bytes[i]);
         }
     }
     numRead = s.ReadByte();
     if (numRead != -1)
     {
         iCountErrors++ ;
         throw new Exception("ReadByte didn't return -1!  got: "+numRead);
     }
     IAsyncResult ar = s.BeginRead(bytes, 0, bytes.Length, null, null);
     numRead = s.EndRead(ar);
     if (numRead != 0)
     {
         iCountErrors++ ;
         throw new Exception("Reading from past end of stream with BeginRead is broken!  Expected 0, got: "+numRead);
     }
     for(int i=0; i<bytes.Length; i++)
         if (bytes[i] != (byte) i)
         {
             iCountErrors++ ;
             throw new Exception("Error in byte[] - BeginRead overwrote it!  pos: "+i+"  got: "+bytes[i]);
         }
     return true;
 }
Ejemplo n.º 48
0
 public AutoClosingStream(Stream stream)
 {
     UnderlyingStream = stream;
     var ss = stream.ToString();
     if (UnderlyingStream is FileStream)
     {
         var io = (System.IO.FileStream)stream;
         string s = io.Name;
         if (s == null || s.Trim().Length == 0)
         {
             s = "" + io.SafeFileHandle;
             writeToLog("Unusual name " + io);
         }
         AddToName(s);
     } else
     {
         origname = "" + stream;
         writeToLog("Non file stream  " + stream.GetType());
     }
 }
Ejemplo n.º 49
0
		public Assembly Load (Stream assemblyStream)
		{
			// SL2 throws a NullReferenceException if assemblyStream is null
			// but returns null if the stream is empty (e.g. Stream.Null)
			if (assemblyStream.Length == 0)
				return null;

			byte[] buffer = null;
			// avoid extra step for MemoryStream (but not any stream that inherits from it)
			if (assemblyStream.GetType () == MemoryStreamType)
				buffer = (assemblyStream as MemoryStream).ToArray ();
			else
				buffer = StreamToBuffer (assemblyStream);

			try {
				Assembly result = Assembly.Load (buffer);
				if (!Deployment.Current.Assemblies.Contains (result))
					Deployment.Current.Assemblies.Add (result);	
				return result;
			}
			catch {
				return null;
			}
		}
Ejemplo n.º 50
0
        [System.Security.SecurityCritical] // auto-generated
        internal static RuntimeAssembly InternalLoadFromStream(Stream assemblyStream, Stream pdbStream, ref StackCrawlMark stackMark)
        {
            if (assemblyStream  == null)
                throw new ArgumentNullException("assemblyStream");

            if (assemblyStream.GetType()!=typeof(UnmanagedMemoryStream))
                throw new NotSupportedException();

            if (pdbStream!= null && pdbStream.GetType()!=typeof(UnmanagedMemoryStream))
                throw new NotSupportedException();

            AppDomain.CheckLoadFromSupported();

            UnmanagedMemoryStream umAssemblyStream = (UnmanagedMemoryStream)assemblyStream;
            UnmanagedMemoryStream umPdbStream = (UnmanagedMemoryStream)pdbStream;
            
            unsafe
            {
                byte* umAssemblyStreamBuffer=umAssemblyStream.PositionPointer;
                byte* umPdbStreamBuffer=(umPdbStream!=null)?umPdbStream.PositionPointer:null; 
                long assemblyDataLength = umAssemblyStream.Length-umAssemblyStream.Position;
                long pdbDataLength = (umPdbStream!=null)?(umPdbStream.Length-umPdbStream.Position):0;
                
                // use Seek() to benefit from boundary checking, the actual read is done using *StreamBuffer
                umAssemblyStream.Seek(assemblyDataLength,SeekOrigin.Current);
                
                if(umPdbStream != null)
                {
                    umPdbStream.Seek(pdbDataLength,SeekOrigin.Current);                  
                }
                
                BCLDebug.Assert(assemblyDataLength > 0L, "assemblyDataLength > 0L");
    
                RuntimeAssembly assembly = null;

                nLoadFromUnmanagedArray(false, 
                                                                 umAssemblyStreamBuffer, 
                                                                 (ulong)assemblyDataLength, 
                                                                 umPdbStreamBuffer,
                                                                 (ulong)pdbDataLength, 
                                                                 JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
                                                                 JitHelpers.GetObjectHandleOnStack(ref assembly));

                return assembly;
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Gets a size of the image.
        /// </summary>
        /// <param name="imageStream">The image stream.</param>
        /// <returns>A size of the image.</returns>
        public Size GetImageSize(Stream imageStream)
        {
            try
            {
                imageStream.Seek(0, SeekOrigin.Begin);

                using (var img = Image.FromStream(imageStream))
                {                    
                    return img.Size;
                }
            }
            catch (ArgumentException e)
            {
                throw new ImagingException(string.Format("Stream {0} is not valid image stream. Can not determine image size.", imageStream.GetType()), e);
            }
        }        
Ejemplo n.º 52
0
        private void init(Stream innerStream)
        {
            if (innerStream == null)
            throw new ArgumentNullException("innerStream");

              _innerStream     = innerStream;
              _innerStreamType = innerStream.GetType();
              _isSecure        = _innerStreamType == typeof(SslStream) ? true : false;
              _forRead         = new object();
              _forWrite        = new object();
        }
        /// <summary>
        /// Some streams are easily represented as byte arrays.
        /// </summary>
        /// <param name="data">The stream</param>
        /// <returns>
        /// The contents of <paramref name="data"/> as a byte array or null if the stream can't easily
        /// be read into a byte array.
        /// </returns>
        private static byte[] TryGetByteArrayFromStream(Stream data)
        {
            byte[] buffer;

            // PERF: If the input is a MemoryStream, we may be able to get at the buffer directly
            var memoryStream = data as MemoryStream;
            if (memoryStream != null && TryGetByteArrayFromMemoryStream(memoryStream, out buffer))
            {
                return buffer;
            }

            // PERF: If the input is a FileStream, we may be able to minimize allocations
            if (data.GetType() == PortableShim.FileStream.Type &&
                TryGetByteArrayFromFileStream(data, out buffer))
            {
                return buffer;
            }

            return null;
        }
Ejemplo n.º 54
0
 public static bool CanPropertiesTest(Stream s) 
 {
     Console.WriteLine("  (06)  Can-Properties Test on "+s.GetType( ).Name);
     byte[]			bytes				= new byte[1];
     int				bytesTransferred;
     IAsyncResult	asyncResult;
     if(s.CanRead) 
     {			//	Ensure all Read methods work, if CanRead is true.
         int		n	= s.ReadByte( );
         if(n==-1)
             throw new Exception("On a readable stream, ReadByte returned -1...");
         bytesTransferred=s.Read(bytes,0,1);
         if(bytesTransferred!=1)
             throw new Exception("Read(byte[],0,1) should have returned 1!  got: "+bytesTransferred);
         asyncResult=s.BeginRead(bytes,0,1,null,null);									/*	BeginRead	*/ 
         bytesTransferred=s.EndRead(asyncResult);										/*	EndRead		*/ 
         if(bytesTransferred!=1)
             throw new Exception("BeginRead(byte[],0,1) should have returned 1!  got: "
                 +bytesTransferred);
     }						//	End of (s.CanRead) Block
     else 
     {					//	Begin of (!s.CanRead) Block
         try 
         {
             s.ReadByte( );
             throw new Exception("ReadByte on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.Read(bytes,0,1);
             throw new Exception("Read(bytes,0,1) on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.BeginRead(bytes,0,1,null,null);											/*	BeginRead	*/ 
             throw new Exception("BeginRead on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
     }						//	End of (!s.CanRead) Block
     if(s.CanWrite) 
     {		//	Ensure write methods work if CanWrite returns true.
         s.WriteByte(0);
         s.Write(bytes,0,1);
         asyncResult = s.BeginWrite(bytes,0,1,null,null);								/*	BeginWrite	*/ 
         s.EndWrite(asyncResult);														/*	EndWrite	*/ 
     }						//	End of (s.CanWrite) Block
     else 
     {					//	Begin of (!s.CanWrite) Block
         try 
         {
             s.WriteByte(2);
             throw new Exception("WriteByte on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.Write(bytes,0,1);
             throw new Exception("Write(bytes,0,1) on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.BeginWrite(bytes,0,1,null,null);											/*	BeginWrite	*/ 
             throw new Exception("BeginWrite on an unreadable stream should have thrown!");
         }
         catch(NotSupportedException)	{	}
     }						//	End of (!s.CanWrite) Block
     if(s.CanSeek) 
     {			//	Ensure length-related methods work if CanSeek returns true
         long	n	= s.Length;
         n=s.Position;
         if(s.Position>s.Length)
             throw new Exception("Position is beyond the length of the stream!");
         s.Position=0;
         s.Position=s.Length;
         if(s.Position!=s.Seek(0,SeekOrigin.Current))
             throw new Exception("s.Position!=s.Seek(0,SeekOrigin.Current)");
         if(s.CanWrite)		//	Verify you can set the length, if it's writable.
             s.SetLength(s.Length);
     }						//	End of (s.CanSeek) Block
     else 
     {					//	Begin of (!s.CanSeek) Block
         try 
         {
             s.Position=5;
             throw new Exception("set_Position should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             long	n	= s.Position;
             throw new Exception("get_Position should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             long	n	= s.Length;
             throw new Exception("get_Length should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.SetLength(1);
             throw new Exception("SetLength should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
         try 
         {
             s.Seek(0,SeekOrigin.Current);
             throw new Exception("Seek should throw on a non-seekable stream!");
         }
         catch(NotSupportedException)	{	}
     }						//	End of (!s.CanSeek) Block
     return true;
 }
Ejemplo n.º 55
0
 public static bool ReadWriteBufferSwitchTest(Stream s) 
 {
     String	writableStr		= "read-only";
     if(s.CanWrite)
         writableStr="read/write";
     Console.WriteLine("  (05)  ReadWriteBufferSwitch test for a "+writableStr+" "+s.GetType( ).Name);
     if(s.Length<8200)		
         Console.WriteLine("ReadWriteBufferSwitchTest assumes stream len is at least 8200");
     s.Position = 0;
     //	Assume buffer size is 8192
     for(int i=0;i<8192;i++)		s.ReadByte( );
     //		Console.WriteLine("  (05)  Pos: "+s.Position+"  s.Length: "+s.Length);
     s.WriteByte(0);
     //	Calling the position property will verify internal buffer state.
     if(8193!=s.Position)
         throw new Exception("Position should be 8193!  Position: "+s.Position);
     s.ReadByte( );
     return true;
 }
Ejemplo n.º 56
0
 /**
  * @param stream the stream to be Closed
  * @param success <c>false</c> if an exception is currently being thrown in the calling method
  */
 private void CloseInputStream(Stream stream, bool success) {
     
     if(stream is MemoryStream) {
         String msg = "POIFS is closing the supplied input stream of type (" 
                 + stream.GetType().Name + ") which supports mark/reset.  "
                 + "This will be a problem for the caller if the stream will still be used.  "
                 + "If that is the case the caller should wrap the input stream to avoid this Close logic.  "
                 + "This warning is only temporary and will not be present in future versions of POI.";
         //_logger.Log(POILogger.WARN, msg);
     }
     try {
         stream.Close();
     } catch (IOException) {
         if(success) {
             throw;
         }
         // else not success? Try block did not complete normally 
         // just print stack trace and leave original ex to be thrown
         //e.StackTrace;
     }
 }
Ejemplo n.º 57
0
 public static bool AsyncTest(Stream s) 
 {
     byte[]				bigArr		= new byte[80000];
     byte[]				smArr		= new byte[128];
     int					numBytes;
     AsyncCallback		cb;
     IAsyncResult		asyncResult;
     DateTime			startWait;
     TimeSpan			thirtySecs	= new TimeSpan(0,0,30);
     bool				firstTime;
     TimeSpan			diff;
     if(s.GetType( )==typeof(IsolatedStorageFileStream)) 
     {
         Console.WriteLine("AsyncTest won't run on an IsolatedStorageFileStream "
             +"since it doesn't support async operations.");
         return true;
     }
     Console.WriteLine("  (08)  Async test on "+s.GetType( ).Name);
     if(s.Position!=0)
         throw new Exception("AsyncTest assumes stream's position will be 0 when starting.");
     for(int i=0;i<smArr.Length;i++)		smArr[i] = (byte)i;
     //	Try writing something more than 64KB so we have a chance of doing an async write.
     for(int i=0;i<bigArr.Length;i++)	bigArr[i] = (byte)((i%26)+(byte)'A');
     //	Ensure that we do run our async callback at some point.
     didAsyncCallbackRun=false;
     cb = new AsyncCallback(AsyncTestCallback);
     asyncResult=s.BeginWrite(smArr,0,smArr.Length,cb,String.Empty);						/*	BeginWrite	*/ 
     s.EndWrite(asyncResult);															/*	EndWrite	*/ 
     if(s.Position!=smArr.Length)
         throw new Exception("After first BeginWrite call, (s.Position!=smArr.Length)  got: "
             +s.Position);
     asyncResult=s.BeginWrite(bigArr,0,bigArr.Length,null,String.Empty);
     s.EndWrite(asyncResult);
     if(s.Position!=bigArr.Length+smArr.Length)
         throw new Exception("After second BeginWrite call, s.Position wasn't right!  expected: "
             +(bigArr.Length+smArr.Length)+"  got: "+s.Position);
     //	And to be sure things work, test write with an offset.
     asyncResult=s.BeginWrite(smArr,smArr.Length/2,smArr.Length/2,null,null);			/*	BeginWrite	*/ 
     s.EndWrite(asyncResult);															/*	EndWrite	*/ 
     if(s.Position!=(smArr.Length/2+bigArr.Length+smArr.Length))
         throw new Exception("After third BeginWrite call, s.Position wasn't correct! expected: "
             +(smArr.Length/2+bigArr.Length+smArr.Length)
             +"  got: "+s.Position);
     startWait=DateTime.Now;
     firstTime=true;
     while(!didAsyncCallbackRun) 
     {
         if(firstTime) 
         {
             Console.WriteLine("Waiting for async callback to be run from first BeginWrite call.");
             firstTime=false;
         }
         else
             Console.Write(".");
         Thread.Sleep(20);
         diff=DateTime.Now-startWait;
         if(diff>thirtySecs)
             throw new Exception("Async callback didn't run yet after 2 BeginWRITE calls and "
                 +"30 seconds of blocking!  "
                 +"This could be a bug in a particular stream class, "
                 +"or an extremely pathetic race condition in this test.");
     }
     didAsyncCallbackRun=false;
     s.Position=0;
     byte[]		input	= new byte[(int)s.Length];
     //	Retest running the async callback here.
     asyncResult=s.BeginRead(input,0,smArr.Length,cb,String.Empty);						/*	BeginRead	*/ 
     numBytes=s.EndRead(asyncResult);													/*	BeginRead	*/ 
     if(numBytes!=smArr.Length)
         throw new Exception("After first BeginRead call, (numBytes!=smArr.Length)  got: "
             +numBytes);
     if(s.Position!=smArr.Length)
         throw new Exception("After first BeginRead call, (s.Position!=smArr.Length)  got: "
             +s.Position);
     asyncResult=s.BeginRead(input,smArr.Length,bigArr.Length,null,String.Empty);		/*	BeginRead	*/ 
     numBytes=s.EndRead(asyncResult);													/*	EndRead		*/ 
     if(numBytes!=bigArr.Length)
         throw new Exception("After second BeginRead call, (numBytes!=bigArr.Length)  got: "
             +numBytes);
     if(s.Position!=bigArr.Length+smArr.Length)
         throw new Exception("After second BeginRead call, s.Position wasn't right!  expected: "
             +(bigArr.Length+smArr.Length)+"  got: "+s.Position);
     asyncResult=s.BeginRead(input,smArr.Length+bigArr.Length,smArr.Length/2,null,null);	/*	BeginRead	*/ 
     numBytes=s.EndRead(asyncResult);													/*	EndRead		*/ 
     if(numBytes!=smArr.Length/2)
         throw new Exception("After third BeginRead call, (numBytes!=smArr.Length/2)  got: "
             +numBytes);
     if(s.Position!=(smArr.Length/2+bigArr.Length+smArr.Length))
         throw new Exception("After third BeginRead call, s.Position wasn't correct! expected: "
             +(smArr.Length/2+bigArr.Length+smArr.Length)
             +"  got: "+s.Position);
     for(int i=0;i<smArr.Length;i++)
         if (smArr[i]!=input[i])
             throw new Exception("When reading first smArr copy, position "
                 +i+" was wrong!  got: "
                 +input[i]+"  expected: "+smArr[i]);
     int		offset	= smArr.Length;
     for(int i=0;i<bigArr.Length;i++)
         if (bigArr[i]!=input[i+offset])
             throw new Exception("When reading bigArr copy, position "
                 +(i+offset)+" was wrong! i: "+i+"  got: "
                 +input[i+offset]+"  expected: "+bigArr[i]);
     offset=smArr.Length+bigArr.Length;
     for(int i=0;i<smArr.Length/2;i++)
         if (smArr[i+smArr.Length/2]!=input[i+offset])
             throw new Exception("When reading second smArr copy, position "
                 +(i+offset)+" was wrong! i: "+i+"  got: "
                 +input[i+offset]+"  expected: "
                 +smArr[i+smArr.Length/2]);
     startWait=DateTime.Now;
     firstTime=true;
     while(!didAsyncCallbackRun) 
     {
         if (firstTime) 
         {
             Console.WriteLine("Waiting for async callback to be run from "
                 +"first BeginRead call.");
             firstTime=false;
         }
         else
             Console.Write(".");
         Thread.Sleep(20);
         diff=DateTime.Now-startWait;
         if(diff>thirtySecs)
             throw new Exception("Async callback didn't run yet after 2 BeginREAD "
                 +"calls and 30 seconds of blocking!  "
                 +"This could be a bug in a particular stream "
                 +"class, or an extremely pathetic race "
                 +"condition in this test.");
     }
     didAsyncCallbackRun=false;
     return true;
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Checks whether an {@link InputStream} is in the Horrible
        /// Property Set Format.
        /// </summary>
        /// <param name="stream">The {@link InputStream} To check. In order To
        /// perform the check, the method Reads the first bytes from the
        /// stream. After Reading, the stream is Reset To the position it
        /// had before Reading. The {@link InputStream} must support the
        /// {@link InputStream#mark} method.</param>
        /// <returns>
        /// 	<c>true</c> if the stream is a property Set
        /// stream; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsPropertySetStream(Stream stream)
        {
            ByteArrayInputStream dis = stream as ByteArrayInputStream;
            /*
             * Read at most this many bytes.
             */
            int BUFFER_SIZE = 50;

            /*
             * Mark the current position in the stream so that we can
             * Reset To this position if the stream does not contain a
             * property Set.
             */
            if (dis == null || !dis.MarkSupported())
                throw new MarkUnsupportedException(stream.GetType().Name);
            dis.Mark(BUFFER_SIZE);

            /*
             * Read a couple of bytes from the stream.
             */
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytes =
                stream.Read(buffer, 0,
                            (int)Math.Min(buffer.Length, dis.Available()));
            bool isPropertySetStream =
                IsPropertySetStream(buffer, 0, bytes);
            stream.Seek(0, SeekOrigin.Begin);
            dis.Reset();
            return isPropertySetStream;
        }
Ejemplo n.º 59
0
 public static bool ErrorTest(Stream s) 
 {
     Console.WriteLine("  (09)  Error test on stream: "+s.GetType( ).Name);
     //	Test EndRead & EndWrite's Type safety
     byte[]				bytes		= new byte[0];
     IAsyncResult		asyncResult;
     BogusIAsyncResult	bogus		= new BogusIAsyncResult( );
     if(s.CanRead) 
     {
         asyncResult = s.BeginRead(bytes,0,0,null,null);									/*	BeginRead	*/ 
         try 
         {
             s.EndWrite(asyncResult);													/*	EndWrite	*/ 
             throw new Exception("EndWrite with an asyncResult from BeginRead should have thrown!");
         }
         catch(ArgumentException)	{	}
     }
     if(s.CanWrite) 
     {
         asyncResult=s.BeginWrite(bytes,0,0,null,null);									/*	BeginWrite	*/ 
         try 
         {
             s.EndRead(asyncResult);														/*	EndRead		*/ 
             throw new Exception("EndRead with an asyncResult from BeginWrite should have thrown!");
         }
         catch(ArgumentException)	{	}
         //	Verify EndWrite doesn't allow using the same asyncResult twice.
         s.EndWrite(asyncResult);														/*	EndWrite	*/ 
         try 
         {
             s.EndWrite(asyncResult);													/*	EndWrite	*/ 
             throw new Exception("Exception EndWrite was called twice w/ same IAsyncResult from "
                 +s.GetType( ).Name+", but didn't throw!");
         }
         catch(InvalidOperationException)	{	}
     }
     try 
     {
         s.EndRead(bogus);																/*	EndRead		*/ 
         throw new Exception("EndRead with a bogus IAsyncResult object should have thrown!");
     }
     catch(ArgumentException)	{	}
     try 
     {
         s.EndWrite(bogus);																/*	EndWrite	*/ 
         throw new Exception("EndWrite with a bogus IAsyncResult object should have thrown!");
     }
     catch(ArgumentException)	{	}
     return true;
 }
Ejemplo n.º 60
0
 public static bool SetLengthTest(Stream s) 
 {
     Console.WriteLine("  (10)  SetLengthTest on "+s.GetType( ).Name);
     if(!s.CanSeek) 
     {
         Console.WriteLine("SetLengthTest shouldn't run on non-seekable stream "+s.GetType( ).Name);
         try 
         {
             s.SetLength(0);
             throw new Exception("SetLength to 0 on a non-seekable stream should have failed!");
         }
         catch(NotSupportedException)	{	}
         return true;
     }
     if(!s.CanWrite) 
     {
         Console.WriteLine("SetLengthTest shouldn't run on non-writable stream "+s.GetType( ).Name);
         try 
         {
             s.SetLength(0);
             throw new Exception("SetLength to 0 on a non-writable stream should have failed!  "
                 +"s.Length: "+s.Length);
         }
         catch(NotSupportedException)	{	}
         return true;
     }
     s.SetLength(0);
     if(s.Length!=0)
         throw new Exception("SetLength to 0, but Length is: "+s.Length);
     if(s.Position!=0)
         throw new Exception("Set length to 0.  Position should be zero too: "+s.Position);
     s.SetLength(10);
     if(s.Length!=10)
         throw new Exception("SetLength to 10, but Length is: "+s.Length);
     if(s.Position!=0)
         throw new Exception("Set length to 10, yet Position should be zero still: "+s.Position);
     if(s.CanRead) 
     {
         byte[]			bytes			= new byte[500];
         IAsyncResult	asyncResult		= s.BeginRead(bytes,0,500,null,null);
         int				numBytes		= s.EndRead(asyncResult);
         if(numBytes!=10)
             throw new Exception("Number of bytes got back from EndRead was wrong!  "
                 +"should have been 10, but got: "+numBytes);
         if(s.Position!=10)
             throw new Exception("After async read, position should be 10, but was: "+s.Position);
     }
     return true;
 }