public override void Write(ref NetworkStream netstream) { using (Stream stream = new MemoryStream()) { // write id stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2); // write body size stream.Write(BitConverter.GetBytes(0), 0, 4); // write isAdult stream.WriteByte(BitConverter.GetBytes(this.isAdult)[0]); // write UnderFifteen stream.WriteByte(BitConverter.GetBytes(this.UnderFifteen)[0]); // write Family stream.WriteByte(BitConverter.GetBytes(this.Family)[0]); // write Status stream.WriteByte(this.Status); // write LastDay stream.Write(BitConverter.GetBytes(this.LastDay), 0, 2); // write PayType stream.WriteByte(this.PayType); // copy stream to netstream stream.Position = 0; stream.CopyTo(netstream); } }
public byte[] ToBytes() { var memoryStream = new MemoryStream(); const bool rsv1 = false; const bool rsv2 = false; const bool rsv3 = false; var bt = (IsFinal ? 1 : 0) * 0x80; bt += (rsv1 ? 0x40 : 0x0); bt += (rsv2 ? 0x20 : 0x0); bt += (rsv3 ? 0x10 : 0x0); bt += (byte)FrameType; memoryStream.WriteByte((byte)bt); byte[] payloadLengthBytes = GetLengthBytes(); memoryStream.Write(payloadLengthBytes, 0, payloadLengthBytes.Length); byte[] payload = Payload; if (IsMasked) { byte[] keyBytes = BitConverter.GetBytes(MaskKey); if (BitConverter.IsLittleEndian) Array.Reverse(keyBytes); memoryStream.Write(keyBytes, 0, keyBytes.Length); payload = TransformBytes(Payload, MaskKey); } memoryStream.Write(payload, 0, Payload.Length); return memoryStream.ToArray(); }
// RFC: http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm private void UrlEncodeAndWrite(string value, MemoryStream memoryStream) { foreach (char symbol in value) { if (unreservedChars.IndexOf(symbol) != -1) { memoryStream.WriteByte((byte)symbol); } else if (symbol == ' ') { memoryStream.WriteByte(plus); } else if (symbol < 255) { var encodedValue = Encoding.ASCII.GetBytes(String.Format("%{0:X2}", (byte)symbol)); memoryStream.Write(encodedValue, 0, encodedValue.Length); } else { var bytes = Encoding.UTF8.GetBytes(new[] { symbol }); foreach (var @byte in bytes) { var encodedValue = Encoding.ASCII.GetBytes(String.Format("%{0:X2}", @byte)); memoryStream.Write(encodedValue, 0, encodedValue.Length); } } } }
public byte[] SerializeEvent(ISourcedEvent e) { byte[] content; using (var ms = new MemoryStream()) { serializer.Serialize(e, e.GetType(), ms); content = ms.ToArray(); } byte[] messageContractBuffer; using (var ms = new MemoryStream()) { var name = e.GetType().GetContractName(); var messageContract = new MessageContract(name, content.Length, 0, e.EventIdentifier, e.EventSequence); serializer.Serialize(messageContract, typeof(MessageContract), ms); messageContractBuffer = ms.ToArray(); } using (var ms = new MemoryStream()) { var headerContract = new MessageHeaderContract(messageContractBuffer.Length); headerContract.WriteHeader(ms); ms.Write(messageContractBuffer, 0, messageContractBuffer.Length); ms.Write(content, 0, content.Length); return ms.ToArray(); } }
public static AESKeyData GenerateKeyDataFromNonces(byte[] serverNonce, byte[] newNonce) { using (SHA1 hash = new SHA1Managed()) { var nonces = new byte[48]; newNonce.CopyTo(nonces, 0); serverNonce.CopyTo(nonces, 32); byte[] hash1 = hash.ComputeHash(nonces); serverNonce.CopyTo(nonces, 0); newNonce.CopyTo(nonces, 16); byte[] hash2 = hash.ComputeHash(nonces); nonces = new byte[64]; newNonce.CopyTo(nonces, 0); newNonce.CopyTo(nonces, 32); byte[] hash3 = hash.ComputeHash(nonces); using (var keyBuffer = new MemoryStream(32)) using (var ivBuffer = new MemoryStream(32)) { keyBuffer.Write(hash1, 0, hash1.Length); keyBuffer.Write(hash2, 0, 12); ivBuffer.Write(hash2, 12, 8); ivBuffer.Write(hash3, 0, hash3.Length); ivBuffer.Write(newNonce, 0, 4); return new AESKeyData(keyBuffer.ToArray(), ivBuffer.ToArray()); } } }
public static Stream CreateCryptoStream(Stream stream, bool encrypt, MasterKey key, KeePassFileHeaderInformation headerInfo) { byte[] encryptionKey = null; try { using (var ms = new MemoryStream()) { byte[] masterKeyData = GenerateKey(key, headerInfo.MasterKeyHashKey, headerInfo.MasterKeyHashRounds); if (masterKeyData == null) throw new Exception("Invalid Master Key or Invalid Master Key Generation"); ms.Write(headerInfo.DatabaseCipherKeySeed); ms.Write(masterKeyData); masterKeyData.Clear(); encryptionKey = ms.ToSHA256Hash(); } if (encryptionKey == null) throw new Exception("Invalid Master Key or Key Generation"); var encryptionEngine = Find(headerInfo.DatabaseCipherId); if (encryptionEngine == null) throw new Exception($"Encryption Engine could not be found for Id {headerInfo.DatabaseCipherId}"); return encryptionEngine.CreateCryptoStream(stream, encrypt, encryptionKey, headerInfo.DatabaseCipherIV); } finally { encryptionKey.Clear(); } }
public void With_WebSocket_CanReadTwoBufferedSmallFrames() { var handshake = GenerateSimpleHandshake(); using (var ms = new MemoryStream()) using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions)) { ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8); ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); var reader = ws.ReadMessageAsync(CancellationToken.None).Result; Assert.IsNotNull(reader); using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true)) { String s = sr.ReadToEnd(); Assert.AreEqual("Hi", s); } reader = ws.ReadMessageAsync(CancellationToken.None).Result; Assert.IsNotNull(reader); using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true)) { String s = sr.ReadToEndAsync().Result; Assert.AreEqual("Hi", s); } reader = ws.ReadMessageAsync(CancellationToken.None).Result; Assert.IsNull(reader); } }
public virtual void SendSync(int frame, byte[] syncData) { var ms = new MemoryStream(); ms.Write(BitConverter.GetBytes(frame)); ms.Write(syncData); Send(ms.ToArray()); }
/// <summary> /// Returns the parameters array formatted for multi-part/form data /// </summary> /// <returns></returns> public byte[] GetPostDataWithMultipart(string boundary) { var ms = new MemoryStream(); foreach (var p in Params) { if (p.Type == PostDataParamType.File) { var header = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\";\r\nContent-Type: application/octet-stream\r\n\r\n", boundary, p.FilePath); ms.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); ms.Write((byte[])p.Value, 0, ((byte[])p.Value).Length); } else { var postData = string.Format("\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, p.Name, p.Value); ms.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } var footer = "\r\n--" + boundary + "--\r\n"; ms.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); ms.Position = 0; var tempBuffer = new byte[ms.Length]; ms.Read(tempBuffer, 0, tempBuffer.Length); ms.Close(); return tempBuffer; }
public byte[] ToBytes() { var memoryStream = new MemoryStream(); byte op = (byte)((byte)FrameType + (IsFinal ? 128 : 0)); memoryStream.WriteByte(op); var payloadLengthBytes = GetLengthBytes(); memoryStream.Write(payloadLengthBytes, 0, payloadLengthBytes.Length); var payload = Payload; if (IsMasked) { var keyBytes = BitConverter.GetBytes(MaskKey); if (BitConverter.IsLittleEndian) Array.Reverse(keyBytes); memoryStream.Write(keyBytes, 0, keyBytes.Length); payload = TransformBytes(Payload, MaskKey); } memoryStream.Write(payload, 0, Payload.Length); return memoryStream.ToArray(); }
public void TestReadContinued() { //simulate a continues Drawing record MemoryStream out1 = new MemoryStream(); //main part DrawingRecord dg = new DrawingRecord(); byte[] data1 = new byte[8224]; Arrays.Fill(data1, (byte)1); dg.Data = (/*setter*/data1); byte[] dataX = dg.Serialize(); out1.Write(dataX, 0, dataX.Length); //continued part byte[] data2 = new byte[4048]; Arrays.Fill(data2, (byte)2); ContinueRecord cn = new ContinueRecord(data2); dataX = cn.Serialize(); out1.Write(dataX, 0, dataX.Length); List<Record> rec = RecordFactory.CreateRecords(new MemoryStream(out1.ToArray())); Assert.AreEqual(2, rec.Count); Assert.IsTrue(rec[0] is DrawingRecord); Assert.IsTrue(rec[1] is ContinueRecord); Assert.IsTrue(Arrays.Equals(data1, ((DrawingRecord)rec[0]).Data)); Assert.IsTrue(Arrays.Equals(data2, ((ContinueRecord)rec[1]).Data)); }
public static void ExportSchedulesFITFile(Stream exportStream, MemoryStream dataStream) { MemoryStream tempDataStream = new MemoryStream(); // Reserve size for header tempDataStream.Write(new Byte[12], 0, 12); // File id message FITMessage fileIdMessage = new FITMessage(FITGlobalMessageIds.FileId); FITMessageField fileType = new FITMessageField((Byte)FITFileIdFieldsIds.FileType); FITMessageField manufacturerId = new FITMessageField((Byte)FITFileIdFieldsIds.ManufacturerId); FITMessageField productId = new FITMessageField((Byte)FITFileIdFieldsIds.ProductId); FITMessageField serialNumber = new FITMessageField((Byte)FITFileIdFieldsIds.SerialNumber); FITMessageField exportDate = new FITMessageField((Byte)FITFileIdFieldsIds.ExportDate); FITMessageField number = new FITMessageField((Byte)FITFileIdFieldsIds.Number); manufacturerId.SetUInt16(1); fileType.SetEnum((Byte)FITFileTypes.Schedules); // Invalid fields productId.SetUInt16(0xFFFF); serialNumber.SetUInt32z(0); exportDate.SetUInt32(0xFFFFFFFF); number.SetUInt16(0xFFFF); fileIdMessage.AddField(serialNumber); fileIdMessage.AddField(exportDate); fileIdMessage.AddField(manufacturerId); fileIdMessage.AddField(productId); fileIdMessage.AddField(number); fileIdMessage.AddField(fileType); fileIdMessage.Serialize(tempDataStream); // Write all passed in data to output stream tempDataStream.Write(dataStream.GetBuffer(), 0, (int)dataStream.Length); // Write FIT header at the start of the stream GarminFitnessByteRange headerSize = new GarminFitnessByteRange(12); GarminFitnessByteRange protocolVersion = new GarminFitnessByteRange((Byte)((FITConstants.FITProtocolMajorVersion << 4) | FITConstants.FITProtocolMinorVersion)); GarminFitnessUInt16Range profileVersion = new GarminFitnessUInt16Range((UInt16)((FITConstants.FITProfileMajorVersion * FITConstants.FITProfileMajorVersionMultiplier) + FITConstants.FITProfileMinorVersion)); GarminFitnessInt32Range dataSize = new GarminFitnessInt32Range(0); tempDataStream.Seek(0, SeekOrigin.Begin); dataSize.Value = (int)tempDataStream.Length - 12; headerSize.Serialize(tempDataStream); protocolVersion.Serialize(tempDataStream); profileVersion.Serialize(tempDataStream); dataSize.Serialize(tempDataStream); tempDataStream.Write(Encoding.UTF8.GetBytes(FITConstants.FITFileDescriptor), 0, 4); // Write CRC GarminFitnessUInt16Range crc = new GarminFitnessUInt16Range(FITUtils.ComputeStreamCRC(tempDataStream)); tempDataStream.Seek(0, SeekOrigin.End); crc.Serialize(tempDataStream); // Write all data to output stream exportStream.Write(tempDataStream.GetBuffer(), 0, (int)tempDataStream.Length); }
/// <summary> /// AES加密 /// </summary> /// <param name="plainText">要加密的字串</param> /// <returns>加密后的字串</returns> public static string EncryptStringAES(string plainText) { if (string.IsNullOrEmpty(plainText)) throw new ArgumentNullException("plainText"); string outStr = null; RijndaelManaged aesAlg = null; try { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _salt); aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { if (aesAlg != null) aesAlg.Clear(); } return outStr; }
public override void Save(Image i, System.IO.Stream dest) { MemoryStream m = new MemoryStream(); m.WriteByte(0); #warning Change this next byte to 255 if you update Image with UInt64 for width and height. m.WriteByte(0); m.WriteByte(0); m.WriteByte(0); // Write the 8 empty bytes at the start of the file. m.WriteByte(0); m.WriteByte(0); m.WriteByte(0); m.WriteByte(0); byte[] dat = BitConverter.GetBytes(i.Height); // Write the height. m.Write(dat, 0, dat.Length); dat = BitConverter.GetBytes(i.Width); // Write the width. m.Write(dat, 0, dat.Length); // Now to write the actual data. Pixel p; for (uint x = 0; x < i.Width; x++) { for (uint y = 0; y < i.Height; y++) { p = i.GetPixel(x, y); m.WriteByte(p.R); m.WriteByte(p.G); m.WriteByte(p.B); m.WriteByte(p.A); } } dat = Orvid.Compression.LZMA.Compress(m.GetBuffer()); dest.WriteByte(255); dest.Write(dat, 0, dat.Length); }
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary) { using (Stream formDataStream = new MemoryStream()) { foreach (var param in postParameters) if (param.Value is FileParameter) { FileParameter fileToUpload = (FileParameter)param.Value; // Add just the first part of this param, since we will write the file data directly to the Stream string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", boundary, param.Key, fileToUpload.FileName ?? param.Key, fileToUpload.ContentType ?? "application/octet-stream"); formDataStream.Write(_encoding.GetBytes(header), 0, header.Length); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length); // Thanks to feedback from commenters, add a CRLF to allow multiple files to be uploaded //formDataStream.Write(encoding.GetBytes("\r\n"), 0, 2); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key, param.Value); formDataStream.Write(_encoding.GetBytes(postData), 0, postData.Length); } // Add the end of the request string footer = String.Format("\r\n--{0}--\r\n", boundary); formDataStream.Write(_encoding.GetBytes(footer), 0, footer.Length); // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return formData; } }
public static string ComputeId(Tree tree) { using (var md = new MessageDigest()) { using (var ms = new MemoryStream()) { foreach (var item in tree.Items) { var data = Encoding.Default.GetBytes(string.Format("{0} {1}\0", item.Mode, item.Name)); ms.Write(data, 0, data.Length); var id = Helper.IdToByteArray(item.Id); ms.Write(id, 0, id.Length); } var header = Encoding.Default.GetBytes(string.Format("tree {0}\0", ms.Length)); ms.Position = 0; md.Update(header); md.Update(ms); } var digest = md.Digest(); return Helper.ByteArrayToId(digest); } }
/// <summary> /// Get header of current frame according to specific Size /// </summary> /// <param name="MinorVersion">Minor version of ID3v2</param> /// <returns>MemoryStream contain frame header</returns> protected MemoryStream FrameHeader(int MinorVersion) { byte[] Buf; MemoryStream ms = new MemoryStream(); int FrameIDLength = MinorVersion == 2 ? 3 : 4; // Length of FrameID according to version string Temp = _FrameID; // if minor version of ID3 were 2, the frameID is 3 character length if (MinorVersion == 2) { Temp = FramesInfo.Get3CharID(Temp); if (Temp == null) // This frame is not availabe in this version return null; } ms.Write(Encoding.ASCII.GetBytes(Temp), 0, FrameIDLength); // Write FrameID Buf = BitConverter.GetBytes(Length); Array.Reverse(Buf); if (MinorVersion == 2) ms.Write(Buf, 1, Buf.Length - 1); // Write Frame Size else ms.Write(Buf, 0, Buf.Length); // Write Frame Size if (MinorVersion != 2) { // If newer than version 2 it have Flags Buf = BitConverter.GetBytes((ushort)_FrameFlags); Array.Reverse(Buf); ms.Write(Buf, 0, Buf.Length); // Write Frame Flag } return ms; }
public static bool CheckValid(byte[] signature, byte[] message, byte[] publicKey) { if (signature.Length != BitLength / 4) throw new ArgumentException("Signature length is wrong"); if (publicKey.Length != BitLength / 8) throw new ArgumentException("Public key length is wrong"); byte[] rByte = Arrays.CopyOfRange(signature, 0, BitLength / 8); var r = DecodePoint(rByte); var a = DecodePoint(publicKey); byte[] sByte = Arrays.CopyOfRange(signature, BitLength / 8, BitLength / 4); BigInteger s = DecodeInt(sByte); BigInteger h; using (var stemp = new MemoryStream(32 + publicKey.Length + message.Length)) { var encodePoint = EncodePoint(r.Item1, r.Item2); stemp.Write(encodePoint, 0, encodePoint.Length); stemp.Write(publicKey, 0, publicKey.Length); stemp.Write(message, 0, message.Length); h = HashInt(stemp.ToArray()); } var ra = ScalarMul(B, s); var ah = ScalarMul(a, h); var rb = Edwards(r.Item1, r.Item2, ah.Item1, ah.Item2); if (!ra.Item1.Equals(rb.Item1) || !ra.Item2.Equals(rb.Item2)) return false; return true; }
private byte[] BuildFormData(Dictionary<string, object> data, string boundary, byte[] boundaryBytes) { using (MemoryStream ms = new MemoryStream()) { string template = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; string fileTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; foreach (KeyValuePair<string, object> kvp in data) { if (kvp.Value == null) continue; ms.Write(boundaryBytes, 0, boundaryBytes.Length); if (kvp.Value.GetType() == typeof(FileInfo)) { FileInfo file = (FileInfo)kvp.Value; if (!file.Exists) throw new FileNotFoundException(file.FullName); byte[] header = Encoding.UTF8.GetBytes(string.Format(fileTemplate, kvp.Key, file.Name, file.GetMimeType())); ms.Write(header, 0, header.Length); byte[] bytes = File.ReadAllBytes(file.FullName); ms.Write(bytes, 0, bytes.Length); } else { byte[] bytes = Encoding.UTF8.GetBytes(string.Format(template, kvp.Key, kvp.Value)); ms.Write(bytes, 0, bytes.Length); } } byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); ms.Write(trailer, 0, trailer.Length); return ms.ToArray(); } }
/// <summary> /// Encrypt the given string using AES. The string can be decrypted using /// DecryptStringAES(). The sharedSecret parameters must match. /// </summary> /// <param name="plainText">The text to encrypt.</param> /// <param name="sharedSecret">A password used to generate a key for encryption.</param> public static byte[] EncryptStringAES(string plainText) { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); using (RijndaelManaged aesAlg = new RijndaelManaged()) { aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { // prepend the IV msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } } return msEncrypt.ToArray(); } } }
private static byte[] FrameData(byte[] payload, FrameType frameType) { using (var memoryStream = new MemoryStream()) { var op = (byte) ((byte) frameType + 128); memoryStream.WriteByte(op); if (payload.Length > UInt16.MaxValue) { memoryStream.WriteByte(127); var lengthBytes = payload.Length.ToBigEndianBytes<ulong>(); memoryStream.Write(lengthBytes, 0, lengthBytes.Length); } else if (payload.Length > 125) { memoryStream.WriteByte(126); var lengthBytes = payload.Length.ToBigEndianBytes<ushort>(); memoryStream.Write(lengthBytes, 0, lengthBytes.Length); } else { memoryStream.WriteByte((byte) payload.Length); } memoryStream.Write(payload, 0, payload.Length); return memoryStream.ToArray(); } }
private static void TestParseCore( string content, string expected, bool writeBom ) { using ( var buffer = new MemoryStream() ) { if ( writeBom ) { var bom = Encoding.UTF8.GetPreamble(); buffer.Write( bom, 0, bom.Length ); } var contentBytes = Encoding.UTF8.GetBytes( content ); buffer.Write( contentBytes, 0, contentBytes.Length ); buffer.Position = 0; SvcDirectiveParserState target = new InitialState(); using ( var reader = new StreamReader( buffer ) ) { do { target = target.Parse( reader ); } while ( !target.IsFinished ); } Assert.That( target.Directive.Service, Is.EqualTo( expected ) ); } }
public static byte[] Protect(byte[] encryptionKey, byte[] validationKey, byte[] initializationVector, byte[] plainText) { using (var provider = new AesCryptoServiceProvider()) { using (ICryptoTransform transform = provider.CreateEncryptor(encryptionKey, initializationVector)) { using (var ms = new MemoryStream()) { ms.Write(initializationVector, 0, initializationVector.Length); using (var cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { // Encrypted payload cryptoStream.Write(plainText, 0, plainText.Length); cryptoStream.FlushFinalBlock(); // Compute signature using (var sha = new HMACSHA256(validationKey)) { checked { byte[] signature = sha.ComputeHash(ms.GetBuffer(), 0, (int)ms.Length); // Write the signature to the paylod ms.Write(signature, 0, signature.Length); // Final bytes return ms.ToArray(); } } } } } } }
public static byte[] Encrypt(byte[] payload, CryptoContext cryptoContext) { var csEncrypt = cryptoContext.CryptoStreamOut; var output = cryptoContext.OutputStream; output.Position = 0; output.SetLength(0); using (MemoryStream hashStream = new MemoryStream()) { // hash SHA256Managed crypt = new SHA256Managed(); hashStream.Write(BitConverter.GetBytes(Interlocked.Increment(ref cryptoContext.SendCounter)), 0, 8); hashStream.Write(payload, 0, payload.Length); hashStream.Write(cryptoContext.Algorithm.Key, 0, cryptoContext.Algorithm.Key.Length); var hashBuffer = hashStream.ToArray(); byte[] validationCheckSum = crypt.ComputeHash(hashBuffer, 0, hashBuffer.Length); byte[] content = payload.Concat(validationCheckSum.Take(8)).ToArray(); csEncrypt.Write(content, 0, content.Length); csEncrypt.Flush(); } return output.ToArray(); }
public static byte[] DecodeFromHex(byte[] inputBytes, bool bUseSpaces) { FromHexTransform hexTransform = new FromHexTransform(); byte[] outputBytes = new byte[hexTransform.OutputBlockSize]; MemoryStream outputStream = new MemoryStream(); int i = 0; while (inputBytes.Length - i > hexTransform.InputBlockSize) { hexTransform.TransformBlock(inputBytes, i, hexTransform.InputBlockSize, outputBytes, 0); i += hexTransform.InputBlockSize; if (bUseSpaces) { i++; } outputStream.Write(outputBytes, 0, hexTransform.OutputBlockSize); } outputBytes = hexTransform.TransformFinalBlock(inputBytes, i, inputBytes.Length - i); outputStream.Write(outputBytes, 0, outputBytes.Length); //string strRet = System.Text.Encoding.UTF8.GetString(outputStream.ToArray()); byte[] arRet = outputStream.ToArray(); outputStream.Close(); return arRet; }
public static Stream Decrypt(Stream source, Headers headers, byte[] masterKey) { byte[] easKey; using (var buffer = new MemoryStream()) { var masterSeed = headers.MasterSeed; buffer.Write(masterSeed, 0, masterSeed.Length); buffer.Write(masterKey, 0, masterKey.Length); easKey = BufferEx.GetHash(buffer.ToArray()); } var eas = new AesManaged { KeySize = 256, Key = BufferEx.Clone(easKey), IV = BufferEx.Clone(headers.EncryptionIV) }; Stream stream = new CryptoStream(source, eas.CreateDecryptor(), CryptoStreamMode.Read); if (!VerifyStartBytes(headers, stream)) return null; stream = new HashedBlockStream(stream, true); return headers.Compression == Compressions.GZip ? new GZipInputStream(stream) : stream; }
public override byte[] GetBytes(ID3v2TagVersion tagVersion) { // TODO: Test if (string.IsNullOrEmpty(Text)) return new byte[0]; byte[] contentDescriptorData; byte[] textData; do { contentDescriptorData = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, ContentDescriptor, true); textData = ID3v2Utils.GetStringBytes(tagVersion, TextEncoding, Text, false); } while ( this.RequiresFix(tagVersion, ContentDescriptor, contentDescriptorData) || this.RequiresFix(tagVersion, Text, textData) ); using (MemoryStream frameData = new MemoryStream()) { frameData.WriteByte((byte)TextEncoding); frameData.Write(ByteUtils.ISO88591GetBytes(LanguageCode)); frameData.Write(contentDescriptorData); frameData.Write(textData); return _frameHeader.GetBytes(frameData, tagVersion, GetFrameID(tagVersion)); } }
public MemoryStream Encode(MemoryStream memoryStream) { memoryStream.Position = 0; byte[] buffer320 = new byte[320]; byte[] buffer32 = new byte[32]; MemoryStream raw2armData = new MemoryStream(); raw2armData.Write(Encoding.UTF8.GetBytes("#!AMR\n"), 0, 6); AMR_Encoder enc = new AMR_Encoder(); int start = 0; int end = Convert.ToInt32(memoryStream.Length); memoryStream.Position = start; while (true) { if (end - start < 320) { memoryStream.Read(buffer320, 0, end - start); for (int i = end - start; i < 320; i++) { buffer320[i] = 0; } } else { memoryStream.Read(buffer320, 0, 320); } enc.Encode(buffer320, 0, buffer32, 0); raw2armData.Write(buffer32, 0, buffer32.Length); start += 320; if (start >= end) break; } return raw2armData; }
/// <summary> /// Generates a buffer in which it puts the lenght of transaction's propagation token, /// the propagation token, and lastly the message bytes. If the transaction propagation token /// is null, we insert 4 null bytes at the beginning of the buffer. /// </summary> public static byte[] WriteTransactionMessageBuffer(byte[] txPropToken, ArraySegment<Byte> message) { // start writing all the info into a memory buffer MemoryStream mem = new MemoryStream(); // copy the bytes encoding the length of the txPropToken // first get the bytes representing the length of the txPropToken byte[] txLengthBytes; if (txPropToken != null) { txLengthBytes = BitConverter.GetBytes(txPropToken.Length); } else { txLengthBytes = BitConverter.GetBytes((int)0); } mem.Write(txLengthBytes, 0, txLengthBytes.Length); // copy the bytes of the transaction propagation token if (txPropToken != null) { mem.Write(txPropToken, 0, txPropToken.Length); } // copy the message bytes mem.Write(message.Array, message.Offset, message.Count); return mem.ToArray(); }
/// <summary> /// Gets the image entries to be written to the file /// </summary> /// <returns></returns> public byte[] GetImageDict(long filePos,out int size) { MemoryStream ms=new MemoryStream(); int s; byte[] ba; foreach (PdfImageEntry ie in images.Values) { ObjectList objList=new ObjectList(ie.objectNum,filePos); ba = PdfUtility.GetUTF8Bytes(ie.imgDict, out s); ms.Write(ba, 0, ba.Length); filePos += s; ms.Write(ie.ba, 0, ie.ba.Length); // write out the image filePos += ie.ba.Length; ba = PdfUtility.GetUTF8Bytes("endstream\r\nendobj\r\n", out s); ms.Write(ba, 0, ba.Length); filePos += s; ie.xref.offsets.Add(objList); } ba = ms.ToArray(); size = ba.Length; return ba; }
string ExecuteAndRead(string pCommand, IPAddress ip, int timeout) { string device_response = ""; int mSendCommandTimeOut = timeout; int mReceiveCommandTimeOut = timeout; TcpClient mClient = new TcpClient(); Debug.Log("in the Execute and Read loop"); //Set send command timeout mClient.SendTimeout = mSendCommandTimeOut; //Set receive response timeout mClient.ReceiveTimeout = mReceiveCommandTimeOut; //Get the message bytes byte[] mMessage = Encoding.ASCII.GetBytes(pCommand); //Get the bytes of encrypted message byte[] mEncryptedMessage = EncryptMessage(mMessage, ProtocolType.Tcp); Debug.Log(mEncryptedMessage + "is the Encrypoted Message"); Debug.Log(mMessage + "is the mMessage"); //Connect to the device IAsyncResult result = mClient.BeginConnect(new IPAddress(ip.GetAddressBytes()), 9999, null, null); bool success = result.AsyncWaitHandle.WaitOne(timeout); if (success) { try { //Send the command using (NetworkStream stream = mClient.GetStream()) { //Write the message stream.Write(mEncryptedMessage, 0, mEncryptedMessage.Length); //Read the response byte[] buffer = new byte[1024]; using (MemoryStream ms = new System.IO.MemoryStream()) { int numBytesRead; while ((numBytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, numBytesRead); } device_response = Encoding.ASCII.GetString(DecryptMessage(ms.ToArray(), ProtocolType.Tcp)); } stream.Close(); } } catch (System.Exception ex) { // throw new NonCompatibleDeviceException(ex.Message, ex); Debug.Log("in the exception loop"); System.Console.WriteLine("non compatible device"); } finally { //Close TCP connection if (mClient.Connected) { mClient.EndConnect(result); } } } else { System.Console.WriteLine("Unable to connect: to IP address"); } return(device_response); }
//Fonction: Envoie de l'image public bool Envoi_image(System.Drawing.Image image) { Program.LogFich.Info("[Sign_Screen_Manager] Envoi_image() - Envoie des données"); bool b = true; MemoryStream mstImage = new MemoryStream(); image.Save(mstImage, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] data = mstImage.GetBuffer(); mstImage.Dispose(); //StringBuilder dataSB = new StringBuilder(); //IntPtr dataPtr = Marshal.AllocHGlobal(data.Length); /* * for (int i = 0; i < data.Length; ++i) * { * data[i] = Marshal.ReadByte(dataPtr, i); * dataSB.Append(data[i]); * } */ try { Uri url = new Uri(urlapp.ToString() + "devices/TOPAZ_SIGPLUS.asp"); //StringBuilder sb = new StringBuilder(); //sb.Append("type_peripherique=").Append(HttpUtility.UrlEncode("TOPAZ_SIGPLUS", Encoding.ASCII)); //sb.Append("&machine=").Append(HttpUtility.UrlEncode(Functions.getHost(), Encoding.ASCII)); //sb.Append("data=").Append(HttpUtility.UrlEncode(data.ToString(), Encoding.ASCII)); //sb.Append("&datalen=").Append(HttpUtility.UrlEncode(data.Length.ToString(), Encoding.ASCII)); string boundary = DateTime.Now.Ticks.ToString("x"); MemoryStream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); string headerTemplate = "Content-Disposition: form-data; name=\"signature\"; filename=\"signature.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"; byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(headerTemplate); memStream.Write(boundarybytes, 0, boundarybytes.Length); memStream.Write(headerbytes, 0, headerbytes.Length); memStream.Write(data, 0, data.Length); memStream.Write(boundarybytes, 0, boundarybytes.Length); memStream.Position = 0; byte[] postBytes = memStream.GetBuffer(); memStream.Dispose(); string s = System.Text.Encoding.ASCII.GetString(postBytes); StringBuilder adr = new StringBuilder(); adr.Append(url.ToString()); adr.Append(this.WebBrowser.Url.Query); Uri adresse = new Uri(adr.ToString()); //CookieAwareWebClient wc = new CookieAwareWebClient(); //wc.UseDefaultCredentials = true; //wc.UploadData(adresse.ToString(), postBytes); //wc.Dispose(); WebBrowser.Navigate(adresse, "", postBytes, "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n" + "Content-Length: " + postBytes.Length + "\r\n" + "\r\n"); Program.LogFich.Info("[Sign_Screen_Manager] Envoi_image() - Envoie termine - Trame envoyee = " + postBytes.ToString()); } catch (Exception e) { b = false; Program.LogFich.Error("[Sign_Screen_Manager] Envoi_image() - Erreur d'envoie = " + e.ToString()); } return(b); }
/// <summary> /// Attempt to extract a stream from an archive /// </summary> /// <param name="entryName">Name of the entry to be extracted</param> /// <param name="realEntry">Output representing the entry name that was found</param> /// <returns>MemoryStream representing the entry, null on error</returns> public override (MemoryStream, string) CopyToStream(string entryName) { MemoryStream ms = new MemoryStream(); string realEntry = null; try { ZipFile zf = new ZipFile(); ZipReturn zr = zf.Open(_filename, new FileInfo(_filename).LastWriteTime.Ticks, true); if (zr != ZipReturn.ZipGood) { throw new Exception(ZipFile.ZipErrorMessageText(zr)); } for (int i = 0; i < zf.EntriesCount && zr == ZipReturn.ZipGood; i++) { if (zf.Entries[i].FileName.Contains(entryName)) { // Open the read stream realEntry = zf.Entries[i].FileName; zr = zf.OpenReadStream(i, false, out Stream readStream, out ulong streamsize, out SabreTools.Library.Data.CompressionMethod cm, out uint lastMod); // If the stream is smaller than the buffer, just run one loop through to avoid issues if (streamsize < _bufferSize) { byte[] ibuffer = new byte[streamsize]; int ilen = readStream.Read(ibuffer, 0, (int)streamsize); ms.Write(ibuffer, 0, ilen); ms.Flush(); } // Otherwise, we do the normal loop else { byte[] ibuffer = new byte[_bufferSize]; int ilen; while (streamsize > _bufferSize) { ilen = readStream.Read(ibuffer, 0, _bufferSize); ms.Write(ibuffer, 0, ilen); ms.Flush(); streamsize -= _bufferSize; } ilen = readStream.Read(ibuffer, 0, (int)streamsize); ms.Write(ibuffer, 0, ilen); ms.Flush(); } zr = zf.CloseReadStream(); } } zf.Dispose(); } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); ms = null; realEntry = null; } return(ms, realEntry); }
private static byte[] GetMultipartFormData(Dictionary <string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; if (postParameters.Count > 1) { foreach (var param in postParameters) { // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. // Skip it on the first parameter, add it to subsequent parameters. if (needsCLRF) { formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); } needsCLRF = true; var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", boundary, param.Key, fileInfo.MimeType); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, param.Key, fileInfo.file); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); } else { foreach (var param in postParameters) { var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = (string)param.Value; formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
/// <summary> /// Serializes objectToSerialize to a byte array using compression provided by compressor if T is an array of primitives. Otherwise returns default value for T. Override /// to serialize other types /// </summary> /// <param name="objectToSerialise">Object to serialize</param> /// <param name="dataProcessors">The compression provider to use</param> /// <param name="options">Options to be used during serialization and processing of data</param> /// <returns>The serialized and compressed bytes of objectToSerialize</returns> public static unsafe StreamSendWrapper SerialiseArrayObject(object objectToSerialise, List <DataProcessor> dataProcessors, Dictionary <string, string> options) { Type objType = objectToSerialise.GetType(); if (objType.IsArray) { var elementType = objType.GetElementType(); //No need to do anything for a byte array if (elementType == typeof(byte) && (dataProcessors == null || dataProcessors.Count == 0)) { byte[] bytesToSerialise = objectToSerialise as byte[]; //return objectToSerialise as byte[]; return(new StreamSendWrapper(new ThreadSafeStream(new MemoryStream(bytesToSerialise, 0, bytesToSerialise.Length, false, true), true))); } else if (elementType.IsPrimitive) { var asArray = objectToSerialise as Array; GCHandle arrayHandle = GCHandle.Alloc(asArray, GCHandleType.Pinned); try { IntPtr safePtr = Marshal.UnsafeAddrOfPinnedArrayElement(asArray, 0); long writtenBytes = 0; MemoryStream tempStream1 = new System.IO.MemoryStream(); using (UnmanagedMemoryStream inputDataStream = new System.IO.UnmanagedMemoryStream((byte *)safePtr, asArray.Length * Marshal.SizeOf(elementType))) { if (dataProcessors == null || dataProcessors.Count == 0) { AsyncStreamCopier.CopyStreamTo(inputDataStream, tempStream1); //return tempStream1.ToArray(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true))); } dataProcessors[0].ForwardProcessDataStream(inputDataStream, tempStream1, options, out writtenBytes); } if (dataProcessors.Count > 1) { MemoryStream tempStream2 = new MemoryStream(); for (int i = 1; i < dataProcessors.Count; i += 2) { tempStream1.Seek(0, 0); tempStream1.SetLength(writtenBytes); tempStream2.Seek(0, 0); dataProcessors[i].ForwardProcessDataStream(tempStream1, tempStream2, options, out writtenBytes); if (i + 1 < dataProcessors.Count) { tempStream1.Seek(0, 0); tempStream2.Seek(0, 0); tempStream2.SetLength(writtenBytes); dataProcessors[i].ForwardProcessDataStream(tempStream2, tempStream1, options, out writtenBytes); } } if (dataProcessors.Count % 2 == 0) { tempStream2.SetLength(writtenBytes + 4); tempStream2.Seek(writtenBytes, 0); tempStream2.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int)); //return tempStream2.ToArray(); tempStream1.Dispose(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream2, true))); } else { tempStream1.SetLength(writtenBytes + 4); tempStream1.Seek(writtenBytes, 0); tempStream1.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int)); //return tempStream1.ToArray(); tempStream2.Dispose(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true))); } } else { tempStream1.SetLength(writtenBytes + 4); tempStream1.Seek(writtenBytes, 0); tempStream1.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int)); //return tempStream1.ToArray(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true))); } } finally { arrayHandle.Free(); } } } return(null); }
public ResponseGetMobileNO uploadA4scan(SubmitMandateImageInput context) { string fileName = string.Empty; string filePath = string.Empty; string extension = string.Empty; string filePath1 = string.Empty; string filePath2 = string.Empty; string RefrenceNo = string.Empty; string croppedFileName = string.Empty; string croppedFilePath = string.Empty; // string Path = ""; //string dirnm = ""; ResponseGetMobileNO pathInfo = new ResponseGetMobileNO(); // byte[] imagedata = System.Convert.FromBase64String(context.base64.ToString()); try { if (context.AppID == "" || context.AppID == null) { pathInfo.message = "Incomplete data"; pathInfo.status = "Failure"; return(pathInfo); } if (context.MandeteId == "" || context.MandeteId == null) { pathInfo.message = "Incomplete data"; pathInfo.status = "Failure"; return(pathInfo); } if (context.UserId == "" || context.UserId == null) { pathInfo.message = "Incomplete data"; pathInfo.status = "Failure"; return(pathInfo); } if (context.ImageBytes == "" || context.ImageBytes == null) { pathInfo.message = "Incomplete data"; pathInfo.status = "Failure"; return(pathInfo); } if (context.ImageBytes.Length < 0 || context.ImageBytes == null) { pathInfo.message = "Incomplete data"; pathInfo.status = "Failure"; return(pathInfo); } string TempJpgpath = string.Empty; string TempTifpath = string.Empty; Boolean Greater = true; string Path = ""; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[Convert.ToString(context.AppID)].ConnectionString); string query = "Sp_Mandate"; SqlCommand cmd = new SqlCommand(query, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@QueryType", "CheckMandateId"); cmd.Parameters.AddWithValue("@MandateId", context.MandeteId); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows[0]["value"].ToString() == "1") { RefrenceNo = (dt.Rows[0]["Refrence1"].ToString()); System.IO.MemoryStream mm = new System.IO.MemoryStream(); byte[] bytes = System.Convert.FromBase64String(context.ImageBytes); mm.Write(bytes, 0, bytes.Length); System.Drawing.Image img = System.Drawing.Image.FromStream(mm); System.Drawing.Image imgtif = System.Drawing.Image.FromStream(mm); if (Convert.ToInt32(img.HorizontalResolution) <= 300) { //bool Flag = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/MandateFile/" + context.MandeteId)); Path = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID].ToString() + "MandateFile/" + context.MandeteId + "/"; string FilePath = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID].ToString() + "MandateFile/" + context.MandeteId + "/"; bool Flag1 = Directory.Exists(FilePath); if (!Flag1) { Directory.CreateDirectory(FilePath); } else { System.IO.DirectoryInfo di = new DirectoryInfo(FilePath); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } } fileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + RefrenceNo + ".jpg"; //filePath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/MandateFile/" + context.MandeteId + "/" + fileName.Trim())); filePath = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID].ToString() + "MandateFile/" + context.MandeteId + "/" + fileName.Trim(); filePath1 = "../MandateFile/" + context.MandeteId + "/" + fileName; if (File.Exists(filePath)) { File.Delete(filePath); img = System.Drawing.Image.FromFile(filePath); if (img.Width > img.Height) { Greater = true; } else { Greater = false; } //System.Drawing.Rectangle areaToCrop = new System.Drawing.Rectangle(Convert.ToInt32(0), // Convert.ToInt32(0), // Convert.ToInt32(img.Width), // Convert.ToInt32(img.Height)); } Bitmap bitMap = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); using (Graphics g = Graphics.FromImage(bitMap)) { g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; } bitMap.SetResolution(96, 96); bitMap.Save(filePath); using (var image = img) { int newWidth = 0; int newHeight = 0; //if (Greater == true) //{ newWidth = 827; // New Width of Image in Pixel newHeight = 356; //} //else //{ // newWidth = 356; // newHeight = 827; //} var thumbImg = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); var thumbGraph = Graphics.FromImage(thumbImg); var imgRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight); thumbGraph.DrawImage(image, imgRectangle); thumbImg.SetResolution(100, 100); System.Drawing.Bitmap b0 = CopyToBpp(thumbImg, 8); b0.SetResolution(100, 100); fileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + RefrenceNo + ".jpg"; filePath1 = "../MandateFile/" + context.MandeteId + "/" + fileName; croppedFilePath = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID].ToString() + "MandateFile/" + context.MandeteId + "/" + fileName.Trim(); TempJpgpath = croppedFilePath; ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; b0.Save(croppedFilePath, jpgEncoder, myEncoderParameters); } // img.Save(filePath); query = "Sp_Mandate"; cmd = new SqlCommand(query, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@QueryType", "CheckLogo"); cmd.Parameters.AddWithValue("@MandateId", context.MandeteId); da = new SqlDataAdapter(cmd); dt = new DataTable(); da.Fill(dt); string Logo = dt.Rows[0]["printlogo"].ToString(); string result = ""; if (Logo == "True") { result = context.MandeteId; } else { // result = GetMandatefromQR(filePath, context.MandeteId); result = context.MandeteId; } if (result == context.MandeteId) { fileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + RefrenceNo + ".tif"; filePath = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID].ToString() + "MandateFile/" + context.MandeteId + "/" + fileName.Trim(); filePath2 = "../MandateFile/" + context.MandeteId + "/" + fileName; if (File.Exists(filePath)) { File.Delete(filePath); imgtif = System.Drawing.Image.FromFile(filePath); //System.Drawing.Rectangle areaToCrop = new System.Drawing.Rectangle(Convert.ToInt32(0), // Convert.ToInt32(0), // Convert.ToInt32(img.Width), // Convert.ToInt32(img.Height)); } //imgtif = System.Drawing.Image.FromFile(filePath); Bitmap bitMap1 = new Bitmap(imgtif.Width, imgtif.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); using (Graphics g = Graphics.FromImage(bitMap1)) { g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; } bitMap1.SetResolution(96, 96); bitMap1.Save(filePath); using (var image1 = imgtif) { int newWidth = 0; int newHeight = 0; //if (Greater == true) //{ // newWidth = imgtif.Width; // newHeight = imgtif.Height; newWidth = 827 * 2; // New Width of Image in Pixel newHeight = 356 * 2; //} //else //{ // newWidth = imgtif.Width; // newHeight = imgtif.Height; // newWidth = 827 * 2; // New Width of Image in Pixel // newHeight = 356 * 2; //} var thumbImg1 = new Bitmap(newWidth, newHeight); var thumbGraph1 = Graphics.FromImage(thumbImg1); var imgRectangle1 = new System.Drawing.Rectangle(0, 0, newWidth, newHeight); thumbGraph1.DrawImage(image1, imgRectangle1); System.Drawing.Bitmap b1 = CopyToBpp(thumbImg1, 1); b1.SetResolution(200, 200); fileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + RefrenceNo + ".tif"; filePath2 = "../MandateFile/" + context.MandeteId + "/" + fileName; croppedFilePath = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID].ToString() + "MandateFile/" + context.MandeteId + "/" + fileName.Trim(); TempTifpath = croppedFilePath; ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Tiff); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Compression; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)EncoderValue.CompressionCCITT4); myEncoderParameters.Param[0] = myEncoderParameter; b1.Save(croppedFilePath, jpgEncoder, myEncoderParameters); //b1.Save(croppedFilePath, image1.RawFormat); } } else { pathInfo.message = "Invalid Mandate"; pathInfo.status = "Failure"; } } else { pathInfo.message = "Image Size Must Be less Than 300Dpi"; pathInfo.status = "Failure"; } filePath2 = "../MandateFile/" + context.MandeteId + "/" + fileName; query = "Sp_Mandate"; cmd = new SqlCommand(query, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@QueryType", "UpdatePNGTIP"); cmd.Parameters.AddWithValue("@MandateId", context.MandeteId); cmd.Parameters.AddWithValue("@PNGPath", filePath1); cmd.Parameters.AddWithValue("@TIPPath", filePath2); da = new SqlDataAdapter(cmd); dt = new DataTable(); da.Fill(dt); pathInfo.message = "Image uploaded successfully"; pathInfo.status = "Success"; try { if (Convert.ToString(ConfigurationManager.AppSettings["SFDC" + context.AppID]) != null && Convert.ToString(ConfigurationManager.AppSettings["SFDC" + context.AppID]) != "") { string apiUrl = Convert.ToString(ConfigurationManager.AppSettings["SFDC" + context.AppID]); var input = new { MdtId = context.MandeteId, ResStatus = "Success", ResCode = "ykR20033", Message = "Image uploaded successfully", MandateStatus = dt.Rows[0]["status"], TiffBase64 = ConvertImageBase64(TempTifpath), JpgBase64 = ConvertImageBase64(TempJpgpath), IsAggregatorValue = dt.Rows[0]["IsAggregatorValue"], }; string inputJson = (new JavaScriptSerializer()).Serialize(input); WebClient client = new WebClient(); client.Headers["Content-type"] = "application/json"; client.Encoding = Encoding.UTF8; string json = client.UploadString(apiUrl, inputJson); string temppath = System.Web.Hosting.HostingEnvironment.MapPath("~/SFDCResponse\\" + context.AppID); if (!Directory.Exists(temppath)) { Directory.CreateDirectory(temppath); } temppath = temppath + "\\" + context.MandeteId + ".txt"; File.WriteAllText(temppath, json); } } catch (Exception ex) { } } else { pathInfo.message = "Invalid MandateId"; pathInfo.status = "Failure"; } } catch (Exception e) { pathInfo.message = e.Message; pathInfo.status = "failure"; } //imag.Dispose(); //Write code here to Save byte code to database.. return(pathInfo); }
private T Parse <T>(Entity.WeixinRequest <T> request, byte[] bytes) where T : Entity.WeixinResponse { var responseString = Encoding.UTF8.GetString(bytes); if (string.IsNullOrWhiteSpace(responseString)) { return(default(T)); } var t = System.Activator.CreateInstance <T>(); t.ResponseBase64String = Convert.ToBase64String(bytes); if (t.ResponseType == Enum.ResponseType.Stream) { return(t); } else if (t.ResponseType == Enum.ResponseType.JSON) { var _t = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseString); _t.ResponseBase64String = t.ResponseBase64String; return(_t); } else if (t.ResponseType == Enum.ResponseType.XML) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { ms.Write(bytes, 0, bytes.Length); ms.Position = 0; var serializor = new System.Xml.Serialization.XmlSerializer(typeof(T)); var obj = serializor.Deserialize(ms) as T; if (obj != null) { obj.ResponseBase64String = Convert.ToBase64String(bytes); } return(obj); } } else if (t.ResponseType == Enum.ResponseType.HTML || t.ResponseType == Enum.ResponseType.JavaScript) { var ps = t.GetType().GetProperties(); foreach (var p in ps) { var at = p.GetCustomAttribute(typeof(Common.RegexAttribute)); if (at != null) { var reg = at as Common.RegexAttribute; var regex = new Regex(reg.RegexPattern, RegexOptions.IgnoreCase); var match = regex.Match(responseString); if (match != null && p.CanWrite) { var propType = Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType; if (propType != typeof(System.String)) { p.SetValue(t, Convert.ChangeType(match.Groups[reg.Key].Value, propType)); } else { p.SetValue(t, match.Groups[reg.Key].Value); } } } } } return(t); }
public void InvokeUploadService(string authtoken, bool isServerMig, string filePath, string mimebuffer, string theDisposition, string theType, int mode, out string rsp) { using (LogBlock logblock = Log.NotTracing() ? null : new LogBlock(GetType() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name)) { // -------------------------------------------------- // Is the data in file, or in string mimebuffer? // -------------------------------------------------- bool bIsBuffer = false; if (mimebuffer.Length > 0) { bIsBuffer = true; } // -------------------------------------------------- // Cert callback // -------------------------------------------------- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate(object sender2, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }); // -------------------------------------------------- // Create the request // -------------------------------------------------- HttpWebRequest webReq = this.CreateWebRequestRaw(authtoken, isServerMig); // ------------------------------- // Get preamble for the request // ------------------------------- string ct; if (theType.Length == 0) { ct = "Content-Type: " + "application/octet-stream"; } else { ct = "Content-Type: " + theType; } string boundary = "--B-00=_" + DateTime.Now.Ticks.ToString("x"); string endBoundary = Environment.NewLine + "--" + boundary + "--" + Environment.NewLine; // FBS bug 73727 -- 5/29/12 -- removed extra "Environment.NewLine +" string contentDisposition1 = "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"requestId\"" + Environment.NewLine + Environment.NewLine + "lsrpc32-client-id" + Environment.NewLine; string cd2 = (theDisposition.Length > 0) ? theDisposition : "Content-Disposition : form-data; name=\"lslib32\"; filename=\"lslib32.bin\""; string contentDisposition2 = "--" + boundary + Environment.NewLine + cd2; string contentType = Environment.NewLine + ct + Environment.NewLine; string contentTransfer = "Content-Transfer-Encoding: binary" + Environment.NewLine + Environment.NewLine; // ------------------------------- // Write data into webReq's stream // ------------------------------- webReq.ContentType = "multipart/form-data; boundary=" + boundary; if (mode == ZimbraAPI.STRING_MODE) // easier -- all text in the request { try { if (bIsBuffer) { // ============================================================================================= // STREAM FROM BUFFER // ============================================================================================= string sDataToUpload = mimebuffer; int nDataLen = sDataToUpload.Length; // for view in debugger // -------------------------------------------------- // Build the request stream // -------------------------------------------------- using (Stream stm = webReq.GetRequestStream()) { using (StreamWriter stmw = new StreamWriter(stm, System.Text.Encoding.Default)) { stmw.Write(contentDisposition1); stmw.Write(contentDisposition2); stmw.Write(contentType); stmw.Write(contentTransfer); stmw.Write(sDataToUpload); stmw.Write(endBoundary); stmw.Close(); } } } else { // ============================================================================================= // STREAM FROM FILE // ============================================================================================= // ------------------------------- // Build the request stream // ------------------------------- long lFileSize = new System.IO.FileInfo(filePath).Length; using (FileStream fileStream = File.OpenRead(filePath)) { // Send it off in chunks of 5MB int bufferSize = 5 * 1024 * 1024; byte[] buffer = new byte[bufferSize]; UTF8Encoding encoding = new UTF8Encoding(); byte[] bytecd1 = encoding.GetBytes(contentDisposition1); byte[] bytecd2 = encoding.GetBytes(contentDisposition2); byte[] byteContType = encoding.GetBytes(contentType); byte[] byteContTransfer = encoding.GetBytes(contentTransfer); byte[] byteEndBoundary = encoding.GetBytes(endBoundary); long lContentLength = bytecd1.Length + bytecd2.Length + byteContType.Length + byteContTransfer.Length + lFileSize + byteEndBoundary.Length; Log.trace("Bytes to upload:" + lContentLength); webReq.AllowWriteStreamBuffering = false; // Without this, the call to GetRequestStream will allocate ContentLength bytes "Setting AllowWriteStreamBuffering to true might cause performance problems when uploading large datasets because the data buffer could use all available memory." YES! // If the AllowWriteStreamBuffering property of HttpWebRequest is set to false,the contentlength has to be set to length of data to be posted else Exception(411) is raised. webReq.ContentLength = lContentLength; using (Stream RqstStrm = webReq.GetRequestStream()) { // Write preamble RqstStrm.Write(bytecd1, 0, bytecd1.Length); RqstStrm.Write(bytecd2, 0, bytecd2.Length); RqstStrm.Write(byteContType, 0, byteContType.Length); RqstStrm.Write(byteContTransfer, 0, byteContTransfer.Length); // Write file contents long nDone = 0; int nBytes = 1; while (nBytes != 0) { nBytes = fileStream.Read(buffer, 0, bufferSize); if (nBytes > 0) { RqstStrm.Write(buffer, 0, nBytes); nDone += nBytes; Log.trace((100 * nDone / lContentLength) + "% uploaded " + nDone + " bytes"); } } // Write end boundary RqstStrm.Write(byteEndBoundary, 0, byteEndBoundary.Length); // All done RqstStrm.Close(); } } } } catch (System.Net.WebException wex) { // catch (Exception ex) Log.err(wex); setErrors(wex); rsp = ""; return; } } else // CONTACT, APPT_VALUE, or APPT_EMB. Not distinguishing yet, but we might later. { try { // ---------------------------------------------------------------- // first get the bytes from the file -- this is the attachment data // ---------------------------------------------------------------- byte[] buf = null; long datalen = 0; if (bIsBuffer) { datalen = mimebuffer.Length; buf = Encoding.ASCII.GetBytes(mimebuffer); } else { System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream); datalen = new System.IO.FileInfo(filePath).Length; buf = binaryReader.ReadBytes((Int32)datalen); fileStream.Close(); fileStream.Dispose(); binaryReader.Close(); } // ---------------------------------------------------------------- // now use a memory stream since we have mixed data // ---------------------------------------------------------------- using (Stream memStream = new System.IO.MemoryStream()) { // write the request data byte[] cd1Bytes = System.Text.Encoding.UTF8.GetBytes(contentDisposition1); memStream.Write(cd1Bytes, 0, cd1Bytes.Length); byte[] cd2Bytes = System.Text.Encoding.UTF8.GetBytes(contentDisposition2); memStream.Write(cd2Bytes, 0, cd2Bytes.Length); byte[] cTypeBytes = System.Text.Encoding.UTF8.GetBytes(contentType); memStream.Write(cTypeBytes, 0, cTypeBytes.Length); byte[] cTransferBytes = System.Text.Encoding.UTF8.GetBytes(contentTransfer); memStream.Write(cTransferBytes, 0, cTransferBytes.Length); memStream.Write(buf, 0, (int)datalen); byte[] cEndBoundaryBytes = System.Text.Encoding.UTF8.GetBytes(endBoundary); memStream.Write(cEndBoundaryBytes, 0, cEndBoundaryBytes.Length); // set up the web request to use our memory stream webReq.ContentLength = memStream.Length; memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); // ---------------------------------------------------------------- // Send it to server // ---------------------------------------------------------------- Stream requestStream = webReq.GetRequestStream(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); } } catch (System.Net.WebException wex) { // catch (Exception ex) setErrors(wex); rsp = ""; return; } } // ======================================================================= // Get the response from the web service // ======================================================================= WebResponse response = null; try { Log.verbose(">GetResponse"); response = webReq.GetResponse(); Log.verbose("<GetResponse"); } catch (System.Net.WebException wex) { // catch (Exception ex) setErrors(wex); rsp = ""; return; } Stream str = response.GetResponseStream(); StreamReader sr = new StreamReader(str); rsp = sr.ReadToEnd(); status = 0; } }
/// <summary> /// Faz o post e retorna uma string com o resultado /// </summary> /// <param name="url">url base para utilizar dentro do post</param> /// <param name="postData">dados a serem enviados junto com o post</param> /// <returns></returns> public string PostForm(string url, IDictionary <string, string> postData) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); string file = postData["f1"]; #region Preparar a requisição HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; request.Credentials = System.Net.CredentialCache.DefaultCredentials; //ajustar para permitir o cabeçalho HTTP/1.0 SetAllowUnsafeHeaderParsing20(); //evitar o erro "The remote server returned an error: (417) Expectation Failed." //para caeçalhos HTTP/1.0 System.Net.ServicePointManager.Expect100Continue = false; if (Proxy != null) { request.UseDefaultCredentials = false; request.Proxy = Proxy; request.Proxy.Credentials = Proxy.Credentials; request.Credentials = Proxy.Credentials; } #endregion #region Crar o stream da solicitação Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; foreach (KeyValuePair <string, string> keyValue in postData) { string formitem = string.Format(formdataTemplate, keyValue.Key, keyValue.Value); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, "f1", file); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); request.ContentLength = memStream.Length; #endregion #region Escrever na requisição Stream requestStream = request.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); #endregion #region Resposta do servidor WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = response.ContentType.IndexOf("charset=") == -1 ? new StreamReader(stream, Encoding.UTF8) : new StreamReader(stream, Encoding.GetEncoding(response.ContentType.Substring(response.ContentType.IndexOf("charset=") + 8))); string result = reader.ReadToEnd(); stream.Dispose(); reader.Dispose(); return(result); #endregion }
protected void Page_Load(object sender, EventArgs e) { var message = Request.Params["Message"]; //message = "227 1111111"; var str = message.ToString().Split(' '); var codeUser = str[0]; var content = str[1]; Bitmap bmp = null; MemoryStream stream = null; try { if (message == null) { Json = "参数Message不能为null!"; return; } //数据加密编码 string strBase64Content = Base64Tool.Base64Code(content); //生成二维码Bitmap QRCodeEncoder qrCode = new QRCodeEncoder(); qrCode.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; qrCode.QRCodeScale = 6; qrCode.QRCodeVersion = 7; qrCode.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; bmp = qrCode.Encode(strBase64Content); //Bitmap转换成MemoryStream stream = new System.IO.MemoryStream(); bmp.Save(stream, ImageFormat.Jpeg); //内存流MemoryStream转成bytes byte[] bt = stream.ToArray(); stream.Write(bt, 0, bt.Length); //获取上传地址 string strQRCodePicPath = FileTool.GetWebConfigKey("QRCodePicUploadPath"); string strQRCodePicName = codeUser + ".jpg"; if (!FileTool.UploadFile(strQRCodePicPath, strQRCodePicName, bt)) { Json = "False"; } Json = JsonConvert.SerializeObject(strQRCodePicName); } catch (Exception ex) { LogTool.WriteLog(typeof(QRCode), ex); Json = "Error"; } finally { if (stream != null) { stream.Close(); } if (bmp != null) { bmp.Dispose(); } } }
public void Insert(string key, T value, TimeSpan expiration) { if (value != null) { long expirationTime = (expiration == TimeSpan.Zero) ? 0 : DateTime.UtcNow.Add(expiration).Ticks; long creationTime = DateTime.UtcNow.Ticks; //Dictionary<string, string> meta = new Dictionary<string, string>(); try { using (var ms = new System.IO.MemoryStream()) { using (StreamWriter sw = new StreamWriter(ms)) { using (JsonWriter writer = new JsonTextWriter(sw)) { if (value is byte[]) { byte[] bvalue = value as byte[]; ms.Write(bvalue, 0, bvalue.Length); } else { //json serialization serializer.Serialize(writer, value); } writer.Flush(); ms.Seek(0, SeekOrigin.Begin); //lock (_lockconnections) //{ var putObj = new Amazon.S3.Model.PutObjectRequest() { BucketName = this.Bucket, Key = fixKey(key), InputStream = ms, AutoCloseStream = false, ContentType = "application/octet-stream", }; putObj.Metadata.Add(_createdMetaTag, creationTime.ToString()); putObj.Metadata.Add(_expiresAtMetaTag, expirationTime.ToString()); var res = client.PutObjectAsync(putObj).Result; //client.PutObjectAsync(this.Bucket, fixKey(key), //ms, ms.Length, // "application/octet-stream", // meta // ).Wait(); //} } } } } catch (Exception e) { ESTraceLogger.Error($"AWS_S3CacheProvider: insert record {fixKey(key)} error {e.Message}", e); } } else { ESTraceLogger.Warning(new Devmasters.Log.LogMessage() .SetMessage("AWS_S3CacheProvider> null value") .SetLevel(Devmasters.Log.PriorityLevel.Warning) .SetCustomKeyValue("objectType", typeof(T).ToString()) .SetCustomKeyValue("cache key", key) ); } }
public WebResponse UploadFile(string pathInfo, FileInfo fileInfo) { long length = 0; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); var httpWebRequest = (HttpWebRequest)WebRequest.Create(base.ServiceClientBaseUri + pathInfo); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Method = "POST"; httpWebRequest.AllowAutoRedirect = false; httpWebRequest.KeepAlive = false; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary); string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "upload", fileInfo.Name, MimeTypes.GetMimeType(fileInfo.Name)); byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); //Image img = null; //img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true); //img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg); using (var fs = fileInfo.OpenRead()) { fs.WriteTo(memStream); } memStream.Write(boundarybytes, 0, boundarybytes.Length); //string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; //string formitem = string.Format(formdataTemplate, "headline", "Sunset"); //byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); //memStream.Write(formitembytes, 0, formitembytes.Length); //memStream.Write(boundarybytes, 0, boundarybytes.Length); httpWebRequest.ContentLength = memStream.Length; var requestStream = httpWebRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); return(httpWebRequest.GetResponse()); }
public UploadResult UploadFile(string filename) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(this.Host + "file/do_upload"); httpReq.ContentType = "multipart/form-data; boundary=" + boundary; httpReq.Method = "POST"; httpReq.KeepAlive = true; httpReq.Credentials = System.Net.CredentialCache.DefaultCredentials; httpReq.Accept = "application/json"; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; NameValueCollection nvc = new NameValueCollection(); nvc.Add("apikey", this.APIKey); foreach (string key in nvc.Keys) { string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; string[] files = new string[] { filename }; for (int i = 0; i < files.Length; i++) { //string header = string.Format(headerTemplate, "file" + i, files[i]); string header = string.Format(headerTemplate, "file", files[i]); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); } httpReq.ContentLength = memStream.Length; Stream requestStream = httpReq.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); int numBytesToRead = (int)memStream.Length; int numBytesRead = 0; int block; while (numBytesToRead > 0) { if (numBytesToRead < 1024) { block = numBytesToRead; } else { block = 1024; } requestStream.Write(tempBuffer, numBytesRead, block); numBytesRead += 1024; numBytesToRead -= 1024; OnUploadProgress(new UploadProgressEventArgs(numBytesRead, tempBuffer.Length)); } memStream.Close(); requestStream.Close(); WebResponse webRes = httpReq.GetResponse(); string jsonOutput; using (Stream stream2 = webRes.GetResponseStream()) { using (StreamReader reader2 = new StreamReader(stream2)) { jsonOutput = reader2.ReadToEnd(); } } webRes.Close(); httpReq = null; webRes = null; JsonObject jsonDownloadResult = (JsonObject)JsonConvert.Import(jsonOutput); UploadResult.UploadStatus status; switch (jsonDownloadResult ["status"].ToString().ToUpperInvariant()) { case "SUCCESS": status = UploadResult.UploadStatus.Success; break; default: status = UploadResult.UploadStatus.Error; break; } List <string> resultData = new List <string>(Jayrock.Json.Conversion.JsonConvert.Import <string[]>(Convert.ToString(jsonDownloadResult["data"]))); UploadResult result = new UploadResult(resultData[0], status); return(result); }
//////////////////// public static System.IO.MemoryStream CompressImage2(string sFile, int flag, int size = 300, bool sfsc = true) { System.IO.FileStream fs = new System.IO.FileStream(sFile, FileMode.Open, FileAccess.Read); System.IO.MemoryStream fs2 = new System.IO.MemoryStream(); Image iSource = Image.FromFile(sFile); System.Drawing.Imaging.ImageFormat tFormat = iSource.RawFormat; //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true FileInfo firstFileInfo = new FileInfo(sFile); if (sfsc == true && firstFileInfo.Length < size * 1024) { byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 fs.Seek(0, SeekOrigin.Begin); fs2.Write(bytes, 0, bytes.Length); //firstFileInfo.CopyTo(dFile); return(fs2); } int dHeight = iSource.Height / 2; int dWidth = iSource.Width / 2; int sW = 0, sH = 0; //按比例缩放 Size tem_size = new Size(iSource.Width, iSource.Height); if (tem_size.Width > dHeight || tem_size.Width > dWidth) { if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) { sW = dWidth; sH = (dWidth * tem_size.Height) / tem_size.Width; } else { sH = dHeight; sW = (tem_size.Width * dHeight) / tem_size.Height; } } else { sW = tem_size.Width; sH = tem_size.Height; } Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 System.Drawing.Imaging.EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { ob.Save(fs2, jpegICIinfo, ep);//dFile是压缩后的新路径 // FileInfo fi = new FileInfo(dFile); // if (fs.Length > 1024 * size) // { // flag = flag - 10; // CompressImage2(sFile, flag, size, false); // } } else { ob.Save(fs2, tFormat); } return(fs2); } catch { return(null); } finally { iSource.Dispose(); ob.Dispose(); } }
public static void Encrypt(string username, string password, byte[] salt, out byte[] result1, out byte[] result2) { byte[] byteUsername = ASCIIEncoding.ASCII.GetBytes(username); byte[] bytePassword = ASCIIEncoding.ASCII.GetBytes(password); // ok, heres the dirty stuff. // take the 16th character from the yahoo seed string and take the modulus of it int sv = (int)salt[15]; sv = (sv % 8) % 5; // md5 encrypt the password Crypto.MD5CryptoServiceProvider md5 = new Crypto.MD5CryptoServiceProvider(); byte[] passwordResult = ToMac64(md5.ComputeHash(bytePassword)); byte[] cryptResult = ToMac64(md5.ComputeHash(YahooCrypt(password, "_2S43d5f"))); // the order of the strings depends on the value of sv (calculated above) byte checksum; IO.MemoryStream result1Stream = new IO.MemoryStream(); IO.MemoryStream result2Stream = new IO.MemoryStream(); switch (sv) { case 0: checksum = salt[salt[7] % 16]; result1Stream.WriteByte(checksum); result1Stream.Write(passwordResult, 0, passwordResult.Length); result1Stream.Write(byteUsername, 0, byteUsername.Length); result1Stream.Write(salt, 0, salt.Length); result2Stream.WriteByte(checksum); result2Stream.Write(cryptResult, 0, cryptResult.Length); result2Stream.Write(byteUsername, 0, byteUsername.Length); result2Stream.Write(salt, 0, salt.Length); break; case 1: checksum = salt[salt[9] % 16]; result1Stream.WriteByte(checksum); result1Stream.Write(byteUsername, 0, byteUsername.Length); result1Stream.Write(salt, 0, salt.Length); result1Stream.Write(passwordResult, 0, passwordResult.Length); result2Stream.WriteByte(checksum); result2Stream.Write(byteUsername, 0, byteUsername.Length); result2Stream.Write(salt, 0, salt.Length); result2Stream.Write(cryptResult, 0, cryptResult.Length); break; case 2: checksum = salt[salt[15] % 16]; result1Stream.WriteByte(checksum); result1Stream.Write(salt, 0, salt.Length); result1Stream.Write(passwordResult, 0, passwordResult.Length); result1Stream.Write(byteUsername, 0, byteUsername.Length); result2Stream.WriteByte(checksum); result2Stream.Write(salt, 0, salt.Length); result2Stream.Write(cryptResult, 0, cryptResult.Length); result2Stream.Write(byteUsername, 0, byteUsername.Length); break; case 3: checksum = salt[salt[1] % 16]; result1Stream.WriteByte(checksum); result1Stream.Write(byteUsername, 0, byteUsername.Length); result1Stream.Write(passwordResult, 0, passwordResult.Length); result1Stream.Write(salt, 0, salt.Length); result2Stream.WriteByte(checksum); result2Stream.Write(byteUsername, 0, byteUsername.Length); result2Stream.Write(cryptResult, 0, cryptResult.Length); result2Stream.Write(salt, 0, salt.Length); break; case 4: checksum = salt[salt[3] % 16]; result1Stream.WriteByte(checksum); result1Stream.Write(passwordResult, 0, passwordResult.Length); result1Stream.Write(salt, 0, salt.Length); result1Stream.Write(byteUsername, 0, byteUsername.Length); result2Stream.WriteByte(checksum); result2Stream.Write(cryptResult, 0, cryptResult.Length); result2Stream.Write(salt, 0, salt.Length); result2Stream.Write(byteUsername, 0, byteUsername.Length); break; } result1 = ToMac64(md5.ComputeHash(result1Stream.ToArray()), 0, 16); result2 = ToMac64(md5.ComputeHash(result2Stream.ToArray()), 0, 16); result1Stream.Close(); result2Stream.Close(); }
private int getPicture() { int progress = 0;//0:progress 1:successfuly finished -1:Failed try { //// Read the data from the stream in chunks byte[] buffer = new byte[constants.CHUNK_SIZE]; //updateUI("Waiting for data. Expecting " + progressData_Remaining + " more bytes."); int bytesRead = socketStream.Read(buffer, 0, buffer.Length); count++; int prg = 100 - (int)((progressData_Remaining / progressData_Total) * 100.0); METState.Current.METCoreObject.SendToForm("(" + prg + "%) : Read " + bytesRead + " bytes into buffer", "tbOutput"); METState.Current.METCoreObject.SendToForm(prg, "progressbar"); dataOutputStream.Write(buffer, 0, bytesRead); //dataOutputStream.WriteByte(buffer); progressData_Remaining -= bytesRead; if (progressData_Remaining <= 0) { // check the integrity of the data byte[] data = dataOutputStream.ToArray(); byte[] receivedDigest = GetMd5Hash(data); socketStream.Write(receivedDigest, 0, receivedDigest.Length); socketStream.Flush(); // check the integrity of the data if (digestMatch(receivedDigest, digest)) { METState.Current.METCoreObject.SendToForm("Picture received", "tbOutput"); METState.Current.METCoreObject.SendToForm(0, "progressbar"); bitmap = Image.FromStream(dataOutputStream); FXPAL_Utils.SetupHyperImage(bitmap); string folder = @"fromGlass\Images\"; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } String photoTime = DateTime.Now.ToString("hh.mm.ss"); String SuspiciousPath = Path.Combine(folder, photoTime + ".jpg"); // bitmap.Save(SuspiciousPath); dataOutputStream.Flush(); dataOutputStream.Close(); progress = 1; } else { METState.Current.METCoreObject.SendToForm("Data NOT received completely!", "tbOutput"); progress = -1; } } } catch (IOException e) { progress = -1; } return(progress); }
public static string UploadFilesToRemoteUrl(string url, string file, string logpath, NameValueCollection nvc) { long length = 0; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url); httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest2.Method = "POST"; httpWebRequest2.KeepAlive = true; httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials; httpWebRequest2.Accept = "application/json"; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); byte[] boundarybytes2 = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; foreach (string key in nvc.Keys) { string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: " + APIConstants.TLOG_MIME_TYPE + "\r\n\r\n"; // for (int i = 0; i < files.Length; i++) { //string header = string.Format(headerTemplate, "file" + i, files[i]); string header = string.Format(headerTemplate, "uplTheFile.tlog", file); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } fileStream.Close(); } // write last boundry memStream.Write(boundarybytes2, 0, boundarybytes2.Length); // write last -- to last boundry memStream.Write(new byte[] { (byte)'-', (byte)'-' }, 0, 2); httpWebRequest2.ContentLength = memStream.Length; Stream requestStream = httpWebRequest2.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); WebResponse webResponse2 = httpWebRequest2.GetResponse(); Stream stream2 = webResponse2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string answer = reader2.ReadToEnd(); webResponse2.Close(); httpWebRequest2 = null; webResponse2 = null; return(answer); }
/// <summary> /// 업로드 *예외처리 안되어 있음 /// </summary> /// <param name="url">업로드 주소</param> /// <param name="files">업로드 파일주소들</param> /// <param name="authzHeader">인증헤더 정보</param> public static string UploadFilesToRemoteUrl(string url, string[] files, string authzHeader) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url); httpWebRequest2.Method = "POST"; httpWebRequest2.PreAuthenticate = true; httpWebRequest2.AllowWriteStreamBuffering = true; //중요) 헤더를 Authorization키로 하여 삽입 httpWebRequest2.Headers.Add("Authorization", authzHeader); httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; for (int i = 0; i < files.Length; i++) { string header = string.Format(headerTemplate, "uplTheFile", files[i]); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); if (File.Exists(files[i]) == false) { throw new Exception(files[i] + "파일이 없습니다."); } FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); } httpWebRequest2.ContentLength = memStream.Length; Stream requestStream = httpWebRequest2.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); WebResponse webResponse2 = httpWebRequest2.GetResponse(); Stream stream2 = webResponse2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string ret = reader2.ReadToEnd(); webResponse2.Close(); httpWebRequest2 = null; webResponse2 = null; return(ret); }
private void buttonSubmit_Click(object sender, EventArgs e) { user.Images.Clear(); user.Title = txtTitle.Text; user.TextField = txtTextField.Text; string searchString = user.Title; foreach (string word in user.Keywords) { searchString = searchString + " " + word; } //*******************************************************************************************************************// // Reference Title: C# windows forms, load first google image in app itself // Author: Joe Shaw // Date: Nov 2 '16 // Source: https://stackoverflow.com/questions/40370423/c-sharp-windows-forms-load-first-google-image-in-app-itself //*******************************************************************************************************************// // Referenced for the purpose of adapting code to bring in first image search term returns from Google // into a list of four based on user input title and list of keywords string templateUrl = @"https://www.google.co.uk/search?q={0}&tbm=isch&site=imghp"; if (string.IsNullOrEmpty(user.Title)) { MessageBox.Show("Please supply a search term"); return; } else { using (WebClient wc = new WebClient()) { string result = wc.DownloadString(String.Format(templateUrl, new object[] { searchString })); if (result.Contains("images_table")) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(result); //lets create a linq query to find all the img's stored in that images_table class. var imgList = from tables in doc.DocumentNode.Descendants("table") from img in tables.Descendants("img") where tables.Attributes["class"] != null && tables.Attributes["class"].Value == "images_table" && img.Attributes["src"] != null && img.Attributes["src"].Value.Contains("images?") select img; byte[] downloadedData; int imgCt = 1; //Adapted function to read images individually from query and correspond to forms picturebox foreach (var img in imgList) { if (imgCt >= 5) { break; } if (img.Attributes["src"].Value != null) { downloadedData = wc.DownloadData(img.Attributes["src"].Value); if (downloadedData != null) { System.IO.MemoryStream ms = new System.IO.MemoryStream(downloadedData, 0, downloadedData.Length); ms.Write(downloadedData, 0, downloadedData.Length); //assign memory stream to each picturebox switch (imgCt) { case 1: pbImage1.Image = Image.FromStream(ms); break; case 2: pbImage2.Image = Image.FromStream(ms); break; case 3: pbImage3.Image = Image.FromStream(ms); break; case 4: pbImage4.Image = Image.FromStream(ms); break; } imgCt++; } } } } } } }
public static byte[] YahooCrypt(string key, string salt) { const string md5SaltPrefix = "$1$"; byte[] byteSaltPrefix = ASCIIEncoding.ASCII.GetBytes(md5SaltPrefix); byte[] byteKey = ASCIIEncoding.ASCII.GetBytes(key); byte[] byteSalt = ASCIIEncoding.ASCII.GetBytes(salt); // create a memory stream for the result IO.MemoryStream result = new IO.MemoryStream(); result.Write(byteKey, 0, byteKey.Length); result.Write(byteSaltPrefix, 0, byteSaltPrefix.Length); result.Write(byteSalt, 0, byteSalt.Length); // create an alternate string for encyption IO.MemoryStream altResult = new IO.MemoryStream(); altResult.Write(byteKey, 0, byteKey.Length); altResult.Write(byteSalt, 0, byteSalt.Length); altResult.Write(byteKey, 0, byteKey.Length); // encrypt alternate result Crypto.MD5CryptoServiceProvider md5 = new Crypto.MD5CryptoServiceProvider(); byte[] altResultHash = md5.ComputeHash(altResult.ToArray()); // Add for any character in the key one byte of the alternate sum. int cnt; for (cnt = byteKey.Length; cnt > 16; cnt -= 16) { result.Write(altResultHash, 0, 16); } result.Write(altResultHash, 0, cnt); /* For the following code we need a NUL byte. */ altResultHash[0] = 0; /* The original implementation now does something weird: for every 1 * bit in the key the first 0 is added to the buffer, for every 0 * bit the first character of the key. This does not seem to be * what was intended but we have to follow this to be compatible. */ for (cnt = key.Length; cnt > 0; cnt >>= 1) { result.Write(((cnt & 1) != 0 ? altResultHash : byteKey), 0, 1); } // create intermediate result altResultHash = md5.ComputeHash(result.ToArray()); /* Now comes another weirdness. In fear of password crackers here * comes a quite long loop which just processes the output of the * previous round again. We cannot ignore this here. */ for (cnt = 0; cnt < 1000; ++cnt) { result.Seek(0, IO.SeekOrigin.Begin); result.SetLength(0); /* Add key or last result. */ if ((cnt & 1) != 0) { result.Write(byteKey, 0, byteKey.Length); } else { result.Write(altResultHash, 0, 16); } /* Add salt for numbers not divisible by 3. */ if (cnt % 3 != 0) { result.Write(byteSalt, 0, byteSalt.Length); } /* Add key for numbers not divisible by 7. */ if (cnt % 7 != 0) { result.Write(byteKey, 0, byteKey.Length); } /* Add key or last result. */ if ((cnt & 1) != 0) { result.Write(altResultHash, 0, 16); } else { result.Write(byteKey, 0, byteKey.Length); } /* Create intermediate result. */ altResultHash = md5.ComputeHash(result.ToArray()); } /* Now we can construct the result string. It consists of three * parts. */ // start with the salt prefix IO.MemoryStream finalResult = new IO.MemoryStream(); finalResult.Write(byteSaltPrefix, 0, byteSaltPrefix.Length); finalResult.Write(byteSalt, 0, byteSalt.Length); finalResult.WriteByte((byte)'$'); b64_from_24bit(altResultHash[0], altResultHash[6], altResultHash[12], 4, finalResult); b64_from_24bit(altResultHash[1], altResultHash[7], altResultHash[13], 4, finalResult); b64_from_24bit(altResultHash[2], altResultHash[8], altResultHash[14], 4, finalResult); b64_from_24bit(altResultHash[3], altResultHash[9], altResultHash[15], 4, finalResult); b64_from_24bit(altResultHash[4], altResultHash[10], altResultHash[5], 4, finalResult); b64_from_24bit(0, 0, altResultHash[11], 2, finalResult); result.Close(); altResult.Close(); byte[] done = finalResult.ToArray(); finalResult.Close(); return(done); }
private void UploadFilesToRemoteUrl(string url, string fileData, string FormFileNameField, string contentType, NameValueCollection nvc, string successConfirm, string filename) { try { string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x"); //----WebKitFormBoundary8eTSdfWMmZzOBme6 //----------------------------8d1222ee216c781 HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url); httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest2.Method = "POST"; httpWebRequest2.KeepAlive = true; httpWebRequest2.CookieContainer = cookies; httpWebRequest2.UserAgent = "Russ Judge Special"; //httpWebRequest2.Connection = "keep-alive"; httpWebRequest2.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; using (Stream memStream = new System.IO.MemoryStream()) { byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; foreach (string key in nvc.Keys) { string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; //string header = string.Format(headerTemplate, "file" + i, files[i]); string header = string.Format(headerTemplate, FormFileNameField, filename, contentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes(fileData); memStream.Write(buffer, 0, buffer.Length); memStream.Write(boundarybytes, 0, boundarybytes.Length); httpWebRequest2.ContentLength = memStream.Length; using (Stream requestStream = httpWebRequest2.GetRequestStream()) { memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); requestStream.Write(tempBuffer, 0, tempBuffer.Length); } } using (WebResponse webResponse2 = httpWebRequest2.GetResponse()) { using (Stream stream2 = webResponse2.GetResponseStream()) { StreamReader reader2 = new StreamReader(stream2); string s = reader2.ReadToEnd(); if (!string.IsNullOrEmpty(successConfirm)) { LastProcessSuccess = s.Contains(successConfirm); } else { LastProcessSuccess = false; } if (!LastProcessSuccess) { ErrorMessage = "Unable to confirm success with upload"; } } } } catch (Exception ex) { LastProcessSuccess = false; ErrorMessage = ex.Message; } }
private T Parse <T>(Entity.SimpleWebRequest <T> request, HttpResponse httpResponse) where T : Entity.SimpleWebResponse { var responseString = ParseEncoding.GetString(httpResponse.ResponseBytes); if (string.IsNullOrWhiteSpace(responseString)) { var obj = System.Activator.CreateInstance <T>(); obj.Headers = httpResponse.Headers; obj.StatusCode = httpResponse.StatusCode; return(obj); } var t = System.Activator.CreateInstance <T>(); t.ResponseBase64String = Convert.ToBase64String(httpResponse.ResponseBytes); t.Headers = httpResponse.Headers; t.StatusCode = httpResponse.StatusCode; if (t.ResponseType == Enum.ResponseType.Stream) { return(t); } else if (t.ResponseType == Enum.ResponseType.JSON) { var _t = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(responseString); _t.ResponseBase64String = t.ResponseBase64String; _t.Headers = httpResponse.Headers; _t.StatusCode = httpResponse.StatusCode; return(_t); } else if (t.ResponseType == Enum.ResponseType.XML) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { ms.Write(httpResponse.ResponseBytes, 0, httpResponse.ResponseBytes.Length); ms.Position = 0; var serializor = new System.Xml.Serialization.XmlSerializer(typeof(T)); var obj = serializor.Deserialize(ms) as T; if (obj != null) { obj.ResponseBase64String = Convert.ToBase64String(httpResponse.ResponseBytes); obj.Headers = httpResponse.Headers; obj.StatusCode = httpResponse.StatusCode; } return(obj); } } else if (t.ResponseType == Enum.ResponseType.HTML || t.ResponseType == Enum.ResponseType.JavaScript) { var ps = t.GetType().GetProperties(); foreach (var p in ps) { var at = p.GetCustomAttribute(typeof(Common.RegexAttribute)); if (at != null) { var reg = at as Common.RegexAttribute; var regex = new Regex(reg.RegexPattern, reg.RegexOptions); var match = regex.Match(responseString); if (match != null && p.CanWrite && match.Success) { var propType = Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType; var _value = match.Groups[reg.Key].Value; if (reg.NeedUrlDecode) { _value = _value.UrlDecode(); } if (reg.NeedHtmlDecode) { _value = _value.HtmlDecode(); } if (propType != typeof(System.String)) { p.SetValue(t, Convert.ChangeType(_value, propType)); } else { p.SetValue(t, _value); } } } } } return(t); }
public ResponseDataorg uploadA4scan(CustomerModel context) { string TempMandateId = ""; var retList = new List <ResponseDataorg>(); //ResponseDataorg retList = new ResponseDataorg(); ResponseDataorg pathInfo = new ResponseDataorg(); //if (context.PrintQr == "1") //{ // TempMandateId = ReadQrCode(context.base64, context.MandateId); //} if (context.AppID == "") { pathInfo.Message = "Incomplete data"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20020"; retList.Add(pathInfo); return(pathInfo); } else if (context.AppID != "" && CheckMandateInfo.ValidateAppID(context.AppID) != true) { pathInfo.Message = "Invalid AppId"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20023"; retList.Add(pathInfo); return(pathInfo); } else if (context.MdtID == "") { pathInfo.Message = "Incomplete data"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20020"; retList.Add(pathInfo); return(pathInfo); } else if (!CheckMandateInfo.CheckManadateID(context.MdtID, context.AppID)) { pathInfo.Message = "Invalid MandateId"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR200203"; retList.Add(pathInfo); return(pathInfo); } else if (context.MerchantKey == "") { pathInfo.Message = "Incomplete data"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20020"; retList.Add(pathInfo); return(pathInfo); } else if (context.MerchantKey != "" && CheckMandateInfo.ValidateEntityMerchantKey(context.MerchantKey, context.AppID) != true) { pathInfo.Message = "Invalid MerchantKey"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20021"; retList.Add(pathInfo); return(pathInfo); } else if (context.ScannedImage == "") { pathInfo.Message = "Incomplete data"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20020"; retList.Add(pathInfo); return(pathInfo); } //else if (!CheckMandateInfo.CheckAccountValidation(context.MdtID, context.AppID)) //{ // pathInfo.Message = "Account should be validated"; // pathInfo.Status = "Failure"; // pathInfo.ResCode = "ykR200204"; // retList.Add(pathInfo); // return pathInfo; //} else if (CheckMandateInfo.CheckENachValidation(context.MdtID, context.AppID)) { pathInfo.Message = "Mandate type already selected as eMandate"; pathInfo.Status = "Failure"; pathInfo.ResCode = "ykR20030"; retList.Add(pathInfo); return(pathInfo); } //else if (TempMandateId.Trim() != context.MdtID.Trim() && context.PrintQr == "1") //{ // pathInfo.Message = "Scan MandateId is not equal to the passed mandateId"; // pathInfo.Status = "Failure"; // pathInfo.ResCode = "ykR200203"; // retList.Add(pathInfo); // return pathInfo; //} else { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[Convert.ToString(context.AppID)].ConnectionString); bool Flag = false; // string temp = ConfigurationManager.AppSettings["EnitityMarchantKey" + context.AppID]; string UserId = ""; string query = "Sp_WebAPI"; //if (temp.Trim() == DBsecurity.Decrypt(context.MerchantKey)) //{ SqlCommand cmd = new SqlCommand(query, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@QueryType", "GetEntityUser"); cmd.Parameters.AddWithValue("@appId", context.AppID); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { UserId = Convert.ToString(dt.Rows[0][0]); Flag = true; } //} if (Flag) { Boolean Greater; try { string ID = Convert.ToString(context.MdtID); string No = CheckMandateInfo.GetRefNO(context.MdtID, context.AppID);//Convert.ToString(context.RefrenceNo); string fileName = string.Empty; string filePath = string.Empty; string extension = string.Empty; string targetPath = string.Empty; string TIFFilepath = string.Empty; string JPGFilepath = string.Empty; string OrgFilepath = string.Empty; byte[] bytes = System.Convert.FromBase64String(context.ScannedImage); float mb = (bytes.Length / 1024f) / 1024f; System.IO.MemoryStream mm = new System.IO.MemoryStream(); mm.Write(bytes, 0, bytes.Length); System.Drawing.Image img = System.Drawing.Image.FromStream(mm); if (Convert.ToInt32(img.HorizontalResolution) >= 300 && mb <= 3) { try { if (!Directory.Exists(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"FullMandate\" + ID)) { Directory.CreateDirectory(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"FullMandate\" + ID); } System.IO.DirectoryInfo di = new DirectoryInfo(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"FullMandate\" + ID); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } fileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"; filePath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\ColouredImage\", fileName); if (!Directory.Exists(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\ColouredImage\")) { Directory.CreateDirectory(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\ColouredImage\"); } using (System.Drawing.Image image = new Bitmap(new MemoryStream(bytes))) { image.Save(filePath, ImageFormat.Png); int newWidth = 4960; // New Width of Image in Pixel int newHeight = 7015; // New Height of Image in Pixel var thumbImg = new Bitmap(newWidth, newHeight); var thumbGraph = Graphics.FromImage(thumbImg); thumbGraph.CompositingQuality = CompositingQuality.HighQuality; thumbGraph.SmoothingMode = SmoothingMode.HighQuality; thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; var imgRectangle = new Rectangle(0, 0, newWidth, newHeight); thumbGraph.DrawImage(image, imgRectangle); // Save the file d targetPath = ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\FullMandate\" + ID + @"\" + fileName; thumbImg.Save(targetPath, image.RawFormat); OrgFilepath = @"\FullMandate\" + ID + @"\" + fileName; } fileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".tif"; if (File.Exists(filePath)) { File.Delete(filePath); } } catch (Exception ex) { // lblMsg.Text = "Oops!! error occured : " + ex.Message.ToString(); } finally { extension = string.Empty; fileName = string.Empty; filePath = string.Empty; } if (!Directory.Exists(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\MandateFile\" + ID)) { Directory.CreateDirectory(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\MandateFile\" + ID); } else { System.IO.DirectoryInfo di = new DirectoryInfo(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\MandateFile\" + ID); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } } string XCoordinate = ""; string YCoordinate = ""; string Width = ""; string Height = ""; string croppedFileName = string.Empty; string croppedFilePath = string.Empty; filePath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\FullMandate\" + ID + "", ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"); //Check if file exists on the path i.e. in the UploadedImages folder. if (File.Exists(filePath)) { //Get the image from UploadedImages folder. System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath); XCoordinate = "0"; YCoordinate = "0"; Width = Convert.ToString(orgImg.Width); Height = Convert.ToString((Convert.ToInt32(orgImg.Height) / 3)); Rectangle areaToCrop = new Rectangle(Convert.ToInt32(XCoordinate), Convert.ToInt32(YCoordinate), Convert.ToInt32(Width), Convert.ToInt32(Height)); try { Bitmap bitMap = new Bitmap(areaToCrop.Width, areaToCrop.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); //Create graphics object for alteration using (Graphics g = Graphics.FromImage(bitMap)) { //Draw image to screen g.DrawImage(orgImg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), areaToCrop, GraphicsUnit.Pixel); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; } bitMap.SetResolution(96, 96); //name the cropped image croppedFileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"; //Create path to store the cropped image if (!Directory.Exists(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\")) { Directory.CreateDirectory(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\"); } croppedFilePath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\", croppedFileName); bitMap.Save(croppedFilePath); var CropImagePath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\", ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"); System.Drawing.Image CropImage = System.Drawing.Image.FromFile(CropImagePath); using (var image = CropImage) { //int newWidth = 4200; // New Width of Image in Pixel //int newHeight = 1750; // New Height of Image in Pixel int newWidth = 827; // New Width of Image in Pixel int newHeight = 356; // New Height of Image in Pixel var thumbImg = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); var thumbGraph = Graphics.FromImage(thumbImg); var imgRectangle = new Rectangle(0, 0, newWidth, newHeight); thumbGraph.DrawImage(image, imgRectangle); thumbImg.SetResolution(100, 100); System.Drawing.Bitmap b0 = CopyToBpp(thumbImg, 8); b0.SetResolution(100, 100); croppedFileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"; croppedFilePath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\MandateFile\" + ID + @"\", croppedFileName); JPGFilepath = "../MandateFile/" + ID + "/" + croppedFileName; ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; b0.Save(croppedFilePath, jpgEncoder, myEncoderParameters); // b0.Save(croppedFilePath, image.RawFormat); } var CropImagePath1 = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\", ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"); System.Drawing.Image CropImage1 = System.Drawing.Image.FromFile(CropImagePath1); using (var image1 = CropImage1) { int newWidth = 827 * 2; int newHeight = 356 * 2; var thumbImg1 = new Bitmap(newWidth, newHeight); var thumbGraph1 = Graphics.FromImage(thumbImg1); var imgRectangle1 = new Rectangle(0, 0, newWidth, newHeight); thumbGraph1.DrawImage(image1, imgRectangle1); thumbImg1.SetResolution(200, 200); System.Drawing.Bitmap b1 = CopyToBpp(thumbImg1, 1); b1.SetResolution(200, 200); croppedFileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".tif"; croppedFilePath = Path.Combine(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\MandateFile\" + ID + @"\", croppedFileName); TIFFilepath = "../MandateFile/" + ID + "/" + croppedFileName; ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Tiff); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Compression; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)EncoderValue.CompressionCCITT4); myEncoderParameters.Param[0] = myEncoderParameter; b1.Save(croppedFilePath, jpgEncoder, myEncoderParameters); // b1.Save(croppedFilePath, image1.RawFormat); } orgImg.Dispose(); con.Open(); cmd = new SqlCommand("Sp_Mandate", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@QueryType", "UpdatePNGTIP"); cmd.Parameters.AddWithValue("@TIPPath", TIFFilepath); cmd.Parameters.AddWithValue("@PNGPath", JPGFilepath); cmd.Parameters.AddWithValue("@MandateId", context.MdtID); cmd.Parameters.AddWithValue("@UserId", UserId); try { cmd.ExecuteNonQuery(); } catch (Exception ex) { pathInfo.Message = ex.Message; } finally { con.Close(); } if (File.Exists(CropImagePath1)) { File.Delete(CropImagePath1); } if (File.Exists(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\" + ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg")) { File.Delete(ConfigurationManager.AppSettings["FileUploadPath" + context.AppID] + @"\CropImage\" + ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"); } bitMap = null; //Show cropped image croppedFileName = ConfigurationManager.AppSettings["DownloadFileName" + context.AppID].ToString() + "_" + DateTime.Now.ToString("ddMMyyyy") + "_" + No + ".jpg"; pathInfo.Status = "Success"; pathInfo.ResCode = "ykR20033"; pathInfo.Message = "Image uploaded successfully"; pathInfo.MdtID = context.MdtID; // pathInfo.FullImagePath = ConfigurationManager.AppSettings["FilePath" + context.AppID].ToString() + "/" + OrgFilepath; pathInfo.JpgImage = ConfigurationManager.AppSettings["FilePathURL" + context.AppID].ToString() + "/" + JPGFilepath.Substring(3, JPGFilepath.Length - 3); pathInfo.TifImage = ConfigurationManager.AppSettings["FilePathURL" + context.AppID].ToString() + "/" + TIFFilepath.Substring(3, TIFFilepath.Length - 3); } catch (Exception ex) { // lblMsg.Text = "Oops!! error occured : " + ex.Message.ToString(); } finally { fileName = string.Empty; filePath = string.Empty; croppedFileName = string.Empty; croppedFilePath = string.Empty; } } retList.Add(pathInfo); return(pathInfo); } else { pathInfo.ResCode = "ykR20027"; pathInfo.Status = "Failure"; pathInfo.Message = "Image resolution should be greater than or equal to 300 DPI-This is for only uploading A4 Scan"; pathInfo.JpgImage = ""; pathInfo.TifImage = ""; } } catch (Exception e) { pathInfo.ResCode = "ykR20020"; pathInfo.Status = "Failure"; pathInfo.Message = "Incomplete data"; pathInfo.JpgImage = ""; pathInfo.TifImage = ""; } retList.Add(pathInfo); return(pathInfo); } else { pathInfo.ResCode = "ykR20020"; pathInfo.Status = "Failure"; pathInfo.Message = "Incomplete data"; retList.Add(pathInfo); return(pathInfo); } } }
public MemoryFileAbstraction(int maxSize, byte [] data) { stream = new System.IO.MemoryStream(maxSize); stream.Write(data, 0, data.Length); stream.Position = 0; }
public void Write(byte[] data) { stream.Write(data, 0, data.Length); }
bool IRequestHandler.OnBeforeResourceLoad(IWebBrowser browser, IRequestResponse requestResponse) { return(false); //System.Diagnostics.Debug.WriteLine("OnBeforeResourceLoad"); //var headers = request.GetHeaders(); string url = requestResponse.Request.Url; if (url.StartsWith("chrome-devtools://") == false) { if (brow_ImportPlugin == false && (url.Contains(".js") || url.Contains("/js/"))) { MemoryStream stream; byte[] bytes; switch (brow_Domain) { case DOMAIN_GOOGLE: case DOMAIN_BING: stream = new System.IO.MemoryStream(); bytes = ASCIIEncoding.ASCII.GetBytes(@"document.addEventListener('DOMContentLoaded', function (event) { var a = document.querySelectorAll('img'); for (var i = 0; i < a.length; i++) { a[i].remove(); }; console.log('DOM_CONTENT_LOADED'); }); "); stream.Write(bytes, 0, bytes.Length); requestResponse.RespondWith(stream, "text/javascript; charset=utf-8"); break; default: stream = new System.IO.MemoryStream(); FileStream file = new FileStream(@"plugin.js", FileMode.Open, FileAccess.Read, FileShare.Read); bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); stream.Write(bytes, 0, (int)file.Length); file.Close(); requestResponse.RespondWith(stream, "text/javascript; charset=utf-8"); break; } Debug.WriteLine("----> JS === " + url); brow_ImportPlugin = true; return(false); } if (url.Contains(".js") || url.Contains("/js/") || url.Contains(brow_Domain) == false || url.Contains("font") || url.Contains(".svg") || url.Contains(".woff") || url.Contains(".ttf") || url.Contains("/image") || url.Contains(".png") || url.Contains(".jpeg") || url.Contains(".jpg") || url.Contains(".gif")) { Debug.WriteLine("----> " + url); return(true); } Debug.WriteLine(url); } #region ////IRequest request = requestResponse.Request; ////string url = request.Url, s = string.Empty; // MemoryStream stream; // byte[] bytes; // if (url.EndsWith(".mp4")) // { // string id = Path.GetFileName(url); // id = id.Substring(0, id.Length - 4); // string desUrl = string.Format("https://drive.google.com/uc?export=download&id={0}", id); // //stream = new System.IO.MemoryStream(); // ////bytes = System.Text.ASCIIEncoding.UTF8.GetBytes(""); // //FileStream file = new FileStream(@"E:\_cs\cef\cef_119_youtube\bin\x86\Debug\player\files\1.mp4", FileMode.Open, FileAccess.Read, FileShare.Read); // //bytes = new byte[file.Length]; // //file.Read(bytes, 0, (int)file.Length); // //file.Close(); // //stream.Write(bytes, 0, bytes.Length); // //requestResponse.RespondWith(stream, "video/mp4"); // desUrl = "https://r6---sn-8qj-i5oed.googlevideo.com/videoplayback?source=youtube&ms=au%2Crdu&mt=1526202288&mv=m&mm=31%2C29&mn=sn-8qj-i5oed%2Csn-i3b7kn7d&requiressl=yes&key=yt6&itag=22&mime=video%2Fmp4&ipbits=0&signature=CFA4FBAB6DAF7D4E1E6F8643865E06BD13C9B2C9.4AE8093B9CC164EE634F1465807AE309CB9EC5C3&dur=234.289&expire=1526223993&pl=20&ratebypass=yes&pcm2cms=yes&fvip=2&lmt=1510741625396835&id=o-APLwY1H9955dAWnARW0t1FTqsoCs-_OffF4spks0P2AQ&ei=GQD4WtupH4mngQOysI3oCw&c=WEB&initcwndbps=960000&sparams=dur%2Cei%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cexpire&ip=14.177.123.70"; // requestResponse.Redirect(desUrl); // } // else // { // url = url.ToLower(); // #region // switch (url) // { // case "http://i.ytimg.com/crossdomain.xml": // case "https://drive.google.com/crossdomain.xml": // #region // stream = new MemoryStream(); // s = @"<?xml version=""1.0""?> //<!DOCTYPE cross-domain-policy SYSTEM //""http://www.adobe.com/xml/dtds/cross-domain-policy.dtd""> //<cross-domain-policy> // <site-control permitted-cross-domain-policies=""all""/> // <allow-access-from domain=""*"" secure=""false""/> // <allow-http-request-headers-from domain=""*"" headers=""*"" secure=""false""/> //</cross-domain-policy>"; // s = @"<cross-domain-policy><allow-access-from domain=""*"" /></cross-domain-policy>"; // bytes = ASCIIEncoding.UTF8.GetBytes(""); // stream.Write(bytes, 0, bytes.Length); // requestResponse.RespondWith(stream, "text/xml"); // #endregion // break; // case "http://l.longtailvideo.com/5/10/logo.png": // stream = new MemoryStream(); // bytes = new byte[] { 0 }; // stream.Write(bytes, 0, bytes.Length); // requestResponse.RespondWith(stream, "image/png"); // break; // case "http://www.youtube.com/apiplayer": // stream = new System.IO.MemoryStream(); // bytes = System.Text.ASCIIEncoding.UTF8.GetBytes(""); // stream.Write(bytes, 0, bytes.Length); // requestResponse.RespondWith(stream, "text/html; charset=utf-8"); // break; // } // ////if (request.Url.EndsWith("header.png")) // ////{ // //// MemoryStream stream = new System.IO.MemoryStream(); // //// FileStream file = new FileStream(@"C:\tmp\header.png", FileMode.Open, FileAccess.Read, FileShare.Read); // //// byte[] bytes = new byte[file.Length]; // //// file.Read(bytes, 0, (int)file.Length); // //// stream.Write(bytes, 0, (int)file.Length); // //// file.Close(); // //// requestResponse.RespondWith(stream, "image/png"); // ////} // #endregion // } #endregion return(false); }
/// <summary> /// 上传文件到远程服务器 /// </summary> /// <param name="url">上传路径</param> /// <param name="files">文件路径数组</param> /// <param name="nvc">同文件一同上传的表单文本域及值</param> public static string UploadFilesToRemoteUrl(string url, string file) { try { StringBuilder sb = new StringBuilder(); string boundary = "----------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; Stream memStream = new System.IO.MemoryStream(); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; /*foreach (string key in nvc.Keys) * { * string formitem = string.Format(formdataTemplate, key, nvc[key]); * sb.Append(formitem); * byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); * memStream.Write(formitembytes, 0, formitembytes.Length); * }*/ string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; // 逐个将文件内容写入流 FileInfo fi = new FileInfo(file); // 写入文件开始标记 string header = string.Format(headerTemplate, "file", fi.Name); sb.Append(header); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024 * 1024 * 8];//每次上传10M int bytesRead = 0; // 写入文件内容 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } fileStream.Close(); sb.Append("\r\n--" + boundary + "--\r\n"); // 将结束标记写入内存流 byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); memStream.Write(boundarybytes, 0, boundarybytes.Length); httpWebRequest.ContentLength = memStream.Length;//流总大小 Stream requestStream = httpWebRequest.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); WebResponse webResponse = httpWebRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream); string ret = reader.ReadToEnd(); return(ret); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(""); }
public void ProcessRequest(HttpContext context) { string url = HttpUtility.UrlDecode(context.Request.QueryString.ToString()); if (url == "") { context.Response.Write("PilotGaea O'view Map Server(" + (IntPtr.Size * 8).ToString() + " bits) " + (m_Server.IsStart() ? "Start" : "Stop")); if (!m_Server.IsStart()) { context.Response.Write(m_Server.GetLastError()); } } else { //轉給mapserver //判斷是GET還是POST bool bPOST = context.Request.InputStream.Length > 0; byte[] postBuffer = null; if (bPOST)//取得POST資料 { postBuffer = new byte[context.Request.InputStream.Length]; context.Request.InputStream.Read(postBuffer, 0, postBuffer.Length); } System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; req.Method = bPOST ? "POST" : "GET"; if (bPOST) { req.ContentLength = postBuffer.Length; req.ContentType = "application/json"; } req.UserAgent = "PilotGaea Proxy Server"; //複製檔頭的cookie System.Collections.Specialized.NameValueCollection headers = context.Request.Headers; for (int i = 0; i < headers.Count; i++) { //context.Response.Write(headers.GetKey(i) + ":" + headers.Get(i) + "<BR>"); if (headers.GetKey(i) == "Cookie") { req.Headers.Set("Cookie", headers.Get(i)); break; } } byte[] retBuffer = null; try { if (bPOST) { //上傳 System.IO.Stream stream_req = req.GetRequestStream(); stream_req.Write(postBuffer, 0, postBuffer.Length); stream_req.Flush(); stream_req.Close(); } System.Net.HttpWebResponse res = req.GetResponse() as System.Net.HttpWebResponse; System.IO.Stream stream_res = res.GetResponseStream(); int len = 1024 * 1024; byte[] tmpBuffer = new byte[len];//一次1MB int readlen = 0; System.IO.MemoryStream ms = new System.IO.MemoryStream(); do { readlen = stream_res.Read(tmpBuffer, 0, len); ms.Write(tmpBuffer, 0, readlen); }while (readlen > 0); retBuffer = ms.ToArray(); //複製回應的檔頭 for (int i = 0; i < res.Headers.Count; i++) { string[] s = res.Headers.GetValues(i); string k = res.Headers.Keys[i]; string v = ""; for (int j = 0; j < s.Length; j++) { if (j > 0) { v += ";"; } v += s[j]; } if (k == "Content-Type") { context.Response.ContentType = v; } else if (k == "Set-Cookie") { context.Response.SetCookie(new HttpCookie(v)); } else if (k == "Last-Modified") { context.Response.Headers.Set(k, v); } else if (k == "Content-Encoding") { context.Response.Headers.Set(k, v); } } //寫入回應的本文 context.Response.BinaryWrite(retBuffer); } catch (System.Net.WebException ex) { if (ex.Response != null) { context.Response.StatusCode = (int)(((System.Net.HttpWebResponse)ex.Response).StatusCode); context.Response.StatusDescription = ((System.Net.HttpWebResponse)ex.Response).StatusDescription; } else { //通常是伺服器沒開 context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server error:" + ex.Message; } } catch (Exception ex) { context.Response.StatusCode = 404; context.Response.StatusDescription = "File not found:" + ex.Message; } } }
public NewByteBuffer put(byte[] src, int offset, int length) { stream.Write(src, offset, length); return(this); }
public static string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; Stream memStream = new System.IO.MemoryStream(); var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; if (formFields != null) { foreach (string key in formFields.Keys) { string formitem = string.Format(formdataTemplate, key, formFields[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } } string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; for (int i = 0; i < files.Length; i++) { memStream.Write(boundarybytes, 0, boundarybytes.Length); String header = string.Format(headerTemplate, "uplTheFile", files[i]); Byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read)) { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } } } memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); request.ContentLength = memStream.Length; using (Stream requestStream = request.GetRequestStream()) { memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); } using (var response = request.GetResponse()) { Stream stream2 = response.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); return(reader2.ReadToEnd()); } }