public override object InternalExecute(Program program, object[] arguments) { using (FileStream file = File.Open((string)arguments[0], FileMode.Append, FileAccess.Write, FileShare.Read)) { if (Operator.Operands[1].DataType.Is(program.DataTypes.SystemString)) { using (StreamWriter writer = new StreamWriter(file)) { writer.Write((string)arguments[1]); } } else { if (arguments[1] is StreamID) { using (Stream sourceStream = program.StreamManager.Open((StreamID)arguments[1], LockMode.Exclusive)) { StreamUtility.CopyStream(sourceStream, file); } } else { byte[] tempValue = (byte[])arguments[1]; file.Write(tempValue, 0, tempValue.Length); } } } return(null); }
/// <summary> /// Find the end of the header section in a byte array.<br/> /// The headers have ended when a blank line is found /// </summary> /// <param name="messageContent">The full message stored as a byte array</param> /// <returns>The position of the line just after the header end blank line</returns> /// <exception cref="ArgumentNullException">If <paramref name="messageContent"/> is <see langword="null"/></exception> private static int FindHeaderEndPosition(byte[] messageContent) { if (messageContent == null) { throw new ArgumentNullException("messageContent"); } // Convert the byte array into a stream using (Stream stream = new MemoryStream(messageContent)) { while (true) { // Read a line from the stream. We know headers are in US-ASCII // therefore it is not problem to read them as such string line = StreamUtility.ReadLineAsAscii(stream); // The end of headers is signaled when a blank line is found // or if the line is null - in which case the email is actually an email with // only headers but no body if (string.IsNullOrEmpty(line)) { return((int)stream.Position); } } } }
/// <summary> /// Get the sizes in bytes of all the messages.<br/> /// Messages marked as deleted are not listed. /// </summary> /// <returns>Size of each message excluding deleted ones</returns> /// <exception cref="PopServerException">If the server did not accept the LIST command</exception> public List <int> GetMessageSizes() { AssertDisposed(); if (State != ConnectionState.Transaction) { throw new InvalidUseException("Cannot get message sizes, when the user has not been authenticated yet"); } // RFC Example: // C: LIST // S: +OK 2 messages (320 octets) // S: 1 120 // S: 2 200 // S: . // End of multi-line SendCommand("LIST"); List <int> sizes = new List <int>(); string response; // Read until end of multi-line while (!".".Equals(response = StreamUtility.ReadLineAsAscii(Stream))) { sizes.Add(int.Parse(response.Split(' ')[1], CultureInfo.InvariantCulture)); } return(sizes); }
private void ImageRead(PipeRequest request, Pipe pipe) { if (Active) { _imageRequest = null; try { if (request.Result.IsNative) { byte[] resultBytes = request.Result.AsByteArray; SetImage(System.Drawing.Image.FromStream(new MemoryStream(resultBytes, 0, resultBytes.Length, false, true))); } else { using (Stream stream = request.Result.OpenStream()) { MemoryStream copyStream = new MemoryStream(); StreamUtility.CopyStream(stream, copyStream); SetImage(System.Drawing.Image.FromStream(copyStream)); } } } catch { SetImage(ImageUtility.GetErrorImage()); } } }
/// <summary> /// Creates a stream with the relative path to the assembly /// </summary> public static Stream CreateRefreshFileStream(string root, string assemblyPath) { string projectPath = PathUtility.EnsureTrailingSlash(root); string relativeAssemblyPath = PathUtility.GetRelativePath(projectPath, assemblyPath); return(StreamUtility.StreamFromString(relativeAssemblyPath)); }
public void Write(EndianBinaryWriter writer) { long start = writer.BaseStream.Position; writer.WriteSignature("VTX1".ToCharArray()); writer.Write(0); // Placeholder for section size writer.Write(0x40); // Offset to attribute data for (int i = 0; i < 13; i++) // Placeholders for attribute data offsets { writer.Write(0); } WriteAttributeHeaders(writer); StreamUtility.PadStreamWithString(writer, 32); WriteAttributeData(writer, (int)start); long end = writer.BaseStream.Position; long length = (end - start); writer.Seek((int)start + 4, System.IO.SeekOrigin.Begin); writer.Write((int)length); writer.Seek((int)end, System.IO.SeekOrigin.Begin); }
protected void LoadImage() { if (!ImageSource.Loading) { try { ImageSource.LoadImage(); if (ImageSource.Stream != null) { using (DAE.Runtime.Data.Scalar newValue = new DAE.Runtime.Data.Scalar(ImageControl.Source.DataSet.Process.ValueManager, ImageControl.Source.DataSet.Process.DataTypes.SystemGraphic)) { using (Stream stream = newValue.OpenStream()) { using (ImageSource.Stream) { ImageSource.Stream.Position = 0; StreamUtility.CopyStream(ImageSource.Stream, stream); ImageControl.DataField.Value = newValue; ImageControl.LoadImage(); } } } } } finally { if (ImageSource.GetType() == typeof(ImageCaptureForm)) { ImageSource = null; } } } }
protected void ImageRead(PipeRequest request, Pipe pipe) { _imageRequest = null; try { if (request.Result.IsNative) { byte[] resultBytes = request.Result.AsByteArray; _image = System.Drawing.Image.FromStream(new MemoryStream(resultBytes, 0, resultBytes.Length, false, true)); } else { using (Stream stream = request.Result.OpenStream()) { MemoryStream copyStream = new MemoryStream(); StreamUtility.CopyStream(stream, copyStream); _image = System.Drawing.Image.FromStream(copyStream); } } } catch { _image = ImageUtility.GetErrorImage(); } FCallBack(this, new EventArgs()); }
public void SetImageAccepted(IFormInterface AForm) { FImageSource = (IImageSource)AForm; if (FImageSource.Stream == null) { DataField.ClearValue(); } else { using (DAE.Runtime.Data.Scalar LNewValue = new DAE.Runtime.Data.Scalar(Source.DataView.Process.ValueManager, Source.DataView.Process.DataTypes.SystemGraphic)) { Stream LStream = LNewValue.OpenStream(); try { FImageSource.Stream.Position = 0; StreamUtility.CopyStream(FImageSource.Stream, LStream); } finally { LStream.Close(); } DataField.Value = LNewValue; } } }
public async Task SplitIntoMailboxes() { var body = "My body\nNext Line"; _queue.References.Add( new MockMailReference( "int-mail", "*****@*****.**", new[] { "*****@*****.**", "*****@*****.**" }.ToImmutableList(), true, body, _queue)); await _dispatcher.ProcessAllMailReferencesAsync(CancellationToken.None); Assert.Empty(_queue.References); Assert.Empty(_transfer.References); Assert.Equal(2, _mailbox.SavedReferences.Count()); var expected = new HashSet <string> { "*****@*****.**", "*****@*****.**" }; foreach (MockMailboxItemReference r in _mailbox.SavedReferences) { Assert.Contains(r.Mailbox, expected); expected.Remove(r.Mailbox); Assert.Equal(body, await StreamUtility.ReadAllFromStreamAsync(r.BackupBodyStream)); r.Dispose(); } }
public async Task InternalSenderCanSendAnywhere() { var body = "My body\nNext Line"; _queue.References.Add( new MockMailReference( "ext-mail", "*****@*****.**", new[] { "*****@*****.**" }.ToImmutableList(), true, body, _queue)); await _dispatcher.ProcessAllMailReferencesAsync(CancellationToken.None); Assert.Empty(_queue.References); Assert.Equal(1, _queue.DeletedReferences.Count); Assert.Equal(1, _transfer.References.Count(r => r.IsSaved)); string newBody; using (MockMailReference reference = _transfer.References.FirstOrDefault(r => r.IsSaved)) { Assert.NotNull(reference); Assert.Equal("*****@*****.**", reference.Sender); SequenceAssert.SameSet(new[] { "*****@*****.**" }, reference.Recipients); newBody = await StreamUtility.ReadAllFromStreamAsync(reference.BackupBodyStream); } Assert.Equal(body, newBody); Assert.Empty(_mailbox.References); }
internal void InternalSaveToFile() { if (String.IsNullOrEmpty(_fileName)) { _fileName = PromptForSaveName(); } // The file must be writable to overwrite if (File.Exists(_fileName)) { FileUtility.EnsureWriteable(_fileName); } // Write/rewrite the file using (FileStream fileStream = new FileStream(_fileName, FileMode.Create, FileAccess.Write)) if (((Schema.ScalarType)DataField.DataType).NativeType == typeof(byte[])) { using (Stream stream = DataField.Value.OpenStream()) StreamUtility.CopyStream(stream, fileStream); } else { using (StreamWriter streamWriter = new StreamWriter(fileStream)) streamWriter.Write(DataField.Value.AsString); } }
/// <summary> /// Initializes a new instance of the <see cref="ErrorHtmlResponse"/> class. /// </summary> /// <param name="statusCode">The status code.</param> public ErrorHtmlResponse(HttpStatusCode statusCode) { this.StatusCode = statusCode; this.ContentType = WebResources.ContentTypeHtmlUtf8; this.Contents = stream => { string page; switch (this.StatusCode) { case HttpStatusCode.NotFound: page = WebResources.PageNotFound; break; case HttpStatusCode.InternalServerError: page = WebResources.PageInternalServerError; break; default: page = string.Empty; break; } StreamUtility.WriteUtf8StringToStream(page, stream); }; }
protected void ImageRead(PipeRequest request, Pipe pipe) { if (Active) { try { _imageRequest = null; try { if (request.Result.IsNative) { byte[] resultBytes = request.Result.AsByteArray; _internalImage = System.Drawing.Image.FromStream(new MemoryStream(resultBytes, 0, resultBytes.Length, false, true)); } else { using (Stream stream = request.Result.OpenStream()) { MemoryStream copyStream = new MemoryStream(); StreamUtility.CopyStream(stream, copyStream); _internalImage = System.Drawing.Image.FromStream(copyStream); } } } catch { _internalImage = ImageUtility.GetErrorImage(); } } finally { UpdateColumn(); } } }
public StreamID Reference(StreamID streamID) { LocalStreamHeader targetHeader; if (_headers.TryGetValue(streamID, out targetHeader) && (targetHeader.Stream != null) && targetHeader.Stream.Modified) { StreamID localStreamID = Allocate(); Stream stream = Open(localStreamID, LockMode.Exclusive); try { Stream targetStream = new CoverStream(targetHeader.Stream); try { StreamUtility.CopyStream(targetStream, stream); return(localStreamID); } finally { targetStream.Close(); } } finally { stream.Close(); Close(localStreamID); } } else { StreamID localStreamID = _sourceStreamManager.Reference(streamID); LocalStreamHeader header = new LocalStreamHeader(localStreamID); _headers.Add(header); return(localStreamID); } }
public void ProcessRequest(HttpContext AContext) { AContext.Response.ContentType = FrontendUtility.CXmlContentType; string LUri = HttpUtility.UrlDecode(AContext.Request.QueryString[DilxUtility.UriParameter]); if (LUri == null) { throw new ServerException(ServerException.Codes.MissingParameter, DilxUtility.UriParameter); } LUri = AContext.Request.MapPath(new Uri(LUri).LocalPath); // Validate that the request is for a DILX document if (String.Compare(Path.GetExtension(LUri), DilxUtility.CDilxExtension, true) != 0) { throw new ServerException(ServerException.Codes.UnknownExtension, Path.GetExtension(LUri)); } // Read the DILX file using (FileStream LStream = new FileStream(LUri, FileMode.Open, FileAccess.Read, FileShare.Read)) { StreamUtility.CopyStream(LStream, AContext.Response.OutputStream); } AContext.Response.End(); }
public Stream Read(string imageID) { string fileName = BuildFileName(imageID); if (File.Exists(fileName)) return File.OpenRead(fileName); else { FileStream fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite); try { object tempValue = _identifiers[imageID]; if (tempValue is String) { using (DAE.Runtime.Data.Scalar scalar = (DAE.Runtime.Data.Scalar)_session.Pipe.RequestDocument((string)tempValue)) StreamUtility.CopyStream(scalar.OpenStream(), fileStream); } else ((GetImageHandler)tempValue)(imageID, fileStream); fileStream.Position = 0; return fileStream; } catch { fileStream.Close(); if (File.Exists(fileName)) File.Delete(fileName); throw; } } }
public void StreamUtility_ReadBoolean_2() { byte[] buffer = new byte[0]; MemoryStream stream = new MemoryStream(buffer); StreamUtility.ReadBoolean(stream); }
private List <Tuple <int, int> > WritePrimitives(EndianBinaryWriter writer) { List <Tuple <int, int> > outList = new List <Tuple <int, int> >(); long start = writer.BaseStream.Position; foreach (Shape shape in Shapes) { foreach (Packet pack in shape.Packets) { int offset = (int)(writer.BaseStream.Position - start); foreach (Primitive prim in pack.Primitives) { prim.Write(writer, shape.Descriptor); } StreamUtility.PadStreamWithZero(writer, 32); outList.Add(new Tuple <int, int>((int)((writer.BaseStream.Position - start) - offset), offset)); } } return(outList); }
public void StreamUtility_HostToNetwork16_1() { byte[] array = { 1, 2 }; StreamUtility.HostToNetwork16(array, 0); Assert.AreEqual(2, array[0]); Assert.AreEqual(1, array[1]); }
public void Write(EndianBinaryWriter writer) { long start = writer.BaseStream.Position; writer.Write("DRW1".ToCharArray()); writer.Write(0); // Placeholder for section size writer.Write((short)WeightTypeCheck.Count); writer.Write((short)-1); writer.Write(20); // Offset to weight type bools, always 20 writer.Write(20 + WeightTypeCheck.Count); // Offset to indices, always 20 + number of weight type bools foreach (bool bol in WeightTypeCheck) { writer.Write(bol); } foreach (int inte in Indices) { writer.Write((short)inte); } StreamUtility.PadStreamWithString(writer, 32); long end = writer.BaseStream.Position; long length = (end - start); writer.Seek((int)start + 4, System.IO.SeekOrigin.Begin); writer.Write((int)length); writer.Seek((int)end, System.IO.SeekOrigin.Begin); }
public void StreamUtility_ReadExact_2() { byte[] buffer = { 1, 2 }; MemoryStream stream = new MemoryStream(buffer); StreamUtility.ReadExact(stream, 4); }
public void WriteImage() { WebSession = (Web.Session)Session["WebSession"]; Response.ClearContent(); Response.BufferOutput = false; string imageID = Request.QueryString["ImageID"]; if ((imageID != null) && (imageID != String.Empty)) { using (Stream stream = WebSession.ImageCache.Read(imageID)) { Response.AppendHeader(ContentLengthHeader, stream.Length.ToString()); StreamUtility.CopyStream(stream, Response.OutputStream); } } else { imageID = Request.QueryString["HandlerID"]; if ((imageID != null) && (imageID != String.Empty)) { LoadImageHandler handler = WebSession.ImageCache.GetImageHandler(imageID); if (handler != null) { handler(Context, imageID, Response.OutputStream); } } } }
public void StreamUtility_ReadAsMuchAsPossible_3() { byte[] buffer = { 1, 2, 3, 4 }; MemoryStream stream = new MemoryStream(buffer); StreamUtility.ReadAsMuchAsPossible(stream, -3); }
/// <summary> /// Loads a dicom file, stopping at a certain tag /// </summary> /// <param name="file">Filename</param> /// <param name="stopTag">Tag to stop parsing at</param> /// <param name="options">DICOM read options</param> public DicomReadStatus Load(String file, DicomTag stopTag, DicomReadOptions options) { using (FileStream fs = File.OpenRead(file)) { fs.Seek(128, SeekOrigin.Begin); CheckFileHeader(fs); DicomStreamReader dsr = new DicomStreamReader(fs); _metainfo = new DcmFileMetaInfo(); dsr.Dataset = _metainfo; dsr.Read(DcmFileMetaInfo.StopTag, options | DicomReadOptions.FileMetaInfoOnly); if (_metainfo.TransferSyntax.IsDeflate) { MemoryStream ms = StreamUtility.Deflate(fs, false); dsr = new DicomStreamReader(ms); } _dataset = new DcmDataset(_metainfo.TransferSyntax); dsr.Dataset = _dataset; DicomReadStatus status = dsr.Read(stopTag, options); fs.Close(); return(status); } }
public void Dispose() { var success = false; try { string indexFileName = Path.Combine(_cachePath, IndexFileName); using (FileStream stream = new FileStream(indexFileName, FileMode.Create, FileAccess.Write, FileShare.None)) { _identifiers.Save(stream); } string cRC32FileName = Path.Combine(_cachePath, RC32FileName); using (FileStream stream = new FileStream(cRC32FileName, FileMode.Create, FileAccess.Write, FileShare.None)) { StreamUtility.SaveDictionary(stream, _cRC32s); } // Synchronize the index and CRC3 file times so that we know they were saved properly File.SetLastWriteTimeUtc(indexFileName, File.GetLastWriteTimeUtc(cRC32FileName)); success = true; } finally { UnlockDirectory(success); } }
/// <summary> /// Gets a list of unique IDs for all messages.<br/> /// Messages marked as deleted are not listed. /// </summary> /// <returns> /// A list containing the unique IDs in sorted order from message number 1 and upwards. /// </returns> /// <exception cref="PopServerException">If the server did not accept the UIDL command</exception> public List <string> GetMessageUids() { AssertDisposed(); if (State != ConnectionState.Transaction) { throw new InvalidUseException("Cannot get message IDs, when the user has not been authenticated yet"); } // RFC Example: // C: UIDL // S: +OK // S: 1 whqtswO00WBw418f9t5JxYwZ // S: 2 QhdPYR:00WBw1Ph7x7 // S: . // this is the end SendCommand("UIDL"); List <string> uids = new List <string>(); string response; // Keep reading until multi-line ends with a "." while (!IsLastLineInMultiLineResponse(response = StreamUtility.ReadLineAsAscii(Stream))) { // Add the unique ID to the list uids.Add(response.Split(' ')[1]); } return(uids); }
private Image LoadImage(string imageExpression) { try { using (IDataValue imageData = FrontendSession.Pipe.RequestDocument(imageExpression)) { var streamCopy = new MemoryStream(); Stream stream = imageData.OpenStream(); try { StreamUtility.CopyStream(stream, streamCopy); } finally { stream.Close(); } return(Image.FromStream(streamCopy)); } } catch (Exception exception) { Dataphoria.Warnings.AppendError(this, exception, true); // Don't rethrow } return(null); }
/// <summary> /// Method that is able to find a specific MultiPart boundary in a Stream.<br/> /// The Stream passed should not be used for anything else then for looking for MultiPart boundaries /// <param name="stream">The stream to find the next MultiPart boundary in. Do not use it for anything else then with this method.</param> /// <param name="multiPartBoundary">The MultiPart boundary to look for. This should be found in the <see cref="ContentType"/> header</param> /// <param name="lastMultipartBoundaryFound">Is set to <see langword="true"/> if the next MultiPart boundary was indicated to be the last one, by having -- appended to it. Otherwise set to <see langword="false"/></param> /// </summary> /// <returns>The position of the first character of the line that contained MultiPartBoundary or -1 if no (more) MultiPart boundaries was found</returns> private static int FindPositionOfNextMultiPartBoundary(Stream stream, string multiPartBoundary, out bool lastMultipartBoundaryFound) { lastMultipartBoundaryFound = false; while (true) { // Get the current position. This is the first position on the line - no characters of the line will // have been read yet int currentPos = (int)stream.Position; // Read the line string line = StreamUtility.ReadLineAsAscii(stream); // If we kept reading until there was no more lines, we did not meet // the MultiPart boundary. -1 is then returned to describe this. if (line == null) { return(-1); } // The MultiPart boundary is the MultiPartBoundary with "--" in front of it // which is to be at the very start of a line if (line.StartsWith("--" + multiPartBoundary, StringComparison.Ordinal)) { // Check if the found boundary was also the last one lastMultipartBoundaryFound = line.StartsWith("--" + multiPartBoundary + "--", StringComparison.OrdinalIgnoreCase); return(currentPos); } } }
public void SaveFileFromStreamTest() { { var stream = GetStream(str); var file = UnitTestHelper.RootPath + "SaveFileFromStreamTest.txt"; StreamUtility.SaveFileFromStream(stream, file); Assert.IsTrue(File.Exists(file)); Assert.IsTrue(UnitTestHelper.CheckKeywordsExist(file, str)); //检查内容已经被记录 File.Delete(file); //删除文件 } #region 测试异步方法 Task.Run(async() => { var stream = GetStream(str); var file = UnitTestHelper.RootPath + "SaveFileFromStreamTest.txt"; await StreamUtility.SaveFileFromStreamAsync(stream, file); Assert.IsTrue(File.Exists(file)); Assert.IsTrue(UnitTestHelper.CheckKeywordsExist(file, str)); //检查内容已经被记录 File.Delete(file); //删除文件 Console.WriteLine("=== 异步完成 ==="); }).GetAwaiter().GetResult(); #endregion }