//https://bitbucket.org/lorenzopolidori/http-form-parser/pull-requests private static NetHttpPostBody Parse(Stream stream, Encoding encoding, String FilePartName = null) { NetHttpPostBody postBody = new NetHttpPostBody() { ContentType = WebOperationContext.Current.IncomingRequest.ContentType }; //postBody.Success = false; // Read the stream into a byte array byte[] data = stream.ToByteArray(); // Copy to a string for header parsing string content = encoding.GetString(data); // The first line should contain the delimiter int delimiterEndIndex = content.IndexOf("\r\n"); if (delimiterEndIndex > -1) { string delimiter = content.Substring(0, content.IndexOf("\r\n")); string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in sections) { if (s.Contains("Content-Disposition")) { // If we find "Content-Disposition", this is a valid multi-part section // Now, look for the "name" parameter Match nameMatch = new Regex(@"(?<=name\=\"")(.*?)(?=\"")").Match(s); string name = nameMatch.Value.Trim().ToLower(); if (name == FilePartName) { // Look for Content-Type Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)"); Match contentTypeMatch = re.Match(content); // Look for filename re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")"); Match filenameMatch = re.Match(content); // Did we find the required values? if (contentTypeMatch.Success && filenameMatch.Success) { // Set properties postBody.ContentType = contentTypeMatch.Value.Trim(); postBody.Filename = filenameMatch.Value.Trim(); // Get the start & end indexes of the file contents int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length; byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter); int endIndex = data.IndexOfArray(delimiterBytes, startIndex);//Misc.IndexOf(data, delimiterBytes, startIndex); int contentLength = endIndex - startIndex; // Extract the file contents from the byte array byte[] fileData = new byte[contentLength]; Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength); postBody.FileContents = fileData; } } else if (!string.IsNullOrEmpty(name.Trim())) { // Get the start & end indexes of the file contents int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length; postBody.Parameters.Add(name, s.Substring(startIndex).TrimEnd(new char[] { '\r', '\n' }).Trim()); } } } // If some data has been successfully received, set success to true //if (postBody.FileContents != null || postBody.Parameters.Count != 0) // postBody.Success = true; } return postBody; }
public void Put(Stream data, Uri path, bool overwrite = false, string userName = "", string password = "") { using (data) { File.WriteAllBytes(path.LocalPath, data.ToByteArray()); } }
//new, it is stream parameter public static bool Decode (Stream buffer) { if (buffer == null) throw new Exception (); if (buffer.Length < sizeof(bool)) throw new Exception (); return BitConverter.ToBoolean (buffer.ToByteArray (), 0); }
public static PatchResult Patch(Stream sourceStream, Stream patchStream, out MemoryStream modifyStream) { modifyStream = null; byte[] patchData = patchStream.ToByteArray(); uint patchSize = (uint)patchData.Length; byte[] sourceData = sourceStream.ToByteArray(); uint sourceSize = (uint)sourceData.Length; byte[] targetData = sourceData.ToList().ToArray(); uint targetSize = (uint)targetData.Length; if (patchSize < 19) return PatchResult.patch_too_small; UInt32 modifyChecksum = 0xFFFFFFFF; UInt32 targetChecksum = 0xFFFFFFFF; uint modifyOffset = 0; uint sourceRelativeOffset = 0; uint targetRelativeOffset = 0; uint outputOffset = 0; re read = () => { byte data = patchData[modifyOffset++]; modifyChecksum = CRC32.Adjust(modifyChecksum, data); return data; }; dec decode = () => { UInt64 data = 0; UInt64 shift = 1; while (true) { byte x = read(); data += (ulong)(x & 0x7f) * shift; if ((x & 0x80) != 0) break; shift <<= 7; data += shift; } return data; }; wr write = (byte data) => { targetData[outputOffset++] = data; targetChecksum = CRC32.Adjust(targetChecksum, data); }; if (read() != 'B') return PatchResult.patch_invalid_header; if (read() != 'P') return PatchResult.patch_invalid_header; if (read() != 'S') return PatchResult.patch_invalid_header; if (read() != '1') return PatchResult.patch_invalid_header; uint modifySourceSize = (uint)decode(); uint modifyTargetSize = (uint)decode(); Array.Resize(ref targetData, (int)modifyTargetSize); targetSize = modifyTargetSize; uint modifyMarkupSize = (uint)decode(); for (uint n = 0; n < modifyMarkupSize; n++) read(); if (modifySourceSize > sourceSize) return PatchResult.source_too_small; if (modifyTargetSize > targetSize) return PatchResult.target_too_small; while (modifyOffset < patchSize - 12) { uint length = (uint)decode(); Operation mode = (Operation)(length & 3); length = (length >> 2) + 1; switch (mode) { case Operation.SourceRead: while (length-- > 0) write(sourceData[outputOffset]); break; case Operation.TargetRead: while (length-- > 0) write(read()); break; case Operation.SourceCopy: case Operation.TargetCopy: int offset = (int)decode(); bool negative = (offset & 1) == 1; offset >>= 1; if (negative) offset = -offset; if (mode == Operation.SourceCopy) { sourceRelativeOffset += (uint)offset; while (length-- > 0) write(sourceData[sourceRelativeOffset++]); } else { targetRelativeOffset += (uint)offset; while (length-- > 0) write(targetData[targetRelativeOffset++]); } break; } } UInt32 modifySourceChecksum = 0; UInt32 modifyTargetChecksum = 0; UInt32 modifyModifyChecksum = 0; for (int n = 0; n < 32; n += 8) modifySourceChecksum |= (uint)(read() << n); for (int n = 0; n < 32; n += 8) modifyTargetChecksum |= (uint)(read() << n); uint finalModifyChecksum = ~modifyChecksum; //CRC32.Calculate(patchData, (uint)patchData.Length - 4); // for (int n = 0; n < 32; n += 8) modifyModifyChecksum |= (uint)(read() << n); UInt32 sourceChecksum = CRC32.Calculate(sourceData, (uint)sourceData.Length); targetChecksum = ~targetChecksum; if (sourceChecksum != modifySourceChecksum) return PatchResult.source_checksum_invalid; if (targetChecksum != modifyTargetChecksum) return PatchResult.target_checksum_invalid; if (finalModifyChecksum != modifyModifyChecksum) return PatchResult.patch_checksum_invalid; modifyStream = new MemoryStream(targetData); return PatchResult.success; }
public static bool Create(Stream sourceStream, Stream modifyStream, out MemoryStream patchStream, string metadata = "", UInt32 Granularity = 1) { MemoryStream patchFile = new MemoryStream(); byte[] sourceData = sourceStream.ToByteArray(); byte[] modifyData = modifyStream.ToByteArray(); uint sourceSize = (uint)sourceData.Length; uint modifySize = (uint)modifyData.Length; UInt32 patchChecksum = 0xFFFFFFFF; uint targetRelativeOffset = 0; uint outputOffset = 0; wri write = (byte data) => { patchFile.WriteByte(data); patchChecksum = CRC32.Adjust(patchChecksum, data); }; enc encode = (UInt64 data) => { while (true) { byte x = (byte)(data & 0x7f); data >>= 7; if (data == 0) { write((byte)(0x80 | x)); break; } write(x); data--; } }; int targetReadLength = 0; flush targetReadFlush = () => { if (targetReadLength != 0) { encode((uint)Operation.TargetRead | (((uint)targetReadLength - 1) << 2)); int offset = (int)outputOffset - targetReadLength; while (targetReadLength > 0) { write(modifyData[offset++]); targetReadLength--; } } }; write((byte)'B'); write((byte)'P'); write((byte)'S'); write((byte)'1'); encode(sourceSize); encode(modifySize); uint markupSize = (uint)metadata.Length; encode(markupSize); for (int n = 0; n < markupSize; n++) write((byte)metadata[n]); while (outputOffset < modifySize) { uint sourceLength = 0; for (uint n = 0; outputOffset + n < Math.Min(sourceSize, modifySize); n++) { if (sourceData[outputOffset + n] != modifyData[outputOffset + n]) break; sourceLength++; } uint rleLength = 0; for (uint n = 1; outputOffset + n < modifySize; n++) { if (modifyData[outputOffset] != modifyData[outputOffset + n]) break; rleLength++; } if (rleLength >= 4) { //write byte to repeat targetReadLength++; outputOffset++; targetReadFlush(); //copy starting from repetition byte encode((uint)Operation.TargetCopy | ((rleLength - 1) << 2)); uint relativeOffset = (outputOffset - 1) - targetRelativeOffset; encode(relativeOffset << 1); outputOffset += rleLength; targetRelativeOffset = outputOffset - 1; } else if (sourceLength >= 4) { targetReadFlush(); encode((uint)Operation.SourceRead | ((sourceLength - 1) << 2)); outputOffset += sourceLength; } else { targetReadLength += (int)Granularity; outputOffset += Granularity; } } targetReadFlush(); UInt32 sourceChecksum = CRC32.Calculate(sourceData, sourceSize); for (int n = 0; n < 32; n += 8) write((byte)(sourceChecksum >> n)); UInt32 modifyChecksum = CRC32.Calculate(modifyData, modifySize); for (int n = 0; n < 32; n += 8) write((byte)(modifyChecksum >> n)); uint finalPatchChecksum = ~patchChecksum; for (int n = 0; n < 32; n += 8) write((byte)(finalPatchChecksum >> n)); patchStream = patchFile; return true; }
public MetadataResult GetMetadata(Stream patchStream, out string metadataString) { metadataString = ""; if (patchStream.Length < 19) return MetadataResult.patch_too_small; byte[] patchData = patchStream.ToByteArray(); uint offset = 4; dec decode = () => { UInt64 d = 0; UInt64 shift = 1; while (true) { byte x = patchData[offset++]; d += ((ulong)(x & 0x7f) * shift); if ((x & 0x80) != 0) break; shift <<= 7; d += shift; } return d; }; decode(); decode(); var modifyMarkupSize = (uint)decode(); char[] buffer = new char[modifyMarkupSize + 1]; for (int n = 0; n < modifyMarkupSize; n++) buffer[n] = (char)patchData[offset++]; buffer[(int)modifyMarkupSize] = (char)0; metadataString = new string(buffer); return MetadataResult.success; }
/* Compress */ public override MemoryStream Compress(ref Stream data, string filename) { try { uint DecompressedSize = (uint)data.Length; MemoryStream CompressedData = new MemoryStream(); byte[] DecompressedData = data.ToByteArray(); uint SourcePointer = 0x0; uint DestPointer = 0x4; // Test if the file is too large to be compressed if (data.Length > 0xFFFFFFFF) throw new Exception("Input file is too large to compress."); // Set up the Lz Compression Dictionary LzWindowDictionary LzDictionary = new LzWindowDictionary(); LzDictionary.SetWindowSize(0x1000); LzDictionary.SetMaxMatchAmount(0xFFFF + 273); // Figure out where we are going to write the decompressed file size if (data.Length <= 0xFFFFFF) CompressedData.Write((uint)('\x11' | (DecompressedSize << 8))); else { CompressedData.Write((uint)('\x11')); CompressedData.Write(DecompressedSize); DestPointer += 0x4; } // Start compression while (SourcePointer < DecompressedSize) { byte Flag = 0x0; uint FlagPosition = DestPointer; CompressedData.WriteByte(Flag); // It will be filled in later DestPointer++; for (int i = 7; i >= 0; i--) { int[] LzSearchMatch = LzDictionary.Search(DecompressedData, SourcePointer, DecompressedSize); if (LzSearchMatch[1] > 0) // There is a compression match { Flag |= (byte)(1 << i); // Write the distance/length pair if (LzSearchMatch[1] <= 0xF + 1) // 2 bytes { CompressedData.WriteByte((byte)((((LzSearchMatch[1] - 1) & 0xF) << 4) | (((LzSearchMatch[0] - 1) & 0xFFF) >> 8))); CompressedData.WriteByte((byte)((LzSearchMatch[0] - 1) & 0xFF)); DestPointer += 2; } else if (LzSearchMatch[1] <= 0xFF + 17) // 3 bytes { CompressedData.WriteByte((byte)(((LzSearchMatch[1] - 17) & 0xFF) >> 4)); CompressedData.WriteByte((byte)((((LzSearchMatch[1] - 17) & 0xF) << 4) | (((LzSearchMatch[0] - 1) & 0xFFF) >> 8))); CompressedData.WriteByte((byte)((LzSearchMatch[0] - 1) & 0xFF)); DestPointer += 3; } else // 4 bytes { CompressedData.WriteByte((byte)((1 << 4) | (((LzSearchMatch[1] - 273) & 0xFFFF) >> 12))); CompressedData.WriteByte((byte)(((LzSearchMatch[1] - 273) & 0xFFF) >> 4)); CompressedData.WriteByte((byte)((((LzSearchMatch[1] - 273) & 0xF) << 4) | (((LzSearchMatch[0] - 1) & 0xFFF) >> 8))); CompressedData.WriteByte((byte)((LzSearchMatch[0] - 1) & 0xFF)); DestPointer += 4; } LzDictionary.AddEntryRange(DecompressedData, (int)SourcePointer, LzSearchMatch[1]); LzDictionary.SlideWindow(LzSearchMatch[1]); SourcePointer += (uint)LzSearchMatch[1]; } else // There wasn't a match { Flag |= (byte)(0 << i); CompressedData.WriteByte(DecompressedData[SourcePointer]); LzDictionary.AddEntry(DecompressedData, (int)SourcePointer); LzDictionary.SlideWindow(1); SourcePointer++; DestPointer++; } // Check for out of bounds if (SourcePointer >= DecompressedSize) break; } // Write the flag. // Note that the original position gets reset after writing. CompressedData.Seek(FlagPosition, SeekOrigin.Begin); CompressedData.WriteByte(Flag); CompressedData.Seek(DestPointer, SeekOrigin.Begin); } return CompressedData; } catch { return null; // An error occured while compressing } }
/// <summary> /// Envia um arquivo para o servidor a partir do conteudo e nome original, dando a opção de gravar no servidor com um novo nome /// </summary> /// <param name="binaryData">Dados do arquivo</param> /// <param name="originalFilename">Nome de origem</param> /// <param name="filename">Nome de destino</param> /// <returns>Id do arquivo gerado pelo índice</returns> public string UploadFile(Stream binaryData, string originalFilename, string filename) { string newFileName = NewFileName(); string destFile = Path.Combine(_folderPath, newFileName); string contentId = NextContentId(); FileStream fs = File.Create(destFile, 2048, FileOptions.None); BinaryWriter bw = new BinaryWriter(fs); bw.Write(binaryData.ToByteArray()); bw.Close(); fs.Close(); IncrementaIndice(contentId, newFileName); return contentId; }
/* Compress */ public override MemoryStream Compress(ref Stream data, string filename) { try { uint DecompressedSize = (uint)data.Length; MemoryStream CompressedData = new MemoryStream(); byte[] DecompressedData = data.ToByteArray(); uint SourcePointer = 0x0; uint DestPointer = 0x10; // Test if the file is too large to be compressed if (data.Length > 0xFFFFFFFF) throw new Exception("Input file is too large to compress."); // Set up the Lz Compression Dictionary LzBufferDictionary LzDictionary = new LzBufferDictionary(); LzDictionary.SetBufferSize(0x1000); LzDictionary.SetBufferStart(0xFEE); LzDictionary.SetMaxMatchAmount(0xF + 3); // Start compression CompressedData.Write("LZ01"); CompressedData.Write((uint)0); // Will be filled in later CompressedData.Write(DecompressedSize); CompressedData.Seek(4, SeekOrigin.Current); // Advance 4 bytes while (SourcePointer < DecompressedSize) { byte Flag = 0x0; uint FlagPosition = DestPointer; CompressedData.WriteByte(Flag); // It will be filled in later DestPointer++; for (int i = 0; i < 8; i++) { int[] LzSearchMatch = LzDictionary.Search(DecompressedData, SourcePointer, DecompressedSize); if (LzSearchMatch[1] > 0) // There is a compression match { Flag |= (byte)(0 << i); CompressedData.WriteByte((byte)(LzSearchMatch[0] & 0xFF)); CompressedData.WriteByte((byte)(((LzSearchMatch[0] & 0xF00) >> 4) | ((LzSearchMatch[1] - 3) & 0xF))); LzDictionary.AddEntryRange(DecompressedData, (int)SourcePointer, LzSearchMatch[1]); SourcePointer += (uint)LzSearchMatch[1]; DestPointer += 2; } else // There wasn't a match { Flag |= (byte)(1 << i); CompressedData.WriteByte(DecompressedData[SourcePointer]); LzDictionary.AddEntry(DecompressedData, (int)SourcePointer); SourcePointer++; DestPointer++; } // Check for out of bounds if (SourcePointer >= DecompressedSize) break; } // Write the flag. // Note that the original position gets reset after writing. CompressedData.Seek(FlagPosition, SeekOrigin.Begin); CompressedData.WriteByte(Flag); CompressedData.Seek(DestPointer, SeekOrigin.Begin); } CompressedData.Seek(0x4, SeekOrigin.Begin); CompressedData.Write((uint)CompressedData.Length); CompressedData.Seek(0, SeekOrigin.End); return CompressedData; } catch { return null; // An error occured while compressing } }
/* Compress */ public override MemoryStream Compress(ref Stream data, string filename) { try { uint DecompressedSize = (uint)data.Length; MemoryStream CompressedData = new MemoryStream(); byte[] DecompressedData = data.ToByteArray(); uint SourcePointer = 0x0; uint DestPointer = 0x40; uint MagicValue = (uint)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds; // Test if the file is too large to be compressed if (data.Length > 0xFFFFFFFF) throw new Exception("Input file is too large to compress."); // Set up the Lz Compression Dictionary LzBufferDictionary LzDictionary = new LzBufferDictionary(); LzDictionary.SetBufferSize(0x1000); LzDictionary.SetBufferStart(0xFEE); LzDictionary.SetMaxMatchAmount(0xF + 3); // Start compression CompressedData.Write("LZ00"); CompressedData.Write(0u); // Will be filled in later CompressedData.Seek(8, SeekOrigin.Current); // Advance 8 bytes // If the file extension is MRZ or TEZ, we probably want to change it if (Path.GetExtension(filename).ToLower() == ".mrz") filename = Path.GetFileNameWithoutExtension(filename) + ".mrg"; else if (Path.GetExtension(filename).ToLower() == ".tez") filename = Path.GetFileNameWithoutExtension(filename) + ".tex"; CompressedData.Write(filename, 31, 32, Encoding.GetEncoding("Shift_JIS")); CompressedData.Write(DecompressedSize); CompressedData.Write(MagicValue); CompressedData.Seek(8, SeekOrigin.Current); // Advance 8 bytes while (SourcePointer < DecompressedSize) { MagicValue = GetNewMagicValue(MagicValue); byte Flag = 0x0; uint FlagPosition = DestPointer; uint FlagMagicValue = MagicValue; // Since it won't be filled in now CompressedData.WriteByte(Flag); // It will be filled in later DestPointer++; for (int i = 0; i < 8; i++) { int[] LzSearchMatch = LzDictionary.Search(DecompressedData, SourcePointer, DecompressedSize); if (LzSearchMatch[1] > 0) // There is a compression match { Flag |= (byte)(0 << i); MagicValue = GetNewMagicValue(MagicValue); CompressedData.WriteByte(EncryptByte((byte)(LzSearchMatch[0] & 0xFF), MagicValue)); MagicValue = GetNewMagicValue(MagicValue); CompressedData.WriteByte(EncryptByte((byte)(((LzSearchMatch[0] & 0xF00) >> 4) | ((LzSearchMatch[1] - 3) & 0xF)), MagicValue)); LzDictionary.AddEntryRange(DecompressedData, (int)SourcePointer, LzSearchMatch[1]); SourcePointer += (uint)LzSearchMatch[1]; DestPointer += 2; } else // There wasn't a match { Flag |= (byte)(1 << i); MagicValue = GetNewMagicValue(MagicValue); CompressedData.WriteByte(EncryptByte(DecompressedData[SourcePointer], MagicValue)); LzDictionary.AddEntry(DecompressedData, (int)SourcePointer); SourcePointer++; DestPointer++; } // Check for out of bounds if (SourcePointer >= DecompressedSize) break; } // Write the flag. // Note that the original position gets reset after writing. CompressedData.Seek(FlagPosition, SeekOrigin.Begin); CompressedData.WriteByte(EncryptByte(Flag, FlagMagicValue)); CompressedData.Seek(DestPointer, SeekOrigin.Begin); } CompressedData.Seek(0x4, SeekOrigin.Begin); CompressedData.Write((uint)CompressedData.Length); CompressedData.Seek(0, SeekOrigin.End); return CompressedData; } catch { return null; // An error occured while compressing } }
/// <summary> /// Envia um arquivo para o servidor a partir do conteudo e nome original, dando a opção de gravar no servidor com um novo nome /// </summary> /// <param name="binaryData">Dados do arquivo</param> /// <param name="originalFilename">Nome de origem</param> /// <param name="filename">Nome de destino</param> /// <returns>Id do arquivo gerado pelo content manager</returns> public string UploadFile(Stream binaryData, string originalFilename, string filename) { // Cria uma nova instancia do WebServices IR4CorrespProxy content = new IR4CorrespProxy(); content.RequireMtom = true; // Aponta a instancia atual do WebService para a URL de desenvolvimento: content.Url = _url; //"http://cmdes.itau/CMBSpecificWebService/services/CMWebService"; // Aponta a instancia atual do WebService para a URL de produção: //content.Url = http://cmcorp2.itau/CMBSpecificWebService/services/CMWebService"; // Cria uma requisição de Criação de Item "CreateItemRequest" CreateItemRequest Request = new CreateItemRequest(); // Autenticação Request.AuthenticationData = new AuthenticationData(); Request.AuthenticationData.ServerDef = new ServerDef(); //Request.AuthenticationData.ServerDef.ServerName = "NLSDB01"; // PRODUCAO Request.AuthenticationData.ServerDef.ServerName = _serverName;// "NLSDBDES"; // DESENVOLVIMENTO Request.AuthenticationData.ServerDef.ServerType = ServerType.ICM; Request.AuthenticationData.LoginData = new AuthenticationDataLoginData(); Request.AuthenticationData.LoginData.UserID = _username;// "USUARIO"; Request.AuthenticationData.LoginData.Password = _password;// "SENHA"; // Cria um novo Item de requisição // Isto é necessário pois esta propriedade não é automaticamente criada pelo //"CreateItemRequest" Request.Item = new CreateItemRequestItem(); // Cria um novo Item de XML Request.Item.ItemXML = new ItemXML(); // Associa o item ao OA0_ExemploCM Request.Item.ItemXML.IR4_CORRESP = new IR4_CORRESP(); // Atribui as propriedades do arquivo nos campos do OA0_ExemploCM. //Request.Item.ItemXML.IR4_CORRESP.IR4_COD_CORRESP = "Titulo de Teste"; Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT = new ICMBASETEXT[1]; Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0] = new ICMBASETEXT(); Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject = new LobObjectType(); Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.label = new LobObjectTypeLabel(); Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.label.name = filename; Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.originalFileName = originalFilename; Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.MIMEType = Path.GetExtension(originalFilename).GetMimeType(); // Definições do arquivo que será incluído MTOMAttachment[] attachments = new MTOMAttachment[1]; attachments[0] = new MTOMAttachment(); attachments[0].ID = originalFilename; attachments[0].MimeType = Path.GetExtension(originalFilename).GetMimeType(); attachments[0].Value = binaryData.ToByteArray(); Request.mtomRef = new MTOMAttachment[1]; Request.mtomRef[0] = attachments[0]; // Realiza a chamada da requisição de novo item, e retorna um "Reply", contendo // informações sobre a situação da requisição. CreateItemReply reply = content.CreateItem(Request); if (reply.RequestStatus.success) { //Console.WriteLine("Arquivo criado com sucesso: " + reply.Item.URI); Uri uri = new Uri(reply.Item.URI); HttpRequest req = new HttpRequest(null, uri.ToString(), uri.Query.Substring(1)); // uri.Query inclui o '?', o que o HttpRequest não espera return req.Params["pid"]; } else { //Console.WriteLine("Falha ao criar arquivo"); ErrorData[] err = reply.RequestStatus.ErrorData; string errorStack = ""; for (int i = 0; i < err.Length; i++) { errorStack += "Item: " + err[i].Item + " Code: " + err[i].returnCode + "Stack: " + err[i].stackTrace + "\n"; } throw new Exception(errorStack); } }
// See if the texture is a Pvr public override bool Check(ref Stream input, string filename) { try { return PvrTexture.IsPvrTexture(input.ToByteArray()); } catch { return false; } }
int WriteToFtp(Stream src, IActivityIOPath dst) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(dst.Path)); request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; request.KeepAlive = false; request.EnableSsl = EnableSsl(dst); if(dst.Username != string.Empty) { request.Credentials = new NetworkCredential(dst.Username, dst.Password); } if(dst.IsNotCertVerifiable) { ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications; } request.ContentLength = src.Length; using(Stream requestStream = request.GetRequestStream()) { using(src) { byte[] payload = src.ToByteArray(); int writeLen = payload.Length; requestStream.Write(payload, 0, writeLen); } } var result = (int)request.ContentLength; using(var response = (FtpWebResponse)request.GetResponse()) { if(response.StatusCode != FtpStatusCode.FileActionOK && response.StatusCode != FtpStatusCode.ClosingData) { throw new Exception("File was not created"); } } return result; }
public byte[] Decrypt(Stream stream, byte[] key = null) { return Decrypt(stream.ToByteArray(), key); }
public int Put(Stream src, IActivityIOPath dst, Dev2CRUDOperationTO args, string whereToPut, List<string> filesToCleanup) { int result = -1; using (src) { //2013.05.29: Ashley Lewis for bug 9507 - default destination to source directory when destination is left blank or if it is not a rooted path if (!Path.IsPathRooted(dst.Path)) { //get just the directory path to put into if (whereToPut != null) { //Make the destination directory equal to that directory dst = ActivityIOFactory.CreatePathFromString(whereToPut + "\\" + dst.Path, dst.Username, dst.Password,dst.PrivateKeyFile); } } if (args.Overwrite || !args.Overwrite && !FileExist(dst)) { _fileLock.EnterWriteLock(); try { if (!RequiresAuth(dst)) { using (src) { File.WriteAllBytes(dst.Path, src.ToByteArray()); result = (int)src.Length; } } else { // handle UNC path SafeTokenHandle safeTokenHandle; bool loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle); if (loginOk) { using (safeTokenHandle) { WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()); using (WindowsImpersonationContext impersonatedUser = newID.Impersonate()) { // Do the operation here using (src) { File.WriteAllBytes(dst.Path, src.ToByteArray()); result = (int)src.Length; } // remove impersonation now impersonatedUser.Undo(); } } } else { // login failed throw new Exception("Failed to authenticate with user [ " + dst.Username + " ] for resource [ " + dst.Path + " ] "); } } } finally { _fileLock.ExitWriteLock(); } } } return result; }
/// <summary> /// ストリームを元にデータをセットします。 /// </summary> /// <param name="bytes"></param> public void LoadData(Stream stream) { var position = stream.Position; var bb = stream.ToByteArray(); if (stream.CanSeek == true) { stream.Position = position; } this.LoadData(bb, "application/octet-stream"); }
/* Decompress */ public override MemoryStream Decompress(ref Stream data) { try { // Compressed & Decompressed Data Information uint CompressedSize = data.ReadUInt(0x4); uint DecompressedSize = data.ReadUInt(0x8); byte[] CompressedData = data.ToByteArray(); byte[] DecompressedData = new byte[DecompressedSize]; byte[] DestBuffer = new byte[0x1000]; uint SourcePointer = 0x10; uint DestPointer = 0x0; uint BufferPointer = 0xFEE; // Start Decompression while (SourcePointer < CompressedSize && DestPointer < DecompressedSize) { byte Flag = CompressedData[SourcePointer]; // Compression Flag SourcePointer++; for (int i = 0; i < 8; i++) { if ((Flag & (1 << i)) > 0) // Data is not compressed { DecompressedData[DestPointer] = CompressedData[SourcePointer]; DestBuffer[BufferPointer] = DecompressedData[DestPointer]; SourcePointer++; DestPointer++; BufferPointer = (BufferPointer + 1) & 0xFFF; } else // Data is compressed { int Offset = ((((CompressedData[SourcePointer + 1] >> 4) & 0xF) << 8) | CompressedData[SourcePointer]); int Amount = (CompressedData[SourcePointer + 1] & 0xF) + 3; SourcePointer += 2; for (int j = 0; j < Amount; j++) { DecompressedData[DestPointer + j] = DestBuffer[(Offset + j) & 0xFFF]; DestBuffer[BufferPointer] = DecompressedData[DestPointer + j]; BufferPointer = (BufferPointer + 1) & 0xFFF; } DestPointer += (uint)Amount; } // Check for out of range if (SourcePointer >= CompressedSize || DestPointer >= DecompressedSize) break; } } return new MemoryStream(DecompressedData); } catch { return null; // An error occured while decompressing } }
/* Decompress */ public override MemoryStream Decompress(ref Stream data) { try { // Compressed & Decompressed Data Information uint CompressedSize = (uint)data.Length; uint DecompressedSize = data.ReadUInt(0x0) >> 8; uint SourcePointer = 0x4; uint DestPointer = 0x0; if (DecompressedSize == 0) // Next 4 bytes are the decompressed size { DecompressedSize = data.ReadUInt(0x4); SourcePointer += 0x4; } byte[] CompressedData = data.ToByteArray(); byte[] DecompressedData = new byte[DecompressedSize]; // Start Decompression while (SourcePointer < CompressedSize && DestPointer < DecompressedSize) { byte Flag = CompressedData[SourcePointer]; // Compression Flag SourcePointer++; for (int i = 7; i >= 0; i--) { if ((Flag & (1 << i)) == 0) // Data is not compressed { DecompressedData[DestPointer] = CompressedData[SourcePointer]; SourcePointer++; DestPointer++; } else // Data is compressed { int Distance; int Amount; // Let's determine how many bytes the distance & length pair take up switch (CompressedData[SourcePointer] >> 4) { case 0: // 3 bytes Distance = (((CompressedData[SourcePointer + 1] & 0xF) << 8) | CompressedData[SourcePointer + 2]) + 1; Amount = (((CompressedData[SourcePointer] & 0xF) << 4) | (CompressedData[SourcePointer + 1] >> 4)) + 17; SourcePointer += 3; break; case 1: // 4 bytes Distance = (((CompressedData[SourcePointer + 2] & 0xF) << 8) | CompressedData[SourcePointer + 3]) + 1; Amount = (((CompressedData[SourcePointer] & 0xF) << 12) | (CompressedData[SourcePointer + 1] << 4) | (CompressedData[SourcePointer + 2] >> 4)) + 273; SourcePointer += 4; break; default: // 2 bytes Distance = (((CompressedData[SourcePointer] & 0xF) << 8) | CompressedData[SourcePointer + 1]) + 1; Amount = (CompressedData[SourcePointer] >> 4) + 1; SourcePointer += 2; break; } // Copy the data for (int j = 0; j < Amount; j++) DecompressedData[DestPointer + j] = DecompressedData[DestPointer - Distance + j]; DestPointer += (uint)Amount; } // Check for out of range if (SourcePointer >= CompressedSize || DestPointer >= DecompressedSize) break; } } return new MemoryStream(DecompressedData); } catch { return null; // An error occured while decompressing } }
/* Compress */ public static MemoryStream Compress(ref Stream data, string filename) { try { var decompressedSize = (uint)data.Length; var compressedData = new MemoryStream(); byte[] decompressedData = data.ToByteArray(); uint sourcePointer = 0x0; uint destPointer = 0x4; // Test if the file is too large to be compressed if (data.Length > 0xFFFFFF) throw new Exception("Input file is too large to compress."); // Set up the Lz Compression Dictionary var lzDictionary = new LzWindowDictionary(); lzDictionary.SetWindowSize(0x1000); lzDictionary.SetMaxMatchAmount(0xF + 3); // Start compression compressedData.Write('\x10' | (decompressedSize << 8)); while (sourcePointer < decompressedSize) { byte flag = 0x0; var flagPosition = destPointer; compressedData.WriteByte(flag); // It will be filled in later destPointer++; for (var i = 7; i >= 0; i--) { var lzSearchMatch = lzDictionary.Search(decompressedData, sourcePointer, decompressedSize); if (lzSearchMatch[1] > 0) // There is a compression match { flag |= (byte)(1 << i); compressedData.WriteByte((byte)((((lzSearchMatch[1] - 3) & 0xF) << 4) | (((lzSearchMatch[0] - 1) & 0xFFF) >> 8))); compressedData.WriteByte((byte)((lzSearchMatch[0] - 1) & 0xFF)); lzDictionary.AddEntryRange(decompressedData, (int)sourcePointer, lzSearchMatch[1]); lzDictionary.SlideWindow(lzSearchMatch[1]); sourcePointer += (uint)lzSearchMatch[1]; destPointer += 2; } else // There wasn't a match { flag |= (byte)(0 << i); compressedData.WriteByte(decompressedData[sourcePointer]); lzDictionary.AddEntry(decompressedData, (int)sourcePointer); lzDictionary.SlideWindow(1); sourcePointer++; destPointer++; } // Check for out of bounds if (sourcePointer >= decompressedSize) break; } // Write the flag. // The original position gets reset after writing. compressedData.Seek(flagPosition, SeekOrigin.Begin); compressedData.WriteByte(flag); compressedData.Seek(destPointer, SeekOrigin.Begin); } return compressedData; } catch { return null; // An error occured while compressing } }
public static void PatchResolution(Stream stream, Size cardres, RenderMode render, bool patchBug = false) { if (!IsCompatible(stream)) return; int choice = (int)render; if (patchBug) { stream.Position = Tools.PatternAt(stream.ToByteArray(), bug).First(); stream.Write(bugfix, 0, bugfix.Length); } switch (GetExeSignature(stream)) { case ExeSignature.v142FP: //no harm in doing this, so might as well make sure it's done //to not have to deal with it when patching resolutions stream.Position = 0x8cda; stream.Write(new byte[] { 0x90, 0x90 }, 0, 2); //patch card output resolution stream.Position = 0x00123440 + 0x841; stream.Write(BitConverter.GetBytes((uint)cardres.Height), 0, 4); stream.Position = 0x00123445 + 0x841; stream.Write(BitConverter.GetBytes((uint)cardres.Width), 0, 4); //first res stream.Position = 0x00122b6a + 0x6f0; stream.Write(res1[choice], 0, 4); stream.Position++; stream.Write(res2[choice], 0, 4); //second res stream.Position = 0x00122bb1 + 0x6f0; stream.Write(res1[choice], 0, 4); stream.Position++; stream.Write(res2[choice], 0, 4); //bg (float) stream.Position = 0x0030f044 + 0x49F0; stream.Write(bg[choice], 0, 8); //personality sticker (float) stream.Position = 0x0030f03c + 0x49F0; stream.Write(sticker[choice], 0, 8); //1st name x (float) stream.Position = 0x0030f084 + 0x49ec; stream.Write(n1x[choice], 0, 4); //1st name y (float) stream.Position = 0x0030ec70 + 0x49d0; stream.Write(n1y[choice], 0, 4); //2nd name x (float) stream.Position = 0x0030ea94 + 0x49cc; stream.Write(n2x[choice], 0, 4); //2nd name y (float) stream.Position = 0x0030f080 + 0x49ec; stream.Write(n2y[choice], 0, 4); break; default: //no harm in doing this, so might as well make sure it's done //to not have to deal with it when patching resolutions stream.Position = 0x8cda; stream.Write(new byte[] { 0x90, 0x90 }, 0, 2); //patch card output resolution stream.Position = 0x00123440; stream.Write(BitConverter.GetBytes((uint)cardres.Height), 0, 4); stream.Position = 0x00123445; stream.Write(BitConverter.GetBytes((uint)cardres.Width), 0, 4); //first res stream.Position = 0x00122b6a; stream.Write(res1[choice], 0, 4); stream.Position++; stream.Write(res2[choice], 0, 4); //second res stream.Position = 0x00122bb1; stream.Write(res1[choice], 0, 4); stream.Position++; stream.Write(res2[choice], 0, 4); //bg (float) stream.Position = 0x0030f044; stream.Write(bg[choice], 0, 8); //personality sticker (float) stream.Position = 0x0030f03c; stream.Write(sticker[choice], 0, 8); //1st name x (float) stream.Position = 0x0030f084; stream.Write(n1x[choice], 0, 4); //1st name y (float) stream.Position = 0x0030ec70; stream.Write(n1y[choice], 0, 4); //2nd name x (float) stream.Position = 0x0030ea94; stream.Write(n2x[choice], 0, 4); //2nd name y (float) stream.Position = 0x0030f080; stream.Write(n2y[choice], 0, 4); break; } }