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; }
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; }
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; } }
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"); }
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; }
private static bool ShouldWrapStream( Stream stream ) { return ( stream != null && !_knownMemoryOrBufferingStreams.Contains( stream.GetType().FullName ) ) #if DEBUG || _alwaysWrap #endif // DEBUG ; }
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); }
/** * 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; }
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; }
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); }
/// <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; }
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; }
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; }
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); }
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); } }
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); } }
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; }
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()); } }
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; } }
/** * @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; } }
/// <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; }
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; }
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; }
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; }
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(); }
[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; } }
/// <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; }
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; }
/// <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); } }
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; }