// Usually called when cloning images that need to have // not only the handle saved, but also the underlying stream // (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image) internal Metafile (IntPtr ptr, Stream stream) { // under Win32 stream is owned by SD/GDI+ code if (GDIPlus.RunningOnWindows ()) this.stream = stream; nativeObject = ptr; }
public void Save(Stream output) { BinaryWriter writer = new BinaryWriter(output); writer.Write(this.version); writer.Write((int)0); writer.Write((int)0); // Double the string length since it's UTF16 writer.Write((byte)(this.partName.Length * 2)); MadScience.StreamHelpers.WriteStringUTF16(output, false, this.partName); writer.Write(this.blendType); this.blendTgi.Save(output); writer.Write((uint)this.geomBoneEntries.Count); for (int i = 0; i < this.geomBoneEntries.Count; i++) { this.geomBoneEntries[i].Save(output); } uint tgiOffset = (uint)output.Position - 8; // Why is this +12? I dunno. :) this.keytable.size = 8; this.keytable.Save(output); output.Seek(4, SeekOrigin.Begin); writer.Write(tgiOffset); writer.Write(this.keytable.size); writer = null; }
public SourceText CreateText(Stream stream, Encoding defaultEncoding, CancellationToken cancellationToken = default(CancellationToken)) { // this API is for a case where user wants us to figure out encoding from the given stream. // if defaultEncoding is given, we will use it if we couldn't figure out encoding used in the stream ourselves. Debug.Assert(stream != null); Debug.Assert(stream.CanSeek); Debug.Assert(stream.CanRead); if (defaultEncoding == null) { // Try UTF-8 try { return CreateTextInternal(stream, s_throwingUtf8Encoding, cancellationToken); } catch (DecoderFallbackException) { // Try Encoding.Default defaultEncoding = Encoding.Default; } } try { return CreateTextInternal(stream, defaultEncoding, cancellationToken); } catch (DecoderFallbackException) { return null; } }
protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { _stream = stream; _ownsStream = ownsStream; _offset = 0; _encoding = encoding; }
/// <summary> /// Compute a hash from the content of a stream and restore the position. /// </summary> /// <remarks> /// Modified FNV Hash in C# /// http://stackoverflow.com/a/468084 /// </remarks> internal static int ComputeHash(Stream stream) { System.Diagnostics.Debug.Assert(stream.CanSeek); unchecked { const int p = 16777619; var hash = (int)2166136261; var prevPosition = stream.Position; stream.Position = 0; var data = new byte[1024]; int length; while((length = stream.Read(data, 0, data.Length)) != 0) { for (var i = 0; i < length; i++) hash = (hash ^ data[i]) * p; } // Restore stream position. stream.Position = prevPosition; hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return hash; } }
public override void WriteProp(Stream output, bool array) { output.WriteF32(this.R); output.WriteF32(this.G); output.WriteF32(this.B); output.WriteF32(this.A); }
internal static byte[] ComputeFileHash(Stream fileStream) { using (var sha1 = new SHA1CryptoServiceProvider()) { return sha1.ComputeHash(fileStream); } }
public static SpriteType DetectSpriteType(Stream s) { if (IsShpTD(s)) return SpriteType.ShpTD; if (IsShpTS(s)) return SpriteType.ShpTS; if (IsR8(s)) return SpriteType.R8; if (IsTmpRA(s)) return SpriteType.TmpRA; if (IsTmpTD(s)) return SpriteType.TmpTD; if (IsTmpTS(s)) return SpriteType.TmpTS; if (IsShpD2(s)) return SpriteType.ShpD2; return SpriteType.Unknown; }
public override void ReadProp(Stream input, bool array) { this.R = input.ReadF32(); this.G = input.ReadF32(); this.B = input.ReadF32(); this.A = input.ReadF32(); }
public static dynamic[] Parse(Stream stream, Dictionary<int, string> fields) { var format = stream.Read<ulong>(); stream.Position = 0; // DMsg format if (format == 0x00000067736D5F64) { return DMsgParser.Parse(stream, fields); } // Dialog format if ((format & 0x10000000) > 0 && format % 0x10000000 == (ulong) stream.Length - 4) { return DialogParser.Parse(stream, fields[0]); } // Auto-translate files (no specific format) if ((format & 0xFFFFFCFF) == 0x00010002) { return ATParser.Parse(stream, fields[0]); } throw new InvalidDataException("Unknown DAT format."); }
public static void WriteToStream(Image img, Stream stream) { IntPtr point = img.gdImageStructPtr; DLLImports.gdImageStruct gdImageStruct = Marshal.PtrToStructure<DLLImports.gdImageStruct>(point); var wrapper = new gdStreamWrapper(stream); DLLImports.gdImageJpegCtx(ref gdImageStruct, ref wrapper.IOCallbacks); }
public CsvStateMachineReportGeneratorTest() { this.stateStream = new MemoryStream(); this.transitionsStream = new MemoryStream(); this.testee = new CsvStateMachineReportGenerator<States, Events>(this.stateStream, this.transitionsStream); }
public static XmlDocument StreamToXml(Stream stream) { var xmlDoc = new XmlDocument(); var reader = new StreamReader(stream); xmlDoc.LoadXml(reader.ReadToEnd()); return xmlDoc; }
public void Save(Stream s) { using (var w = new StreamWriter(s)) { w.Write(JsonConvert.SerializeObject(this, Formatting.Indented)); } }
static MemoryStream StreamToMemory(Stream input) { byte[] buffer = new byte[1024]; int count = 1024; MemoryStream output; // build a new stream if (input.CanSeek) { output = new MemoryStream((int)input.Length); } else { output = new MemoryStream(); } // iterate stream and transfer to memory stream do { count = input.Read(buffer, 0, count); if (count == 0) break; // TODO: might not be correct. Was : Exit Do output.Write(buffer, 0, count); } while (true); // rewind stream output.Position = 0; // pass back return output; }
public override IOpcode ReadOpcode(Stream stream) { int contourCount = ReadUnsignedByte(stream); //extended count if (contourCount == 0) { contourCount = 256 + ReadUnsignedShort(stream); } for (int i = 0; i < contourCount; i++) { //each contour has a list of points int pointsCount = ReadUnsignedByte(stream); //points extended count if (pointsCount == 0) { pointsCount = 256 + ReadUnsignedShort(stream); } //first vertex ReadSignedShort(stream); ReadSignedShort(stream); for (int j = 0; j < pointsCount; j++) { //vertex(j) ReadSignedShort(stream); ReadSignedShort(stream); } } return new DrawContourSetShort(); }
internal LimitedInputStream( Stream inStream, int limit) { this._in = inStream; this._limit = limit; }
private static XmlSchemaSet LoadSchema(Stream xsd) { var reader = XmlReader.Create(xsd); var set = new XmlSchemaSet(); set.Add(null, reader); return set; }
public void Read(Stream inputStream) { BinaryReader reader = new BinaryReader(inputStream, Encoding.UTF8, true); int magicNumber = reader.ReadInt32(); int version = reader.ReadInt32(); // GZ 2, TPP 3 int endianess = reader.ReadInt32(); // LE, BE int entryCount = reader.ReadInt32(); int valuesOffset = reader.ReadInt32(); int keysOffset = reader.ReadInt32(); inputStream.Position = valuesOffset; Dictionary<int, LangEntry> offsetEntryDictionary = new Dictionary<int, LangEntry>(); for (int i = 0; i < entryCount; i++) { int valuePosition = (int)inputStream.Position - valuesOffset; short valueConstant = reader.ReadInt16(); Debug.Assert(valueConstant == 1); string value = reader.ReadNullTerminatedString(); offsetEntryDictionary.Add(valuePosition, new LangEntry { Value = value }); } inputStream.Position = keysOffset; for (int i = 0; i < entryCount; i++) { uint key = reader.ReadUInt32(); int offset = reader.ReadInt32(); offsetEntryDictionary[offset].Key = key; } Entries = offsetEntryDictionary.Values.ToList(); }
public override void OnPut(string key, Stream data, RavenJObject metadata) { if (key.StartsWith("Raven/")) // we don't deal with system attachment return; using (Database.DisableAllTriggersForCurrentThread()) { var attachmentMetadata = GetAttachmentMetadata(key); if (attachmentMetadata != null) { RavenJArray history = new RavenJArray(metadata.Value<RavenJArray>(Constants.RavenReplicationHistory)); metadata[Constants.RavenReplicationHistory] = history; if (attachmentMetadata.ContainsKey(Constants.RavenReplicationVersion) && attachmentMetadata.ContainsKey(Constants.RavenReplicationSource)) { history.Add(new RavenJObject { {Constants.RavenReplicationVersion, attachmentMetadata[Constants.RavenReplicationVersion]}, {Constants.RavenReplicationSource, attachmentMetadata[Constants.RavenReplicationSource]} }); } if (history.Length > Constants.ChangeHistoryLength) { history.RemoveAt(0); } } metadata[Constants.RavenReplicationVersion] = RavenJToken.FromObject(HiLo.NextId()); metadata[Constants.RavenReplicationSource] = RavenJToken.FromObject(Database.TransactionalStorage.Id); } }
public List<Status> DeserializeStatusList(Stream stream) { XmlSerializer serializer = new XmlSerializer( typeof(List<Status>), new XmlRootAttribute("statuses")); return (List<Status>)serializer.Deserialize(stream); }
public GenericBinaryFile(Stream stream) { _path = string.Empty; _data = new byte[stream.Length]; stream.Read(_data, 0, (int)stream.Length); stream.Dispose(); }
public override ReadVetoResult AllowRead(string key, Stream data, RavenJObject metadata, ReadOperation operation) { RavenJToken value; if (metadata.TryGetValue("Raven-Delete-Marker", out value)) return ReadVetoResult.Ignore; return ReadVetoResult.Allowed; }
private static string AddToArchive(string entryName, Stream inputStream, ZipArchive zipArchive, string hashName) { var entry = zipArchive.CreateEntry(entryName); HashAlgorithm hashAlgorithm = null; BinaryWriter zipEntryWriter = null; try { hashAlgorithm = HashAlgorithm.Create(hashName); zipEntryWriter = new BinaryWriter(entry.Open()); var readBuffer = new byte[StreamReadBufferSize]; int bytesRead; while ((bytesRead = inputStream.Read(readBuffer, 0, readBuffer.Length)) > 0) { zipEntryWriter.Write(readBuffer, 0, bytesRead); hashAlgorithm.TransformBlock(readBuffer, 0, bytesRead, readBuffer, 0); } hashAlgorithm.TransformFinalBlock(readBuffer, 0, 0); var hashHexStringBuilder = new StringBuilder(); foreach (byte hashByte in hashAlgorithm.Hash) { hashHexStringBuilder.Append(hashByte.ToString("x2")); } return hashHexStringBuilder.ToString(); } finally { hashAlgorithm.SafeDispose(); zipEntryWriter.SafeDispose(); } }
public YmlEntry Parse(Stream stream) { var root = new YmlEntry("root"); ICollection<YmlEntry> categories = root.Values; IEnumerable<string> rows = ReadAllRows(stream); YmlEntry parent = null; foreach (string row in rows) { if (row.StartsWith("\"")) { string name = row.Substring(1, row.IndexOf("\"", 1) - 1); parent = new YmlEntry(name); categories.Add(parent); } else if (row.StartsWith(" ")) { var nameValue = row.Trim().Split(':'); var entry = new YmlEntry(nameValue[0]); var values = nameValue[1].Split('|'); foreach (var value in values) entry.AddValue(value.Trim()); parent.Values.Add(entry); } } return root; }
public BundleFetchConnection(Transport transportBundle, Stream src) { transport = transportBundle; bin = new BufferedStream(src, IndexPack.BUFFER_SIZE); try { switch (readSignature()) { case 2: readBundleV2(); break; default: throw new TransportException(transport.Uri, "not a bundle"); } } catch (TransportException) { Close(); throw; } catch (IOException err) { Close(); throw new TransportException(transport.Uri, err.Message, err); } }
public static AcmeRegistration Load(Stream s) { using (var r = new StreamReader(s)) { return JsonConvert.DeserializeObject<AcmeRegistration>(r.ReadToEnd()); } }
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { bool result = false; string[] p = SplitParams(path); if (p.Length > 0) { if (m_allowedTypes != AllowedRemoteDeleteTypes.None) { string assetID = p[0]; AssetBase asset = m_AssetService.Get(assetID); if (asset != null) { if (m_allowedTypes == AllowedRemoteDeleteTypes.All || (int)(asset.Flags & AssetFlags.Maptile) != 0) { result = m_AssetService.Delete(assetID); } else { m_log.DebugFormat( "[ASSET SERVER DELETE HANDLER]: Request to delete asset {0}, but type is {1} and allowed remote delete types are {2}", assetID, (AssetFlags)asset.Flags, m_allowedTypes); } } } } XmlSerializer xs = new XmlSerializer(typeof(bool)); return ServerUtils.SerializeResult(xs, result); }
public void Send(string toEmail, string subject, string body, Stream stream, string fileName) { SmtpClient smtp = new SmtpClient { Host = SmtpServer, Port = SmtpPort, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(FromEmail, Password) }; using (MailMessage message = new MailMessage(FromEmail, toEmail)) { message.Subject = subject; message.Body = body; if (stream != null) { Attachment attachment = new Attachment(stream, fileName); message.Attachments.Add(attachment); } smtp.Send(message); } }
public HttpResponseStreamWrapper(Stream stream, IRequest request) { this.OutputStream = stream; this.Request = request; this.Headers = new Dictionary<string, string>(); this.Items = new Dictionary<string, object>(); }
public static string postSync(string urlPost, string dados) { string Out = String.Empty; System.Net.WebRequest req = System.Net.WebRequest.Create(urlPost); try { req.Method = "POST"; req.Timeout = 300000; req.ContentType = "application/x-www-form-urlencoded"; byte[] sentData = Encoding.UTF8.GetBytes(dados); req.ContentLength = sentData.Length; using (System.IO.Stream sendStream = req.GetRequestStream()) { sendStream.Write(sentData, 0, sentData.Length); sendStream.Close(); } WebResponse res = req.GetResponse(); IO.Stream ReceiveStream = res.GetResponseStream(); using (IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8)) { Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); Out += str; count = sr.Read(read, 0, 256); } } } catch (ArgumentException ex) { Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message); } catch (WebException ex) { Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message); } catch (Exception ex) { Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message); } return(Out); }
public static ThenType Deserialize(System.IO.Stream s) { return((ThenType)(Serializer.Deserialize(s))); }
public void Save(System.IO.Stream stream) { }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = this.mTitle; report.EnableExternalImages = true; report.EnableHyperlinks = true; EnterpriseService enterprise = new EnterpriseService(); DataSet ds = new DataSet(this.mDSName); foreach (GridViewRow row in SelectedRows) { DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex]; DataSet _ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { dataKey["PickupID"].ToString() }); ds.Merge(_ds); } if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(this.mSource); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.SetParameters(new ReportParameter[] { new ReportParameter("PickupID", "0") }); report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName, "RGXVMSQLR.TSORT")); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=LOccitaneCartonInfo.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex, 4); } }
public abstract void renderDocument(ITemplate template, IDictionary <string, object> values, ref System.IO.Stream outputStream);
public void Serialize(IO.Stream serializationStream, object graph) { throw new NotImplementedException(); }
public object Deserialize(IO.Stream serializationStream) { throw new NotImplementedException(); }
public void Write(System.IO.Stream stream) { using (Writer writer = new Writer(stream)) this.Write(writer); }
//Thanks to https://github.com/GoldFarmer/rouge_sdf/blob/master/main.cpp for docs/structs public void Load(System.IO.Stream stream) { using (var reader = new FileReader(stream)) { reader.ByteOrder = Syroot.BinaryData.ByteOrder.LittleEndian; //Read header Header = new SDFTOC_Header(); Header.Read(reader); //Read first id var startId = new SDFTOC_ID(reader); //Check this flag byte Flag1 = reader.ReadByte(); if (Flag1 != 0) { byte[] unk = reader.ReadBytes(0x140); } if (Header.DataOffset != 0) { reader.SeekBegin(Header.DataOffset + 0x51); //Here is the compressed block. Check the magic first uint magic = reader.ReadUInt32(); reader.Seek(-4, SeekOrigin.Current); //Read and decompress the compressed block //Contains file names and block info DecompressNameBlock(magic, reader.ReadBytes((int)Header.CompressedSize), Header); //Read last id var endId = new SDFTOC_ID(reader); } else { //Read first block var block1 = reader.ReadInt32s((int)Header.Block1Count); //Read ID blocks var blockIds = new SDFTOC_ID[Header.Block1Count]; for (int i = 0; i < Header.Block1Count; i++) { blockIds[i] = new SDFTOC_ID(reader); } //Read block 2 (DDS headers) block2Array = new SDFTOC_Block2[Header.Block2Count]; for (int i = 0; i < Header.Block2Count; i++) { block2Array[i] = new SDFTOC_Block2(reader, Header); } //Here is the compressed block. Check the magic first uint magic = reader.ReadUInt32(); reader.Seek(-4, SeekOrigin.Current); //Read and decompress the compressed block //Contains file names and block info DecompressNameBlock(magic, reader.ReadBytes((int)Header.CompressedSize), Header); //Read last id var endId = new SDFTOC_ID(reader); } Dictionary <string, int> Extensions = new Dictionary <string, int>(); for (int i = 0; i < FileEntries.Count; i++) { string ext = Utils.GetExtension(FileEntries[i].FileName); if (!Extensions.ContainsKey(ext)) { Extensions.Add(ext, 1); } else { Extensions[ext]++; } } for (int i = 0; i < FileEntries.Count; i++) { string ext = Utils.GetExtension(FileEntries[i].FileName); if (Extensions[ext] > 10000 && ext != ".mmb") { FileEntries[i].CanLoadFile = false; } files.Add(FileEntries[i]); } List <string> FilteredExtensions = new List <string>(); foreach (var ext in Extensions) { if (ext.Value > 10000 && ext.Key != ".mmb") { FilteredExtensions.Add(ext.Key); } } if (FilteredExtensions.Count > 0) { MessageBox.Show($"File extensions have a very large amount of nodes used." + $" This will be filtered out to prevent slow booting. {ExtsToString(FilteredExtensions.ToArray())}"); } //Remove unused data startId = null; FilteredExtensions.Clear(); Extensions.Clear(); // block1 = new int[0]; // blockIds = new SDFTOC_ID[0]; // endId = null; } }
/// <summary> /// 转换为DataTable(内存流) /// </summary> public static DataTable TranslateToTable(System.IO.Stream stream) { ExcelUtils utils = new ExcelUtils(stream); return(utils.ToDataTable(0)); }
/// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> /// and the specified <c>CompressionLevel</c>, and explicitly specify /// whether the stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive /// stream remain open after the deflation or inflation occurs. By /// default, after <c>Close()</c> is called on the stream, the captive /// stream is also closed. In some cases this is not desired, for example /// if the stream is a <see cref="System.IO.MemoryStream"/> that will be /// re-read after compression. Specify true for the <paramref /// name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a ZlibStream to compress the data from a file, /// and store the result into another file. The filestream remains open to allow /// additional data to be written to it. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress & ".zlib") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n <> 0) /// If (n > 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after /// inflation/deflation. /// </param> /// /// <param name="level"> /// A tuning knob to trade speed for effectiveness. This parameter is /// effective only when mode is <c>CompressionMode.Compress</c>. /// </param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen); }
/// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// The "captive" stream will be closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the /// compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress & ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n <> 0) /// If (n > 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { }
public static NumTrigNumType111 Deserialize(System.IO.Stream s) { return((NumTrigNumType111)(Serializer.Deserialize(s))); }
/// <summary> /// Used by the controlAPI to get a snapshot. We act like a web server. /// I assume that the snapshots are taken infrequently. Hopefully, this API will not be used at 30 fps /// (because of the PNG compression overhead). Note that the overhead is onerous when taking SNAPshots frequently might make sense /// </summary> /// <param name="result"></param> public void sendScreenShot(IAsyncResult result) { // Take the request off the queue and prepare the webserver to accept further requests HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); HttpListenerRequest request = context.Request; String c = request.Url.LocalPath; int width = _bitmapWidth, height = _bitmapHeight; if (request.Url.Query.Length > 0) { String cmd = request.Url.Query.Substring(1).ToUpper(); char[] delimiters = { '=', '&' }; String[] words = cmd.Split(delimiters); // Specify width to scale the screen snapshot if (words.Length == 2) { if ((words[0].Equals("WIDTH"))) { width = Convert.ToInt32(words[1]); if (width <= 0) { width = _bitmapWidth; } else { height = (int)((float)_bitmapHeight * (float)width / (float)_bitmapWidth); } } } if (words.Length == 4) { if ((words[0].Equals("WIDTH"))) { width = Convert.ToInt32(words[1]); if (width <= 0) { width = _bitmapWidth; } else { height = (int)((float)_bitmapHeight * (float)width / (float)_bitmapWidth); } } else { if ((words[2].Equals("WIDTH"))) { width = Convert.ToInt32(words[3]); if (width <= 0) { width = _bitmapWidth; } else { height = (int)((float)_bitmapHeight * (float)width / (float)_bitmapWidth); } } } } } // Fillscreen() is not needed while actively streaming // when there are no players, screen is out of date and refreshed on a new connect. // Since snapshot is asynchronous to that logic, we force a new fill fillScreen(); // Convert the screen to a PNG image Bitmap bmp = new Bitmap(_bitmapWidth, _bitmapHeight, PixelFormat.Format32bppRgb); //Create a BitmapData and Lock all pixels to be written BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); //Copy the data from the byte array into BitmapData.Scan0 System.Runtime.InteropServices.Marshal.Copy(screen, 0, bmpData.Scan0, screen.Length); //Unlock the pixels bmp.UnlockBits(bmpData); if (Program.maskValid == true) { using (Graphics g = Graphics.FromImage(bmp)) { g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; Brush blackBrush = new SolidBrush(Color.Black); // Create array of rectangles. RectangleF[] rects = { new RectangleF(0.0F, 0.0F, _bitmapWidth, Program.maskY), new RectangleF(0.0F, Program.maskY, Program.maskX, Program.maskHeight), new RectangleF(Program.maskX + Program.maskWidth, Program.maskY, _bitmapWidth - Program.maskX - Program.maskWidth, Program.maskHeight), new RectangleF(0.0F, Program.maskY + Program.maskHeight, _bitmapWidth, _bitmapHeight - Program.maskY - Program.maskHeight) }; // Draw rectangles to screen. g.FillRectangles(blackBrush, rects); } } if (width != _bitmapWidth) { Size newsz = new Size(width, height); Bitmap resized = new Bitmap(bmp, newsz); bmp.Dispose(); bmp = resized; } byte[] buffer = null; try { using (MemoryStream stream = new MemoryStream()) { bmp.Save(stream, ImageFormat.Png); buffer = stream.ToArray(); } context.Response.ContentType = "image/png"; context.Response.ContentLength64 = buffer.Length; // context.Response.Headers.Add("Expires", "Sat, 1 Jan 2011 01:01:01 GMT"); } catch { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } context.Response.KeepAlive = false; System.IO.Stream output = context.Response.OutputStream; try { output.Write(buffer, 0, buffer.Length); output.Close(); } catch (Exception) { // Oh well } // Ready to receive the next request listener.BeginGetContext(sendScreenShot, listener); }
/// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the captive stream should be left open after /// Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use /// the default compression level. /// </para> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream /// open. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream">The stream which will be read or written. This is called the /// "captive" stream in other places in this documentation.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain /// open after inflation/deflation.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { }
public Model.ProvisioningTemplate ToProvisioningTemplate(System.IO.Stream template) { return(this.ToProvisioningTemplate(template, null)); }
/// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> /// will use the default compression level. The "captive" stream will be /// closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress a file, and writes the /// compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress & ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n <> 0) /// If (n > 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { }
/// <summary> /// 转换为DataTable(内存流+表名) /// </summary> public static DataTable TranslateToTable(System.IO.Stream stream, string sheetName) { ExcelUtils utils = new ExcelUtils(stream); return(utils.ToDataTable(sheetName)); }
private IList <PakAnass> GetDataLocalUploadExcel(HttpPostedFileBase file, IList <string> errMesgs) { HSSFWorkbook hssfwb = null; using (System.IO.Stream file2 = file.InputStream) { hssfwb = new HSSFWorkbook(file2); } if (hssfwb == null) { throw new ArgumentException("Cannot create Workbook object from excel file" + file.FileName); } IRow row = null; ICell cell = null; IList <PakAnass> listPakanas = new List <PakAnass>(); int indexRow = DATA_ROW_INDEX_START; bool isAllCellEmpty = true; bool isBreak = false; ISheet sheet = hssfwb.GetSheetAt(0); for (indexRow = DATA_ROW_INDEX_START; indexRow <= sheet.LastRowNum; indexRow++) { isAllCellEmpty = true; isBreak = false; row = sheet.GetRow(indexRow); row = sheet.GetRow(indexRow); if (row != null) //null is when the row only contains empty celss { PakAnass Pak = new PakAnass(); //org_code try { cell = row.GetCell(0); if (cell == null || cell.CellType == CellType.BLANK) { cell = row.GetCell(1); if (indexRow != DATA_ROW_INDEX_START && (cell == null || cell.CellType == CellType.BLANK)) { break; } else { errMesgs.Add(string.Format("org_code row {0} is empty", indexRow + 1)); isAllCellEmpty = true; } } else { if (cell.CellType == CellType.NUMERIC) { Pak.org_code = Convert.ToString(cell.NumericCellValue); isAllCellEmpty = false; } else if (cell.CellType == CellType.STRING) { Pak.org_code = cell.StringCellValue; isAllCellEmpty = false; } else { errMesgs.Add(string.Format("org_code row {0} is incorrect Format", indexRow + 1)); isAllCellEmpty = true; } } } catch (Exception ex) { errMesgs.Add(string.Format("Unable To get value of PakAnas No at row {0}, Error Mesg : {1}", indexRow + 1, ex.Message)); } //org_name try { cell = row.GetCell(1); if (cell.CellType == CellType.BLANK) { errMesgs.Add(string.Format("org_name row {0} is empty", indexRow + 1)); isAllCellEmpty = true; } else { if (cell.CellType == CellType.STRING) { Pak.org_name = cell.StringCellValue; isAllCellEmpty = false; } else { errMesgs.Add(string.Format("org_name row {0} is Incorrect Format", indexRow + 1)); isAllCellEmpty = true; } } } catch (Exception ex) { errMesgs.Add(string.Format("Unable to get value of org_name at row {0}, Error Mesg : {1}", indexRow + 1, ex.Message)); isAllCellEmpty = true; } listPakanas.Add(Pak); } } return(listPakanas); }
public void ProcessRequest(HttpContext context) { try { string Code = context.Request.Form["customCode"]; WebClient web = new WebClient(); StreamReader reader = null; //获取公司服务地址 string getCompanyAddress1 = System.Web.Configuration.WebConfigurationManager.AppSettings["getCompanyAddress1"].ToString(); string getCompanyAddress2 = System.Web.Configuration.WebConfigurationManager.AppSettings["getCompanyAddress2"].ToString(); web = new WebClient(); getCompanyAddress1 = getCompanyAddress1 + Code; getCompanyAddress2 = getCompanyAddress2 + Code; //远程获取公司信息 System.IO.Stream getCompany1 = web.OpenRead(getCompanyAddress1); System.IO.Stream getCompany2 = web.OpenRead(getCompanyAddress2); reader = new StreamReader(getCompany1); string strCompany1 = reader.ReadToEnd(); getCompany1.Close(); reader = new StreamReader(getCompany2); string strCompany2 = reader.ReadToEnd(); getCompany2.Close(); reader.Dispose(); if (!strCompany1.Equals("")) { try { //转换为公司对像 JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(strCompany1); PageBase.CompanyData obj = serializer.Deserialize <PageBase.CompanyData>(new JsonTextReader(sr)); context.Response.Write(JsonConvert.SerializeObject(new Data("", obj.FULL_NAME))); } catch (Exception ex) { context.Response.Write(JsonConvert.SerializeObject(new Data("转换企业对像失败:" + strCompany1 + "|" + ex.Message.ToString(), ""))); } } else if (!strCompany2.Equals("")) { try { //转换为公司对像 JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(strCompany2); PageBase.CompanyData obj = serializer.Deserialize <PageBase.CompanyData>(new JsonTextReader(sr)); context.Response.Write(JsonConvert.SerializeObject(new Data("", obj.FULL_NAME))); } catch (Exception ex) { context.Response.Write(JsonConvert.SerializeObject(new Data("转换企业对像失败:" + strCompany2 + "|" + ex.Message.ToString(), ""))); } } else { context.Response.Write(JsonConvert.SerializeObject(new Data("获取公司信息失败!", ""))); } } catch (Exception ex) { context.Response.Write(JsonConvert.SerializeObject(new Data(ex.Message.ToString(), ""))); } }
public static MonoSymbolFile ReadSymbolFile(ModuleDefinition module, System.IO.Stream stream) { return(new MonoSymbolFile(stream, module)); }
public static SectionBaseType Deserialize(System.IO.Stream s) { return((SectionBaseType)(Serializer.Deserialize(s))); }
public static hexBinary_DEtype Deserialize(System.IO.Stream s) { return((hexBinary_DEtype)(Serializer.Deserialize(s))); }
private static void Main(string[] args) { if (!HttpListener.IsSupported) { Console.WriteLine("A more recent Windows version is required to use the HttpListener class."); return; } // Create a listener. HttpListener listener = new HttpListener(); // Trap Ctrl-C and exit Console.CancelKeyPress += delegate { listener.Stop(); System.Environment.Exit(0); }; // Add the prefixes. if (args.Length != 0) { foreach (string s in args) { listener.Prefixes.Add(s); // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy // with netsh http add urlacl url=http://localhost:xxxx/ user="******" // and netsh http add urlacl url=http://localhost:yyyy/ user="******" // user="******" is language dependent, use user=Everyone in english } } else { Console.WriteLine("Syntax error: the call must contain at least one web server url as argument"); } listener.Start(); foreach (string s in args) { Console.WriteLine("Listening for connections on " + s); } while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; string documentContents; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { documentContents = readStream.ReadToEnd(); } } Console.WriteLine($"Received request for {request.Url}"); Console.WriteLine(documentContents); // Obtain a response object. HttpListenerResponse response = context.Response; NameValueCollection headers = context.Request.Headers; Header header = new Header(request.Headers); Console.WriteLine(header); // Construct a response. string responseString = "<HTML><BODY> Hello world!</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); } // Httplistener neither stop ... // listener.Stop(); }
public static byte_Stype Deserialize(System.IO.Stream s) { return((byte_Stype)(Serializer.Deserialize(s))); }
override public void Load(System.IO.Stream fs, Plane sblock) { base.Load(fs, sblock); lodgersCount = (byte)fs.ReadByte(); }
public override void Deserialise(System.IO.Stream inStr) { Deserialise(new BinaryReader(inStr)); }