/// <summary> /// Creates a zip archive from a byte array /// </summary> /// <param name="buffer">The file in byte[] format</param> /// <param name="fileName">The name of the file you want to add to the archive</param> /// <returns></returns> public static byte[] CreateZipByteArray(byte[] buffer, string fileName) { ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream()) { ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream); zipOutputStream.SetLevel(6); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); zipEntry.DateTime = DateTime.Now; zipEntry.Size = buffer.Length; crc.Reset(); crc.Update(buffer); zipEntry.Crc = crc.Value; zipOutputStream.PutNextEntry(zipEntry); zipOutputStream.Write(buffer, 0, buffer.Length); zipOutputStream.Finish(); byte[] zipByteArray = new byte[zipMemoryStream.Length]; zipMemoryStream.Position = 0; zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length); zipOutputStream.Close(); return zipByteArray; } }
public void TestExtractArchiveTarGzCreateContainer() { CloudFilesProvider provider = (CloudFilesProvider)Bootstrapper.CreateObjectStorageProvider(); string containerName = TestContainerPrefix + Path.GetRandomFileName(); string sourceFileName = "DarkKnightRises.jpg"; byte[] content = File.ReadAllBytes("DarkKnightRises.jpg"); using (MemoryStream outputStream = new MemoryStream()) { using (GZipOutputStream gzoStream = new GZipOutputStream(outputStream)) { gzoStream.IsStreamOwner = false; gzoStream.SetLevel(9); using (TarOutputStream tarOutputStream = new TarOutputStream(gzoStream)) { tarOutputStream.IsStreamOwner = false; TarEntry entry = TarEntry.CreateTarEntry(containerName + '/' + sourceFileName); entry.Size = content.Length; tarOutputStream.PutNextEntry(entry); tarOutputStream.Write(content, 0, content.Length); tarOutputStream.CloseEntry(); tarOutputStream.Close(); } } outputStream.Flush(); outputStream.Position = 0; ExtractArchiveResponse response = provider.ExtractArchive(outputStream, "", ArchiveFormat.TarGz); Assert.IsNotNull(response); Assert.AreEqual(1, response.CreatedFiles); Assert.IsNotNull(response.Errors); Assert.AreEqual(0, response.Errors.Count); } using (MemoryStream downloadStream = new MemoryStream()) { provider.GetObject(containerName, sourceFileName, downloadStream, verifyEtag: true); Assert.AreEqual(content.Length, GetContainerObjectSize(provider, containerName, sourceFileName)); downloadStream.Position = 0; byte[] actualData = new byte[downloadStream.Length]; downloadStream.Read(actualData, 0, actualData.Length); Assert.AreEqual(content.Length, actualData.Length); using (MD5 md5 = MD5.Create()) { byte[] contentMd5 = md5.ComputeHash(content); byte[] actualMd5 = md5.ComputeHash(actualData); Assert.AreEqual(BitConverter.ToString(contentMd5), BitConverter.ToString(actualMd5)); } } /* Cleanup */ provider.DeleteContainer(containerName, deleteObjects: true); }
/******************************************************** * CLASS METHODS *********************************************************/ /// <summary> /// /// </summary> /// <param name="zipPath"></param> /// <param name="filenamesAndData"></param> /// <returns></returns> public static bool Zip(string zipPath, System.Collections.Generic.Dictionary<string, string> filenamesAndData) { var success = true; var buffer = new byte[4096]; try { using (var stream = new ZipOutputStream(System.IO.File.Create(zipPath))) { foreach (var filename in filenamesAndData.Keys) { var file = filenamesAndData[filename].GetBytes(); var entry = stream.PutNextEntry(filename); using (var ms = new System.IO.MemoryStream(file)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } stream.Flush(); stream.Close(); } } catch (System.Exception err) { System.Console.WriteLine("Compression.ZipData(): " + err.Message); success = false; } return success; }
/// <summary> /// 将图片转换成字节流 /// </summary> /// <param name="img"></param> /// <returns></returns> private byte[] ImageToByteArr(Image img) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; byte[] imageBytes = new byte[ms.Length]; ms.Read(imageBytes, 0, imageBytes.Length); return imageBytes; } }
private static string SerializeColumnInfo(List<ColumnInfo> arr) { using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(stream, arr); stream.Position = 0; byte[] buffer = new byte[(int)stream.Length]; stream.Read(buffer, 0, buffer.Length); return Convert.ToBase64String(buffer); } }
public void Save(Beetle.BufferWriter writer) { writer.Write(Message.GetType().FullName); byte[] data; using (System.IO.Stream stream = new System.IO.MemoryStream()) { ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(stream, Message); data = new byte[stream.Length]; stream.Position = 0; stream.Read(data, 0, data.Length); } writer.Write(data); }
public System.Windows.Media.Imaging.BitmapImage BitmapToBitMapImage(Bitmap bitmap) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); stream.Position = 0; byte[] data = new byte[stream.Length]; stream.Read(data, 0, Convert.ToInt32(stream.Length)); BitmapImage bmapImage = new BitmapImage(); bmapImage.BeginInit(); bmapImage.StreamSource = stream; bmapImage.EndInit(); return bmapImage; }
public static byte[] GZip(this byte[] bytes) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true); gs.Write(bytes, 0, bytes.Length); gs.Close(); gs.Dispose(); ms.Position = 0; bytes = new byte[ms.Length]; ms.Read(bytes, 0, (int)ms.Length); ms.Close(); ms.Dispose(); return bytes; }
/// <summary> /// Generates a check sum from the serializable object. /// </summary> /// <param name="any">Any object that can be serialized.</param> /// <returns>A check sum.</returns> public static UInt16 GenerateCheckSum(object any) { System.Xml.Serialization.XmlSerializer xser = new System.Xml.Serialization.XmlSerializer(any.GetType()); System.IO.MemoryStream ms = new System.IO.MemoryStream(); xser.Serialize(ms, any); ms.Seek(0, System.IO.SeekOrigin.Begin); byte[] streambytes = new byte[ms.Length]; ms.Read(streambytes, 0, streambytes.Length); UInt16[] ckarray = OrcaLogic.Collections.ArrayConverter.ToUInt16(streambytes); ms.Close(); ms = null; return OrcaLogic.Math.CheckSum.Generate(ckarray, ckarray.Length); }
//*************************************************************************** // Public Methods // public void ProcessRequest(HttpContext context) { HttpRequest req = context.Request; string qsImgUrl = req.QueryString["src"], qsAct = req.QueryString["a"]; bool buttonActive = (string.IsNullOrEmpty(qsAct) || qsAct == "1"); string srcUrl = WebUtil.MapPath(WebUtil.UrlDecode(qsImgUrl)); System.IO.FileInfo fiImg = new System.IO.FileInfo(srcUrl); if (!fiImg.Exists) { context.Response.StatusCode = 404; } else { byte[] imgData = null; string contentType = string.Format("image/{0}", fiImg.Extension.TrimStart('.')); using (System.IO.FileStream fs = fiImg.OpenRead()) { if (buttonActive) { // If the button is active, just load the image directly. imgData = new byte[fs.Length]; fs.Read(imgData, 0, imgData.Length); } else { // If the button is disabled, load the image into a Bitmap object, then run it through the grayscale filter. using (System.Drawing.Bitmap img = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(fs)) using (System.Drawing.Bitmap imgGs = RainstormStudios.Drawing.BitmapFilter.GrayScale(img)) using(System.IO.MemoryStream imgGsStrm = new System.IO.MemoryStream()) { imgGs.Save(imgGsStrm, img.RawFormat); imgData = new byte[imgGsStrm.Length]; imgGsStrm.Read(imgData, 0, imgData.Length); } } } context.Response.StatusCode = 200; context.Response.ContentType = contentType; context.Response.OutputStream.Write(imgData, 0, imgData.Length); } }
/// <summary> /// Generates a check sum from the serializable object. /// </summary> /// <param name="any">Any object that can be serialized.</param> /// <returns>A check sum.</returns> public static UInt16 GenerateCheckSum(object any) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); bf.Serialize(ms, any); ms.Seek(0,System.IO.SeekOrigin.Begin); byte[] streambytes = new byte[ms.Length]; ms.Read(streambytes, 0, streambytes.Length); UInt16[] ckarray = OrcaLogic.Collections.ArrayConverter.ToUInt16(streambytes); ms.Close(); ms = null; bf = null; return OrcaLogic.Math.CheckSum.Generate(ckarray, ckarray.Length); }
/// <summary> /// /// </summary> /// <param name="objectNeedSerialized"></param> /// <param name="formatType"></param> /// <returns></returns> public static byte[] SerializeObjectToBytes(object objectNeedSerialized,SeralizeFormatType formatType) { System.Runtime.Serialization.IFormatter oFormatter = null; if (formatType == SeralizeFormatType.BinaryFormat) oFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); else if (formatType == SeralizeFormatType.XmlFortmat) oFormatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); System.IO.MemoryStream oStream = new System.IO.MemoryStream(); oFormatter.Serialize(oStream, objectNeedSerialized); byte[] oBuffer = new byte[oStream.Length]; oStream.Position = 0; oStream.Read(oBuffer, 0, oBuffer.Length); return oBuffer; }
// // GET: /QR/ /// <summary> /// /// </summary> /// <param name="qrUrl"></param> /// <returns></returns> public ImageResult Index(string qrUrl) { using (var bitmap = EncodeUrl(qrUrl)) { const string contentType = "image/jpg"; byte[] data; using (var stream = new System.IO.MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); stream.Close(); } return this.Image(data, contentType); } }
public static string decriptUrl(string Valor) { string Chave = "#Cho053D4t@R0r!s#"; Valor = Valor.Replace("MAIS", "+"); TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.IV = new byte[8]; PasswordDeriveBytes pdb = new PasswordDeriveBytes(Chave, new byte[-1 + 1]); des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]); byte[] encryptedBytes = Convert.FromBase64String(Valor); System.IO.MemoryStream MS = new System.IO.MemoryStream(Valor.Length); CryptoStream decStreAM = new CryptoStream(MS, des.CreateDecryptor(), CryptoStreamMode.Write); decStreAM.Write(encryptedBytes, 0, encryptedBytes.Length); decStreAM.FlushFinalBlock(); byte[] plainBytes = new byte[Convert.ToInt32(MS.Length - 1) + 1]; MS.Position = 0; MS.Read(plainBytes, 0, Convert.ToInt32(MS.Length)); decStreAM.Close(); return System.Text.Encoding.UTF8.GetString(plainBytes); }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.Clear(); response.ContentType = MimiType; response.AddHeader("content-disposition", String.Format("attachment;filename={0}.{1}", ReportName, FileExt)); byte[] buf = new byte[32768]; using (var spreadsheet = new System.IO.MemoryStream(RenderBytes)) { while (true) { int read = spreadsheet.Read(buf, 0, buf.Length); if (read <= 0) break; response.OutputStream.Write(buf, 0, read); } } response.Flush(); }
/// <summary> /// 将图片转换成字节数组 /// </summary> /// <param name="image"></param> /// <returns></returns> public static byte[] ImageToByte(Image image) { try { Image sceneImage = new Bitmap(image); ////实例化流 System.IO.MemoryStream imageStream = new System.IO.MemoryStream(); //将图片的实例保存到流中 sceneImage.Save(imageStream, ImageFormat.Png); //保存流的二进制数组 byte[] imageContent = new Byte[imageStream.Length]; imageStream.Position = 0; //将流写入数组中 imageStream.Read(imageContent, 0, (int)imageStream.Length); return imageStream.ToArray(); } catch (Exception ex) { throw(ex); } }
public static string criptUrl(string valor) { string chave = "#Cho053D4t@R0r!s#"; TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.IV = new byte[8]; PasswordDeriveBytes pdb = new PasswordDeriveBytes(chave, new byte[-1 + 1]); des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]); System.IO.MemoryStream ms = new System.IO.MemoryStream((valor.Length * 2) - 1); CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(valor); encStream.Write(plainBytes, 0, plainBytes.Length); encStream.FlushFinalBlock(); byte[] encryptedBytes = new byte[Convert.ToInt32(ms.Length - 1) + 1]; ms.Position = 0; ms.Read(encryptedBytes, 0, Convert.ToInt32(ms.Length)); encStream.Close(); string c = null; c = Convert.ToBase64String(encryptedBytes).Replace("+", "MAIS"); return c; }
public void SetType(PieceType type) { this.Type = type; pieceImaging = null; pieceImaging = new System.Windows.Media.Imaging.BitmapImage(); Bitmap tile = this.Color == PieceColor.WHITE ? tileWhites : tileBlack; pieceImage = tile.Clone(new Rectangle(((int)this.Type) * 75, 0, 75, 75), System.Drawing.Imaging.PixelFormat.DontCare); byte[] data; System.IO.MemoryStream stream = new System.IO.MemoryStream(); pieceImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Position = 0; data = new byte[stream.Length]; stream.Read(data, 0, data.Length); pieceImaging.BeginInit(); pieceImaging.StreamSource = stream; pieceImaging.EndInit(); this.Source = pieceImaging; //stream.Close(); }
static byte[] Pbkdf2(string password, byte[] salt, int iterationCount, int derivedKeyLength) { // Pbkdf2 is defined in NIST SP800-132: // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf var passwordBytes = StringToByte(password); using (var hmac = new System.Security.Cryptography.HMACSHA256(passwordBytes)) { Array.Clear(passwordBytes, 0, passwordBytes.Length); int hashLength = hmac.HashSize / 8; if ((hmac.HashSize & 7) != 0) { hashLength++; } if (derivedKeyLength > (0xFFFFFFFFL * hashLength) || derivedKeyLength < 0) { throw new ArgumentOutOfRangeException("derivedKeyLength"); } int keyLength = derivedKeyLength / hashLength; if (derivedKeyLength % hashLength != 0) { keyLength++; } var saltWithIdx = new byte[salt.Length + 4]; Buffer.BlockCopy(salt, 0, saltWithIdx, 0, salt.Length); using (var ms = new System.IO.MemoryStream()) { for (var block = 1; block <= keyLength; block++) { saltWithIdx[saltWithIdx.Length - 4] = (byte)(block >> 24); saltWithIdx[saltWithIdx.Length - 3] = (byte)(block >> 16); saltWithIdx[saltWithIdx.Length - 2] = (byte)(block >> 8); saltWithIdx[saltWithIdx.Length - 1] = (byte)(block); var u = hmac.ComputeHash(saltWithIdx); Array.Clear(saltWithIdx, salt.Length, 4); var f = u; for (var j = 1; j < iterationCount; j++) { u = hmac.ComputeHash(u); for (var k = 0; k < f.Length; k++) { f[k] ^= u[k]; } } ms.Write(f, 0, f.Length); Array.Clear(u, 0, u.Length); Array.Clear(f, 0, f.Length); } Array.Clear(saltWithIdx, 0, saltWithIdx.Length); var derivedKey = new byte[derivedKeyLength]; //Set Key ms.Position = 0; ms.Read(derivedKey, 0, derivedKeyLength); //Clear MemoryStream ms.Position = 0; for (long i = 0; i < ms.Length; i++) { ms.WriteByte(0); } return(derivedKey); } } }
protected override void ReadValue(System.IO.MemoryStream reader, uint byteToRead) { byte[] buff = new byte[byteToRead]; reader.Read(buff, 0, buff.Length); this.Value = buff; }
public static void ParseTransforData(byte[] data) { //参考源码来自 // https://github.com/neo-project/neo // Transaction.cs // 源码采用c#序列化技术 //参考源码2 // https://github.com/AntSharesSDK/antshares-ts // Transaction.ts // 采用typescript开发 System.IO.MemoryStream ms = new System.IO.MemoryStream(data); TransactionType type = (TransactionType)ms.ReadByte();//读一个字节,交易类型 Console.WriteLine("datatype:" + type); byte version = (byte)ms.ReadByte(); Console.WriteLine("dataver:" + version); if (type == TransactionType.ContractTransaction)//每个交易类型有一些自己独特的处理 { //ContractTransaction 就是最常见的合约交易, //他没有自己的独特处理 } else { throw new Exception("未编写针对这个交易类型的代码"); } //attributes var countAttributes = readVarInt(ms); Console.WriteLine("countAttributes:" + countAttributes); for (UInt64 i = 0; i < countAttributes; i++) { //读取attributes byte[] attributeData; var Usage = (TransactionAttributeUsage)ms.ReadByte(); if (Usage == TransactionAttributeUsage.ContractHash || Usage == TransactionAttributeUsage.Vote || (Usage >= TransactionAttributeUsage.Hash1 && Usage <= TransactionAttributeUsage.Hash15)) { attributeData = new byte[32]; ms.Read(attributeData, 0, 32); } else if (Usage == TransactionAttributeUsage.ECDH02 || Usage == TransactionAttributeUsage.ECDH03) { attributeData = new byte[33]; attributeData[0] = (byte)Usage; ms.Read(attributeData, 1, 32); } else if (Usage == TransactionAttributeUsage.Script) { attributeData = new byte[20]; ms.Read(attributeData, 0, 20); } else if (Usage == TransactionAttributeUsage.DescriptionUrl) { var len = (byte)ms.ReadByte(); attributeData = new byte[len]; ms.Read(attributeData, 0, len); } else if (Usage == TransactionAttributeUsage.Description || Usage >= TransactionAttributeUsage.Remark) { var len = (int)readVarInt(ms, 65535); attributeData = new byte[len]; ms.Read(attributeData, 0, len); } else { throw new FormatException(); } } //inputs 输入表示基于哪些交易 var countInputs = readVarInt(ms); Console.WriteLine("countInputs:" + countInputs); for (UInt64 i = 0; i < countInputs; i++) { byte[] hash = new byte[32]; byte[] buf = new byte[2]; ms.Read(hash, 0, 32); ms.Read(buf, 0, 2); UInt16 index = (UInt16)(buf[1] * 256 + buf[0]); hash = hash.Reverse().ToArray();//反转 var strhash = Bytes2HexString(hash); Console.WriteLine(" input:" + strhash + " index:" + index); } //outputes 输出表示最后有哪几个地址得到多少钱,肯定有一个是自己的地址,因为每笔交易都会把之前交易的余额清空,刨除自己,就是要转给谁多少钱 //这个机制叫做UTXO var countOutputs = readVarInt(ms); Console.WriteLine("countOutputs:" + countOutputs); for (UInt64 i = 0; i < countOutputs; i++) { //资产种类 var assetid = new byte[32]; ms.Read(assetid, 0, 32); assetid = assetid.Reverse().ToArray(); //反转 Int64 value = 0; //钱的数字是一个定点数,乘以D Int64 D = 100000000; byte[] buf = new byte[8]; ms.Read(buf, 0, 8); value = BitConverter.ToInt64(buf, 0); decimal number = ((decimal)value / (decimal)D); if (number <= 0) { throw new FormatException(); } //资产数量 var scripthash = new byte[20]; ms.Read(scripthash, 0, 20); var address = GetAddressFromScriptHash(scripthash); Console.WriteLine(" output" + i + ":" + Bytes2HexString(assetid) + "=" + number); Console.WriteLine(" address:" + address); } }
//public static byte[] SaveImageToByteArray(Image images, int jpegQuality = 75) //{ // //System.Web.UI.WebControls.Image images = new System.Web.UI.WebControls.Image(); // using (var ms = new MemoryStream()) // { // var jpegEncoder = GetEncoder(ImageFormat.Jpeg); // var encoderParameters = new EncoderParameters(1); // encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)jpegQuality); // images.Save(ms, jpegEncoder, encoderParameters); // return ms.ToArray(); // } //} //private Image getImageFromBytes(byte[] myByteArray) //{ // System.IO.MemoryStream newImageStream = new System.IO.MemoryStream(myByteArray, 0, myByteArray.Length); // Image image = Image.FromStream(newImageStream, true); // Bitmap resized = new Bitmap(image, image.Width / 2, image.Height / 2); // image.Dispose(); // newImageStream.Dispose(); // return resized; //} protected void btnPrueba_Click(object sender, EventArgs e) { //if (FUDiscoDuro.HasFile) //{ // // Find the fileUpload control // string filename = FUDiscoDuro.FileName; // // Check if the directory we want the image uploaded to actually exists or not // if (!Directory.Exists(MapPath(@"Uploaded-Files"))) // { // // If it doesn't then we just create it before going any further // Directory.CreateDirectory(MapPath(@"Uploaded-Files")); // } // // Specify the upload directory // string directory = Server.MapPath(@"Uploaded-Files\"); // // Create a bitmap of the content of the fileUpload control in memory // Bitmap originalBMP = new Bitmap(FUDiscoDuro.FileContent); // // Calculate the new image dimensions // int origWidth = originalBMP.Width; // int origHeight = originalBMP.Height; // int sngRatio = origWidth / origHeight; // int newWidth = 100; // int newHeight = newWidth / sngRatio; // //int newWidth = 100; // //int newHeight = newWidth / sngRatio; // // Create a new bitmap which will hold the previous resized bitmap // Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight); // // Create a graphic based on the new bitmap // Graphics oGraphics = Graphics.FromImage(newBMP); // // Set the properties for the new graphic file // oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; // // Draw the new graphic based on the resized bitmap // oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); // // Save the new graphic file to the server // newBMP.Save(directory + "tn_" + filename); // // Once finished with the bitmap objects, we deallocate them. // originalBMP.Dispose(); // newBMP.Dispose(); // oGraphics.Dispose(); // //Image1.ImageUrl = @"/Uploaded-Files/tn_" + filename; //} //IMAGENES1 //String vNombreDepot1 = String.Empty; //HttpPostedFile bufferDeposito1 = FUDiscoDuro.PostedFile; //byte[] vFileDeposito1 = null; //string vExtension1 = string.Empty; //if (bufferDeposito1 != null) //{ // vNombreDepot1 = FUDiscoDuro.FileName; // Stream vStream1 = bufferDeposito1.InputStream; // BinaryReader vReader1 = new BinaryReader(vStream1); // vFileDeposito1 = vReader1.ReadBytes((int)vStream1.Length); // vExtension1 = System.IO.Path.GetExtension(FUDiscoDuro.FileName); //} //String vArchivo1 = String.Empty; //if (vFileDeposito1 != null) // vArchivo1 = Convert.ToBase64String(vFileDeposito1); Bitmap originalBMP = new Bitmap(FUDiscoDuro.FileContent); byte[] imageData; var newSize = originalBMP.Width / 3; //var newHeight = originalBMP.Height * newSize / originalBMP.Width; var newHeight = originalBMP.Height / 3; //newSize = originalBMP.Width*3; //newSize = originalBMP.Width * newSize / originalBMP.Height; Bitmap originalBMP2 = new Bitmap(originalBMP.GetThumbnailImage(newSize, newHeight, null, IntPtr.Zero)); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { originalBMP.Save(stream, ImageFormat.Jpeg); stream.Position = 0; imageData = new byte[stream.Length]; stream.Read(imageData, 0, imageData.Length); stream.Close(); } string vArchivo1 = Convert.ToBase64String(imageData); // Bitmap newImage = new Bitmap(newWidth, newHeight); //using (Graphics gr = Graphics.FromImage(newImage)) //{ // gr.SmoothingMode = SmoothingMode.HighQuality; // gr.InterpolationMode = InterpolationMode.HighQualityBicubic; // gr.PixelOffsetMode = PixelOffsetMode.HighQuality; // gr.DrawImage(imgDiscoDuro, new Rectangle(0, 0, newWidth, newHeight)); //} string vQuery = "[STEISP_ATM_Generales] 42, '" + vArchivo1 + "'"; Int32 vInfo = vConexion.ejecutarSQL(vQuery); DataTable vDatos2 = new DataTable(); String vQuery2 = "STEISP_ATM_Generales 43"; vDatos2 = vConexion.ObtenerTabla(vQuery2); foreach (DataRow item in vDatos2.Rows) { string vImagen1 = item["IMG"].ToString(); string srcImgen1 = "data:image;base64," + vImagen1; imgDiscoDuro.Src = srcImgen1; } }
/// <summary> /// 指定したオブジェクトを指定した型として文字列に変換します。 /// </summary> /// <param name="t">変換元のオブジェクトの型を指定します。</param> /// <param name="value">変換元のオブジェクトを指定します。</param> /// <returns>変換後の文字列を返します。</returns> public static string From(System.Type t, object value) { switch (Types.GetTypeCode(t)) { case TypeCodes.SByte: return(FromSByte((sbyte)value)); case TypeCodes.Byte: return(FromByte((byte)value)); case TypeCodes.Short: return(FromInt16((short)value)); case TypeCodes.UShort: return(FromUInt16((ushort)value)); case TypeCodes.Int: return(FromInt32((int)value)); case TypeCodes.UInt: return(FromUInt32((uint)value)); case TypeCodes.Long: return(FromInt64((long)value)); case TypeCodes.ULong: return(FromUInt64((ulong)value)); case TypeCodes.Decimal: return(FromDecimal((decimal)value)); case TypeCodes.Float: return(FromSingle((float)value)); case TypeCodes.Double: return(FromDouble((double)value)); case TypeCodes.Bool: return(FromBoolean((bool)value)); case TypeCodes.Char: return(FromChar((char)value)); case TypeCodes.String: return((string)value); case TypeCodes.Guid: return(FromGuid((System.Guid)value)); case TypeCodes.TimeSpan: return(FromTimeSpan((System.TimeSpan)value)); //.NET Framework 2.0 : System.Xml.XmlDateTimeSerializationMode を指定 case TypeCodes.DateTime: return(FromDateTime((System.DateTime)value)); case TypeCodes.IntPtr: return(FromInt64((long)(System.IntPtr)value)); case TypeCodes.UIntPtr: return(FromUInt64((ulong)(System.UIntPtr)value)); case TypeCodes.BoolArray: return(FromBooleanArray((bool[])value)); case TypeCodes.ByteArray: return(FromByteArray((byte[])value)); case TypeCodes.Type: return(((System.Type)value).FullName); default: // typeconv: if (t.IsEnum) { return(value.ToString()); //System.Enum } if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0) { goto serial; } System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t); if (conv.CanConvertTo(typeof(string)) && conv.CanConvertFrom(typeof(string))) { try{ return(conv.ConvertToString(value)); }catch {} } serial: if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0) { goto op_implicit; } using (System.IO.MemoryStream memstr = new System.IO.MemoryStream()){ binF.Serialize(memstr, value); //--長さ int len; try{ len = (int)memstr.Length; }catch (System.Exception e) { throw new System.Exception("データの量が大きすぎるので文字列に変換できません", e); } //--文字列に変換 byte[] buff = new byte[len]; memstr.Position = 0; memstr.Read(buff, 0, len); return(System.Convert.ToBase64String(buff)); } op_implicit: System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic); for (int i = 0; i < ms.Length; i++) { if (ms[i].Name != "op_Implicit" || ms[i].ReturnType != typeof(string)) { continue; } System.Reflection.ParameterInfo[] ps = ms[i].GetParameters(); if (ps.Length != 1 || ps[0].ParameterType != t) { continue; } return((string)ms[i].Invoke(null, new object[] { value })); } throw new System.ArgumentException(string.Format(TOSTR_NOTSUPPORTEDTYPE, t), "t"); } }
private void OnProcessRequest(object sender, CfxProcessRequestEventArgs e) { var request = e.Request; var uri = new Uri(request.Url); var headers = request.GetHeaderMap().Select(x => new { Key = x[0], Value = x[1] }).ToList(); var contentRange = headers.FirstOrDefault(x => x.Key.ToLower() == "range"); if (contentRange != null) { var group = System.Text.RegularExpressions.Regex.Match(contentRange.Value, @"(?<start>\d+)-(?<end>\d*)").Groups; if (group != null) { int startPos, endPos; if (!string.IsNullOrEmpty(group["start"].Value) && int.TryParse(group["start"].Value, out startPos)) { buffStartPostition = startPos; } if (!string.IsNullOrEmpty(group["end"].Value) && int.TryParse(group["end"].Value, out endPos)) { buffEndPostition = endPos; } } isPartContent = true; } readResponseStreamOffset = 0; if (buffStartPostition.HasValue) { readResponseStreamOffset = buffStartPostition.Value; } var filePath = Uri.UnescapeDataString(uri.AbsolutePath); if (string.IsNullOrEmpty(CgiResource.Domain)) { filePath = string.Format("{0}{1}", uri.Authority, filePath); } filePath = filePath.Trim('/'); var scriptName = filePath; var physicalPath = System.IO.Path.Combine(documentRoot, filePath); if (!System.IO.File.Exists(physicalPath)) { scriptName = ""; physicalPath = documentRoot; string[] splitPath = filePath.Split('/'); foreach (string fileName in splitPath) { var realPath = System.IO.Path.Combine(physicalPath, fileName); if (!System.IO.Directory.Exists(realPath) && !System.IO.File.Exists(realPath)) { break; } scriptName += "/" + fileName; physicalPath = realPath; } } if (System.IO.Directory.Exists(physicalPath)) { var realPath = System.IO.Path.Combine(physicalPath, scriptIndex); if (System.IO.File.Exists(realPath)) { scriptName += "/" + scriptIndex; physicalPath = realPath; } } if (System.IO.File.Exists(physicalPath)) { var fileExt = System.IO.Path.GetExtension(physicalPath); if (fileExt == scriptExt) { var process = new System.Diagnostics.Process(); process.StartInfo.Arguments = physicalPath; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = execgiPath; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.WorkingDirectory = documentRoot; process.StartInfo.EnvironmentVariables.Add("SERVER_SOFTWARE", "PhpWin"); process.StartInfo.EnvironmentVariables.Add("SERVER_NAME", uri.Host); process.StartInfo.EnvironmentVariables.Add("SERVER_PORT", uri.Port.ToString()); process.StartInfo.EnvironmentVariables.Add("SERVER_PROTOCOL", "HTTP/1.1"); process.StartInfo.EnvironmentVariables.Add("HTTP_HOST", uri.Host); process.StartInfo.EnvironmentVariables.Add("GATEWAY_INTERFACE", "CGI/1.1"); process.StartInfo.EnvironmentVariables.Add("REQUEST_METHOD", request.Method); if (uri.Query.Length > 1) { process.StartInfo.EnvironmentVariables.Add("QUERY_STRING", uri.Query.Substring(1)); } process.StartInfo.EnvironmentVariables.Add("REQUEST_URI", string.Format("/{0}{1}", filePath, uri.Query)); if (filePath.Length > scriptName.Length) { process.StartInfo.EnvironmentVariables.Add("PATH_INFO", filePath.Substring(scriptName.Length - 1)); } process.StartInfo.EnvironmentVariables.Add("SCRIPT_NAME", scriptName); process.StartInfo.EnvironmentVariables.Add("DOCUMENT_URI", "/" + filePath); process.StartInfo.EnvironmentVariables.Add("DOCUMENT_ROOT", documentRoot); process.StartInfo.EnvironmentVariables.Add("SCRIPT_FILENAME", physicalPath); process.StartInfo.EnvironmentVariables.Add("REDIRECT_STATUS", "200"); foreach (var item in headers) { if (item.Key == "PROXY") { continue; } if (item.Key.ToUpper() == "CONTENT-TYPE") { process.StartInfo.EnvironmentVariables.Add("CONTENT_TYPE", item.Value); } else { process.StartInfo.EnvironmentVariables.Add("HTTP_" + item.Key.Replace("-", "_").ToUpper(), item.Value); } } ulong contentLength = 0; if (request.PostData != null) { foreach (var element in request.PostData.Elements) { if (element.Type == CfxPostdataElementType.Bytes) { contentLength += element.BytesCount; } else if (element.Type == CfxPostdataElementType.File) { var fileInfo = new System.IO.FileInfo(element.File); contentLength += Convert.ToUInt64(fileInfo.Length); } } } process.StartInfo.EnvironmentVariables.Add("CONTENT_LENGTH", contentLength.ToString()); if (process.Start()) { if (request.PostData != null && contentLength > 0) { foreach (var element in request.PostData.Elements) { if (element.Type == CfxPostdataElementType.Bytes) { var buffer = new byte[element.BytesCount]; GCHandle hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr pBuffer = hBuffer.AddrOfPinnedObject(); var count = element.GetBytes(element.BytesCount, pBuffer); process.StandardInput.Write(Encoding.ASCII.GetChars(buffer, 0, Convert.ToInt32(count))); if (hBuffer.IsAllocated) { hBuffer.Free(); } } else if (element.Type == CfxPostdataElementType.File) { try { var buffer = System.IO.File.ReadAllBytes(element.File); process.StandardInput.BaseStream.Write(buffer, 0, Convert.ToInt32(buffer.Length)); } catch (Exception ex) { MessageBox.Show(ex.Message); e.Callback.Dispose(); e.SetReturnValue(false); return; } } } } } using (var output = new System.IO.MemoryStream()) { int read; byte[] buffer = new byte[16 * 1024]; var stream = process.StandardOutput.BaseStream; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } output.Seek(0, System.IO.SeekOrigin.Begin); var offset = 0; var reader = new System.IO.StreamReader(output); while (!reader.EndOfStream) { var readline = reader.ReadLine(); offset += readline.Length + 2; if (readline.Equals("")) { break; } var header = readline.Split(':'); if (header.Length < 2) { break; } header[1] = header[1].Trim(); if (header[0].ToUpper() == "CONTENT-TYPE") { mimeType = header[1].Split(';')[0].Trim(); } else if (header[0].ToUpper() == "STATUS") { httpStatus = int.Parse(header[1].Split(' ')[0]); } else if (header[0].ToUpper() == "LOCATION") { if (header[1].StartsWith("/")) { redirectUrl = CgiResource.GetFullUrl(header[1]); } else { redirectUrl = header[1]; } } scriptHeaders.Add(header); } var count = output.Length - offset; data = new byte[count]; output.Seek(offset, System.IO.SeekOrigin.Begin); output.Read(data, 0, Convert.ToInt32(count)); } } else { data = System.IO.File.ReadAllBytes(physicalPath); mimeType = CfxRuntime.GetMimeType(fileExt.TrimStart('.')); } e.Callback.Continue(); e.SetReturnValue(true); } else { e.Callback.Continue(); e.SetReturnValue(false); } }
/// <summary> /// HttpWebRequest读取网页 字符集将自动匹配如果找不倒指定字符集,则使用utf-8 /// </summary> /// <param name="url">url</param> /// <param name="parament">一个用于区分的参数 </param> private static string GetWeb(string url, string encoding) { string strHtmlContent = ""; System.IO.Stream mystream = new System.IO.MemoryStream(); System.Net.HttpWebRequest myrequest = null; try { myrequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); //字符集编码 if (url.IndexOf("http") == -1)//如果米有HTTP { throw new Exception("请提供完整的HTTP地址"); } myrequest.Timeout = 20 * 1000;//超时时间 20秒 //设置没有缓存 myrequest.Headers.Set("Pragma", "no-cache"); System.Net.HttpWebResponse myresponse = null; if (myrequest.KeepAlive) { try { myresponse = (System.Net.HttpWebResponse)myrequest.GetResponse(); mystream = myresponse.GetResponseStream(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(DateTime.Now + "获取网页内容出错:url:" + url + "\r\n" + ex.Message + " " + (ex.StackTrace == null ? " " : " " + ex.StackTrace)); return(strHtmlContent); } } //用于读取数据的内存流 System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); #region 自动判断编码字符集 //查看流长时是不是有效数据 int len = 0; byte[] buff = new byte[512]; while ((len = mystream.Read(buff, 0, buff.Length)) > 0) { memoryStream.Write(buff, 0, len); } if (memoryStream.Length > 0) { //设置流指向头 memoryStream.Seek(0, System.IO.SeekOrigin.Begin); int DetLen = 0; //编码字符体的buffer 默认需要4KB的数据 byte[] DetectBuff = new byte[4096]; //开始取得编码 UniversalDetector Det = new UniversalDetector(null); //从当前流中读取块并写入到buff中 while ((DetLen = memoryStream.Read(DetectBuff, 0, DetectBuff.Length)) > 0 && !Det.IsDone()) { Det.HandleData(DetectBuff, 0, DetectBuff.Length); } Det.DataEnd(); //得到字符集合 if (Det.GetDetectedCharset() != null) { if (encoding == "") { //得到字符集 encoding = Det.GetDetectedCharset(); } } //设置流指向头 memoryStream.Seek(0, System.IO.SeekOrigin.Begin); } #endregion System.Text.Encoding myencoding = System.Text.Encoding.GetEncoding(encoding); System.IO.StreamReader mystreamreader = new System.IO.StreamReader(memoryStream, myencoding); strHtmlContent = mystreamreader.ReadToEnd(); mystreamreader.Dispose(); if (myresponse != null) { myresponse.Close(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(DateTime.Now + "获取网页内容出错:url:" + url + "\r\n" + ex.Message + " " + (ex.StackTrace == null ? " " : " " + ex.StackTrace)); } finally { mystream.Close(); mystream.Dispose(); // HttpWebRequest 不会自己销毁对象 //销毁关闭连接 if (myrequest != null) { myrequest.Abort(); } } return(strHtmlContent); }
/// <summary> /// 获得消息包的字节流 /// </summary> /// <param name="remoteIp">远程主机地址</param> /// <param name="packageNo">包编号</param> /// <param name="command">命令</param> /// <param name="options">参数</param> /// <param name="userName">用户名</param> /// <param name="hostName">主机名</param> /// <param name="content">正文消息</param> /// <param name="extendContents">扩展消息</param> /// <returns></returns> public static Entity.PackedNetworkMessage[] BuildNetworkMessage(IPEndPoint remoteIp, ulong packageNo, Define.Consts.Commands command, ulong options, string userName, string hostName, byte[] content, byte[] extendContents) { options |= (ulong)Define.Consts.Cmd_Send_Option.Content_Unicode; //每次发送所能容下的数据量 int maxBytesPerPackage = Define.Consts.MAX_UDP_PACKAGE_LENGTH - PackageHeaderLength; //压缩数据流 System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(zip, System.Text.Encoding.Unicode); //写入头部数据 bw.Write(packageNo); //包编号 bw.Write(((ulong)command) | options); //命令|选项 bw.Write(userName); //用户名 bw.Write(hostName); //主机名 bw.Write(content == null ? 0 : content.Length); //数据长度 //写入消息数据 if (content != null) { bw.Write(content); } bw.Write(extendContents == null ? 0 : extendContents.Length); //补充数据长度 if (extendContents != null) { bw.Write(extendContents); } bw.Close(); zip.Close(); ms.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); //打包数据总量 int dataLength = (int)ms.Length; int packageCount = (int)Math.Ceiling(dataLength * 1.0 / maxBytesPerPackage); Entity.PackedNetworkMessage[] pnma = new PackedNetworkMessage[packageCount]; for (int i = 0; i < packageCount; i++) { int count = i == packageCount - 1 ? dataLength - maxBytesPerPackage * (packageCount - 1) : maxBytesPerPackage; byte[] buf = new byte[count + PackageHeaderLength]; buf[0] = VersionHeader; BitConverter.GetBytes(packageNo).CopyTo(buf, 1); BitConverter.GetBytes(dataLength).CopyTo(buf, 9); BitConverter.GetBytes(packageCount).CopyTo(buf, 13); BitConverter.GetBytes(i).CopyTo(buf, 17); buf[21] = Define.Consts.Check(options, Define.Consts.Cmd_All_Option.RequireReceiveCheck) ? (byte)1 : (byte)0; //包确认标志? ms.Read(buf, 32, buf.Length - 32); pnma[i] = new Entity.PackedNetworkMessage() { Data = buf, PackageCount = packageCount, PackageIndex = i, PackageNo = packageNo, RemoteIP = remoteIp, SendTimes = 0, Version = 2, IsReceiveSignalRequired = buf[21] == 1 }; } ms.Close(); return(pnma); }
public JobOutcome Execute(IJobProcessorServices context, IJob job) { var wsm = context.Connection.WebServiceManager; #region Property Definitions var propDefs = wsm.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE"); var propDefInternalId = propDefs.Single(n => n.DispName == "Internal ID"); var propDefProvider = propDefs.Single(n => n.DispName == "Provider"); var propDefOriginalCreateDate = propDefs.Single(n => n.DispName == "Original Create Date"); #endregion #region Search Conditions var srchCondInternalId = new SrchCond { PropDefId = propDefInternalId.Id, PropTyp = PropertySearchType.SingleProperty, SrchOper = 4, // Is empty SrchRule = SearchRuleType.Must }; var srchCondInternalProvider = new SrchCond { PropDefId = propDefProvider.Id, PropTyp = PropertySearchType.SingleProperty, SrchOper = 3, // Is exactly (or equals) SrchRule = SearchRuleType.Must, SrchTxt = "Inventor" }; var srchCondDateTime = new SrchCond { PropDefId = propDefOriginalCreateDate.Id, PropTyp = PropertySearchType.SingleProperty, SrchOper = 7, // Greater than or equal to SrchRule = SearchRuleType.Must, SrchTxt = DateTime.Now.AddDays(-15).ToUniversalTime().ToString( "MM/dd/yyyy HH:mm:ss") }; #endregion string bookmark = null; SrchStatus status = null; var files = new List <File>(); while (status == null || files.Count < status.TotalHits) { var results = wsm.DocumentService.FindFilesBySearchConditions( new[] { srchCondInternalId, srchCondInternalProvider, srchCondDateTime }, null, null, false, true, ref bookmark, out status); if (results != null) { files.AddRange(results); } else { break; } } foreach (var file in files) { var localFilePath = string.Format(@"C:\temp\{0}", file.Name); try { #region Download file var fileSize = file.FileSize; var maxPartSize = wsm.FilestoreService.GetMaximumPartSize(); var ticket = wsm.DocumentService.GetDownloadTicketsByMasterIds( new[] { file.MasterId })[0]; byte[] bytes; using (var stream = new System.IO.MemoryStream()) { var startByte = 0; while (startByte < fileSize) { var endByte = startByte + maxPartSize; if (endByte > fileSize) { endByte = fileSize; } using (var filePart = wsm.FilestoreService.DownloadFilePart( ticket.Bytes, startByte, endByte, true)) { byte[] buffer = StreamToByteArray(filePart); stream.Write(buffer, 0, buffer.Length); startByte += buffer.Length; } } bytes = new byte[stream.Length]; stream.Seek(0, System.IO.SeekOrigin.Begin); stream.Read(bytes, 0, (int)stream.Length); stream.Close(); } System.IO.File.WriteAllBytes(localFilePath, bytes); #endregion #region Get InternalName var internalId = Apprentice.GetInternalId(localFilePath); #endregion #region Update properties var util = Autodesk.Connectivity.Explorer.ExtensibilityTools.ExplorerLoader. LoadExplorerUtil( wsm.WebServiceCredentials.ServerIdentities.DataServer, wsm.WebServiceCredentials.VaultName, context.Connection.UserID, context.Connection.Ticket); var properties = new Dictionary <PropDef, object> { { propDefInternalId, internalId } }; util.UpdateFileProperties(file, properties); #endregion } catch (Exception ex) { Console.WriteLine(ex); } finally { #region Delete local file if (System.IO.File.Exists(localFilePath)) { try { System.IO.File.Delete(localFilePath); } catch (Exception ex) { Console.WriteLine(ex); } } #endregion } } return(JobOutcome.Success); }
private void BuildListView( ) { try { if (this.InvokeRequired) { this.Invoke(new SetControlVisibleDelegate(SetControlVisible), new object[] { loadingPanel, true }); this.Invoke(new DroidExplorer.UI.GenericDelegate(packagesList.Items.Clear)); } else { SetControlVisible(loadingPanel, true); packagesList.Items.Clear( ); } List <DroidExplorer.Core.AaptBrandingCommandResult> apks = CommandRunner.Instance.GetInstalledPackagesApkInformation( ); foreach (var item in apks) { ApkPackageListViewItem lvi = new ApkPackageListViewItem(item); // cant uninstall if we dont know the package if (string.IsNullOrEmpty(lvi.ApkInformation.Package)) { continue; } string keyName = lvi.ApkInformation.DevicePath; if (keyName.StartsWith("/")) { keyName = keyName.Substring(1); } keyName = keyName.Replace("/", "."); if (!Program.SystemIcons.ContainsKey(keyName)) { // get apk and extract the app icon Image img = CommandRunner.Instance.GetLocalApkIconImage(item.LocalApk); if (img == null) { img = DroidExplorer.Resources.Images.package32; } else { using (System.IO.MemoryStream stream = new System.IO.MemoryStream( )) { string fileName = System.IO.Path.Combine(System.IO.Path.Combine(CommandRunner.Settings.UserDataDirectory, Cache.APK_IMAGE_CACHE), string.Format("{0}.png", keyName)); img.Save(stream, ImageFormat.Png); stream.Position = 0; using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { byte[] buffer = new byte[2048]; int readBytes = 0; while ((readBytes = stream.Read(buffer, 0, buffer.Length)) != 0) { fs.Write(buffer, 0, readBytes); } } } } SystemImageListHost.Instance.AddFileTypeImage(keyName, img, img); } if (this.InvokeRequired) { this.Invoke(new SetListViewItemImageIndexDelegate(this.SetListViewItemImageIndex), new object[] { lvi, Program.SystemIcons[keyName] }); this.Invoke(new AddListViewItemDelegate(this.AddListViewItem), new object[] { packagesList, lvi }); } else { SetListViewItemImageIndex(lvi, Program.SystemIcons[keyName]); AddListViewItem(packagesList, lvi); } } } catch (Exception ex) { this.LogError(ex.Message, ex); } finally { if (this.InvokeRequired) { this.Invoke(new SetControlVisibleDelegate(SetControlVisible), new object[] { loadingPanel, false }); } else { SetControlVisible(loadingPanel, false); } } }
/// <summary> /// Creates a JpegFrame from a System.Drawing.Image /// </summary> /// <param name="source">The Image to create a JpegFrame from</param> public JpegFrame(System.Drawing.Image source, uint quality = 100, uint?ssrc = null, uint?sequenceNo = null, uint?timeStamp = null) : this() { //Must calculate correctly the Type, Quality, FragmentOffset and Dri uint TypeSpecific = 0, Type = 0, Quality = quality, Width = (uint)source.Width, Height = (uint)source.Height; byte[] RestartInterval = null; List <byte> QTables = new List <byte>(); //Save the image in Jpeg format and request the PropertyItems from the Jpeg format of the Image using (System.IO.MemoryStream temp = new System.IO.MemoryStream()) { //Create Encoder Parameters for the Jpeg Encoder System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(3); // Set the quality parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality); // Set the render method to Progressive parameters.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)System.Drawing.Imaging.EncoderValue.RenderProgressive); // Set the scan method to Progressive parameters.Param[2] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ScanMethod, (int)System.Drawing.Imaging.EncoderValue.ScanMethodNonInterlaced); //Determine if there are multiple frames in the image //if(source.FrameDimensionsList.Count() > 0) //{ // System.Drawing.Imaging.FrameDimension dimension = new System.Drawing.Imaging.FrameDimension(source.FrameDimensionsList[0]); // int frameCount = source.GetFrameCount(dimension); // if (frameCount > 1) // { // ///Todo - Handle Multiple Frames from a System.Drawing.Image (Gif) // ///Perhaps the sender should just SetActiveFrame and then we will use the active frame // } //} if (source.Width > JpegFrame.MaxWidth || source.Height > JpegFrame.MaxHeight) { using (System.Drawing.Image thumb = source.GetThumbnailImage(JpegFrame.MaxWidth, JpegFrame.MaxHeight, null, IntPtr.Zero)) { //Save the source to the temp stream using the jpeg coded and given encoder params thumb.Save(temp, JpegCodecInfo, parameters); } } else { //Save the source to the temp stream using the jpeg coded and given encoder params source.Save(temp, JpegCodecInfo, parameters); } //Check for the EOI Marker temp.Seek(-1, System.IO.SeekOrigin.Current); //If present we will ignore it when creating the packets long endOffset = temp.ReadByte() == Tags.EndOfInformation ? temp.Length - 2 : temp.Length; //Enure at the beginning temp.Seek(0, System.IO.SeekOrigin.Begin); //Read the JPEG Back from the stream so it's pixel format is JPEG Image = System.Drawing.Image.FromStream(temp, false, true); //Determine if there are Quantization Tables which must be sent if (Image.PropertyIdList.Contains(0x5090) && Image.PropertyIdList.Contains(0x5091)) { //QTables.AddRange((byte[])Image.GetPropertyItem(0x5090).Value); //16 bit //QTables.AddRange((byte[])Image.GetPropertyItem(0x5091).Value); //16 bit //This is causing the QTables to be read on the reciever side Quality |= 128; } else { //Values less than 128 cause QTables to be generated on reciever side Quality = 127; } //Determine if there is a DataRestartInterval if (Image.PropertyIdList.Contains(0x0203)) { RestartInterval = Image.GetPropertyItem(0x0203).Value; Type = 64; } else { Type = 63; } //used for reading the JPEG data int Tag, TagSize, //The max size of each Jpeg RtpPacket (Allow for any overhead) BytesInPacket = RtpPacket.MaxPayloadSize - 200; //The current packet RtpPacket currentPacket = new RtpPacket(temp.Length < BytesInPacket ? (int)temp.Length : BytesInPacket); SynchronizationSourceIdentifier = currentPacket.SynchronizationSourceIdentifier = (ssrc ?? (uint)SynchronizationSourceIdentifier); currentPacket.TimeStamp = (uint)(timeStamp ?? Utility.DateTimeToNptTimestamp(DateTime.UtcNow)); currentPacket.SequenceNumber = (ushort)(sequenceNo ?? 1); currentPacket.PayloadType = JpegFrame.RtpJpegPayloadType; //Where we are in the current packet int currentPacketOffset = 0; //Determine if we need to write OnVif Extension? if (Width > MaxWidth || Height > MaxHeight) { //packet.Extensions = true; //Write Extension Headers } //Ensure at the begining temp.Seek(0, System.IO.SeekOrigin.Begin); //Find a Jpeg Tag while we are not at the end of the stream //Tags come in the format 0xFFXX while ((Tag = temp.ReadByte()) != -1) { //If the prefix is a tag prefix then read another byte as the Tag if (Tag == Tags.Prefix) { //Get the Tag Tag = temp.ReadByte(); //If we are at the end break if (Tag == -1) { break; } //Determine What to do for each Tag //Start and End Tag (No Length) if (Tag == Tags.StartOfInformation) { continue; } else if (Tag == Tags.EndOfInformation) { break; } //Read Length Bytes byte h = (byte)temp.ReadByte(), l = (byte)temp.ReadByte(); //Calculate Length TagSize = h * 256 + l; //Correct Length TagSize -= 2; //Not including their own length //QTables are copied when Quality is > 127 if (Tag == Tags.QuantizationTable && Quality > 127) { //byte Precision = (byte)temp.ReadByte();//Discard Precision //if (Precision != 0) throw new Exception("Only 8 Bit Precision is Supported"); temp.ReadByte();//Discard Table Id (And Precision which is in the same byte) byte[] table = new byte[TagSize - 1]; temp.Read(table, 0, TagSize - 1); QTables.AddRange(table); } else if (Tag == Tags.DataRestartInterval) //RestartInterval is copied { //Make DRI? //Type = 64; //RestartInterval = CreateRtpDataRestartIntervalMarker((int)temp.Length, 1, 1, 0x3fff); throw new NotImplementedException(); } //Last Marker in Header before EntroypEncodedScan else if (Tag == Tags.StartOfScan) { //Read past the Start of Scan temp.Seek(TagSize, System.IO.SeekOrigin.Current); //Create RtpJpegHeader and CopyTo currentPacket advancing currentPacketOffset { byte[] data = CreateRtpJpegHeader(TypeSpecific, 0, Type, Quality, Width, Height, RestartInterval, QTables); data.CopyTo(currentPacket.Payload, currentPacketOffset); currentPacketOffset += data.Length; } //Determine how much to read int packetRemains = BytesInPacket - currentPacketOffset; //How much remains in the stream relative to the endOffset long streamRemains = endOffset - temp.Position; //A RtpJpegHeader which must be in the Payload of each Packet (8 Bytes without QTables and RestartInterval) byte[] RtpJpegHeader = CreateRtpJpegHeader(TypeSpecific, 0, Type, Quality, Width, Height, RestartInterval, null); //While we are not done reading while (temp.Position < endOffset) { //Read what we can into the packet packetRemains -= temp.Read(currentPacket.Payload, currentPacketOffset, packetRemains); //Update how much remains streamRemains = endOffset - temp.Position; //Add current packet Add(currentPacket); //Determine if we need to adjust the size and add the packet if (streamRemains < BytesInPacket - 8) { //8 for the RtpJpegHeader and this will cause the Marker be to set packetRemains = (int)(streamRemains + 8); } else { //Size is normal packetRemains = BytesInPacket; } //Make next packet currentPacket = new RtpPacket(packetRemains) { TimeStamp = currentPacket.TimeStamp, SequenceNumber = (ushort)(currentPacket.SequenceNumber + 1), SynchronizationSourceIdentifier = currentPacket.SynchronizationSourceIdentifier, PayloadType = JpegFrame.RtpJpegPayloadType, Marker = packetRemains < BytesInPacket || temp.Position >= endOffset }; //Correct FragmentOffset System.Array.Copy(BitConverter.GetBytes(Utility.ReverseUnsignedInt((uint)temp.Position)), 1, RtpJpegHeader, 1, 3); //Todo //Restart Interval // //Copy header RtpJpegHeader.CopyTo(currentPacket.Payload, 0); //Set offset in packet.Payload packetRemains -= currentPacketOffset = 8; } } else //Skip past tag { temp.Seek(TagSize, System.IO.SeekOrigin.Current); } } } //To allow the stream to be closed Image = new System.Drawing.Bitmap(Image); } }
//private int _cacheCounter = 0; private CacheEntry GetCache(DirectoryEntry e) { CacheEntry ce; if (!_cache.TryGetValue(e.Offset, out ce)) { ce = new CacheEntry() { File = e.Filename }; byte[] data; lock (_data) { switch (e.Flags & FileFlags.COMPRESSION_FLAGS) { case FileFlags.CompressLZS: data = new byte[e.Length]; _data.Position = e.Offset; _data.Read(data, 0, e.Length); var ms = new System.IO.MemoryStream(data); var output = new System.IO.MemoryStream(); Lzs.Decode(ms, output); data = new byte[output.Length]; output.Position = 0; output.Read(data, 0, data.Length); ce.Data = data; break; case FileFlags.CompressLZMA: _data.Position = e.Offset; int decSize = _data.ReadInt(), propSize = _data.ReadInt(); byte[] props = new byte[propSize]; _data.Read(props, 0, props.Length); byte[] cdata = new byte[e.Length - propSize - 8]; _data.Read(cdata, 0, cdata.Length); data = new byte[decSize]; var lzma = new SharpCompress.Compressors.LZMA.LzmaStream(props, new System.IO.MemoryStream(cdata)); lzma.Read(data, 0, data.Length); /*int srcSize = cdata.Length; * switch (LzmaUncompress(data, ref decSize, cdata, ref srcSize, props, props.Length)) { * case SZ_OK: * //Woohoo! * break; * default: * throw new IrosArcException("Error decompressing " + e.Filename); * }*/ ce.Data = data; break; default: throw new IrosArcException("Bad compression flags " + e.Flags.ToString()); } } _cache.AddOrUpdate(e.Offset, ce, (_, __) => ce); } ce.LastAccess = DateTime.Now; CleanCache(); /* * if ((_cacheCounter++ % 100) == 0) * System.Diagnostics.Debug.WriteLine("IRO cache contents; " + String.Join(",", _cache.Values.Select(e => e.File))); */ return(ce); }
/// <summary> /// HttpWebRequest读取网页 字符集将自动匹配如果找不倒指定字符集,则使用utf-8 /// </summary> /// <param name="url">url</param> /// <param name="parament">一个用于区分的参数 </param> private static string GetWeb(string url, string encoding) { string strHtmlContent = ""; //字符集编码 if (url.IndexOf("http") == -1)//如果米有HTTP { throw new Exception("请提供完整的HTTP地址"); } System.Net.HttpWebRequest myrequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); myrequest.Timeout = 600000;//超时时间 10 分钟 //设置没有缓存 myrequest.Headers.Set("Pragma", "no-cache"); System.IO.Stream mystream = new System.IO.MemoryStream(); System.Net.HttpWebResponse myresponse = (System.Net.HttpWebResponse)myrequest.GetResponse(); mystream = myresponse.GetResponseStream(); //用于读取数据的内存流 System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); #region 自动判断编码字符集 //查看流长时是不是有效数据 int len = 0; byte[] buff = new byte[512]; while ((len = mystream.Read(buff, 0, buff.Length)) > 0) { memoryStream.Write(buff, 0, len); } if (memoryStream.Length > 0) { //设置流指向头 memoryStream.Seek(0, System.IO.SeekOrigin.Begin); int DetLen = 0; //编码字符体的buffer 默认需要4KB的数据 byte[] DetectBuff = new byte[4096]; //开始取得编码 UniversalDetector Det = new UniversalDetector(null); //从当前流中读取块并写入到buff中 while ((DetLen = memoryStream.Read(DetectBuff, 0, DetectBuff.Length)) > 0 && !Det.IsDone()) { Det.HandleData(DetectBuff, 0, DetectBuff.Length); } Det.DataEnd(); //得到字符集合 if (Det.GetDetectedCharset() != null) { if (encoding == "") { //得到字符集 encoding = Det.GetDetectedCharset(); } } //设置流指向头 memoryStream.Seek(0, System.IO.SeekOrigin.Begin); } #endregion System.Text.Encoding myencoding = System.Text.Encoding.GetEncoding(encoding); System.IO.StreamReader mystreamreader = new System.IO.StreamReader(memoryStream, myencoding); strHtmlContent = mystreamreader.ReadToEnd(); mystream.Close(); mystreamreader.Dispose(); mystream.Close(); mystream.Dispose(); return(strHtmlContent); }
public bool GetFromClipboard() { IDataObject dataObj = Clipboard.GetDataObject(); if (dataObj == null) { return(false); } if (!dataObj.GetDataPresent("C64Studio.ImageList")) { return(false); } System.IO.MemoryStream ms = (System.IO.MemoryStream)dataObj.GetData("C64Studio.ImageList"); GR.Memory.ByteBuffer spriteData = new GR.Memory.ByteBuffer((uint)ms.Length); ms.Read(spriteData.Data(), 0, (int)ms.Length); GR.IO.MemoryReader memIn = spriteData.MemoryReader(); int numEntries = memIn.ReadInt32(); ColumnBased = (memIn.ReadInt32() > 0) ? true : false; var incomingColorSettings = new ColorSettings(); incomingColorSettings.BackgroundColor = memIn.ReadInt32(); incomingColorSettings.MultiColor1 = memIn.ReadInt32(); incomingColorSettings.MultiColor2 = memIn.ReadInt32(); incomingColorSettings.BGColor4 = memIn.ReadInt32(); incomingColorSettings.Palettes.Clear(); int numPalettes = memIn.ReadInt32(); for (int j = 0; j < numPalettes; ++j) { int numPaletteEntries = memIn.ReadInt32(); var pal = new Palette(numPaletteEntries); for (int i = 0; i < numPaletteEntries; ++i) { pal.ColorValues[i] = memIn.ReadUInt32(); } pal.CreateBrushes(); incomingColorSettings.Palettes.Add(pal); } for (int i = 0; i < numEntries; ++i) { var entry = new Entry(); entry.Index = memIn.ReadInt32(); entry.Tile.Mode = (GraphicTileMode)memIn.ReadInt32(); entry.Tile.CustomColor = memIn.ReadInt32(); int palIndex = memIn.ReadInt32(); entry.Tile.Width = memIn.ReadInt32(); entry.Tile.Height = memIn.ReadInt32(); uint dataLength = memIn.ReadUInt32(); entry.Tile.Data = new GR.Memory.ByteBuffer(); memIn.ReadBlock(entry.Tile.Data, dataLength); entry.Tile.Colors = new ColorSettings(incomingColorSettings); entry.Tile.Colors.ActivePalette = palIndex; int originalIndex = memIn.ReadInt32(); Entries.Add(entry); } return(true); }
public override void ReadBytes(byte[] b, int offset, int len) { buffer.Read(b, offset, len); }
static byte[] CaptureWebPageBytesP(string body, int width, int height) { byte[] data; using (WebBrowser web = new WebBrowser()) { web.ScrollBarsEnabled = false; // no scrollbars web.ScriptErrorsSuppressed = true; // no errors web.DocumentText = body; while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } web.Width = web.Document.Body.ScrollRectangle.Width; web.Height = web.Document.Body.ScrollRectangle.Height; // a bitmap that we will draw to using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(web.Width, web.Height)) { // draw the web browser to the bitmap web.DrawToBitmap(bmp, new Rectangle(web.Location.X, web.Location.Y, web.Width, web.Height)); // draw the web browser to the bitmap GraphicsUnit units = GraphicsUnit.Pixel; RectangleF destRect = new RectangleF(0F, 0F, width, height); RectangleF srcRect = new RectangleF(0, 0, web.Width, web.Width * 1.5F); Bitmap b = new Bitmap(width, height); Graphics g = Graphics.FromImage((Image)b); g.Clear(Color.White); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(bmp, destRect, srcRect, units); g.Dispose(); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { EncoderParameter qualityParam = null; EncoderParameters encoderParams = null; try { ImageCodecInfo imageCodec = null; imageCodec = GetEncoderInfo("image/jpeg"); qualityParam = new EncoderParameter(Encoder.Quality, 100L); encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; b.Save(stream, imageCodec, encoderParams); } catch (Exception) { throw new Exception(); } finally { if (encoderParams != null) { encoderParams.Dispose(); } if (qualityParam != null) { qualityParam.Dispose(); } } b.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); } } } return(data); }
protected override void ReadValue(System.IO.MemoryStream reader, uint byteToRead) { byte[] data = new byte[byteToRead]; reader.Read(data, 0, data.Length); this.Value = data; }
public void TestVerifyLargeObjectETag() { IObjectStorageProvider provider = Bootstrapper.CreateObjectStorageProvider(); ((CloudFilesProvider)provider).LargeFileBatchThreshold = 81920; string containerName = TestContainerPrefix + Path.GetRandomFileName(); string sourceFileName = "DarkKnightRises.jpg"; byte[] content = File.ReadAllBytes("DarkKnightRises.jpg"); ObjectStore containerResult = provider.CreateContainer(containerName); Assert.AreEqual(ObjectStore.ContainerCreated, containerResult); ProgressMonitor progressMonitor = new ProgressMonitor(content.Length); provider.CreateObjectFromFile(containerName, sourceFileName, progressUpdated: progressMonitor.Updated); Assert.IsTrue(progressMonitor.IsComplete, "Failed to notify progress monitor callback of status update."); try { using (MemoryStream downloadStream = new MemoryStream()) { provider.GetObject(containerName, sourceFileName, downloadStream, verifyEtag: true); Assert.AreEqual(content.Length, GetContainerObjectSize(provider, containerName, sourceFileName)); downloadStream.Position = 0; byte[] actualData = new byte[downloadStream.Length]; downloadStream.Read(actualData, 0, actualData.Length); Assert.AreEqual(content.Length, actualData.Length); using (MD5 md5 = MD5.Create()) { byte[] contentMd5 = md5.ComputeHash(content); byte[] actualMd5 = md5.ComputeHash(actualData); Assert.AreEqual(BitConverter.ToString(contentMd5), BitConverter.ToString(actualMd5)); } } /* Cleanup */ provider.DeleteContainer(containerName, deleteObjects: true); } catch (NotSupportedException) { Assert.Inconclusive("The provider does not support verifying ETags for large objects."); } }
public ByteBuffer Get(byte[] dst, int offset, int length) { stream.Read(dst, offset, length); return(this); }
public override void WriteJson(JsonWriter writer, object obj, JsonSerializer serializer) { Type type = obj.GetType(); writer.WriteStartObject(); writer.WritePropertyName("t"); writer.WriteValue(getTypedescIndex(type)); if (type == typeof(System.Data.DataTable) || type == typeof(System.Data.DataSet)) { //可以序列化,那就直接序列化 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter se = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { se.Serialize(ms, obj); ms.Position = 0; byte[] bs = new byte[ms.Length]; ms.Read(bs, 0, bs.Length); writer.WritePropertyName("b"); writer.WriteValue(bs); } writer.WriteEndObject(); return; } writer.WritePropertyName("v"); if (type.IsValueType || obj is string) { writer.WriteValue(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); } else if (obj is System.Collections.IDictionary) { writer.WriteStartArray(); var dict = (System.Collections.IDictionary)obj; foreach (var key in dict.Keys) { var value = dict[key]; if (value == null) { continue; } serializer.Serialize(writer, key); serializer.Serialize(writer, value); } writer.WriteEndArray(); } else if (obj is Array) { writer.WriteStartArray(); var enumerator = ((System.Collections.IEnumerable)obj).GetEnumerator(); while (enumerator.MoveNext()) { serializer.Serialize(writer, enumerator.Current); } writer.WriteEndArray(); } else { writer.WriteStartObject(); Type thisType = type; while (thisType != typeof(object)) { var fields = thisType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var field in fields) { if (field.GetCustomAttribute(typeof(NonSerializedAttribute)) != null) { continue; } var value = field.GetValue(obj); if (thisType == type) { writer.WritePropertyName(field.Name); } else { writer.WritePropertyName($"{thisType.FullName}-{field.Name}"); } serializer.Serialize(writer, value); } thisType = thisType.BaseType; } writer.WriteEndObject(); } writer.WriteEndObject(); }
public Invoice(byte[] fileBytes, DateTime Open_From_Date, DateTime Open_To_Date, int _openYearFrom, int _openYearTo, string _UAGRFC) { string emisorNombre = ""; string emisorRFC = ""; string receptorNombre = ""; string receptorRFC = ""; string comprobanteTotal = ""; string comprobanteFolio = ""; string comprobantemetodoPago = ""; string comprobanteFecha = ""; _openFromDate = Open_From_Date; _openToDate = Open_To_Date; _id = -1; _receptionDate = DateTime.Now; _annotations = String.Empty; _binaryFile = fileBytes; _fileSize = _binaryFile.Length; _fileExtension = InvoiceFileExtension.INVALID; _paymentMethods = new List <PaymentMethod>(); UAGRFC = _UAGRFC; OpenYearFrom = _openYearFrom; OpenYearTo = _openYearTo; usuarioAutenticado = HttpContext.Current.User as CustomPrincipal; if (usuarioAutenticado != null) { identidad = usuarioAutenticado.Identity as CustomIdentity; } System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(_binaryFile); if (memoryStream.CanSeek) { byte[] bof = new byte[4]; memoryStream.Read(bof, 0, 4); /* * EF BB BF = utf-8 * FF FE = ucs-2le, ucs-4le, and ucs-16le * FE FF = utf-16 and ucs-2 * 00 00 FE FF = ucs-4 */ if (((bof[0] == 0xEF) && (bof[1] == 0xBB) && (bof[2] == 0xBF)) || ((bof[0] == 0xFF) && (bof[1] == 0xFE)) || ((bof[0] == 0xFE) && (bof[1] == 0xFF)) || ((bof[0] == 0x0) && (bof[1] == 0x0) && (bof[2] == 0xFE) && (bof[3] == 0xFF))) { if ((bof[0] == 0xEF) && (bof[1] == 0xBB) && (bof[2] == 0xBF)) { _encoding = "UTF-8"; } else { _encoding = "Unicode"; } } else { if ((bof[0] == 0x3C) && (bof[1] == 0x3F) && (bof[2] == 0x78) && (bof[3] == 0x6D)) { _encoding = "UTF-8"; _fileExtension = InvoiceFileExtension.XML; } else { _encoding = "ASCII"; if ((bof[0] == 0x25) && (bof[1] == 0x50) && (bof[2] == 0x44) && (bof[3] == 0x46)) { _fileExtension = InvoiceFileExtension.PDF; _currency = Currency.MXN; _exchangeRate = 1; } } } memoryStream.Seek(0, System.IO.SeekOrigin.Begin); if (!String.IsNullOrEmpty(_encoding) && (_fileExtension != InvoiceFileExtension.PDF)) { _cfdi = new System.Xml.XmlDocument(); try { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(memoryStream); _cfdi.Load(reader); } catch (Exception ex) { memoryStream.Seek(0, System.IO.SeekOrigin.Begin); _encoding = "ISO-8859-1"; System.IO.StreamReader streamReader = new System.IO.StreamReader(memoryStream, System.Text.Encoding.GetEncoding(_encoding)); try { _cfdi.Load(streamReader); } catch (Exception exc) { _fileExtension = InvoiceFileExtension.INVALID; return; } } _fileExtension = InvoiceFileExtension.XML; try { System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(cfdi.NameTable); nsmgr.AddNamespace("cfdi", "http://www.sat.gob.mx/cfd/3"); nsmgr.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital"); System.Xml.XmlNode xmlVoucher = cfdi.SelectSingleNode("cfdi:Comprobante", nsmgr); System.Xml.XmlNode xmlClient = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Receptor", nsmgr); System.Xml.XmlNode xmlProvider = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Emisor", nsmgr); System.Xml.XmlNode xmlTimbreFiscal = cfdi.SelectSingleNode("cfdi:Comprobante/cfdi:Complemento/tfd:TimbreFiscalDigital", nsmgr); if (xmlVoucher.Attributes["version"] == null) { //version 3.3 if (xmlVoucher.Attributes["Version"] != null) { emisorNombre = "Nombre"; emisorRFC = "Rfc"; receptorNombre = "Nombre"; receptorRFC = "Rfc"; comprobanteTotal = "Total"; comprobanteFolio = "Folio"; comprobantemetodoPago = "MetodoPago"; comprobanteFecha = "Fecha"; } } else { //version 3.2 or last emisorNombre = "nombre"; emisorRFC = "rfc"; receptorNombre = "nombre"; receptorRFC = "rfc"; comprobanteTotal = "total"; comprobanteFolio = "folio"; comprobantemetodoPago = "metodoDePago"; comprobanteFecha = "fecha"; } provider = new Enterprise(xmlProvider.Attributes[emisorNombre] == null ? xmlProvider.Attributes[emisorRFC].Value.Trim() : xmlProvider.Attributes[emisorNombre].Value, xmlProvider.Attributes[emisorRFC].Value.Trim()); _providerNameSpecified = xmlProvider.Attributes[emisorNombre] != null; client = new Enterprise(xmlClient.Attributes[receptorNombre] == null ? xmlClient.Attributes[receptorRFC].Value.Trim() : xmlClient.Attributes[receptorNombre].Value, xmlClient.Attributes[receptorRFC].Value.Trim()); _originalPaymentAmount = xmlVoucher.Attributes[comprobanteTotal] == null ? 0 : Double.Parse(xmlVoucher.Attributes[comprobanteTotal].Value); providerInvoiceId = xmlVoucher.Attributes[comprobanteFolio] == null ? "" : xmlVoucher.Attributes[comprobanteFolio].Value; if (xmlClient.Attributes[receptorRFC].Value == UAGRFC) { client.id = 1; } _currency = xmlVoucher.Attributes["Moneda"] == null ? Currency.MXN : ((xmlVoucher.Attributes["Moneda"].Value.ToUpper().Replace(".", "").Trim().Contains("MX") || (xmlVoucher.Attributes["Moneda"].Value.ToUpper().Replace(".", "").Trim().Equals("MN") || xmlVoucher.Attributes["Moneda"].Value.ToUpper().Replace("É", "E").Trim().Contains("MEX")) ? Currency.MXN : Currency.OTHER)); if (_currency == Currency.MXN) { _exchangeRate = 1; } else { if (xmlVoucher.Attributes["TipoCambio"] == null) { _exchangeRate = 0; } else { Double.TryParse(xmlVoucher.Attributes["TipoCambio"].Value, NumberStyles.Currency, CultureInfo.CreateSpecificCulture("es-MX"), out _exchangeRate); if ((_exchangeRate == 0) && (xmlVoucher.Attributes["TipoCambio"].Value.ToUpper().Contains("PESOS"))) { _exchangeRate = 1; } } } _currencySymbol = xmlVoucher.Attributes["Moneda"] == null ? "MXN" : xmlVoucher.Attributes["Moneda"].Value; paymentAmount = _originalPaymentAmount * _exchangeRate; invoiceDate = System.Xml.XmlConvert.ToDateTime(xmlVoucher.Attributes[comprobanteFecha].Value, System.Xml.XmlDateTimeSerializationMode.Utc); uid = Guid.Parse(xmlTimbreFiscal.Attributes["UUID"].Value); //version 3.2 or last string[] tmpPaymentMethods = xmlVoucher.Attributes[comprobantemetodoPago] == null ? new string[0] : xmlVoucher.Attributes[comprobantemetodoPago].Value.Split(','); foreach (string tmpPaymentMethod in tmpPaymentMethods) { paymentMethods.Add(new PaymentMethod(tmpPaymentMethod)); } } catch (Exception ex) { _fileExtension = InvoiceFileExtension.INVALID; } } } }
private byte[] decompress(byte[] inData) { byte[] result = null; using (var outMemoryStream = new System.IO.MemoryStream()) using (var inMemoryStream = new System.IO.MemoryStream(inData)) using (var outZStream = new ComponentAce.Compression.Libs.zlib.ZOutputStream(outMemoryStream)) { try { CopyStream(inMemoryStream, outZStream); result = new byte[outMemoryStream.Length]; outMemoryStream.Position = 0; var ok = outMemoryStream.Read(result, 0, (int)outMemoryStream.Length); } finally { outZStream.Close(); outMemoryStream.Close(); inMemoryStream.Close(); } } return result; }
public byte ReadByte() { _stream.Read(_tmpBuffer, 0, sizeof(byte)); return(_tmpBuffer[0]); }
public static BD2.RawProxy.RawProxyv1 DeserializeFromRawData(byte[] value) { System.IO.MemoryStream MS = new System.IO.MemoryStream (value); byte[] guidBytes = new byte[16]; MS.Read (guidBytes, 0, 16); Guid guid = new Guid (guidBytes); byte[] payload = new byte[value.Length - 16]; MS.Read (payload, 0, value.Length - 16); return attribs [guid].Deserialize (payload); }
public void WriteBytes(System.IO.MemoryStream memoryStream, int size) { EnsureCapacity(_writePosition + size); memoryStream.Read(_data, _writePosition, size); _writePosition += size; }
/// <summary> /// Private-usage method to manage data retrieval /// </summary> private void OnReceive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) { byte[] obtainedData = new byte[_maxBufferLength]; try { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(e.Buffer)) { memStream.Read(obtainedData, e.Offset, e.BytesTransferred); } } catch (Exception ex) { throw new Exception("Socket Client: Could not read from stream.\n" + ex.Message); } if (e.SocketError != System.Net.Sockets.SocketError.Success) { // Host has abruptly disconnected if (e.SocketError == System.Net.Sockets.SocketError.ConnectionReset) { OnDisconnect(); return; } // Notify the subscribers of the error if (Receiving != null) { Receiving(null, e.SocketError, this); } } else { // Store the data _receivedDatas = obtainedData; // Notify the subscribers of a successful operation if (Receiving != null) { Receiving(obtainedData, e.SocketError, this); } // Begin to listen yet again _mainSocket.ReceiveAsync(_receiveSocketArgs); } }
public static byte[] ImageToBuffer(Image Image, System.Drawing.Imaging.ImageFormat imageFormat) { if (Image == null) { return null; } byte[] data = null; using (System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream()) { //建立副本 using (Bitmap oBitmap = new Bitmap(Image)) { //儲存圖片到 MemoryStream 物件,並且指定儲存影像之格式 oBitmap.Save(oMemoryStream, imageFormat); //設定資料流位置 oMemoryStream.Position = 0; //設定 buffer 長度 data = new byte[oMemoryStream.Length]; //將資料寫入 buffer oMemoryStream.Read(data, 0, Convert.ToInt32(oMemoryStream.Length)); //將所有緩衝區的資料寫入資料流 oMemoryStream.Flush(); } } return data; }
}/* restart_header */ /* * init_memory * * Allocate memory and load the story file. * */ internal static void init_memory() { long size; zword addr; zword n; int i, j; // TODO Abstract this part /* Open story file */ // story_fp = new System.IO.FileStream(main.story_name, System.IO.FileMode.Open, System.IO.FileAccess.Read); story_fp = os_.path_open(main.story_data); if (story_fp == null) { os_.fatal("Cannot open story file"); } init_fp_pos = story_fp.Position; storyData = new byte[story_fp.Length]; story_fp.Read(storyData, 0, storyData.Length); story_fp.Position = 0; DebugState.Output("Starting story: {0}", main.story_name); /* Allocate memory for story header */ ZMData = new byte[64]; Frotz.Other.ZMath.clearArray(ZMData); /* Load header into memory */ if (story_fp.Read(ZMData, 0, 64) != 64) { os_.fatal("Story file read error"); } /* Copy header fields to global variables */ LOW_BYTE(ZMachine.H_VERSION, out main.h_version); if (main.h_version < ZMachine.V1 || main.h_version > ZMachine.V8) { os_.fatal("Unknown Z-code version"); } LOW_BYTE(ZMachine.H_CONFIG, out main.h_config); if (main.h_version == ZMachine.V3 && ((main.h_config & ZMachine.CONFIG_BYTE_SWAPPED) != 0)) { os_.fatal("Byte swapped story file"); } LOW_WORD(ZMachine.H_RELEASE, out main.h_release); LOW_WORD(ZMachine.H_RESIDENT_SIZE, out main.h_resident_size); LOW_WORD(ZMachine.H_START_PC, out main.h_start_pc); LOW_WORD(ZMachine.H_DICTIONARY, out main.h_dictionary); LOW_WORD(ZMachine.H_OBJECTS, out main.h_objects); LOW_WORD(ZMachine.H_GLOBALS, out main.h_globals); LOW_WORD(ZMachine.H_DYNAMIC_SIZE, out main.h_dynamic_size); LOW_WORD(ZMachine.H_FLAGS, out main.h_flags); for (i = 0, addr = ZMachine.H_SERIAL; i < 6; i++, addr++) { LOW_BYTE(addr, out main.h_serial[i]); } // TODO serial might need to be a char /* Auto-detect buggy story files that need special fixes */ main.story_id = Story.UNKNOWN; for (i = 0; records[i].story_id != Story.UNKNOWN; i++) { if (main.h_release == records[i].release) { for (j = 0; j < 6; j++) if (main.h_serial[j] != records[i].serial[j]) goto no_match; main.story_id = records[i].story_id; } no_match: ; /* null statement */ } LOW_WORD(ZMachine.H_ABBREVIATIONS, out main.h_abbreviations); LOW_WORD(ZMachine.H_FILE_SIZE, out main.h_file_size); /* Calculate story file size in bytes */ if (main.h_file_size != 0) { main.story_size = 2 * main.h_file_size; if (main.h_version >= ZMachine.V4) { main.story_size *= 2; } if (main.h_version >= ZMachine.V6) { main.story_size *= 2; } if (main.story_id == Story.AMFV && main.h_release == 47) { main.story_size = 2 * main.h_file_size; } else if (main.story_size > 0) {/* os_path_open() set the size */ } else {/* some old games lack the file size entry */ main.story_size = story_fp.Length - init_fp_pos; story_fp.Position = init_fp_pos + 64; } LOW_WORD(ZMachine.H_CHECKSUM, out main.h_checksum); LOW_WORD(ZMachine.H_ALPHABET, out main.h_alphabet); LOW_WORD(ZMachine.H_FUNCTIONS_OFFSET, out main.h_functions_offset); LOW_WORD(ZMachine.H_STRINGS_OFFSET, out main.h_strings_offset); LOW_WORD(ZMachine.H_TERMINATING_KEYS, out main.h_terminating_keys); LOW_WORD(ZMachine.H_EXTENSION_TABLE, out main.h_extension_table); /* Zork Zero beta and Macintosh versions don't have the graphics flag set */ if (main.story_id == Story.ZORK_ZERO) { if (main.h_release == 96 || main.h_release == 153 || main.h_release == 242 || main.h_release == 296) { main.h_flags |= ZMachine.GRAPHICS_FLAG; } } /* Adjust opcode tables */ if (main.h_version <= ZMachine.V4) { Process.op0_opcodes[0x09] = new Process.zinstruction(Variable.z_pop); Process.op0_opcodes[0x0f] = new Process.zinstruction(Math.z_not); } else { Process.op0_opcodes[0x09] = new Process.zinstruction(Process.z_catch); Process.op0_opcodes[0x0f] = new Process.zinstruction(Process.z_call_n); } /* Allocate memory for story data */ byte[] temp = new byte[ZMData.Length]; Frotz.Other.ZMath.clearArray(temp); System.Array.Copy(ZMData, temp, ZMData.Length); ZMData = new byte[main.story_size]; Frotz.Other.ZMath.clearArray(ZMData); System.Array.Copy(temp, ZMData, temp.Length); /* Load story file in chunks of 32KB */ n = 0x8000; for (size = 64; size < main.story_size; size += n) { if (main.story_size - size < 0x8000) n = (ushort)(main.story_size - size); SET_PC(size); int read = story_fp.Read(ZMData, (int)pcp, n); if (read != n) os_.fatal("Story file read error"); } // Take a moment to calculate the checksum of the story file in case verify is called ZMData_checksum = 0; for (int k = 64; k < ZMData.Length; k++) { ZMData_checksum += ZMData[k]; } } DebugState.Output("Story Size: {0}", main.story_size); first_restart = true; /* Read header extension table */ main.hx_table_size = get_header_extension(ZMachine.HX_TABLE_SIZE); main.hx_unicode_table = get_header_extension(ZMachine.HX_UNICODE_TABLE); main.hx_flags = get_header_extension(ZMachine.HX_FLAGS); }/* init_memory */
private void ParseFile(string filename, uint depth, ref System.Collections.Generic.List <string> outputfiles) { SFWorkflow.WFFileType.FileType type = SFWorkflow.WFFileType.GetFileType(filename); if (type == SFWorkflow.WFFileType.FileType.OlePowerPoint) { uint fileidx = 0; System.Collections.Generic.List <string> pptfiles = new System.Collections.Generic.List <string>(); DIaLOGIKa.b2xtranslator.StructuredStorage.Reader.StructuredStorageReader ssr = new DIaLOGIKa.b2xtranslator.StructuredStorage.Reader.StructuredStorageReader(filename); DIaLOGIKa.b2xtranslator.PptFileFormat.PowerpointDocument ppt = new DIaLOGIKa.b2xtranslator.PptFileFormat.PowerpointDocument(ssr); foreach (uint persistId in ppt.PersistObjectDirectory.Keys) { UInt32 offset = ppt.PersistObjectDirectory[persistId]; ppt.PowerpointDocumentStream.Seek(offset, System.IO.SeekOrigin.Begin); DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleObjStgAtom obj = DIaLOGIKa.b2xtranslator.OfficeDrawing.Record.ReadRecord(ppt.PowerpointDocumentStream) as DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleObjStgAtom; if (obj != null) { string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(filename).FullName)); if (!System.IO.Directory.Exists(filedir)) { System.IO.Directory.CreateDirectory(filedir); } if (System.IO.Directory.Exists(filedir)) { byte[] data = obj.DecompressData(); System.IO.MemoryStream ms = new System.IO.MemoryStream(data); SFWorkflow.WFFileType.FileType oletype = SFWorkflow.WFFileType.GetOleFileType(data); if (oletype == WFFileType.FileType.OlePackage || oletype == WFFileType.FileType.OleContents) { using (OpenMcdf.CompoundFile cf = new OpenMcdf.CompoundFile(ms)) { WriteStorage(cf.RootStorage, filedir, depth, ref pptfiles); } } else { string filenm = String.Format("{0}\\pptembed{1}", filedir, fileidx); using (System.IO.FileStream fs = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { byte[] buffer = new byte[1024]; int len; while ((len = ms.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, len); } pptfiles.Add(filenm); } fileidx++; ms.Close(); ms.Dispose(); } } } } #if false foreach (DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleEmbedContainer ole in ppt.OleObjects.Values) { string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, diridx++); if (!System.IO.Directory.Exists(filedir)) { System.IO.Directory.CreateDirectory(filedir); } if (System.IO.Directory.Exists(filedir)) { string filenm = String.Format("{0}\\pptembed{1}", filedir, ole.SiblingIdx); try { System.IO.FileStream fss = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write); byte[] data = ole.stgAtom.DecompressData(); fss.Write(data, 0, data.Length); fss.Flush(); fss.Close(); fss.Dispose(); pptfiles.Add(filenm); } catch (Exception ex) { } } } #endif foreach (DIaLOGIKa.b2xtranslator.OfficeDrawing.Record record in ppt.PicturesContainer._pictures.Values) //.Where(x => x.TypeCode == 0xF01C || x.TypeCode == 0xF01D || x.TypeCode == 0xF01E || x.TypeCode == 0xF01F || x.TypeCode == 0xF029 || x.TypeCode == 0xF02A)) { string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, "PPTPictures"); //, SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(filename).FullName)); if (!System.IO.Directory.Exists(filedir)) { System.IO.Directory.CreateDirectory(filedir); } if (System.IO.Directory.Exists(filedir)) { string extension = string.Empty; int skip = 0; switch (record.TypeCode) { case 0xF01A: extension = ".emf"; break; case 0xF01B: extension = ".wmf"; break; case 0xF01C: extension = ".pict"; break; case 0xF01D: case 0xF02A: extension = ".jpg"; skip = 17; break; case 0xF01E: extension = ".png"; skip = 17; break; case 0xF01F: extension = ".dib"; break; case 0xF029: extension = ".tiff"; break; } string filenm = String.Format("{0}\\pptembed{1}{2}", filedir, fileidx++, extension); using (System.IO.FileStream fs = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { // need to skip 17 byte header in raw data stream byte[] data = ((extension == ".emf" || extension == ".wmf")) ? ((DIaLOGIKa.b2xtranslator.OfficeDrawing.MetafilePictBlip)record).Decrompress() : record.RawData.Skip(skip).ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); fs.Dispose(); pptfiles.Add(filenm); } } } ssr.Close(); ssr.Dispose(); outputfiles.AddRange(pptfiles); depth--; if (depth > 0) { foreach (string fn in pptfiles) { ParseFile(fn, depth, ref outputfiles); } } } else { using (OpenMcdf.CompoundFile cf = new OpenMcdf.CompoundFile(filename)) { WriteStorage(cf.RootStorage, System.IO.Directory.GetParent(filename).FullName, depth, ref outputfiles); } } }
/// <summary> 通信 </summary> private void Communication(object o) { object[] obS = null; EndPoint rmE = null; try { obS = o as object[]; if (obS == null || obS.Length < 1) { return; } long? l = null; Socket dataSock = obS[1] as Socket; rmE = dataSock.RemoteEndPoint; PopMsg(this, DateTime.Now, rmE + " Connected."); System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] data = new byte[2048]; while (true) { #region - Receive Data - int rec = dataSock.Receive(data, data.Length, SocketFlags.None); if (rec <= 0) { break; } ms.Write(data, 0, rec); if (l == null && ms.Length >= 8) { ms.Position = 0; byte[] btL = new byte[8]; ms.Read(btL, 0, 8); l = BitConverter.ToInt64(btL, 0); ms.Position = ms.Length; } #endregion #region - Rrocess Data - if (l != null && ms.Length - 8 == l) { byte[] rstBt = null; if (l >= 16)//(l == 1016) { byte[] btID = new byte[16]; ms.Position = 8; ms.Read(btID, 0, 16); try { if (new Guid(btID).Equals(FTP_LCS)) { rstBt = M_InteractiveData(FTP_LCS, ms.ToArray()); } } catch (Exception e) { PopErr(this, DateTime.Now, e); } } if (rstBt == null) { #region - 处理参数 - using (System.IO.MemoryStream resultMs = new System.IO.MemoryStream()) { bool isSended = false; resultMs.Write(new byte[9], 0, 9); try { //返回结果 object resultObj = null; #region - 形成参数 - ms.Position = 8; object rcvDataO = _bf.Deserialize(ms); object[] rcvData = rcvDataO as object[]; List <object> listData = new List <object>(rcvData); listData.RemoveAt(0); string methodTag = rcvData[0] as string; #endregion #region - 查找 & 执行方法 - if (methodTag != null) { DataRow[] drs = null; int pointCount = methodTag.Split('.').Length - 1; if (pointCount == 0) { drs = _methodCache.Select(string.Format("MtdName = '{0}' And ParamNum = {1}", methodTag, listData.Count)); } else if (pointCount == 1) { drs = _methodCache.Select(string.Format("ClsMtdName = '{0}' And ParamNum = {1}", methodTag, listData.Count)); } else { drs = _methodCache.Select(string.Format("ClsMtdFullName = '{0}' And ParamNum = {1}", methodTag, listData.Count)); } int rowIndex = 0; if (drs == null || drs.Length < 1) { throw new NoFindInterfaceException(); } else if (drs.Length > 1) { //查找重载方法 StringBuilder sbPrmt = new StringBuilder(); foreach (var oFor in listData) { sbPrmt.Append(oFor.GetType().FullName + "|"); } if (sbPrmt.Length > 1) { sbPrmt.Remove(sbPrmt.Length - 1, 1); } int findCount = 0; for (int i = 0; i < drs.Length; i++) { if (drs[i][3].ToString() == sbPrmt.ToString()) { rowIndex = i; findCount++; } } if (findCount > 1) { throw new MultiInterfaceException(); } else if (findCount < 1) { throw new NoFindInterfaceException(); } } System.Reflection.MethodInfo mi = drs[rowIndex][5] as System.Reflection.MethodInfo; if (listData.Count < 1) { resultObj = mi.Invoke(drs[rowIndex][4], null); } else { resultObj = mi.Invoke(drs[rowIndex][4], listData.ToArray()); } } else { throw new Exception("方法标识为空!"); } #endregion if (resultObj == null) { resultMs.Position = 0; resultMs.Write(new byte[] { 1 }, 0, 1); resultMs.Position = 1; resultMs.Write(BitConverter.GetBytes((long)0), 0, 8); } else if (resultObj is System.IO.Stream) { isSended = true; using (System.IO.Stream stream = resultObj as System.IO.Stream) { if (stream != null) { dataSock.Send(new byte[] { 2 }, SocketFlags.None);//3:流 dataSock.Send(BitConverter.GetBytes(stream.Length), SocketFlags.None); byte[] tempBt = new byte[2048]; if (stream.Length > 0) { while (stream.Position < stream.Length) { int red = stream.Read(tempBt, 0, tempBt.Length); dataSock.Send(tempBt, 0, red, SocketFlags.None); } } stream.Close(); } } } else { resultMs.Position = 0; resultMs.Write(new byte[] { 0 }, 0, 1); resultMs.Position = 9; _bf.Serialize(resultMs, resultObj); resultMs.Position = 1; resultMs.Write(BitConverter.GetBytes(resultMs.Length - 9), 0, 8); } } catch (Exception ex) { Exception extemp = ex is TargetInvocationException ? (ex as TargetInvocationException).InnerException : ex; resultMs.Position = 0; resultMs.Write(new byte[] { 0 }, 0, 1); resultMs.Position = 9; _bf.Serialize(resultMs, extemp); resultMs.Position = 1; resultMs.Write(BitConverter.GetBytes(resultMs.Length - 9), 0, 8); } if (!isSended) { rstBt = resultMs.ToArray(); } } #endregion } if (rstBt != null) { dataSock.Send(rstBt, SocketFlags.None); } //释放接受到的资源 l = null; ms.Dispose(); ms = new System.IO.MemoryStream(); } #endregion } _t_Cmnc.Remove(o as object[]); } catch (ThreadAbortException) { } catch (Exception e) { PopErr(this, DateTime.Now, e); } finally { if (obS != null) { _t_Cmnc.Remove(obS); } if (rmE != null) { PopMsg(this, DateTime.Now, rmE + " Disconnected."); } } }
public void TestExtractArchiveTarBz2() { CloudFilesProvider provider = (CloudFilesProvider)Bootstrapper.CreateObjectStorageProvider(); string containerName = TestContainerPrefix + Path.GetRandomFileName(); string sourceFileName = "DarkKnightRises.jpg"; byte[] content = File.ReadAllBytes("DarkKnightRises.jpg"); using (MemoryStream outputStream = new MemoryStream()) { using (BZip2OutputStream bz2Stream = new BZip2OutputStream(outputStream)) { bz2Stream.IsStreamOwner = false; using (TarArchive archive = TarArchive.CreateOutputTarArchive(bz2Stream)) { archive.IsStreamOwner = false; archive.RootPath = Path.GetDirectoryName(Path.GetFullPath(sourceFileName)).Replace('\\', '/'); TarEntry entry = TarEntry.CreateEntryFromFile(sourceFileName); archive.WriteEntry(entry, true); archive.Close(); } } outputStream.Flush(); outputStream.Position = 0; ExtractArchiveResponse response = provider.ExtractArchive(outputStream, containerName, ArchiveFormat.TarBz2); Assert.IsNotNull(response); Assert.AreEqual(1, response.CreatedFiles); Assert.IsNotNull(response.Errors); Assert.AreEqual(0, response.Errors.Count); } using (MemoryStream downloadStream = new MemoryStream()) { provider.GetObject(containerName, sourceFileName, downloadStream, verifyEtag: true); Assert.AreEqual(content.Length, GetContainerObjectSize(provider, containerName, sourceFileName)); downloadStream.Position = 0; byte[] actualData = new byte[downloadStream.Length]; downloadStream.Read(actualData, 0, actualData.Length); Assert.AreEqual(content.Length, actualData.Length); using (MD5 md5 = MD5.Create()) { byte[] contentMd5 = md5.ComputeHash(content); byte[] actualMd5 = md5.ComputeHash(actualData); Assert.AreEqual(BitConverter.ToString(contentMd5), BitConverter.ToString(actualMd5)); } } /* Cleanup */ provider.DeleteContainer(containerName, deleteObjects: true); }
/// <summary> /// Atualiza o arquivo selecionado na pasta dos arquivos CalcEngine. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void odsArquivoCalcEngine_Updating(object sender, Colosoft.WebControls.VirtualObjectDataSourceMethodEventArgs e) { var arquivoCalcEngine = e.InputParameters[0] as Glass.Data.Model.ArquivoCalcEngine; // Salva o arquivo que será subido. var fluArquivoCalcEngine = ((FileUpload)dtvArquivoCalcEngine.FindControl("fluArquivoCalcEngine")); if (fluArquivoCalcEngine != null && !String.IsNullOrEmpty(fluArquivoCalcEngine.FileName)) { // Salva o nome do arquivo CalcEngine. var nomeArquivo = fluArquivoCalcEngine.FileName; /* Chamado 62033. */ if (arquivoCalcEngine.Nome != nomeArquivo.ToUpper().Replace(".CALCPACKAGE", string.Empty)) { throw new Exception("Não é possível atualizar inserir um arquivo com o nome diferente do arquivo atualizado."); } // Variável criada para recuperar os arquivos do .calcpackage. CalcEngine.ProjectFilesPackage pacote = null; // Variável criada para ler a configuração do projeto. CalcEngine.Dxf.DxfProject projeto = null; // Lista criada para setar as variáveis do CalcEngine. var lstVariaveisCalcEngine = new List <ArquivoCalcEngineVariavel>(); // Apaga o arquivo CalcEngine antigo. if (System.IO.File.Exists(ProjetoConfig.CaminhoSalvarCalcEngine + arquivoCalcEngine.Nome + ".calcpackage")) { System.IO.File.Delete(ProjetoConfig.CaminhoSalvarCalcEngine + arquivoCalcEngine.Nome + ".calcpackage"); } // Salva o arquivo CalcEngine. using (var m = new System.IO.MemoryStream(fluArquivoCalcEngine.FileBytes)) { //if (!ArquivoMesaCorteDAO.Instance.ValidarCadastroCalcEngine(m)) // throw new Exception("O arquivo inserido está com falhas de validação"); //m.Position = 0; var buffer = new byte[1024]; var read = 0; using (var file = System.IO.File.Create(ProjetoConfig.CaminhoSalvarCalcEngine + fluArquivoCalcEngine.FileName)) { while ((read = m.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, read); } file.Flush(); } } using (System.IO.Stream pacoteStream = fluArquivoCalcEngine.FileContent) { // Esse método deserializa os dados do pacote que estão contidos na Stream a recupera a instância do pacote de configuração. pacote = CalcEngine.ProjectFilesPackage.LoadPackage(pacoteStream); } // Lê a configuração do projeto. projeto = CalcEngine.Dxf.DxfProject.LoadFromPackage(pacote); try { // Seta as variáveis do CalcEngine em uma lista. foreach (var variavel in projeto.Variables.Where(f => f.GetType() == typeof(CalcEngine.Variable))) { // Cria uma nova variável CalcEngine. var variavelCalcEngine = new ArquivoCalcEngineVariavel(); variavelCalcEngine.VariavelCalcEngine = variavel.Name; // Salva o valor padrão da variável somente se não forem medidas de altura ou largura. variavelCalcEngine.ValorPadrao = (decimal)(variavel.Name.ToLower() == "altura" || variavel.Name.ToLower() == "largura" || variavel.Name.ToLower() == "alturabase" || variavel.Name.ToLower() == "largurabase" ? 0 : variavel.Value); if (variavel.Name.ToLower() == "altura" || variavel.Name.ToLower() == "largura" || variavel.Name.ToLower() == "alturabase" || variavel.Name.ToLower() == "largurabase") { variavelCalcEngine.VariavelSistema = variavelCalcEngine.VariavelCalcEngine; } // Seta a variável CalcEngine na lista. lstVariaveisCalcEngine.Add(variavelCalcEngine); } ArquivoCalcEngineVariavelDAO.Instance.DeletaPeloIdArquivoCalcEngine(arquivoCalcEngine.IdArquivoCalcEngine); // Salva as variáveis do CalcEngine. foreach (var variavel in lstVariaveisCalcEngine) { variavel.IdArquivoCalcEngine = arquivoCalcEngine.IdArquivoCalcEngine; // Insere a variável do arquivo CalcEngine e associa-a ao arquivo. ArquivoCalcEngineVariavelDAO.Instance.Insert(variavel); } } catch (Exception ex) { // Deleta as variáveis associadas ao arquivo CalcEngine. ArquivoCalcEngineVariavelDAO.Instance.DeletaPeloIdArquivoCalcEngine(arquivoCalcEngine.IdArquivoCalcEngine); // Retorna uma mensagem informando o erro ocorrido ao salvar o arquivo. throw ex; } } }
static byte[] CaptureWebPageBytesP(string body, int width, int height) { byte[] data; using (WebBrowser web = new WebBrowser()) { web.ScrollBarsEnabled = false; // no scrollbars web.ScriptErrorsSuppressed = true; // no errors web.DocumentText = body; while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents(); web.Width = web.Document.Body.ScrollRectangle.Width; web.Height = web.Document.Body.ScrollRectangle.Height; // a bitmap that we will draw to using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(web.Width, web.Height)) { // draw the web browser to the bitmap web.DrawToBitmap(bmp, new Rectangle(web.Location.X, web.Location.Y, web.Width, web.Height)); // draw the web browser to the bitmap GraphicsUnit units = GraphicsUnit.Pixel; RectangleF destRect = new RectangleF(0F, 0F, width, height); RectangleF srcRect = new RectangleF(0, 0, web.Width, web.Width * 1.5F); Bitmap b = new Bitmap(width, height); Graphics g = Graphics.FromImage((Image)b); g.Clear(Color.White); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(bmp, destRect, srcRect, units); g.Dispose(); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { EncoderParameter qualityParam = null; EncoderParameters encoderParams = null; try { ImageCodecInfo imageCodec = null; imageCodec = GetEncoderInfo("image/jpeg"); qualityParam = new EncoderParameter(Encoder.Quality, 100L); encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; b.Save(stream, imageCodec, encoderParams); } catch (Exception) { throw new Exception(); } finally { if (encoderParams != null) encoderParams.Dispose(); if (qualityParam != null) qualityParam.Dispose(); } b.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); } } } return data; }
static public void Merge(IList <MergeStream> srcList, System.IO.Stream destStream) { List <long> srcEndPositionList = new List <long>(); for (int i = 0; i < srcList.Count; i++) { srcEndPositionList.Add(srcList[i].Stream.Position + srcList[i].Length); } int docsCount = 0; List <DocumentPosition> skipDocIndex = new List <DocumentPosition>(); foreach (MergeStream ms in srcList) { int count = VInt.sReadFromStream(ms.Stream); ms.Count = count; if (count == 0) { //This index has skip doc index ms.SkipDocIndex = (DeserializeSkipDocIndex(ms.Stream, true)); count = VInt.sReadFromStream(ms.Stream); } docsCount += count; } int lastDocId = -1; System.IO.Stream originalDestStream = destStream; destStream = new System.IO.MemoryStream(8192); int remainCount = 0; //remain count does not build in skip doc index for (int i = 0; i < srcList.Count; i++) { System.IO.Stream src = srcList[i].Stream; long srcFirstDocIdPosition = src.Position; int firstDocId = VInt.sReadFromStream(src); long srcFirstDocIdLength = src.Position - srcFirstDocIdPosition; long destFirstDocIdPosition = destStream.Position; if (lastDocId < 0) { VInt.sWriteToStream(firstDocId, destStream); } else { VInt.sWriteToStream(firstDocId - lastDocId, destStream); } long destFirstDocIdLength = destStream.Position - destFirstDocIdPosition; int delta = (int)(destFirstDocIdLength - srcFirstDocIdLength); //build skip doc index if (srcList[i].SkipDocIndex != null) { //Merge skip doc index if (i > 0) { skipDocIndex.Add(new DocumentPosition(lastDocId, (int)destFirstDocIdPosition)); } foreach (DocumentPosition dp in srcList[i].SkipDocIndex) { skipDocIndex.Add(new DocumentPosition(dp.DocId, (int)(destFirstDocIdPosition + dp.Position + delta))); } } else { if (remainCount > 1024) { skipDocIndex.Add(new DocumentPosition(lastDocId, (int)destFirstDocIdPosition)); remainCount = 0; } else { remainCount += srcList[i].Count; } } byte[] buf = new byte[8192]; int remain = (int)(srcEndPositionList[i] - sizeof(int) - src.Position); int len = src.Read(buf, 0, Math.Min(buf.Length, remain)); while (len > 0) { destStream.Write(buf, 0, len); remain -= len; len = src.Read(buf, 0, Math.Min(buf.Length, remain)); } //Get last docid of src byte[] lastDocIdBuf = new byte[sizeof(int)]; src.Read(lastDocIdBuf, 0, lastDocIdBuf.Length); lastDocId = BitConverter.ToInt32(lastDocIdBuf, 0); } //Write last doc id destStream.Write(BitConverter.GetBytes(lastDocId), 0, sizeof(int)); //Write skip doc index if (skipDocIndex.Count > 0) { SerializeSkipDocIndex(originalDestStream, skipDocIndex); } //Write docs count VInt.sWriteToStream(docsCount, originalDestStream); //Write memory buffer to original dest stream destStream.Position = 0; byte[] buffer = new byte[8192]; int c = 0; do { c = destStream.Read(buffer, 0, buffer.Length); if (c > 0) { originalDestStream.Write(buffer, 0, c); } } while (c > 0); }
private static void ParseAvcConfig( MediaStreamDescription stream, List<MediaStreamSample> samples, byte[] data) { System.IO.Stream ios = new System.IO.MemoryStream(data); ios.Seek(5, System.IO.SeekOrigin.Begin); int num_sps = ios.ReadByte() & 0x1f; for (int i = 0; i < num_sps; ++i) { int len_sps = (ios.ReadByte() << 8) | ios.ReadByte(); byte[] sps = new byte[len_sps]; ios.Read(sps, 0, len_sps); samples.Add(new MediaStreamSample( stream, new System.IO.MemoryStream(sps), 0, len_sps, 0, new Dictionary<MediaSampleAttributeKeys, string>())); } int num_pps = ios.ReadByte(); for (int i = 0; i < num_pps; ++i) { int len_pps = (ios.ReadByte() << 8) | ios.ReadByte(); byte[] pps = new byte[len_pps]; ios.Read(pps, 0, len_pps); samples.Add(new MediaStreamSample( stream, new System.IO.MemoryStream(pps), 0, len_pps, 0, new Dictionary<MediaSampleAttributeKeys, string>())); } }
static void Main(string[] args) { var memoryStream = new System.IO.MemoryStream(); // Creates serializer. var serializer = MessagePackSerializer.Get <MyDtoClass>(); MyDtoClass obj = new MyDtoClass(); obj.ID = 2; obj.Name = "Test"; obj.Type = MaleType.Female; // Pack obj to stream. serializer.Pack(memoryStream, obj); memoryStream.Position = 0; var length = memoryStream.Length; byte[] buffer = new byte[length]; memoryStream.Read(buffer, 0, (int)length); memoryStream.Position = 0; // Unpack from stream. var unpackedObject = serializer.Unpack(memoryStream); //obj.ShouldSatisfyAllConditions(unpackedObject); obj.ID.ShouldBe(unpackedObject.ID); obj.Type.ShouldBe(unpackedObject.Type); obj.Name.ShouldBe(unpackedObject.Name); // Creates serializer. var serializer1 = MessagePackSerializer.Get <MyDtoStruct>(); var memoryStream1 = new System.IO.MemoryStream(); MyDtoStruct obj1 = new MyDtoStruct(); obj1.ID = 2; obj1.Name = "Test"; obj1.Type = MaleType.Female; // Pack obj to stream. serializer1.Pack(memoryStream1, obj1); memoryStream1.Position = 0; var length1 = memoryStream.Length; byte[] buffer1 = new byte[length1]; memoryStream1.Read(buffer1, 0, (int)length1); memoryStream1.Position = 0; // Unpack from stream. var unpackedStruct1 = serializer1.Unpack(memoryStream1); Assert.AreEqual(obj1, unpackedStruct1); Assert.AreEqual(buffer, buffer1); }
public bool UploadCaptcha(byte[] jpeg) { HttpClient m_Client=new HttpClient(); string m_Response=""; //Формируем тело POST-запроса string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); string NameAffix = "--" + boundary + "\r\nContent-Disposition: form-data; name=\""; string NameSuffix = "\"\r\n\r\n"; System.IO.MemoryStream postdata = new System.IO.MemoryStream(); //Данные формы string formdata = ""; formdata += NameAffix + "method" + NameSuffix + "post" + "\r\n"; formdata += NameAffix + "key" + NameSuffix + Key + "\r\n"; formdata += NameAffix + "phrase" + NameSuffix + "1" + "\r\n"; //Заголовок для файла formdata += NameAffix + "file\"; filename=\"captcha.jpg\"\r\n"; formdata += "Content-Type: image/jpeg\r\n\r\n"; //Пишемс postdata.Write(Encoding.ASCII.GetBytes(formdata),0,formdata.Length); postdata.Write(jpeg, 0, jpeg.Length); //Готовим окончание formdata="\r\nContent-Disposition: form-data; name=\"commit\"\r\nMake changes\r\n"; formdata += "--" + boundary + "--"; //Пишемс postdata.Write(Encoding.ASCII.GetBytes(formdata), 0, formdata.Length); byte[] buffer=new byte[postdata.Length]; postdata.Seek(0, System.IO.SeekOrigin.Begin); postdata.Read(buffer, 0, buffer.Length); //System.IO.File.WriteAllBytes("log.txt", buffer); //ConsoleLog.WriteLine(buffer, "CapchaLog.txt"); m_Client.Timeout = m_Client.Timeout * 10; m_Response = m_Client.UploadMultipartData( "http://antigate.com/in.php", buffer, boundary); if(m_Response.Substring(0,2)=="OK") { CaptchaID=m_Response.Substring(3); return true; } return false; }
protected void Page_Load(object sender, EventArgs e) { String recNums = "default"; String containerNameConStr = "ContainerConnectionString"; String storageConStr = "StorageConnectionString"; if (Request.QueryString["recordNumber"] != null && Request.QueryString["docType"] != null) { if (authorizedownload()) { try { recNums = (Request.QueryString["recordNumber"]).Trim(); List <String> downLoadFilesCollection = new List <String>(); downLoadFilesCollection = recNums.Split(',').ToList(); containerNameConStr = (Request.QueryString["docType"]).Trim() + containerNameConStr; storageConStr = (Request.QueryString["docType"]).Trim() + storageConStr; String containerName = ConfigurationManager.ConnectionStrings[containerNameConStr].ConnectionString; CloudStorageAccount storageAccount = CloudStorageAccount.Parse( ConfigurationManager.ConnectionStrings[storageConStr].ConnectionString); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(containerName); //ZIp File Name var downloadzipFileName = string.Format((Request.QueryString["docType"]).Trim(), DateTime.Now.ToString()); Response.ContentType = "application/zip"; Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadzipFileName + ".zip"); byte[] buffer = new byte[4096]; ZipOutputStream zipoutputstream = new ZipOutputStream(Response.OutputStream); zipoutputstream.SetLevel(3); // Create Zip File by looping in the collection foreach (String downloadFile in downLoadFilesCollection) { // Retrieve reference to a blob named blobName CloudBlockBlob blockBlob = container.GetBlockBlobReference(downloadFile.Trim()); System.IO.MemoryStream mem = new System.IO.MemoryStream(); blockBlob.DownloadToStream(mem); int count = (int)mem.Length; ZipEntry zipEntry = new ZipEntry(ZipEntry.CleanName(downloadFile + ".tif")); zipEntry.Size = count; zipoutputstream.PutNextEntry(zipEntry); while (count > 0) { zipoutputstream.Write(mem.ToArray(), 0, count); count = mem.Read(mem.ToArray(), 0, count); } } zipoutputstream.Close(); Response.Flush(); } catch (Exception ex) { if (ex.Message.Contains("404")) { Response.Write("No Document found"); } } } } else { Response.Write("Please provide the parameters"); } }
public override void ReadBytes(byte[] b, int offset, int len) { while (len > curAvail) { curBuf.Read(b, offset, curAvail); len -= curAvail; offset += curAvail; curBufIndex++; if (curBufIndex >= buffers.Length) throw new System.IO.IOException("read past EOF"); curBuf = buffers[curBufIndex]; curBuf.Seek(0, System.IO.SeekOrigin.Begin); curAvail = bufSizes[curBufIndex]; } curBuf.Read(b, offset, len); curAvail -= len; }
public long Read(byte[] buffer) { return(ms.Read(buffer, 0, buffer.Length)); }
// TODO: re-add encryption private void BeginReceiveCallback(IAsyncResult ar) { Queue<Action> actionQueue = new Queue<Action>(); try { TcpClient lEndPoint = EndPoint; Thread.MemoryBarrier(); if (lEndPoint == null) { ("NoEndPoint for " + this.DisplayName).Log(); fragmentBuffer = new byte[0]; return; } int cb = lEndPoint.Client.EndReceive(ar); if (cb == 0) { //Disconnect(); return; } byte[] receiveBuffer = ar.AsyncState as byte[]; if (fragmentBuffer.Length > 0) { var temp = new byte[cb + fragmentBuffer.Length]; fragmentBuffer.CopyTo(temp, 0); Array.ConstrainedCopy(receiveBuffer, 0, temp, fragmentBuffer.Length, cb); fragmentBuffer = new byte[0]; receiveBuffer = temp; } else { var temp = new byte[cb]; Array.ConstrainedCopy(receiveBuffer, 0, temp, 0, cb); receiveBuffer = temp; } //("MCNC: receiveBuffer=" + System.Text.Encoding.ASCII.GetString(receiveBuffer)).Log(); var stream = new System.IO.MemoryStream(receiveBuffer); using (var reader = new System.IO.BinaryReader(stream)) { while (stream.Position < stream.Length && stream.ReadByte() == 0x1b) { var lastReadPosition = stream.Position - 1; object o = null; try { var len = reader.ReadUInt16(); byte[] payload = new byte[len]; stream.Read(payload, 0, payload.Length); using (var payloadStream = new System.IO.MemoryStream(payload)) { o = Serializer.ReadObject(payloadStream); } } catch (Exception ex) { //("MCNC: lastReadPosition=" + lastReadPosition + " currentPosition=" + stream.Position).Log(); ex.Log(); // TODO: log/debug exception types thrown here, not documented on MSDN and it's not clear how to handle a buffer underrun in ReadObject // TODO: if the exception is due to an unknown type, the fragmentBuffer logic will result in a deadlock on the network (always retrying a bad object) o = null; } if (o == null) { stream.Seek(lastReadPosition, System.IO.SeekOrigin.Begin); fragmentBuffer = new byte[stream.Length - lastReadPosition]; stream.Read(fragmentBuffer, 0, fragmentBuffer.Length); break; } else { EnqueueAction(actionQueue, o); } } } if (actionQueue.Count == 0) { ("NoActions for " + this.DisplayName).Log(); return; } #region process action queue while (actionQueue.Count > 0) { Action action = actionQueue.Dequeue(); if (action != null) { try { action(); } catch (Exception ex) { ex.Log(); } } } #endregion process action queue } catch (SocketException) { Disconnect(); } catch (ObjectDisposedException) { Disconnect(); } catch (Exception ex) { ex.Log(); } finally { StartReceiving(); } }
/// <summary> /// 指定したオブジェクトを指定した型として文字列に変換します。 /// </summary> /// <param name="t">変換元のオブジェクトの型を指定します。</param> /// <param name="value">変換元のオブジェクトを指定します。</param> /// <returns>変換後の文字列を返します。</returns> public static string ToString(System.Type t, object value) { switch (t.FullName.GetHashCode() & 0x7fffffff) { case 0x038D0F82: if (t != typeof(System.Int16)) { goto default; } return(System.Convert.ToString((System.Int16)value)); case 0x6D318EFD: if (t != typeof(System.UInt16)) { goto default; } return(System.Convert.ToString((System.UInt16)value)); case 0x1B47F8B8: if (t != typeof(System.Int32)) { goto default; } return(System.Convert.ToString((System.Int32)value)); case 0x03FB8EF9: if (t != typeof(System.UInt32)) { goto default; } return(System.Convert.ToString((System.UInt32)value)); case 0x4A1B9AE7: if (t != typeof(System.Int64)) { goto default; } return(System.Convert.ToString((System.Int64)value)); case 0x61CC8EFB: if (t != typeof(System.UInt64)) { goto default; } return(System.Convert.ToString((System.UInt64)value)); case 0x4EE7D89D: if (t != typeof(System.SByte)) { goto default; } return(System.Convert.ToString((System.SByte)value)); case 0x2F001A17: if (t != typeof(System.Byte)) { goto default; } return(System.Convert.ToString((System.Byte)value)); case 0x1B1EFB13: if (t != typeof(System.Decimal)) { goto default; } return(System.Convert.ToString((System.Decimal)value)); case 0x44059415: if (t != typeof(System.Char)) { goto default; } return(System.Convert.ToString((System.Char)value)); case 0x3EACB635: if (t != typeof(System.Single)) { goto default; } return(System.Convert.ToString((System.Single)value)); case 0x0ED5FC72: if (t != typeof(System.Double)) { goto default; } return(System.Convert.ToString((System.Double)value)); case 0x71309BFC: if (t != typeof(System.Boolean)) { goto default; } return(System.Convert.ToString((System.Boolean)value)); case 0x5981F920: if (t != typeof(System.String)) { goto default; } return((string)value); case 0x1D77C984: if (t != typeof(System.IntPtr)) { goto default; } return(System.Convert.ToString((System.Int64)value)); case 0x65648F3B: if (t != typeof(System.UIntPtr)) { goto default; } return(System.Convert.ToString((System.UInt64)value)); case 0x29BD8EB6: if (t != typeof(System.Guid)) { goto default; } return(System.Xml.XmlConvert.ToString((System.Guid)value)); case 0x1FE98930: if (t != typeof(System.TimeSpan)) { goto default; } return(System.Xml.XmlConvert.ToString((System.TimeSpan)value)); case 0x4A398CD8: if (t != typeof(System.DateTime)) { goto default; } //.NET Framework 2.0 : System.Xml.XmlDateTimeSerializationMode を指定 return(System.Convert.ToString((System.DateTime)value)); case 0x7F721A17: if (t != typeof(System.Type)) { goto default; } return(((System.Type)value).FullName); case 0x0458EA59: if (t != typeof(System.Boolean[])) { goto default; } return(ToString((bool[])value)); default: // typeconv: if (t.IsEnum) { return(value.ToString()); //System.Enum } if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0) { goto serial; } System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t); if (conv.CanConvertTo(typeof(string)) && conv.CanConvertFrom(typeof(string))) { try{ return(conv.ConvertToString(value)); }catch {} } serial: if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0) { goto op_implicit; } using (System.IO.MemoryStream memstr = new System.IO.MemoryStream()){ Convert.binF.Serialize(memstr, value); //--長さ int len; try{ len = (int)memstr.Length; }catch (System.Exception e) { throw new System.Exception("データの量が大きすぎるので文字列に変換できません", e); } //--文字列に変換 byte[] buff = new byte[len]; memstr.Position = 0; memstr.Read(buff, 0, len); return(System.Convert.ToBase64String(buff)); } op_implicit: System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic); for (int i = 0; i < ms.Length; i++) { if (ms[i].Name != "op_Implicit" || ms[i].ReturnType != typeof(string)) { continue; } System.Reflection.ParameterInfo[] ps = ms[i].GetParameters(); if (ps.Length != 1 || ps[0].ParameterType != t) { continue; } return((string)ms[i].Invoke(null, new object[] { value })); } throw new System.ArgumentException(string.Format(TOSTR_NOTSUPPORTEDTYPE, t), "t"); } #if NET1_1 switch (t.FullName.GetHashCode() & 0x7fffffff) { case 0x2DBDA61A: //case 0xE31638: if (t != typeof(System.Int16)) { goto default; } return(System.Convert.ToString((System.Int16)value)); case 0x1107D7EF: //case 0xE3166C: if (t != typeof(System.UInt16)) { goto default; } return(System.Convert.ToString((System.UInt16)value)); case 0x2DBDA65C: //case 0xE312F4: if (t != typeof(System.Int32)) { goto default; } return(System.Convert.ToString((System.Int32)value)); case 0x1107D829: //case 0xE316A0: if (t != typeof(System.UInt32)) { goto default; } return(System.Convert.ToString((System.UInt32)value)); case 0x2DBDA63F: //case 0xE316D4: if (t != typeof(System.Int64)) { goto default; } return(System.Convert.ToString((System.Int64)value)); case 0x1107D84A: //case 0xE31708: if (t != typeof(System.UInt64)) { goto default; } return(System.Convert.ToString((System.UInt64)value)); case 0x2EF00F97: //case 0xE315D0: if (t != typeof(System.SByte)) { goto default; } return(System.Convert.ToString((System.SByte)value)); case 0x244D3E44: //case 0xE31604: if (t != typeof(System.Byte)) { goto default; } return(System.Convert.ToString((System.Byte)value)); case 0x32C73145: //case 0xE317A4: if (t != typeof(System.Decimal)) { goto default; } return(System.Convert.ToString((System.Decimal)value)); case 0x244C7CD6: //case 0xE3159C: if (t != typeof(System.Char)) { goto default; } return(System.Convert.ToString((System.Char)value)); case 0x0EC74674: //case 0xE3173C: if (t != typeof(System.Single)) { goto default; } return(System.Convert.ToString((System.Single)value)); case 0x5E38073B: //case 0xE31770: if (t != typeof(System.Double)) { goto default; } return(System.Convert.ToString((System.Double)value)); case 0x604332EA: //case 0xE31568: if (t != typeof(System.Boolean)) { goto default; } return(System.Convert.ToString((System.Boolean)value)); case 0x0DE37C3B: //case 0xE31328: if (t != typeof(System.String)) { goto default; } return((string)value); case 0x6572ED4B: //case 0xE37678: if (t != typeof(System.IntPtr)) { goto default; } return(System.Convert.ToString((System.Int64)value)); case 0x3203515E: //case 0xE376AC: if (t != typeof(System.UIntPtr)) { goto default; } return(System.Convert.ToString((System.UInt64)value)); case 0x244AC511: //case 0xE376E0: if (t != typeof(System.Guid)) { goto default; } return(System.Xml.XmlConvert.ToString((System.Guid)value)); case 0x4BD7DD17: //case 0xE37714: if (t != typeof(System.TimeSpan)) { goto default; } return(System.Xml.XmlConvert.ToString((System.TimeSpan)value)); case 0x7F9DDECF: //case 0xE317D8: if (t != typeof(System.DateTime)) { goto default; } //.NET Framework 2.0 : System.Xml.XmlDateTimeSerializationMode を指定 return(System.Convert.ToString((System.DateTime)value)); case 0x24524716: //case 0xE37610: if (t != typeof(System.Type)) { goto default; } return(((System.Type)value).FullName); // case 0x2453BC7A://case 0xE37748: // if(t!=typeof(void))goto default; // break; case 0x7DDB9ECC: //case 0xE37778: if (t != typeof(System.Boolean[])) { goto default; } return(ToString((bool[])value)); // case 0x45EBBE0: // if(t!=typeof(System.Windows.Forms.SelectionRange))goto default; // return Convert.selectionRangeConv.ConvertToString(value); // case 0x244D9E9D://case 0xE311BC: // if(t!=typeof(System.Enum))goto default; // return System.Xml.XmlConvert.ToString((System.Int64)value); default: // typeconv: if (t.IsEnum) { return(value.ToString()); //System.Enum } if (t.GetCustomAttributes(typeof(System.ComponentModel.TypeConverterAttribute), false).Length == 0) { goto serial; } System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(t); if (conv.CanConvertTo(typeof(string)) && conv.CanConvertFrom(typeof(string))) { try{ return(conv.ConvertToString(value)); }catch {} } serial: if (t.GetCustomAttributes(typeof(System.SerializableAttribute), false).Length == 0) { goto op_implicit; } using (System.IO.MemoryStream memstr = new System.IO.MemoryStream()){ Convert.binF.Serialize(memstr, value); //--長さ int len; try{ len = (int)memstr.Length; }catch (System.Exception e) { throw new System.Exception("データの量が大きすぎるので文字列に変換できません", e); } //--文字列に変換 byte[] buff = new byte[len]; memstr.Position = 0; memstr.Read(buff, 0, len); return(System.Convert.ToBase64String(buff)); } op_implicit: System.Reflection.MethodInfo[] ms = t.GetMethods(BF_PublicStatic); for (int i = 0; i < ms.Length; i++) { if (ms[i].Name != "op_Implicit" || ms[i].ReturnType != typeof(string)) { continue; } System.Reflection.ParameterInfo[] ps = ms[i].GetParameters(); if (ps.Length != 1 || ps[0].ParameterType != t) { continue; } return((string)ms[i].Invoke(null, new object[] { value })); } throw new System.ArgumentException(string.Format(TOSTR_NOTSUPPORTEDTYPE, t), "t"); } #endif }