private byte[] readRequest(Stream fileContents, int bites) { System.IO.MemoryStream memStream = new System.IO.MemoryStream(); int BUFFER_SIZE = bites; int iRead = 0; int idx = 0; Int64 iSize = 0; memStream.SetLength(BUFFER_SIZE); while (true) { byte[] reqBuffer = new byte[BUFFER_SIZE]; try { iRead = fileContents.Read(reqBuffer, 0, BUFFER_SIZE); } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } if (iRead == 0) { break; } iSize += iRead; memStream.SetLength(iSize); memStream.Write(reqBuffer, 0, iRead); idx += iRead; } byte[] content = memStream.ToArray(); memStream.Close(); return(content); }
public static byte[] ConvertDictionaryToByteArray(Dictionary <string, string> dict) { var list = dict.ToList(); m_memoryStream.SetLength(0); m_memoryStream.Position = 0; m_binaryFormatter.Serialize(m_memoryStream, list); return(m_memoryStream.ToArray()); }
public bool Delete(int Position) { try { Validate(); Buffer.SetLength((Length()) - 1); } catch (System.Exception Excpt) { Err.Add(Excpt); return(false); } return(true); }
/// <summary> /// Saves the movie to a file. /// </summary> /// <param name="filename">the file where the movie must be stored.</param> public void Save(string filename) { PrepareForWriting(); try { System.IO.File.WriteAllBytes(filename, MovieStream.ToArray()); } finally { MovieStream.SetLength(MovieStream.Length - 1); } }
public void Write(Message message, object obj) { if (mStream == null) { mStream = new System.IO.MemoryStream(4096); } mStream.Position = 0; mStream.SetLength(4095); string value = JsonConvert.SerializeObject(obj, setting); int count = Encoding.UTF8.GetBytes(value, 0, value.Length, mStream.GetBuffer(), 0); mStream.SetLength(count); message.BodyStream = mStream; }
/// <summary> /// 插入List. dictionary .dataset缓存。 /// </summary> /// <param name="key">redis保存键</param> /// <param name="dicdss">Dictionary string 键 dataset 值 </param> /// <param name="minute">缓存时间</param> public static void SetListDicDataSets(string key, List <Dictionary <string, DataSet> > Listdicdss, int minute) { using (IRedisClient redis = Prcm.GetClient()) { DateTime expiryTime = DateTime.Now.AddMinutes(minute); System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //定义BinaryFormatter以序列化DataSet对象 List <Dictionary <string, byte[]> > nlistdic = new List <Dictionary <string, byte[]> >(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); //创建内存流对象 foreach (var dicdss in Listdicdss) { //dataset转为二进制流 Dictionary <string, byte[]> ndic = new Dictionary <string, byte[]>(); foreach (var dsentry in dicdss) { formatter.Serialize(ms, dsentry.Value); //把DataSet对象序列化到内存流 byte[] buffer = ms.ToArray(); //把内存流对象写入字节数组 ndic.Add(dsentry.Key, buffer); //清空流 ms.SetLength(0); ms.Position = 0; } nlistdic.Add(ndic); } ms.Close(); //关闭内存流对象 ms.Dispose(); //释放资源 redis.Set(key, nlistdic, expiryTime); } }
public override void Update() { if (Monitor.TryEnter(mRecevieLock)) { byte[] receiveData = null; if (mReceiveStream.Length != 0) { receiveData = mReceiveStream.ToArray(); mReceiveStream.Position = 0; mReceiveStream.SetLength(0); } Monitor.Exit(mRecevieLock); if (receiveData != null) { if (EvtRecive != null) { //UnityEngine.Debug.Log("receiveData.Length = " + receiveData.Length); EvtRecive(mSession, receiveData, receiveData.Length); } } } //if (mIsAccepConnect) //{ // if (EvtSessionAccept != null) // EvtSessionAccept(mSession); // mSock.BeginReceive(mReciveBuff, 0, mReciveBuff.Length, SocketFlags.None, new AsyncCallback(Handle_Recevie_WorkThread), mRecevieLock); // mIsAccepConnect = false; //} }
public override void Fetch() { if (Data != null) { return; } try { Data = new System.IO.MemoryStream(); using (var file = System.IO.File.OpenRead(currentURL)) { const int CHUNK_SIZE = 1024;// 1kb byte[] buffer = new byte[CHUNK_SIZE]; Data.SetLength(file.Length); while (file.Position < file.Length) { file.Read(Data.GetBuffer(), 0, CHUNK_SIZE); } } State = DOM.Enums.EDataRequestState.CompletelyAvailable; } catch { State = DOM.Enums.EDataRequestState.Broken; } }
/// <summary> /// 截取字节数组 /// </summary> /// <param name="srcBytes">要截取的字节数组</param> /// <param name="startIndex">开始截取位置的索引</param> /// <param name="length">要截取的字节长度</param> /// <returns>截取后的字节数组</returns> public static byte[] SubByte(byte[] srcBytes, int startIndex, int length) { using (System.IO.MemoryStream bufferStream = new System.IO.MemoryStream()) { byte[] returnByte = new byte[] { }; if (srcBytes == null) { return(returnByte); } if (startIndex < 0) { startIndex = 0; } if (startIndex < srcBytes.Length) { if (length < 1 || length > srcBytes.Length - startIndex) { length = srcBytes.Length - startIndex; } bufferStream.Write(srcBytes, startIndex, length); returnByte = bufferStream.ToArray(); bufferStream.SetLength(0); bufferStream.Position = 0; } bufferStream.Close(); bufferStream.Dispose(); return(returnByte); } }
/// <summary> /// 解包Proto /// </summary> /// <param name="stream">流</param> /// <param name="protoBinaryReserved">是否以二进制形式解决</param> /// <param name="msg">消息包</param> /// <returns>是否根据规定方案解包</returns> private static bool UnpackProto(MMStream stream, bool protoBinaryReserved, out object msg) { var fullname = (string)stream.ReadString(); var msgBuf = stream.ReadBytes(); //var msgId = (int)stream.ReadUInt16(); //var msgInfo = MsgService.Instance.GetMsgById(msgId); //if (protoBinaryReserved) //{ // //if (msgInfo == null) // //{ // // msg = msgBuf; // // return false; // //} // msg = new RawProto { name = msgInfo.Name, rawData = msgBuf }; // return true; //} var ProtocolType = Type.GetType(fullname); var pstream = new System.IO.MemoryStream(msgBuf, 0, msgBuf.Length); pstream.SetLength(msgBuf.Length); msg = ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(pstream, null, ProtocolType); //msg = PacketPolicy.Unpacked(msgInfo, new ArraySegment<byte>(msgBuf, 0, msgBuf.Length)); return(true); }
/// <summary> /// Expands the specified info. /// </summary> /// <param name="info">optional context and application specific information (can be a zero-length string)</param> /// <param name="l">length of output keying material in octets (<= 255*HashLen)</param> /// <returns>OKM (output keying material) of L octets</returns> public byte[] Expand(byte[] info, int l) { if (info == null) info = new byte[0]; hmac.Key = this.prk; var n = (int) System.Math.Ceiling(l * 1f / hashLength); var t = new byte[n * hashLength]; using (var ms = new System.IO.MemoryStream()) { var prev = new byte[0]; for (var i = 1; i <= n; i++) { ms.Write(prev, 0, prev.Length); if (info.Length > 0) ms.Write(info, 0, info.Length); ms.WriteByte((byte)(0x01 * i)); prev = hmac.ComputeHash(ms.ToArray()); Array.Copy(prev, 0, t, (i - 1) * hashLength, hashLength); ms.SetLength(0); //reset } } var okm = new byte[l]; Array.Copy(t, okm, okm.Length); return okm; }
public void SaveSettings() { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { if (ms.Length != 0) { ms.SetLength(0); ms.Seek(0, System.IO.SeekOrigin.Begin); } XmlDocument doc = new System.Xml.XmlDocument(); XmlElement root_elem = doc.CreateElement("root"); foreach (IModbusStation stat in stations) { XmlElement elem = doc.CreateElement("station"); StationFactory.SaveStation(elem, stat); root_elem.AppendChild(elem); } foreach (IChannel ch in channels) { XmlElement elem = doc.CreateElement("channel"); ChannelFactory.SaveChannel(elem, ch); root_elem.AppendChild(elem); } doc.AppendChild(root_elem); doc.Save(ms); environment.Project.SetData("settings/" + StringConstants.PluginId + "_channels", ms); } }
public override void Serialize(Archive archive) { archive.Serialize(ref _netID); archive.Serialize(ref _rpcID); _archive.Flush(); int len = (int)stream.Position; archive.Serialize(ref len); if (archive.isLoading) { stream.SetLength(len); if (archive.Read(stream.GetBuffer(), 0, len) != len) { throw new System.IO.IOException("Premature end of archive stream!"); } stream.Position = 0; _archive.OpenRead(); } else if (len > 0) { archive.Write(stream.GetBuffer(), 0, len); } }
public ByteBuffer flip() { mode = Mode.Read; stream.SetLength(stream.Position); stream.Position = 0; return(this); }
public void SendMsg(ProtoBuf.IExtensible pMsg, Int32 n32MsgID) { if (m_Client != null) { //清除stream mSendStream.SetLength(0); mSendStream.Position = 0; //序列到stream ProtoBuf.Serializer.Serialize(mSendStream, pMsg); CMsg pcMsg = new CMsg((int)mSendStream.Length); pcMsg.SetProtocalID(n32MsgID); pcMsg.Add(mSendStream.ToArray(), 0, (int)mSendStream.Length); //ms.Close(); #if UNITY_EDITOR #else try { #endif #if LOG_FILE && UNITY_EDITOR if (n32MsgID != 8192 && n32MsgID != 16385) { string msgName = ""; if (Enum.IsDefined(typeof(GCToBS.MsgNum), n32MsgID)) { msgName = ((GCToBS.MsgNum)n32MsgID).ToString(); } else if (Enum.IsDefined(typeof(GCToCS.MsgNum), n32MsgID)) { msgName = ((GCToCS.MsgNum)n32MsgID).ToString(); } else if (Enum.IsDefined(typeof(GCToLS.MsgID), n32MsgID)) { msgName = ((GCToLS.MsgID)n32MsgID).ToString(); } else if (Enum.IsDefined(typeof(GCToSS.MsgNum), n32MsgID)) { msgName = ((GCToSS.MsgNum)n32MsgID).ToString(); } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"E:\Log.txt", true)) { sw.WriteLine(Time.time + " 发送消息:\t" + n32MsgID + "\t" + msgName); } } #endif m_Client.GetStream().Write(pcMsg.GetMsgBuffer(), 0, (int)pcMsg.GetMsgSize()); #if UNITY_EDITOR #else } catch (Exception exc) { Debugger.LogError(exc.ToString()); Close(); } #endif } }
public override byte[] GetMessageBody() { using (System.IO.MemoryStream MS = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter(MS)) { BW.Write(requestID.ToByteArray()); BW.Write(tables.Length); for (int n = 0; n != tables.Length; n++) { byte[] bytes = tables [n].Serialize(); BW.Write(bytes.Length); BW.Write(bytes); } if (exception == null) { MS.WriteByte(0); } else { MS.WriteByte(1); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); long p = MS.Position; try { BF.Serialize(MS, exception); } catch { MS.Position = p; BF.Serialize(MS, exception.ToString()); MS.SetLength(MS.Position); } } return(MS.ToArray()); } } }
internal void reset() { blockNum = 0; blocks = new byte[0]; blockSize = 0; nextBlockNum = 1; data.SetLength(0); }
public override Buffer Flip() { base.Flip(); mode = Mode.Read; stream.SetLength(stream.Position); stream.Position = 0; return(this); }
public void OnDataReceived(object sender, DataEventArgs e) { int m_CurPos = 0; while (m_RecvPos - m_CurPos >= 16) { int cmdId = BitConverter.ToInt32(m_RecvBuffer, m_CurPos); cmdId = IPAddress.NetworkToHostOrder(cmdId); int len = BitConverter.ToInt32(m_RecvBuffer, m_CurPos + 4); len = IPAddress.NetworkToHostOrder(len); UInt64 reserve = BitConverter.ToUInt64(m_RecvBuffer, m_CurPos + 8); Int64 error_code = IPAddress.NetworkToHostOrder(Convert.ToInt64(reserve)); Debug.Log("Recv Message:" + "cmd=" + cmdId + ",len=" + len + ",error_code=" + error_code); if (len > m_RecvBuffer.Length) { Debug.LogError("can't pause message"); break; } if (len > m_RecvPos - m_CurPos) { break;//wait net recv more buffer to parse. } //获取stream System.IO.MemoryStream tempStream = null; if (mReceiveStreamsPool.Count > 0) { tempStream = mReceiveStreamsPool[0]; tempStream.SetLength(0); tempStream.Position = 0; mReceiveStreamsPool.RemoveAt(0); } else { tempStream = new System.IO.MemoryStream(); } //往stream填充网络数据 tempStream.Write(m_RecvBuffer, m_CurPos + 16, len - 16); tempStream.Position = 0; m_CurPos += len; mReceiveMsgIDs.Add(cmdId); mReceiveStreams.Add(tempStream); mReceiveMsgErrs.Add(error_code); } if (m_CurPos > 0) { m_RecvPos = m_RecvPos - m_CurPos; if (m_RecvPos < 0) { Debug.LogError("m_RecvPos < 0"); } if (m_RecvPos > 0) { Buffer.BlockCopy(m_RecvBuffer, m_CurPos, m_RecvBuffer, 0, m_RecvPos); } } }
public void Discard() { if (Buffer != null) { Commit(); DiscardPosition = CommitPosition; Buffer.SetLength(0); } }
public void Dispose() { if (Result != null) { Result.Position = 0; Result.SetLength(0); _owner._memoryStream = Result; } }
/// <summary> /// Executa o parser dos cabeçalhos. /// </summary> private void ParseHeaders() { string line; while ((line = Client.ReadBuffer.ReadLine()) != null) { string[] parts; if (line.Length == 0) { string contentDispositionHeader; if (!_headers.TryGetValue("Content-Disposition", out contentDispositionHeader)) { throw new System.ServiceModel.ProtocolException("Expected Content-Disposition header with multipart"); } parts = contentDispositionHeader.Split(';'); _readingFile = false; for (int i = 0; i < parts.Length; i++) { string part = parts[i].Trim(); if (part.StartsWith("filename=", StringComparison.OrdinalIgnoreCase)) { _readingFile = true; break; } } if (_readingFile) { _fileName = System.IO.Path.GetTempFileName(); _fileStream = System.IO.File.Create(_fileName, 4096, System.IO.FileOptions.DeleteOnClose); } else { if (_fieldStream == null) { _fieldStream = new System.IO.MemoryStream(); } else { _fieldStream.Position = 0; _fieldStream.SetLength(0); } } _state = ParserState.ReadingContent; ParseContent(); return; } parts = line.Split(new[] { ':' }, 2); if (parts.Length != 2) { throw new System.ServiceModel.ProtocolException("Received header without colon"); } _headers[parts[0].Trim()] = parts[1].Trim(); } }
//接收数据处理 public void OnDataReceived(object sender, DataEventArgs e) { int m_CurPos = 0; while (m_RecvPos - m_CurPos >= 8) { int len = BitConverter.ToInt32(m_RecvBuffer, m_CurPos); int type = BitConverter.ToInt32(m_RecvBuffer, m_CurPos + 4); if (len > m_RecvBuffer.Length) { Debugger.LogError("can't pause message" + "type=" + type + "len=" + len); break; } if (len > m_RecvPos - m_CurPos) { break;//wait net recv more buffer to parse. } //获取stream System.IO.MemoryStream tempStream = null; if (mReceiveStreamsPool.Count > 0) { tempStream = mReceiveStreamsPool[0]; tempStream.SetLength(0); tempStream.Position = 0; mReceiveStreamsPool.RemoveAt(0); } else { tempStream = new System.IO.MemoryStream(); } //往stream填充网络数据 tempStream.Write(m_RecvBuffer, m_CurPos + 8, len - 8); tempStream.Position = 0; m_CurPos += len; mReceiveMsgIDs.Add(type); mReceiveStreams.Add(tempStream); } if (m_CurPos > 0) { m_RecvPos = m_RecvPos - m_CurPos; if (m_RecvPos < 0) { Debug.LogError("m_RecvPos < 0"); } if (m_RecvPos > 0) { Buffer.BlockCopy(m_RecvBuffer, m_CurPos, m_RecvBuffer, 0, m_RecvPos); } } }
public T unpack <T>() { // todo: 这里需要接入统一的打包策略 if (unpackedData != null) { return((T)unpackedData); } var stream = new System.IO.MemoryStream(rawData); stream.SetLength(rawData.Length); unpackedData = (T)ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, typeof(T)); return((T)unpackedData); }
public void SendPacket(PacketData.Packet packet, Client client) { System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); memoryStream.SetLength(0); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); memoryStream.Position = 0; binaryFormatter.Serialize(memoryStream, packet); byte[] buffer = memoryStream.GetBuffer(); client._binaryWriter.Write(buffer.Length); client._binaryWriter.Write(buffer); }
readonly private HashAlgorithm ha = HashAlgorithm.Create("SHA1"); // 160bit of entropy public NamesGenerator(Guid itemid, int dataversion, byte[] salt) { ms = new System.IO.MemoryStream(); bw = new System.IO.BinaryWriter(ms); bw.Write(itemid.ToByteArray()); bw.Write(dataversion); bw.Write(salt); bw.Flush(); seedpos = ms.Position; bw.Write(seed); bw.Flush(); ms.SetLength(ms.Position); }
/// <summary> /// A function to comress and return the data parameter with possible context takeover support (reusing the DeflateStream). /// </summary> private byte[] Compress(byte[] data) { if (compressorOutputStream == null) { compressorOutputStream = new System.IO.MemoryStream(); } compressorOutputStream.SetLength(0); if (compressorDeflateStream == null) { compressorDeflateStream = new DeflateStream(compressorOutputStream, CompressionMode.Compress, this.Level, true, this.ClientMaxWindowBits); compressorDeflateStream.FlushMode = FlushType.Sync; } byte[] result = null; try { compressorDeflateStream.Write(data, 0, data.Length); compressorDeflateStream.Flush(); compressorOutputStream.Position = 0; // http://tools.ietf.org/html/rfc7692#section-7.2.1 // Remove 4 octets (that are 0x00 0x00 0xff 0xff) from the tail end. After this step, the last octet of the compressed data contains (possibly part of) the DEFLATE header bits with the "BTYPE" bits set to 00. compressorOutputStream.SetLength(compressorOutputStream.Length - 4); result = compressorOutputStream.ToArray(); } finally { if (this.ClientNoContextTakeover) { compressorDeflateStream.Dispose(); compressorDeflateStream = null; } } return(result); }
/// <summary> /// 从DataTable和对应的GroupBox中的内容得到XML串 /// </summary> /// <param name="p_objclsElementAttributeArr">p_dtbTable列数 ==p_objclsElementAttributeArr的长度(GroupBox中各项+签名+时间,每项对应一个clsElementAttribute对象)</param> /// <param name="p_dtbTable">记录对应的DataTable</param> /// <param name="p_objXmlMemStream"></param> /// <param name="p_xmlWriter"></param> /// <returns>若参数错误返回null</returns> public string m_strGetXMLFromDataTable(clsElementAttribute[] p_objclsElementAttributeArr, System.Data.DataTable p_dtbTable, ref System.IO.MemoryStream p_objXmlMemStream, ref System.Xml.XmlTextWriter p_xmlWriter) { if (p_objclsElementAttributeArr == null || p_dtbTable.Columns.Count != p_objclsElementAttributeArr.Length) { return(null); } p_objXmlMemStream.SetLength(0); p_xmlWriter.WriteStartDocument(); p_xmlWriter.WriteStartElement("Main"); clsElementAttribute objclsElementAttribute = new clsElementAttribute(); bool blnIsModified = m_blnIsModified(p_objclsElementAttributeArr, p_dtbTable); if (blnIsModified == true) //如果被修改,添加当前值 { p_xmlWriter.WriteStartElement("Sub"); for (int j0 = 0; j0 < p_objclsElementAttributeArr.Length; j0++) { m_mthAddElementAttibute(p_objclsElementAttributeArr[j0], ref p_xmlWriter); } p_xmlWriter.WriteEndElement(); } for (int i1 = 0; i1 < p_dtbTable.Rows.Count; i1++) //重写原来的痕迹 { p_xmlWriter.WriteStartElement("Sub"); for (int j2 = 0; j2 < p_objclsElementAttributeArr.Length; j2++) { objclsElementAttribute.m_blnIsDST = p_objclsElementAttributeArr[j2].m_blnIsDST; //默认为非DST格式,即为bool类型 objclsElementAttribute.m_strElementName = p_objclsElementAttributeArr[j2].m_strElementName; if (objclsElementAttribute.m_blnIsDST == false) { objclsElementAttribute.m_strValue = p_dtbTable.Rows[i1][j2].ToString(); } else { objclsElementAttribute.m_strValue = ((clsDSTRichTextBoxValue)(p_dtbTable.Rows[i1][j2])).m_strText; objclsElementAttribute.m_strValueXML = ((clsDSTRichTextBoxValue)(p_dtbTable.Rows[i1][j2])).m_strDSTXml; } m_mthAddElementAttibute(objclsElementAttribute, ref p_xmlWriter); } p_xmlWriter.WriteEndElement(); } p_xmlWriter.WriteEndElement(); p_xmlWriter.WriteEndDocument(); p_xmlWriter.Flush(); return(System.Text.Encoding.Unicode.GetString(p_objXmlMemStream.ToArray(), 39 * 2, (int)p_objXmlMemStream.Length - 39 * 2)); }
/// <summary> /// 解包 /// </summary> /// <param name="packet">接受数据包</param> /// <param name="next">投递到下一个处理器</param> /// <returns>解包的对象</returns> public static object Unpacked(ReceivePackage packet, Func <ReceivePackage, object> next) { if (packet.MsgInfo == null || packet.MsgInfo.MsgType != MsgTypes.Protobuf) { return(next(packet)); } // 如果这里引发了异常,那么这个协议会被抛弃 // 所以我们不捕获这里的异常 var stream = new System.IO.MemoryStream(packet.Body.Array, packet.Body.Offset, packet.Body.Count); stream.SetLength(packet.Body.Count); return(ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, packet.MsgInfo.ProtocolType)); }
/// <summary> /// Executes a python command like in console /// </summary> /// <param name="expression">command to execute</param> /// <returns>returns standard out of executed command</returns> public static string execute(string expression) { if (!(expression == null)) { string ret; ms.SetLength(0); ms.Flush(); try { Engine.Execute(expression); ms.Position = 0; ret = sr.ReadToEnd(); } catch (Exception ex) { ret = ex.Message; } return(ret); } else { return(string.Empty); } }
internal static System.Collections.Generic.IEnumerable <System.IO.MemoryStream> Streams(this System.Collections.Generic.IEnumerable <System.Drawing.Image> source) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); foreach (System.Drawing.Image img in source) { ms.SetLength(0); img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); yield return(ms); } // Next img ms.Close(); ms = null; yield break; } // End Function Streams
public override byte[] GetBytes(int countBytes) { using (var okm = new System.IO.MemoryStream()) { do { if (k_unused > 0) { var min = Math.Min(k_unused, countBytes); okm.Write(k, hashLength - k_unused, min); countBytes -= min; k_unused -= min; } if (countBytes == 0) break; var n = countBytes / hashLength; if (countBytes % hashLength > 0) ++n; using (var hmac_msg = new System.IO.MemoryStream()) { for (var i = 1; i <= n; ++i) { hmac_msg.Write(k, 0, k.Length); if (context != null) hmac_msg.Write(context, 0, context.Length); hmac_msg.WriteByte(counter); checked { ++counter; }; k = hmac.ComputeHash(hmac_msg.GetBuffer(), 0, (int)hmac_msg.Length); okm.Write(k, 0, i < n ? hashLength : countBytes); countBytes -= hashLength; hmac_msg.SetLength(0); } k_unused = -countBytes; }// using hmac_msg } while (false); return okm.ToArray(); }// using okm }
public override byte[] GetMessageBody() { using (System.IO.MemoryStream MS = new System.IO.MemoryStream ()) { using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter (MS)) { BW.Write (requestID.ToByteArray ()); BW.Write (tables.Length); for (int n = 0; n != tables.Length; n++) { byte[] bytes = tables [n].Serialize (); BW.Write (bytes.Length); BW.Write (bytes); } if (exception == null) { MS.WriteByte (0); } else { MS.WriteByte (1); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter (); long p = MS.Position; try { BF.Serialize (MS, exception); } catch { MS.Position = p; BF.Serialize (MS, exception.ToString ()); MS.SetLength (MS.Position); } } return MS.ToArray (); } } }
public static System.Windows.Media.Imaging.BitmapImage GetImage(string fileId) { if (string.IsNullOrWhiteSpace(fileId)) { if (_olaf == null) { _olaf = GetImage(Olaf); } return _olaf; } using (var db = new PetoeterDb(PetoeterDb.FileName)) { var file = db.FileStorage.FindById(fileId); if (file == null) { if (fileId == Olaf) { SaveFile(Olaf, @"olaf.png"); } return null; } using(var reader = file.OpenRead()) { System.IO.MemoryStream mem = new System.IO.MemoryStream(); mem.SetLength(file.Length); reader.Read(mem.GetBuffer(), 0, (int)file.Length); mem.Flush(); System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage(); image.BeginInit(); image.StreamSource = mem; image.EndInit(); image.Freeze(); return image; } } }
private ArrayList SplitSql(string sql) { ArrayList commands = new ArrayList(); System.IO.MemoryStream ms = new System.IO.MemoryStream(sql.Length); // first we tack on a semi-colon, if not already there, to make our // sql processing code easier. Then we ask our encoder to give us // the bytes for this sql string byte[] bytes = connection.Encoding.GetBytes(sql + ";"); byte left_byte = 0; bool escaped = false; int parm_start=-1; for (int x=0; x < bytes.Length; x++) { byte b = bytes[x]; // if we see a quote marker, then check to see if we are opening // or closing a quote if ((b == '\'' || b == '\"') && ! escaped ) { if (b == left_byte) left_byte = 0; else if (left_byte == 0) left_byte = b; } else if (b == '\\') { escaped = !escaped; } // if we see the marker for a parameter, then save its position and // look for the end else if (b == '@' && left_byte == 0 && ! escaped && parm_start==-1) parm_start = x; // if we see a space and we are tracking a parameter, then end the parameter and have // that parameter serialize itself to the memory stream else if (parm_start > -1 && (b != '@') && (b != '$') && (b != '_') && (b != '.') && ! Char.IsLetterOrDigit((char)b)) { string parm_name = sql.Substring(parm_start, x-parm_start); if (parameters.Contains( parm_name )) { MySqlParameter p = (parameters[parm_name] as MySqlParameter); p.SerializeToBytes(ms, connection ); } else { // otherwise assume system param. just write it out byte[] buf = connection.Encoding.GetBytes(parm_name); ms.Write(buf, 0, buf.Length); } parm_start=-1; } // if we are not in a string and we are not escaped and we are on a semi-colon, // then write out what we have as a command if (left_byte == 0 && ! escaped && b == ';' && ms.Length > 0) { bool goodcmd = false; byte[] byteArray = ms.ToArray(); foreach (byte cmdByte in byteArray) if (cmdByte != ' ') { goodcmd = true; break; } if (goodcmd) commands.Add( byteArray ); ms.SetLength(0); } else if (parm_start == -1) ms.WriteByte(b); // we want to write out the bytes in all cases except when we are parsing out a parameter if (escaped && b != '\\') escaped = false; } return commands; }
// GET /api/music/5 public HttpResponseMessage Get(Guid id, string play) { string musicPath = HttpContext.Current.Server.MapPath("~/Content/Music") + "\\" + id.ToString() + ".mp3"; if (System.IO.File.Exists(musicPath)) { HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK); System.IO.FileStream stream = new System.IO.FileStream(musicPath, System.IO.FileMode.Open); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ms.SetLength(stream.Length); stream.Read(ms.GetBuffer(), 0, (int)stream.Length); ms.Flush(); stream.Close(); stream.Dispose(); result.Content = new StreamContent(ms); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("audio/mpeg"); return result; } else { return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound); } }
/// <summary> This method creates the tileparts from the buffered tile headers, /// packet headers and packet data /// /// </summary> /// <exception cref="java.io.IOException">If an I/O error ocurred. /// /// </exception> private void createTileParts() { int i, prem, t, length; int pIndex; // phIndex removed int tppStart; int tilePart; int p, np, nomnp; int numTileParts; int numPackets; System.IO.MemoryStream temp = new System.IO.MemoryStream(); byte[] tempByteArr; // Create tile parts tileParts = new byte[nt][][]; maxtp = 0; for (t = 0; t < nt; t++) { // Calculate number of tile parts. If tileparts are not used, // put all packets in the first tilepart if (pptp == 0) pptp = ppt[t]; prem = ppt[t]; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" numTileParts = (int) System.Math.Ceiling(((double) prem) / pptp); numPackets = packetHeaders[t].Length; maxtp = (numTileParts > maxtp)?numTileParts:maxtp; tileParts[t] = new byte[numTileParts][]; // Create all the tile parts for tile t tppStart = 0; pIndex = 0; p = 0; //phIndex = 0; for (tilePart = 0; tilePart < numTileParts; tilePart++) { // Calculate number of packets in this tilepart nomnp = (pptp > prem)?prem:pptp; np = nomnp; // Write tile part header if (tilePart == 0) { // Write original tile part header up to SOD marker temp.Write(tileHeaders[t], 0, tileHeaders[t].Length - 2); } else { // Write empty header of length TP_HEAD_LEN-2 temp.Write(new byte[TP_HEAD_LEN - 2], 0, TP_HEAD_LEN - 2); } // Write PPT marker segments if PPT used if (pptUsed) { int pptLength = 3; // Zppt and Lppt int pptIndex = 0; int phLength; p = pIndex; while (np > 0) { phLength = packetHeaders[t][p].Length; // If the total legth of the packet headers is greater // than MAX_LPPT, several PPT markers are needed if (pptLength + phLength > CSJ2K.j2k.codestream.Markers.MAX_LPPT) { temp.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8)); temp.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPT & 0x00FF)); temp.WriteByte((System.Byte) SupportClass.URShift(pptLength, 8)); temp.WriteByte((System.Byte) pptLength); temp.WriteByte((System.Byte) pptIndex++); for (i = pIndex; i < p; i++) { temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length); } pptLength = 3; // Zppt and Lppt pIndex = p; } pptLength += phLength; p++; np--; } // Write last PPT marker temp.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8)); temp.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPT & 0x00FF)); temp.WriteByte((System.Byte) SupportClass.URShift(pptLength, 8)); temp.WriteByte((System.Byte) pptLength); temp.WriteByte((System.Byte) pptIndex); for (i = pIndex; i < p; i++) { temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length); } } pIndex = p; np = nomnp; // Write SOD marker temp.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOD, 8)); temp.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.SOD & 0x00FF)); // Write packet data and packet headers if PPT and PPM not used for (p = tppStart; p < tppStart + np; p++) { if (!tempSop) { temp.Write(sopMarkSeg[t][p], 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH); } if (!(ppmUsed || pptUsed)) { temp.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length); } temp.Write(packetData[t][p], 0, packetData[t][p].Length); } tppStart += np; // Edit tile part header tempByteArr = temp.ToArray(); tileParts[t][tilePart] = tempByteArr; length = (int)temp.Length; if (tilePart == 0) { // Edit first tile part header tempByteArr[6] = (byte) (SupportClass.URShift(length, 24)); // Psot tempByteArr[7] = (byte) (SupportClass.URShift(length, 16)); tempByteArr[8] = (byte) (SupportClass.URShift(length, 8)); tempByteArr[9] = (byte) (length); tempByteArr[10] = (byte) SupportClass.Identity((0)); // TPsot tempByteArr[11] = (byte) (numTileParts); // TNsot } else { // Edit tile part header tempByteArr[0] = (byte) (SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOT, 8)); // SOT tempByteArr[1] = (byte) (CSJ2K.j2k.codestream.Markers.SOT & 0x00FF); tempByteArr[2] = (byte) SupportClass.Identity((0)); // Lsot tempByteArr[3] = (byte) SupportClass.Identity((10)); tempByteArr[4] = (byte) (SupportClass.URShift(t, 8)); // Isot tempByteArr[5] = (byte) (t); // tempByteArr[6] = (byte) (SupportClass.URShift(length, 24)); // Psot tempByteArr[7] = (byte) (SupportClass.URShift(length, 16)); tempByteArr[8] = (byte) (SupportClass.URShift(length, 8)); tempByteArr[9] = (byte) (length); tempByteArr[10] = (byte) (tilePart); //TPsot tempByteArr[11] = (byte) (numTileParts); // TNsot } //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" //temp.reset(); temp.SetLength(0); prem -= np; } } temp.Close(); }
/// <summary> This method writes the new codestream to the file. /// /// </summary> /// <param name="fi">The file to write the new codestream to /// /// </param> /// <exception cref="java.io.IOException">If an I/O error ocurred. /// /// </exception> private void writeNewCodestream(BufferedRandomAccessFile fi) { int t, p, tp; // i removed int numTiles = tileParts.Length; int[][] packetHeaderLengths = new int[numTiles][]; for (int i2 = 0; i2 < numTiles; i2++) { packetHeaderLengths[i2] = new int[maxtp]; } byte[] temp; int length; // Write main header up to SOT marker fi.write(mainHeader, 0, mainHeader.Length); // If PPM used write all packet headers in PPM markers if (ppmUsed) { System.IO.MemoryStream ppmMarkerSegment = new System.IO.MemoryStream(); int numPackets; int totNumPackets; int ppmIndex = 0; int ppmLength; int pStart, pStop; int[] prem = new int[numTiles]; // Set number of remaining packets for (t = 0; t < numTiles; t++) { prem[t] = packetHeaders[t].Length; } // Calculate Nppm values for (tp = 0; tp < maxtp; tp++) { for (t = 0; t < numTiles; t++) { if (tileParts[t].Length > tp) { totNumPackets = packetHeaders[t].Length; // Calculate number of packets in this tilepart numPackets = (tp == tileParts[t].Length - 1)?prem[t]:pptp; pStart = totNumPackets - prem[t]; pStop = pStart + numPackets; // Calculate number of packet header bytes for this // tile part for (p = pStart; p < pStop; p++) packetHeaderLengths[t][tp] += packetHeaders[t][p].Length; prem[t] -= numPackets; } } } // Write first PPM marker ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8)); ppmMarkerSegment.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPM & 0x00FF)); ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value ppmMarkerSegment.WriteByte((System.Byte) 0); // zppm ppmLength = 3; ppmIndex++; // Set number of remaining packets for (t = 0; t < numTiles; t++) prem[t] = packetHeaders[t].Length; // Write all PPM markers and information for (tp = 0; tp < maxtp; tp++) { for (t = 0; t < numTiles; t++) { if (tileParts[t].Length > tp) { totNumPackets = packetHeaders[t].Length; // Calculate number of packets in this tilepart numPackets = (tp == tileParts[t].Length - 1)?prem[t]:pptp; pStart = totNumPackets - prem[t]; pStop = pStart + numPackets; // If Nppm value wont fit in current PPM marker segment // write current PPM marker segment and start new if (ppmLength + 4 > CSJ2K.j2k.codestream.Markers.MAX_LPPM) { // Write current PPM marker temp = ppmMarkerSegment.ToArray(); length = temp.Length - 2; temp[2] = (byte) (SupportClass.URShift(length, 8)); temp[3] = (byte) length; fi.write(temp, 0, length + 2); // Start new PPM marker segment //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" //ppmMarkerSegment.reset(); ppmMarkerSegment.SetLength(0); ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8)); ppmMarkerSegment.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPM & 0x00FF)); ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value ppmMarkerSegment.WriteByte((System.Byte) ppmIndex++); // zppm ppmLength = 3; } // Write Nppm value length = packetHeaderLengths[t][tp]; ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(length, 24)); ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(length, 16)); ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(length, 8)); ppmMarkerSegment.WriteByte((System.Byte) length); ppmLength += 4; // Write packet headers for (p = pStart; p < pStop; p++) { length = packetHeaders[t][p].Length; // If next packet header value wont fit in // current PPM marker segment write current PPM // marker segment and start new if (ppmLength + length > CSJ2K.j2k.codestream.Markers.MAX_LPPM) { // Write current PPM marker temp = ppmMarkerSegment.ToArray(); length = temp.Length - 2; temp[2] = (byte) (SupportClass.URShift(length, 8)); temp[3] = (byte) length; fi.write(temp, 0, length + 2); // Start new PPM marker segment //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'" //ppmMarkerSegment.reset(); ppmMarkerSegment.SetLength(0); ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8)); ppmMarkerSegment.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPM & 0x00FF)); ppmMarkerSegment.WriteByte((System.Byte) 0); // Temp Lppm value ppmMarkerSegment.WriteByte((System.Byte) 0); // Temp Lppm value ppmMarkerSegment.WriteByte((System.Byte) ppmIndex++); // zppm ppmLength = 3; } // write packet header ppmMarkerSegment.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length); ppmLength += packetHeaders[t][p].Length; } prem[t] -= numPackets; } } } // Write last PPM marker segment temp = ppmMarkerSegment.ToArray(); length = temp.Length - 2; temp[2] = (byte) (SupportClass.URShift(length, 8)); temp[3] = (byte) length; fi.write(temp, 0, length + 2); } // Write tile parts interleaved for (tp = 0; tp < maxtp; tp++) { for (t = 0; t < nt; t++) { if (tileParts[t].Length > tp) { temp = tileParts[t][tp]; length = temp.Length; fi.write(temp, 0, length); } } } fi.writeShort(CSJ2K.j2k.codestream.Markers.EOC); }