// DSFチャンクの数字はリトルエンディアンバイトオーダー private void BwWriteLE4(BinaryWriter bw, uint v) { bw.Write((byte)(v & 0xff)); bw.Write((byte)((v >> 8) & 0xff)); bw.Write((byte)((v >> 16) & 0xff)); bw.Write((byte)((v >> 24) & 0xff)); }
public DiscordAudioPacket(char seq, int timestamp, int ssrc, byte[] encodedaudio) { this.seq = seq; this.timestamp = timestamp; this.ssrc = ssrc; this.encodedAudio = encodedaudio; byte[] fullPacket = new byte[RTP_HEADER_BYTE_LENGTH + encodedAudio.Length]; using (MemoryStream ms = new MemoryStream(fullPacket)) { using (BinaryWriter writer = new BinaryWriter(ms)) { writer.BaseStream.Position = RTP_VERSION_PAD_EXTEND_INDEX; writer.Write(RTP_VERSION_PAD_EXTEND); writer.BaseStream.Position = RTP_PAYLOAD_INDEX; writer.Write(RTP_PAYLOAD_TYPE); writer.BaseStream.Position = SEQ_INDEX; writer.Write(seq); writer.BaseStream.Position = TIMESTAMP_INDEX; writer.Write(timestamp); writer.BaseStream.Position = SSRC_INDEX; writer.Write(ssrc); writer.BaseStream.Position = RTP_HEADER_BYTE_LENGTH; writer.Write(fullPacket); } } }
static void Main(string[] args) { FileStream filStream; BinaryWriter binWriter; Console.Write("Enter name of the file: "); string fileName = Console.ReadLine(); if (File.Exists(fileName)) { Console.WriteLine("File - {0} already exists!", fileName); } else { filStream = new FileStream(fileName, FileMode.CreateNew); binWriter = new BinaryWriter(filStream); decimal aValue = 2.16M; binWriter.Write("Sample Run"); for (int i = 0; i < 11; i++) { binWriter.Write(i); } binWriter.Write(aValue); binWriter.Close(); filStream.Close(); Console.WriteLine("File Created successfully"); } Console.ReadKey(); }
/// <summary> /// Write the data of each frame in the file. /// </summary> /// <param name="controller">Controller that represent the device.</param> /// <param name="path">Path of the file where the data will be write.<br/> /// If one already exist it will be deleted and a new empty on is created.</param> public void RecordData(Controller controller, String path) { if (Directory.Exists(path) == true) { String destination = path + "leapMotion.data"; try { if (File.Exists(destination) == true) File.Delete(destination); file = File.Create(destination); } catch (ArgumentException e) { throw e; } } else throw new System.ArgumentException("Destination path doesn't exist", "path"); BinaryWriter writer = new BinaryWriter(file); for (int f = 9; f >= 0; f--) { Frame frameToSerialize = controller.Frame(f); byte[] serialized = frameToSerialize.Serialize; Int32 length = serialized.Length; writer.Write(length); writer.Write(serialized); } }
public void writeBinary() { string nom = tbName.Text + ".bytes"; byte i; BinaryReader br = null; BinaryWriter bw = null; FileStream fs = null; //Ecriture d'octets dans le fichier bw = new BinaryWriter(File.Create(nom)); i = Convert.ToByte(width.Text); bw.Write(i); i = Convert.ToByte(height.Text); bw.Write(i); i = Convert.ToByte(random.Checked); bw.Write(i); for (int j = 3; j < Convert.ToInt32(width.Text); j++) { bw.Write(Convert.ToSByte(0)); } foreach (DataGridViewRow data in dataGridView1.Rows) { for(int j = 0; j < dataGridView1.Columns.Count;j++) { i = Convert.ToByte(data.Cells[j].Value); bw.Write(i); } } bw.Close(); }
internal void Write(BinaryWriter writer, float CoordZ, float scale) { SkinVertPos[2] *= CoordZ; writer.Write(SkinVertIndex); for (int i = 0; i < SkinVertPos.Length; i++) writer.Write(SkinVertPos[i] * scale); }
public override byte[] WritedData() { using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { var inventory = _player.Inventory; writer.WriteC(1); writer.WriteC(1); writer.WriteD(_player.GameSessionId); writer.Skip(12); writer.WriteH(inventory.Items.Count); writer.WriteC(0); for (short i = 0; i < inventory.Items.Count; i++) { var item = inventory.Items[(short) (i + 1)]; writer.WriteC(i); writer.WriteD(item.ItemId); writer.WriteQ(item.Count); writer.Write("FFFFFFFFFFFFFFFF".ToBytes()); writer.WriteD(i == 0 ? 0 : 1); writer.WriteD(0); writer.WriteC(0); writer.Write("0100FF7FFF7F3A38E56FF2862300FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000".ToBytes()); } return stream.ToArray(); } }
public static bool RequestImageComparisonStatus(string testName = null) { if (!Connect()) throw new InvalidOperationException("Could not connect to image comparer server"); try { if (testName == null && NUnit.Framework.TestContext.CurrentContext == null) { testName = NUnit.Framework.TestContext.CurrentContext.Test.FullName; } var networkStream = ImageComparisonServer.GetStream(); var binaryWriter = new BinaryWriter(networkStream); var binaryReader = new BinaryReader(networkStream); // Header binaryWriter.Write((int)ImageServerMessageType.RequestImageComparisonStatus); binaryWriter.Write(testName); return binaryReader.ReadBoolean(); } catch (Exception) { throw; } }
public static void WriteVec3(Vector3 v, BinaryWriter bw) { bw.Write(v.X); bw.Write(v.Y); bw.Write(v.Z); bw.Flush(); }
public void save(Stream file) { if (!file.CanWrite) { throw new NotSupportedException("Cannot write to stream"); } using (var bw = new BinaryWriter(file)) { long basePos = file.Position; bw.Write(0x01524142u); int fileC = fileList.Count; bw.Write(fileC); bw.Write(0u); bw.Write(0u); uint offset = 16*((uint) fileC + 1); for (int i = 0; i < fileC; i++) { file.Position = basePos + 16*(i + 1); BARFile bf = fileList[i]; bw.Write(bf.type); bw.Write(bf._id); bw.Write(offset); bw.Write(bf.data.Length); uint szPad = (uint) Math.Ceiling((double) bf.data.Length/16)*16; file.Position = basePos + offset; bw.Write(bf.data); offset += szPad; } } //BinaryWriter should close file }
public override void Encode() { MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); NumStrings = StringList.Count; writer.Write(TotalOccurance); writer.Write(NumStrings); this.ContinuedRecords.Clear(); Record currentRecord = this; foreach (String stringVar in StringList) { int stringlength = Record.GetStringDataLength(stringVar); if (stream.Length + stringlength > Record.MaxContentLength) { currentRecord.Data = stream.ToArray(); currentRecord.Size = (UInt16)currentRecord.Data.Length; stream = new MemoryStream(); writer = new BinaryWriter(stream); CONTINUE continuedRecord = new CONTINUE(); this.ContinuedRecords.Add(continuedRecord); currentRecord = continuedRecord; } Record.WriteString(writer, stringVar, 16); } currentRecord.Data = stream.ToArray(); currentRecord.Size = (UInt16)currentRecord.Data.Length; }
public void Serialize(BinaryWriter writer, Type type, object parent) { foreach (var propertyInfo in type.GetProperties()) { if (propertyInfo.PropertyType.IsGenericType) { var genericArguments = propertyInfo.PropertyType.GetGenericArguments(); var values = propertyInfo.GetValue(parent, null) as IList; writer.Write(values.Count); foreach (var item in values) { Serialize(writer, genericArguments[0], item as SerializableType); } return; } if (propertyInfo.PropertyType.IsEnum) { var enumValue = Convert.ToInt32(propertyInfo.GetValue(parent, null)); writer.Write(enumValue); continue; } if (typeof(SerializableType).IsAssignableFrom(propertyInfo.PropertyType)) { Serialize(writer, propertyInfo.PropertyType, propertyInfo.GetValue(parent, null)); return; } ToBinary(writer, propertyInfo, parent); } }
/// <summary> /// Writes the event data to the underlying stream. /// </summary> /// <param name="writer">The writer.</param> public override void Write(BinaryWriter writer) { base.Write(writer); writer.Write(Colour.Minimum); writer.Write(Colour.Maximum); }
/// <summary> /// Notifies an enlisted object that a transaction is being prepared for commitment. /// </summary> /// <param name="preparingEnlistment">A <see cref="T:System.Transactions.PreparingEnlistment"/> object used to send a response to the transaction manager.</param> public void Prepare(PreparingEnlistment preparingEnlistment) { onTxComplete(); try { using (var machineStoreForApplication = IsolatedStorageFile.GetMachineStoreForDomain()) { var name = TransactionRecoveryInformationFileName; using (var file = machineStoreForApplication.CreateFile(name + ".temp")) using(var writer = new BinaryWriter(file)) { writer.Write(session.ResourceManagerId.ToString()); writer.Write(PromotableRavenClientEnlistment.GetLocalOrDistributedTransactionId(transaction).ToString()); writer.Write(session.DatabaseName ?? ""); writer.Write(preparingEnlistment.RecoveryInformation()); file.Flush(true); } machineStoreForApplication.MoveFile(name + ".temp", name); } } catch (Exception e) { logger.ErrorException("Could not prepare distributed transaction", e); preparingEnlistment.ForceRollback(e); return; } preparingEnlistment.Prepared(); }
public byte[] Write() { using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(Version); bw.Write(Counter); bw.Write((int)Autodetect); var ba = Utf8.GetBytes(ProxyServer ?? ""); bw.Write(ba.Length); bw.Write(ba); ba = Utf8.GetBytes(ExtraData ?? ""); bw.Write(ba.Length); bw.Write(ba); ba = Utf8.GetBytes(AutodetectScript ?? ""); bw.Write(ba.Length); bw.Write(ba); bw.Write(Junk); bw.Flush(); return ms.ToArray(); } }
/// <summary> /// Start a new command of a speicifc type with a global and/or local buffer on the EV3 brick /// </summary> /// <param name="commandType">The type of the command to start</param> /// <param name="globalSize">The size of the global buffer in bytes (maximum of 1024 bytes)</param> /// <param name="localSize">The size of the local buffer in bytes (maximum of 64 bytes)</param> public void Initialize(CommandType commandType, ushort globalSize, int localSize) { if(globalSize > 1024) throw new ArgumentException("Global buffer must be less than 1024 bytes", "globalSize"); if(localSize > 64) throw new ArgumentException("Local buffer must be less than 64 bytes", "localSize"); _stream = new MemoryStream(); _writer = new BinaryWriter(_stream); Response = ResponseManager.CreateResponse(); CommandType = commandType; // 2 bytes (this gets filled in later when the user calls ToBytes()) _writer.Write((ushort)0xffff); // 2 bytes _writer.Write(Response.Sequence); // 1 byte _writer.Write((byte)commandType); if(commandType == CommandType.DirectReply || commandType == CommandType.DirectNoReply) { // 2 bytes (llllllgg gggggggg) _writer.Write((byte)globalSize); // lower bits of globalSize _writer.Write((byte)((localSize << 2) | (globalSize >> 8) & 0x03)); // upper bits of globalSize + localSize } }
internal static byte[] GetBytesFromStruct(HeaderMsg header) { //byte[] arr = null; //try //{ // int size = Marshal.SizeOf(header); // arr = new byte[size]; // IntPtr ptr = Marshal.AllocHGlobal(size); // Marshal.StructureToPtr(header, ptr, true); // Marshal.Copy(ptr, arr, 0, size); // Marshal.FreeHGlobal(ptr); //} //catch(Exception e) //{ // Console.WriteLine(e.Message); //} //return arr; var stream = new MemoryStream(); var writer = new BinaryWriter(stream); writer.Write(header.messageID); writer.Write(header.messageFrom); writer.Write(header.messageTO); writer.Write(header.messageSize); return stream.ToArray(); }
public void SerializeInto(BinaryWriter writer) { writer.Write(new char[] { 'F', 'S', 'O', 'v' }); Context.SerializeInto(writer); writer.Write(Entities.Length); foreach (var ent in Entities) { byte type = (byte)((ent is VMAvatarMarshal) ? 1 : 0); writer.Write(type); ent.SerializeInto(writer); } writer.Write(Threads.Length); foreach(var thr in Threads) thr.SerializeInto(writer); writer.Write(MultitileGroups.Length); foreach (var grp in MultitileGroups) grp.SerializeInto(writer); writer.Write(GlobalState.Length); foreach (var val in GlobalState) { writer.Write(val); } writer.Write(ObjectId); }
public override void Save(BinaryWriter outStream) { outStream.Write(Id); outStream.Write(Unknown0); outStream.Write(Text); outStream.Write(AudioPath); }
//Reset determins whether it's a "shift move" or a move that replaces all other moves public void SendMoveInput(float x, float y, ushort[] entityIds, bool reset = false, bool attackMove = true) { Console.WriteLine("SENT " + DateTime.Now.Ticks); var memory = new MemoryStream(); var writer = new BinaryWriter(memory); writer.Write((byte) Protocol.Input); writer.Write((byte) InputSignature.Movement); writer.Write(x); writer.Write(y); writer.Write(reset); writer.Write(attackMove); writer.Write((byte) entityIds.Length); for (int i = 0; i < (byte) entityIds.Count(); i++) { writer.Write(entityIds[i]); } client.SendData(memory.ToArray()); writer.Close(); memory.Close(); }
private static void OutputFileVersion(BinaryWriter output) { output.Write((byte) FileVersion.Major); output.Write((byte) FileVersion.Minor); output.Write((byte) FileVersion.Revision); output.Write((byte) FileVersion.Build); }
public override void SerializeInto(BinaryWriter writer) { base.SerializeInto(writer); writer.Write(Interaction); writer.Write(CalleeID); writer.Write(Param0); }
public void WriteDataTo(BinaryWriter writer) { writer.Write(File == null ? "" : File); writer.Write((int) LineNumber); writer.Write((int) LinePosition); writer.Write(ErrorMessage == null ? "" : ErrorMessage); }
internal void Write(Task task, DoWorkArgs progress, ProgressChangedArgs args) { using (FileStream fileStream = File.Create(this.name)) { using (DeflateStream compress = new DeflateStream(fileStream, CompressionMode.Compress)) { using (BinaryWriter writer = new BinaryWriter(compress)) { writer.Write((byte)this.files.Count); foreach (string file in this.files.Keys) { if (task != null) { args.message = "Saving " + file + "..."; task.ReportProgress(progress.background, -1, args); } writer.Write(file); writer.Write(this.files[file].Length); writer.Write(this.files[file]); } if (task != null) { args.message = "Done"; task.ReportProgress(progress.background, -1, args); } } } } }
public override void Write(Stream output, IDirectory inputDirectory) { BinaryWriter writer = new BinaryWriter(output, Encoding.ASCII, true); const int sbpHeaderSize = 8; int entityHeaderSize = Entries.Count * SbpEntry.HeaderSize; int headerSize = sbpHeaderSize + entityHeaderSize; long headerPosition = output.Position; output.Position += headerSize; output.AlignWrite(16, 0x00); foreach (var entry in Entries) { entry.WriteData(output, inputDirectory); output.AlignWrite(16, 0x00); } long endPosition = output.Position; output.Position = headerPosition; writer.Write(0x4C504253); // SBPL writer.Write(Convert.ToByte(Entries.Count)); writer.Write(Convert.ToUInt16(headerSize)); writer.Write((byte)0x00); foreach (var entry in Entries) { entry.Write(output); } output.Position = endPosition; }
public static void DumpLocation(GeoPoint p, Stream stream) { using (var writer = new BinaryWriter (stream, System.Text.Encoding.UTF8, true)) { writer.Write (p.Lat); writer.Write (p.Lon); } }
public void CallMethodRef () { var expected = "value"; var moduleBuilder = CreateModuleBuilder (); var typeBuilder = moduleBuilder.DefineType ("NewType"); var methodBuilder1 = typeBuilder.DefineMethod ("NewMethod1", MethodAttributes.Public | MethodAttributes.Static, typeof (string), Type.EmptyTypes); var gen1 = methodBuilder1.GetILGenerator (); gen1.Emit (OpCodes.Ldstr, expected); gen1.Emit (OpCodes.Ret); var methodBuilder2 = typeBuilder.DefineMethod ("NewMethod2", MethodAttributes.Public | MethodAttributes.Static, typeof (string), Type.EmptyTypes); var ilStream = new MemoryStream (); var ilWriter = new BinaryWriter (ilStream); ilWriter.Write ((byte) 0x28); // call ilWriter.Write ((int) moduleBuilder.GetMethodToken (methodBuilder1).Token); ilWriter.Write ((byte) 0x2A); // ret SetIL (methodBuilder2, ilStream); var type = typeBuilder.CreateType (); Assert.AreEqual (expected, Invoke (type, methodBuilder2)); }
public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); bw.Write(pts); bw.Write(pts_count); bw.Write(offset); }
public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); ObjectUtils.SerializeObject(webpage,bw); bw.Write(pts); bw.Write(pts_count); }
public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); bw.Write(chat_id); ObjectUtils.SerializeObject(participants,bw); bw.Write(version); }
private void BytesDecodeTest(CS2CPrtcData p) { if (p == null || p.Type != 10531) { return; } const int count = 10000; Single totalTime = 0; IntPtr L = LuaScriptMgr.Instance.GetL(); if (L != IntPtr.Zero) { var startTime = DateTime.Now; for (int i = 0; i < count; i++) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getglobal(L, "ProcessMoveProtocol2"); if (!LuaDLL.lua_isnil(L, -1)) { LuaDLL.lua_pushinteger(L, p.Type); LuaDLL.lua_pushlstring(L, p.Buffer, p.Buffer.Length); LuaDLL.lua_pushboolean(L, false); LuaDLL.lua_pushboolean(L, false); if (LuaDLL.lua_pcall(L, 4, 0, 0) != 0) { HobaDebuger.LogLuaError(LuaDLL.lua_tostring(L, -1)); } } LuaDLL.lua_settop(L, oldTop); } totalTime = (DateTime.Now - startTime).Ticks; } UnityEngine.Debug.LogErrorFormat("ProcessMovePBProtocol * {0} = {1} ticks", count, totalTime); byte[] inputBytes = new byte[100]; System.IO.MemoryStream ms = new System.IO.MemoryStream(inputBytes); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms); { //entityid bw.Write(2); //CurrentPosition bw.Write(1.0f); bw.Write(2.0f); bw.Write(3.0f); //CurrentOrientation bw.Write(4.0f); bw.Write(5.0f); bw.Write(6.0f); //MoveType bw.Write(3); //MoveDirection bw.Write(7.0f); bw.Write(8.0f); bw.Write(9.0f); //MoveSpeed bw.Write(10.0f); //TimeInterval bw.Write(4); //DstPosition bw.Write(11.0f); bw.Write(12.0f); bw.Write(33.0f); //IsDestPosition bw.Write(false); ms.Seek(0, System.IO.SeekOrigin.Begin); } System.IO.BinaryReader br = new System.IO.BinaryReader(ms); { var startTime = DateTime.Now; for (int i = 0; i < count; i++) { br.BaseStream.Position = 0; var EntityId = br.ReadInt32(); var vecX = br.ReadSingle(); var vecY = br.ReadSingle(); var vecZ = br.ReadSingle(); var CurrentPosition = new UnityEngine.Vector3(vecX, vecY, vecZ); vecX = br.ReadSingle(); vecY = br.ReadSingle(); vecZ = br.ReadSingle(); var CurrentOrientation = new UnityEngine.Vector3(vecX, vecY, vecZ); var MoveType = br.ReadInt32(); vecX = br.ReadSingle(); vecY = br.ReadSingle(); vecZ = br.ReadSingle(); var MoveDirection = new UnityEngine.Vector3(vecX, vecY, vecZ); var MoveSpeed = br.ReadSingle(); var TimeInterval = br.ReadInt32(); vecX = br.ReadSingle(); vecY = br.ReadSingle(); vecZ = br.ReadSingle(); var DstPosition = new UnityEngine.Vector3(vecX, vecY, vecZ); var IsDestPosition = br.ReadBoolean(); if (L != IntPtr.Zero) { int oldTop = LuaDLL.lua_gettop(L); LuaDLL.lua_getglobal(L, "ProcessMoveProtocol1"); if (!LuaDLL.lua_isnil(L, -1)) { LuaScriptMgr.Push(L, EntityId); LuaScriptMgr.Push(L, CurrentPosition); LuaScriptMgr.Push(L, CurrentOrientation); LuaScriptMgr.Push(L, MoveType); LuaScriptMgr.Push(L, MoveDirection); LuaScriptMgr.Push(L, MoveSpeed); LuaScriptMgr.Push(L, TimeInterval); LuaScriptMgr.Push(L, DstPosition); LuaScriptMgr.Push(L, IsDestPosition); if (LuaDLL.lua_pcall(L, 9, 0, 0) != 0) { HobaDebuger.LogLuaError(LuaDLL.lua_tostring(L, -1)); } } LuaDLL.lua_settop(L, oldTop); } } totalTime = (DateTime.Now - startTime).Ticks; } bw.Close(); br.Close(); ms.Close(); ms.Dispose(); UnityEngine.Debug.LogErrorFormat("ProcessMoveProtocol * {0} = {1} ticks", count, totalTime); }
//public void DeSerialize (AstarPath active, bool runtime, out NavGraph graph) { // DeSerialize (active, runtime, out graph, null); //} /** Serializes links placed by the user */ public virtual void SerializeUserConnections(UserConnection[] userConnections) { System.IO.BinaryWriter stream = writerStream; AddAnchor("UserConnections"); if (userConnections != null) { stream.Write(userConnections.Length); for (int i = 0; i < userConnections.Length; i++) { UserConnection conn = userConnections[i]; stream.Write(conn.p1.x); stream.Write(conn.p1.y); stream.Write(conn.p1.z); stream.Write(conn.p2.x); stream.Write(conn.p2.y); stream.Write(conn.p2.z); stream.Write(conn.doOverrideCost); stream.Write(conn.overrideCost); stream.Write(conn.oneWay); stream.Write(conn.width); stream.Write((int)conn.type); } } else { stream.Write(0); } }
public static void saveToPly(string filename, List <Single> vertices, List <byte> colors, bool binary) { int nVertices = vertices.Count / 3; int faces = nVertices / 3; FileStream fileStream = File.Open(filename, FileMode.Create); System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream); System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(fileStream); //PLY file header is written here. streamWriter.WriteLine("ply"); if (binary) { streamWriter.WriteLine("format binary_little_endian 1.0"); } else { streamWriter.WriteLine("format ascii 1.0"); } streamWriter.WriteLine("element vertex " + nVertices.ToString()); streamWriter.WriteLine("property float x"); streamWriter.WriteLine("property float y"); streamWriter.WriteLine("property float z"); streamWriter.WriteLine("property uchar red"); streamWriter.WriteLine("property uchar green"); streamWriter.WriteLine("property uchar blue"); streamWriter.WriteLine("end_header"); streamWriter.Flush(); //Vertex and color data are written here. if (binary) { for (int j = 0; j < vertices.Count / 3; j++) { for (int k = 0; k < 3; k++) { binaryWriter.Write(vertices[j * 3 + k]); } for (int k = 0; k < 3; k++) { byte temp = colors[j * 3 + k]; binaryWriter.Write(temp); } } } else { for (int j = 0; j < vertices.Count / 3; j++) { string s = ""; for (int k = 0; k < 3; k++) { s += vertices[j * 3 + k].ToString(CultureInfo.InvariantCulture) + " "; } for (int k = 0; k < 3; k++) { s += colors[j * 3 + k].ToString(CultureInfo.InvariantCulture) + " "; } streamWriter.WriteLine(s); } } streamWriter.Flush(); binaryWriter.Flush(); fileStream.Close(); }
private void WriteHeader(System.IO.BinaryWriter writer) { using (MemoryStream allContentStream = new MemoryStream((int)m_contentStream.Length + (int)m_resourcesStream.Length)) { m_contentStream.WriteTo(allContentStream); m_resourcesStream.WriteTo(allContentStream); // calculate MD5 hash of allContentStream MD5 md5 = MD5.Create(); byte[] md5hash = md5.ComputeHash(allContentStream); // calculate signature byte[] sha1signature = new byte[128]; byte[] certData = null; if (Settings.Certificate != null) { certData = Settings.Certificate.Export(X509ContentType.Cert); var dsa = Settings.Certificate.GetRSAPrivateKey(); sha1signature = dsa.SignData(allContentStream.ToArray(), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); } writer.Write(new byte[] { 184, 67, 68, 67, 79, 77, 13, 10 }); // magic number ( 184, c, d, c, o, m, \r, \n ) writer.Write(BinaryConstants.FormatVersion); // format version writer.Write(md5hash); // MD5 hash of content (16-bytes) writer.Write(0u); // flags/reserved writer.Write((uint)((Settings.Certificate != null ? 8u + sha1signature.Length + certData.Length : 0) + 42u + m_contentStream.Length + m_resourcesStream.Length)); // length of file including header writer.Write((uint)(Settings.Certificate != null ? 8u + +sha1signature.Length + certData.Length : 0) + 42u); // offset to data from start of file (in bytes) writer.Write((uint)(Descriptions.Count + Resources.Count)); // number of content items writer.Write(Settings.Certificate != null); // is signed if (Settings.Certificate != null) { writer.Write(sha1signature.Length); writer.Write(sha1signature); // SHA-1 (RSA) signature of content (128-bytes) writer.Write(certData.Length); writer.Write(certData); } } }
/// <summary> /// Transform an input stream using the given rule /// </summary> /// <param name="input">Input stream</param> /// <param name="output">Output stream</param> /// <param name="keepReadOpen">True if the underlying read stream should be kept open, false otherwise</param> /// <param name="keepWriteOpen">True if the underlying write stream should be kept open, false otherwise</param> /// <returns>True if the file was transformed properly, false otherwise</returns> public bool TransformStream(Stream input, Stream output, bool keepReadOpen = false, bool keepWriteOpen = false) { bool success = true; // If the sizes are wrong for the values, fail long extsize = input.Length; if ((Operation > HeaderSkipOperation.Bitswap && (extsize % 2) != 0) || (Operation > HeaderSkipOperation.Byteswap && (extsize % 4) != 0) || (Operation > HeaderSkipOperation.Bitswap && (StartOffset == null || StartOffset % 2 == 0))) { Globals.Logger.Error("The stream did not have the correct size to be transformed!"); return(false); } // Now read the proper part of the file and apply the rule BinaryWriter bw = null; BinaryReader br = null; try { Globals.Logger.User("Applying found rule to input stream"); bw = new BinaryWriter(output); br = new BinaryReader(input); // Seek to the beginning offset if (StartOffset == null) { success = false; } else if (Math.Abs((long)StartOffset) > input.Length) { success = false; } else if (StartOffset > 0) { input.Seek((long)StartOffset, SeekOrigin.Begin); } else if (StartOffset < 0) { input.Seek((long)StartOffset, SeekOrigin.End); } // Then read and apply the operation as you go if (success) { byte[] buffer = new byte[4]; int pos = 0; while (input.Position < (EndOffset ?? input.Length) && input.Position < input.Length) { byte b = br.ReadByte(); switch (Operation) { case HeaderSkipOperation.Bitswap: // http://stackoverflow.com/questions/3587826/is-there-a-built-in-function-to-reverse-bit-order uint r = b; int s = 7; for (b >>= 1; b != 0; b >>= 1) { r <<= 1; r |= (byte)(b & 1); s--; } r <<= s; buffer[pos] = (byte)r; break; case HeaderSkipOperation.Byteswap: if (pos % 2 == 1) { buffer[pos - 1] = b; } if (pos % 2 == 0) { buffer[pos + 1] = b; } break; case HeaderSkipOperation.Wordswap: buffer[3 - pos] = b; break; case HeaderSkipOperation.WordByteswap: buffer[(pos + 2) % 4] = b; break; case HeaderSkipOperation.None: default: buffer[pos] = b; break; } // Set the buffer position to default write to pos = (pos + 1) % 4; // If we filled a buffer, flush to the stream if (pos == 0) { bw.Write(buffer); bw.Flush(); buffer = new byte[4]; } } // If there's anything more in the buffer, write only the left bits for (int i = 0; i < pos; i++) { bw.Write(buffer[i]); } } } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return(false); } finally { // If we're not keeping the read stream open, dispose of the binary reader if (!keepReadOpen) { br?.Dispose(); } // If we're not keeping the write stream open, dispose of the binary reader if (!keepWriteOpen) { bw?.Dispose(); } } return(success); }
private void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession) { //保存 { Utility.Configuration.ConfigurationData.ConfigConnection c = Utility.Configuration.Config.Connection; if (c.SaveReceivedData) { try { if (c.SaveResponse && oSession.fullUrl.Contains("/kcsapi/")) { // 非同期で書き出し処理するので取っておく // stringはイミュータブルなのでOK string url = oSession.fullUrl; string body = oSession.GetResponseBodyAsString(); Task.Run((Action)(() => { SaveResponse(url, body); })); } else if (oSession.fullUrl.Contains("/kcs/") && ((c.SaveSWF && oSession.oResponse.MIMEType == "application/x-shockwave-flash") || c.SaveOtherFile)) { string saveDataPath = c.SaveDataPath; // スレッド間の競合を避けるため取っておく string tpath = string.Format("{0}\\{1}", saveDataPath, oSession.fullUrl.Substring(oSession.fullUrl.IndexOf("/kcs/") + 5).Replace("/", "\\")); { int index = tpath.IndexOf("?"); if (index != -1) { if (Utility.Configuration.Config.Connection.ApplyVersion) { string over = tpath.Substring(index + 1); int vindex = over.LastIndexOf("VERSION=", StringComparison.CurrentCultureIgnoreCase); if (vindex != -1) { string version = over.Substring(vindex + 8).Replace('.', '_'); tpath = tpath.Insert(tpath.LastIndexOf('.', index), "_v" + version); index += version.Length + 2; } } tpath = tpath.Remove(index); } } // 非同期で書き出し処理するので取っておく byte[] responseCopy = new byte[oSession.ResponseBody.Length]; Array.Copy(oSession.ResponseBody, responseCopy, oSession.ResponseBody.Length); Task.Run((Action)(() => { try { lock (this) { // 同時に書き込みが走るとアレなのでロックしておく Directory.CreateDirectory(Path.GetDirectoryName(tpath)); //System.Diagnostics.Debug.WriteLine( oSession.fullUrl + " => " + tpath ); using (var sw = new System.IO.BinaryWriter(System.IO.File.OpenWrite(tpath))) { sw.Write(responseCopy); } } Utility.Logger.Add(1, string.Format("通信からファイル {0} を保存しました。", tpath.Remove(0, saveDataPath.Length + 1))); } catch (IOException ex) { //ファイルがロックされている; 頻繁に出るのでエラーレポートを残さない Utility.Logger.Add(3, "通信内容の保存に失敗しました。 " + ex.Message); } })); } } catch (Exception ex) { Utility.ErrorReporter.SendErrorReport(ex, "通信内容の保存に失敗しました。"); } } } if (oSession.fullUrl.Contains("/kcsapi/") && oSession.oResponse.MIMEType == "text/plain") { // 非同期でGUIスレッドに渡すので取っておく // stringはイミュータブルなのでOK string url = oSession.fullUrl; string body = oSession.GetResponseBodyAsString(); UIControl.BeginInvoke((Action)(() => { LoadResponse(url, body); })); } if (ServerAddress == null) { string url = oSession.fullUrl; int idxb = url.IndexOf("/kcsapi/"); if (idxb != -1) { int idxa = url.LastIndexOf("/", idxb - 1); ServerAddress = url.Substring(idxa + 1, idxb - idxa - 1); } } }
/// <summary> /// Writes the u int32. /// </summary> /// <param name="value">The value.</param> public void WriteUInt32(uint value) { _binaryWriter.Write(value); }
private void WriteDescriptions() { BW mainWriter = new BW(m_contentStream); foreach (ComponentDescription description in Descriptions) { using (MemoryStream tempStream = new MemoryStream()) { BW writer = new BW(tempStream); writer.Write(NewResourceID()); // ID writer.Write((uint)(6 + (Settings.WriteExtendedMetadada ? 1 : 0))); // 6 sections #region Metadata // Write METADATA /* Component name (string) * Can resize (bool) * Minimum size (bool) * GUID (byte[16]) * Author (string) * Version (major, minor) (uint, uint) * AdditionalInformation (string) * Implement set (string) * Implement item (string) * IconresourceID (int) * Timestamp (long) */ using (MemoryStream metadatSectionStream = new MemoryStream()) { BW metadataWriter = new BW(metadatSectionStream); metadataWriter.WriteNullString(description.ComponentName); metadataWriter.Write(!description.GetDefaultFlag(FlagOptions.NoResize)); metadataWriter.Write(description.GetDefaultFlag(FlagOptions.FlipPrimary)); metadataWriter.Write(description.MinSize); metadataWriter.Write(description.Metadata.GUID.ToByteArray()); metadataWriter.WriteNullString(description.Metadata.Author); metadataWriter.Write((ushort)description.Metadata.Version.Major); metadataWriter.Write((ushort)description.Metadata.Version.Minor); metadataWriter.WriteNullString(description.Metadata.AdditionalInformation); metadataWriter.WriteNullString(description.Metadata.ImplementSet); metadataWriter.WriteNullString(description.Metadata.ImplementItem); if (description.Metadata.Icon != null) { uint iconResourceID = NewResourceID(); foreach (var icon in description.Metadata.Icon as MultiResolutionImage) { BinaryResource iconResource = new BinaryResource(); iconResource.ID = iconResourceID; // Only PNG images can be written at the moment iconResource.ResourceType = BinaryResourceType.PNGImage; iconResource.Buffer = icon.Data; Resources.Add(iconResource); } metadataWriter.Write((int)iconResourceID); } else { metadataWriter.Write(-1); } metadataWriter.Write(DateTime.Now.ToBinary()); writer.Write((ushort)BinaryConstants.ComponentSectionType.Metadata); writer.Write((uint)metadatSectionStream.Length); writer.Write(metadatSectionStream.ToArray()); } #endregion #region Flags // Write FLAGS using (MemoryStream flagsSectionStream = new MemoryStream()) { BW flagsWriter = new BW(flagsSectionStream); flagsWriter.Write((uint)description.Flags.Count); foreach (Conditional <FlagOptions> flags in description.Flags) { flagsWriter.Write(flags.Conditions); flagsWriter.Write((uint)flags.Value); } writer.Write((ushort)BinaryConstants.ComponentSectionType.Flags); writer.Write((uint)flagsSectionStream.Length); writer.Write(flagsSectionStream.ToArray()); } #endregion #region Properties // Write PROPERTIES using (MemoryStream propertiesSectionStream = new MemoryStream()) { BW propertiesWriter = new BW(propertiesSectionStream); propertiesWriter.Write((uint)description.Properties.Length); foreach (ComponentProperty property in description.Properties) { propertiesWriter.Write(property.Name); propertiesWriter.Write(property.SerializedName.Value); propertiesWriter.Write(property.DisplayName); propertiesWriter.WriteType(property.Default, property.EnumOptions != null); if (property.EnumOptions != null) { propertiesWriter.Write(property.EnumOptions.Length); foreach (string option in property.EnumOptions) { propertiesWriter.Write(option); } } // Format rules propertiesWriter.Write((uint)property.FormatRules.Length); foreach (ComponentPropertyFormat formatRule in property.FormatRules) { propertiesWriter.Write(formatRule.Conditions); propertiesWriter.Write(formatRule.Value); } // Other conditions propertiesWriter.Write((uint)property.OtherConditions.Count); foreach (KeyValuePair <PropertyOtherConditionType, IConditionTreeItem> otherCondition in property.OtherConditions) { propertiesWriter.Write((uint)otherCondition.Key); propertiesWriter.Write(otherCondition.Value); } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Properties); writer.Write((uint)propertiesSectionStream.Length); writer.Write(propertiesSectionStream.ToArray()); } #endregion #region Configurations // Write CONFIGURATIONS using (MemoryStream configurationsStream = new MemoryStream()) { BW configurationWriter = new BW(configurationsStream); configurationWriter.Write((uint)description.Metadata.Configurations.Count); foreach (ComponentConfiguration configuration in description.Metadata.Configurations) { configurationWriter.Write(configuration.Name); configurationWriter.Write((configuration.ImplementationName ?? "")); configurationWriter.Write(configuration.Setters.Count); foreach (var setter in configuration.Setters) { foreach (ComponentProperty property in description.Properties) { if (property.SerializedName == setter.Key) { configurationWriter.Write(property.SerializedName.Value); break; } } configurationWriter.WriteType(setter.Value); } if (!Settings.IgnoreIcons && configuration.Icon != null) { uint iconResourceID = NewResourceID(); foreach (var icon in configuration.Icon as MultiResolutionImage) { BinaryResource iconResource = new BinaryResource(); iconResource.ID = iconResourceID; // Only PNG images can be written at the moment iconResource.ResourceType = BinaryResourceType.PNGImage; iconResource.Buffer = icon.Data; Resources.Add(iconResource); } configurationWriter.Write((int)iconResourceID); } else { configurationWriter.Write(-1); } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Configurations); writer.Write((uint)configurationsStream.Length); writer.Write(configurationsStream.ToArray()); } #endregion #region Connections // Write CONNECTIONS using (MemoryStream connectionsStream = new MemoryStream()) { BW connectionsWriter = new BW(connectionsStream); connectionsWriter.Write((uint)description.Connections.Length); foreach (ConnectionGroup connectionGroup in description.Connections) { connectionsWriter.Write(connectionGroup.Conditions); connectionsWriter.Write((uint)connectionGroup.Value.Length); foreach (ConnectionDescription connection in connectionGroup.Value) { connectionsWriter.Write(connection.Start); connectionsWriter.Write(connection.End); connectionsWriter.Write((int)connection.Edge); connectionsWriter.Write(connection.Name.Value); } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Connections); writer.Write((uint)connectionsStream.Length); writer.Write(connectionsStream.ToArray()); } #endregion #region Render // Write RENDER using (MemoryStream renderStream = new MemoryStream()) { BW renderWriter = new BW(renderStream); renderWriter.Write(description.RenderDescriptions.Length); foreach (RenderDescription renderDescription in description.RenderDescriptions) { renderWriter.Write(renderDescription.Conditions); renderWriter.Write(renderDescription.Value.Length); // number of render commands foreach (IRenderCommand command in renderDescription.Value) { renderWriter.Write((uint)command.Type); // command type switch (command.Type) { case RenderCommandType.Line: { Line line = command as Line; renderWriter.Write(line.Start); renderWriter.Write(line.End); renderWriter.Write(line.Thickness); } break; case RenderCommandType.Rect: { Rectangle rect = command as Rectangle; renderWriter.Write(rect.Location); renderWriter.Write(rect.Width); renderWriter.Write(rect.Height); renderWriter.Write(rect.StrokeThickness); renderWriter.Write((rect.Fill ? (uint)1 : (uint)0)); // 0 for transparent, 1 for filled } break; case RenderCommandType.Ellipse: { Ellipse ellipse = command as Ellipse; renderWriter.Write(ellipse.Centre); renderWriter.Write(ellipse.RadiusX); renderWriter.Write(ellipse.RadiusY); renderWriter.Write(ellipse.Thickness); renderWriter.Write((ellipse.Fill ? (uint)1 : (uint)0)); // 0 for transparent, 1 for filled } break; case RenderCommandType.Path: { RenderPath path = command as RenderPath; renderWriter.Write(path.Start); renderWriter.Write(path.Thickness); renderWriter.Write((path.Fill ? (uint)1 : (uint)0)); // 0 for transparent, 1 for filled renderWriter.Write(path.Commands.Count); foreach (IPathCommand pCommand in path.Commands) { renderWriter.Write((int)pCommand.Type); pCommand.Write(renderWriter); } } break; case RenderCommandType.Text: { var text = command as RenderText; renderWriter.Write(BinaryConstants.FormattedTextVersion); // Formatted text version renderWriter.Write(text.Location); // Text location renderWriter.Write((uint)text.Alignment); // Text alignment renderWriter.Write((uint)text.TextRuns.Count); // Number of text runs foreach (TextRun run in text.TextRuns) { renderWriter.Write((uint)run.Formatting.FormattingType); // Run formatting type renderWriter.Write(run.Formatting.Size); // Run text size renderWriter.Write(run.Text); // Text } } break; } } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Render); writer.Write((uint)renderStream.Length); writer.Write(renderStream.ToArray()); } #endregion #region ExtendedMetadata if (Settings.WriteExtendedMetadada) { using (var extendedMetadataStream = new MemoryStream()) { var extendedMetadataWriter = new BW(extendedMetadataStream); extendedMetadataWriter.Write((byte)BinaryConstants.ExtendedMetadataField.SemanticVersion); extendedMetadataWriter.WriteType(new Circuit.PropertyValue(description.Metadata.Version.ToString())); writer.Write((ushort)BinaryConstants.ComponentSectionType.ExtendedMetadata); writer.Write((uint)extendedMetadataStream.Length); writer.Write(extendedMetadataStream.ToArray()); } } #endregion mainWriter.Write((ushort)BinaryConstants.ContentItemType.Component); mainWriter.Write((uint)tempStream.Length); mainWriter.Write(tempStream.ToArray()); } } }
public byte[] SaveToBytes() { var ms = new System.IO.MemoryStream(); var writer = new System.IO.BinaryWriter(ms); writer.Write(Encoding.ASCII.GetBytes("EFKM")); writer.Write((int)Version); writer.Write(GUID); { var bw = new Utils.BinaryWriter(); bw.Push(Names.Count); var keys = Names.Keys.ToArray(); for (int i = 0; i < keys.Length; i++) { bw.Push((int)keys[i]); bw.Push(Names[keys[i]], Encoding.UTF8); bw.Push(Descriptions[keys[i]], Encoding.UTF8); } var binary = bw.GetBinary(); writer.Write(Encoding.ASCII.GetBytes("DESC")); writer.Write(binary.Length); writer.Write(binary); } { var bw = new Utils.BinaryWriter(); bw.Push(ShadingModel); bw.Push(HasNormal); bw.Push(HasRefraction); bw.Push(CustomData1Count); bw.Push(CustomData2Count); bw.Push(Textures.Length); foreach (var info in Textures) { bw.Push(info.Name, Encoding.UTF8); bw.Push(info.UniformName, Encoding.UTF8); bw.Push(info.DefaultPath, Encoding.UTF8); bw.Push(info.Index); bw.Push(info.Priority); bw.Push(info.IsParam); bw.Push((int)info.Type); bw.Push(info.Sampler); } bw.Push(Uniforms.Length); foreach (var info in Uniforms) { bw.Push(info.Name, Encoding.UTF8); bw.Push(info.UniformName, Encoding.UTF8); bw.Push(info.Offset); bw.Push(info.Priority); bw.Push(info.Type); bw.Push(info.DefaultValues[0]); bw.Push(info.DefaultValues[1]); bw.Push(info.DefaultValues[2]); bw.Push(info.DefaultValues[3]); } var binary = bw.GetBinary(); writer.Write(Encoding.ASCII.GetBytes("PRM_")); writer.Write(binary.Length); writer.Write(binary); } { var bw = new Utils.BinaryWriter(); bw.Push(CustomData.Length); foreach (var data in CustomData) { bw.Push(data.Summaries.Count); var keys = data.Summaries.Keys.ToArray(); foreach (var key in keys) { bw.Push((int)key); bw.Push(data.Summaries[key], Encoding.UTF8); bw.Push(data.Descriptions[key], Encoding.UTF8); } } bw.Push(Textures.Length); foreach (var texture in Textures) { bw.Push(texture.Summaries.Count); var keys = texture.Summaries.Keys.ToArray(); foreach (var key in keys) { bw.Push((int)key); bw.Push(texture.Summaries[key], Encoding.UTF8); bw.Push(texture.Descriptions[key], Encoding.UTF8); } } bw.Push(Uniforms.Length); foreach (var uniform in Uniforms) { bw.Push(uniform.Summaries.Count); var keys = uniform.Summaries.Keys.ToArray(); foreach (var key in keys) { bw.Push((int)key); bw.Push(uniform.Summaries[key], Encoding.UTF8); bw.Push(uniform.Descriptions[key], Encoding.UTF8); } } var binary = bw.GetBinary(); writer.Write(Encoding.ASCII.GetBytes("PRM2")); writer.Write(binary.Length); writer.Write(binary); } { var bw = new Utils.BinaryWriter(); bw.Push(CustomData.Length); for (int j = 0; j < CustomData.Length; j++) { bw.Push(CustomData[j].DefaultValues[0]); bw.Push(CustomData[j].DefaultValues[1]); bw.Push(CustomData[j].DefaultValues[2]); bw.Push(CustomData[j].DefaultValues[3]); } var binary = bw.GetBinary(); writer.Write(Encoding.ASCII.GetBytes("E_CD")); writer.Write(binary.Length); writer.Write(binary); } { var bw = new Utils.BinaryWriter(); bw.Push(Code, Encoding.UTF8); var binary = bw.GetBinary(); writer.Write(Encoding.ASCII.GetBytes("GENE")); writer.Write(binary.Length); writer.Write(binary); } { string jsonText = JsonConvert.SerializeObject(EditorData); jsonText = jsonText.Replace("/", "\\/"); var bw = new Utils.BinaryWriter(); bw.Push(jsonText, Encoding.UTF8, true, 0); var binary = bw.GetBinary(); writer.Write(Encoding.ASCII.GetBytes("DATA")); writer.Write(binary.Length); writer.Write(binary); } return(ms.ToArray()); }
static public void ExportMapAs(string targetName) { var tubLevel = Object.FindObjectOfType <TubLevel>(); CheckExport(tubLevel); EditorUtility.DisplayProgressBar("Exporting Map", "...", 0.0f); var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene(); var bundles = new List <AssetBundleBuild>(); var timer = Stopwatch.StartNew(); bundles.AddRange(UnityEditor.AssetDatabase.GetAllAssetBundleNames().Select(x => new AssetBundleBuild { assetBundleName = x, assetNames = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundle(x) })); var sceneBundle = new AssetBundleBuild { assetBundleName = $"{tubLevel.UniqueIdentifier}.map", assetNames = new[] { scene.path } }; bundles.Add(sceneBundle); if (!System.IO.Directory.Exists("TempBundleBuild")) { System.IO.Directory.CreateDirectory("TempBundleBuild"); } EditorUtility.DisplayProgressBar("Exporting Map", "Bundling..", 5.0f); BuildPipeline.BuildAssetBundles("TempBundleBuild", bundles.ToArray(), BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.StandaloneWindows64); UnityEngine.Debug.Log($"Created bundles in {timer.Elapsed.TotalSeconds:0.00} seconds"); byte[] thumb = new byte[0]; if (tubLevel.Icon != null) { thumb = tubLevel.Icon.EncodeToPNG(); } var sceneBundleInfo = new System.IO.FileInfo($"TempBundleBuild/{sceneBundle.assetBundleName}"); var missionHeader = new MissionHeader { Version = 2, Identifier = tubLevel.UniqueIdentifier, MapVersion = tubLevel.Version, BundleSize = (int)sceneBundleInfo.Length, ThumbSize = thumb.Length, Title = tubLevel.Title, Description = tubLevel.Description }; var json = JsonUtility.ToJson(missionHeader); EditorUtility.DisplayProgressBar("Exporting Map", "Deleting Old File..", 9.5f); if (System.IO.File.Exists(targetName)) { System.IO.File.Delete(targetName); } EditorUtility.DisplayProgressBar("Exporting Map", "Writing..", 9.9f); using (var stream = new System.IO.FileStream(targetName, System.IO.FileMode.OpenOrCreate)) { using (var writer = new System.IO.BinaryWriter(stream)) { writer.Write(json); writer.Write(thumb); writer.Write(System.IO.File.ReadAllBytes($"TempBundleBuild/{sceneBundle.assetBundleName}")); } } EditorUtility.ClearProgressBar(); }
internal void SaveTo(System.IO.BinaryWriter writer) { writer.Write(LastAccess.ToBinary()); writer.Write(BodyLength); writer.Write(MappedNameIDX); writer.Write(ETag); writer.Write(LastModified); writer.Write(Expires.ToBinary()); writer.Write(Age); writer.Write(MaxAge); writer.Write(Date.ToBinary()); writer.Write(MustRevalidate); writer.Write(Received.ToBinary()); }
/// <summary> /// High quality /// </summary> /// <param name="img"></param> /// <returns></returns> public static Icon IconFromImage(Image img) { var ms = new System.IO.MemoryStream(); var bw = new System.IO.BinaryWriter(ms); // Header bw.Write((short)0); // 0 : reserved bw.Write((short)1); // 2 : 1=ico, 2=cur bw.Write((short)1); // 4 : number of images // Image directory var w = img.Width; if (w >= 256) { w = 0; } bw.Write((byte)w); // 0 : width of image var h = img.Height; if (h >= 256) { h = 0; } bw.Write((byte)h); // 1 : height of image bw.Write((byte)0); // 2 : number of colors in palette bw.Write((byte)0); // 3 : reserved bw.Write((short)0); // 4 : number of color planes bw.Write((short)0); // 6 : bits per pixel var sizeHere = ms.Position; bw.Write((int)0); // 8 : image size var start = (int)ms.Position + 4; bw.Write(start); // 12: offset of image data // Image data img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); var imageSize = (int)ms.Position - start; ms.Seek(sizeHere, System.IO.SeekOrigin.Begin); bw.Write(imageSize); ms.Seek(0, System.IO.SeekOrigin.Begin); // And load it return(new Icon(ms)); }
private Bitmap CreateBitmap(IntPtr hDC, Size bmpSize, byte[] data) { System.IO.MemoryStream mem = new System.IO.MemoryStream(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(mem); //BITMAPINFO bmpInfo = new BITMAPINFO(); BITMAPINFOHEADER bmiHeader = new BITMAPINFOHEADER(); bmiHeader.biSize = 40; bmiHeader.biWidth = bmpSize.Width; bmiHeader.biHeight = bmpSize.Height; bmiHeader.biPlanes = 1; bmiHeader.biBitCount = 8; bmiHeader.biCompression = BI_RGB; bw.Write(bmiHeader.biSize); bw.Write(bmiHeader.biWidth); bw.Write(bmiHeader.biHeight); bw.Write(bmiHeader.biPlanes); bw.Write(bmiHeader.biBitCount); bw.Write(bmiHeader.biCompression); bw.Write(bmiHeader.biSizeImage); bw.Write(bmiHeader.biXPelsPerMeter); bw.Write(bmiHeader.biYPelsPerMeter); bw.Write(bmiHeader.biClrUsed); bw.Write(bmiHeader.biClrImportant); for (int i = 0; i < 256; i++) { bw.Write((byte)i); bw.Write((byte)i); bw.Write((byte)i); bw.Write((byte)0); } IntPtr hBitmap; if (data != null) { hBitmap = CreateDIBitmap(hDC, ref bmiHeader, CBM_INIT, data, mem.ToArray(), DIB_RGB_COLORS); } else { hBitmap = CreateDIBitmap(hDC, ref bmiHeader, 0, null, mem.ToArray(), DIB_RGB_COLORS); } return(Bitmap.FromHbitmap(hBitmap)); }
protected override void Save(System.IO.BinaryWriter writer) { writer.Write(m_data); }
public void Serialize(System.IO.BinaryWriter writer) { writer.Write(peerId); writer.Write(address); }
/** Serialize metadata about all graphs */ byte[] SerializeMeta() { if (graphs == null) { throw new System.Exception("No call to SerializeGraphs has been done"); } meta.version = AstarPath.Version; meta.graphs = graphs.Length; meta.guids = new string[graphs.Length]; meta.typeNames = new string[graphs.Length]; meta.nodeCounts = new int[graphs.Length]; // For each graph, save the guid // of the graph and the type of it for (int i = 0; i < graphs.Length; i++) { if (graphs[i] == null) { continue; } meta.guids[i] = graphs[i].guid.ToString(); meta.typeNames[i] = graphs[i].GetType().FullName; } #if !ASTAR_NO_JSON // Grab a cached string builder to avoid allocations var output = GetStringBuilder(); var writer = new JsonWriter(output, writerSettings); writer.Write(meta); return(encoding.GetBytes(output.ToString())); #else // Serialize the metadata without using json for compatibility var mem = new System.IO.MemoryStream(); var writer = new System.IO.BinaryWriter(mem); writer.Write("A*"); // Magic string writer.Write(meta.version.Major); writer.Write(meta.version.Minor); writer.Write(meta.version.Build); writer.Write(meta.version.Revision); writer.Write(meta.graphs); writer.Write(meta.guids.Length); for (int i = 0; i < meta.guids.Length; i++) { writer.Write(meta.guids[i] ?? ""); } writer.Write(meta.typeNames.Length); for (int i = 0; i < meta.typeNames.Length; i++) { writer.Write(meta.typeNames[i] ?? ""); } writer.Write(meta.nodeCounts.Length); for (int i = 0; i < meta.nodeCounts.Length; i++) { writer.Write(meta.nodeCounts[i]); } return(mem.ToArray()); #endif }
public void SaveChanges(System.IO.BinaryWriter binWriter) { for (int i = 0; i < 7; ++i) { binWriter.Write((byte)ObjectBanks[i]); } binWriter.Write((byte)0); binWriter.Write(ObjectBanks[7]); //0x5c binWriter.Write((long)0); //0x60-0x68 binWriter.Write(BMDFileID); //0x68 binWriter.Write(KCLFileID); //0x6a binWriter.Write(MinimapTsetFileID); //0x6c binWriter.Write(MinimapPalFileID); //0x6e binWriter.Write(new byte[5]); //0x70-0x75 binWriter.Write(CameraStartZoomedOut); //0x75 binWriter.Write(MinimapCoordinateScale); //0x76 binWriter.Write((byte)(QuestionMarks | Background << 4)); //0x78 binWriter.Write(new byte[3]); //0x79-0x7c, maybe (and hopefully!) part of Background binWriter.Write(MusicBytes); //0x7c-0x7f binWriter.Write((byte)((OverlayInitialiserVersion << 4) | LevelFormatVersion)); //0x7f binWriter.Write(new byte[20]); //0x80-0x94 }
void HttpProxy_AfterSessionComplete(Session session) { Utility.Configuration.ConfigurationData.ConfigConnection c = Utility.Configuration.Config.Connection; string baseurl = session.Request.PathAndQuery; //debug //Utility.Logger.Add( 1, baseurl ); // request if (baseurl.Contains("/kcsapi/")) { string url = baseurl; string body = session.Request.BodyAsString; //保存 if (c.SaveReceivedData && c.SaveRequest) { Task.Run((Action)(() => { SaveRequest(url, body); })); } UIControl.BeginInvoke((Action)(() => { LoadRequest(url, body); })); } //response //保存 if (c.SaveReceivedData) { try { if (!Directory.Exists(c.SaveDataPath)) { Directory.CreateDirectory(c.SaveDataPath); } if (c.SaveResponse && baseurl.Contains("/kcsapi/")) { // 非同期で書き出し処理するので取っておく // stringはイミュータブルなのでOK string url = baseurl; string body = session.Response.BodyAsString; Task.Run((Action)(() => { SaveResponse(url, body); })); } else if (baseurl.Contains("/kcs/") && ((c.SaveSWF && session.Response.MimeType == "application/x-shockwave-flash") || c.SaveOtherFile)) { string saveDataPath = c.SaveDataPath; // スレッド間の競合を避けるため取っておく string tpath = string.Format("{0}\\{1}", saveDataPath, baseurl.Substring(baseurl.IndexOf("/kcs/") + 5).Replace("/", "\\")); { int index = tpath.IndexOf("?"); if (index != -1) { if (Utility.Configuration.Config.Connection.ApplyVersion) { string over = tpath.Substring(index + 1); int vindex = over.LastIndexOf("VERSION=", StringComparison.CurrentCultureIgnoreCase); if (vindex != -1) { string version = over.Substring(vindex + 8).Replace('.', '_'); tpath = tpath.Insert(tpath.LastIndexOf('.', index), "_v" + version); index += version.Length + 2; } } tpath = tpath.Remove(index); } } // 非同期で書き出し処理するので取っておく byte[] responseCopy = new byte[session.Response.Body.Length]; Array.Copy(session.Response.Body, responseCopy, session.Response.Body.Length); Task.Run((Action)(() => { try { lock (this) { // 同時に書き込みが走るとアレなのでロックしておく Directory.CreateDirectory(Path.GetDirectoryName(tpath)); //System.Diagnostics.Debug.WriteLine( oSession.fullUrl + " => " + tpath ); using (var sw = new System.IO.BinaryWriter(System.IO.File.OpenWrite(tpath))) { sw.Write(responseCopy); } } Utility.Logger.Add(1, string.Format("通信からファイル {0} を保存しました。", tpath.Remove(0, saveDataPath.Length + 1))); } catch (IOException ex) { //ファイルがロックされている; 頻繁に出るのでエラーレポートを残さない Utility.Logger.Add(3, "通信内容の保存に失敗しました。 " + ex.Message); } })); } } catch (Exception ex) { Utility.ErrorReporter.SendErrorReport(ex, "通信内容の保存に失敗しました。"); } } if (baseurl.Contains("/kcsapi/") && session.Response.MimeType == "text/plain") { // 非同期でGUIスレッドに渡すので取っておく // stringはイミュータブルなのでOK string url = baseurl; string body = session.Response.BodyAsString; UIControl.BeginInvoke((Action)(() => { LoadResponse(url, body); })); // kancolle-db.netに送信する if (Utility.Configuration.Config.Connection.SendDataToKancolleDB) { Task.Run((Action)(() => DBSender.ExecuteSession(session))); } } if (ServerAddress == null && baseurl.Contains("/kcsapi/")) { ServerAddress = session.Request.Headers.Host; } }
public bool beginSplit() { System.IO.BinaryReader breader = null; System.IO.BinaryWriter bwriter = null; byte[] buffer = null; long fSize = 0; int curFileSplit = 0; long numLeftOverBytes = 0; long bytesRead = 0; long curSplitSize = 0; string curSplitFileName = ""; string baseName = ""; System.Security.AccessControl.FileSecurity targfileACL = default(System.Security.AccessControl.FileSecurity); //store file access control list, used on each split file if (!checkInputs(true, true)) { return(false); } fSize = Microsoft.VisualBasic.FileSystem.FileLen(targFileName); if (fSize < MaxSplitSize) { return(false); } targfileACL = new System.IO.FileInfo(targFileName).GetAccessControl(); //bufferSize was checked so now we'll set it up buffer = new byte[BufferSize]; UpdateStats(); //make sure stats are setup and ready curStats.startTime = System.DateTime.Now; baseName = targFileName.Substring(targFileName.LastIndexOf("\\") + 1, targFileName.Length - (targFileName.LastIndexOf("\\") + 1)); curSplitFileName = outputDir + "\\" + baseName + splitFirstName + splitReplaceToken + splitExt; try { //according to documentation opening the file this way may be faster due to the IO.FileOptions.SequentialScan flag //not sure if file.open class uses this flag anyway breader = new System.IO.BinaryReader(new System.IO.FileStream(targFileName, FileMode.Open, FileAccess.Read, FileShare.None, BufferSize, FileOptions.SequentialScan)); //we'll setup the new file and give it the same ACLs as the target bwriter = new System.IO.BinaryWriter(System.IO.File.Create(curSplitFileName.Replace(splitReplaceToken, curFileSplit.ToString()), BufferSize, FileOptions.None, targfileACL)); bytesRead = breader.Read(buffer, 0, BufferSize); while (bytesRead > 0) { if ((curSplitSize + bytesRead) > MaxSplitSize) { numLeftOverBytes = MaxSplitSize - curSplitSize; bwriter.Write(buffer, 0, Convert.ToInt32(numLeftOverBytes)); bwriter.Flush(); bwriter.Close(); curFileSplit += 1; bwriter = new System.IO.BinaryWriter(System.IO.File.Create(curSplitFileName.Replace(splitReplaceToken, curFileSplit.ToString()), BufferSize, FileOptions.SequentialScan | FileOptions.WriteThrough, targfileACL)); curSplitSize = bytesRead - numLeftOverBytes; if (onProgressStep != null) { double temp789 = breader.BaseStream.Position / fSize; double temp147 = curFileSplit / curStats.NumSplits; onProgressStep(Convert.ToInt32(Math.Floor((temp789) * 100)), Convert.ToInt32(Math.Floor((temp147) * 100))); } //RaiseEvent onProgressStep(Math.Floor((curSplitSize / MaxSplitSize) * 100), Math.Floor((curFileSplit / requiredSplits) * 100)) if (!(numLeftOverBytes == 0)) { bwriter.Write(buffer, Convert.ToInt32(numLeftOverBytes - 1), Convert.ToInt32(curSplitSize)); } else { //if CurSplitSize is = MaxSplitsize before the above if is evaluated //you'll end up with a full buffer here but leftOverBytes will be 0 bwriter.Write(buffer, Convert.ToInt32(numLeftOverBytes), Convert.ToInt32(curSplitSize)); } } else { bwriter.Write(buffer, 0, Convert.ToInt32(bytesRead)); curSplitSize += bytesRead; if (onProgressStep != null) { double temp258 = breader.BaseStream.Position / fSize; double temp369 = curFileSplit / curStats.NumSplits; onProgressStep(Convert.ToInt32(Math.Floor((temp258) * 100)), Convert.ToInt32(Math.Floor((temp369) * 100))); } } bytesRead = breader.Read(buffer, 0, BufferSize); } curStats.finishTime = System.DateTime.Now; } catch (Exception ex) { //might want to do return(false); } finally { if ((breader != null)) { breader.Close(); } if ((bwriter != null)) { bwriter.Flush(); bwriter.Close(); } } if (delAfterSplit) { Microsoft.VisualBasic.FileSystem.Kill(targFileName); } return(true); }
public void Save(System.IO.BinaryWriter writer) { version = VERSION; writer.Write(version); writer.Write(name); writer.Write(objdname); writer.Write((ushort)valuenames.Length); foreach (string s in valuenames) { writer.Write(s); } writer.Write((ushort)type); writer.Write(pfd.Type); writer.Write(pfd.Group); writer.Write(pfd.LongInstance); writer.Write(guid); if (thumb == null) { writer.Write((int)0); } else { MemoryStream ms = new MemoryStream(); thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] data = ms.ToArray(); writer.Write(data.Length); writer.Write(data); } }
public void Save(System.IO.BinaryWriter writer) { version = VERSION; writer.Write(version); writer.Write(name); writer.Write(modelname); writer.Write(pfd.Type); writer.Write(pfd.Group); writer.Write(localgroup); writer.Write(pfd.LongInstance); if (thumb == null) { writer.Write((int)0); } else { try { MemoryStream ms = new MemoryStream(); thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); byte[] data = ms.ToArray(); writer.Write(data.Length); writer.Write(data); ms.Close(); } catch { writer.Write((int)0); } } writer.Write((ushort)objtype); writer.Write(objfuncsort); writer.Write(objname); writer.Write(use); writer.Write((byte)oclass); }
public bool beginReassembly() { System.IO.BinaryReader breader = null; System.IO.BinaryWriter bwriter = null; byte[] buffer = null; int curFileSplit = 0; long bytesRead = 0; string curSplitFileName = ""; string baseName = ""; System.Security.AccessControl.FileSecurity targfileACL = null; //store file access control list, used on each split file long fSize = 0; try { if (!checkInputs(true, false)) { return(false); } targfileACL = new System.IO.FileInfo(targFileName).GetAccessControl(); //bufferSize was checked so now we'll set it up buffer = new byte[BufferSize]; UpdateStats(); //make sure stats are setup and ready curStats.startTime = System.DateTime.Now; baseName = targFileName.Substring(targFileName.LastIndexOf("\\") + 1, targFileName.Length - (targFileName.LastIndexOf("\\") + 1)); baseName = baseName.Substring(0, baseName.LastIndexOf(splitFileFirstName)); curSplitFileName = outputDir + "\\" + baseName + splitFirstName + splitReplaceToken + splitExt; //we'll setup the new file and give it the same ACLs as the target bwriter = new System.IO.BinaryWriter(System.IO.File.Create(outputDir + "\\" + baseName, BufferSize, System.IO.FileOptions.None, targfileACL)); while (System.IO.File.Exists(curSplitFileName.Replace(splitReplaceToken, curFileSplit.ToString()))) { breader = new System.IO.BinaryReader(new System.IO.FileStream(curSplitFileName.Replace(splitReplaceToken, curFileSplit.ToString()), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, BufferSize, System.IO.FileOptions.SequentialScan)); bytesRead = breader.Read(buffer, 0, BufferSize); fSize = Microsoft.VisualBasic.FileSystem.FileLen(curSplitFileName.Replace(splitFileReplaceToken, curFileSplit.ToString())); while (bytesRead > 0) { bwriter.Write(buffer, 0, Convert.ToInt32(bytesRead)); if (onProgressStep != null) { double temp14 = (breader.BaseStream.Position / fSize) * 100; double temp15 = (curFileSplit / curStats.NumSplits) * 100; onProgressStep(Convert.ToInt32(Math.Floor(temp14)), Convert.ToInt32(Math.Floor(temp15))); } bytesRead = breader.Read(buffer, 0, BufferSize); } breader.Close(); breader = null; //avoid exception in finally block if (delAfterReasm) { Microsoft.VisualBasic.FileSystem.Kill(curSplitFileName.Replace(splitReplaceToken, curFileSplit.ToString())); } curFileSplit += 1; } curStats.finishTime = System.DateTime.Now; //frmMain.ToolStripProgressBar1.Value = 0; //frmMain.tlStrpMainProgressBar.Value = 0; } catch (Exception ex) { return(false); } finally { if ((breader != null)) { breader.Close(); } if ((bwriter != null)) { bwriter.Flush(); bwriter.Close(); } } return(true); }
/// <summary> /// 导出proto文件 /// </summary> /// <param name="platform"></param> /// <param name="selectList"></param> public static void ExportProto(List <string> selectList = null) { string serverConfigProtoPath = PlayerPrefs.GetString(ExcelPathKey); if (string.IsNullOrEmpty(serverConfigProtoPath)) { Debug.Log("没有设置服务器SNV目录"); return; } DirectoryInfo serverDirectoryInfo = new DirectoryInfo(serverConfigProtoPath); System.IO.FileInfo[] serverFileInfos = serverDirectoryInfo.GetFiles("*.xlsx", SearchOption.TopDirectoryOnly); //可导配置列表 List <string> excelNames = new List <string>(); //可导配置相关信息(用于创建初始化代码) List <CreateConfigScrptData> scriptDataList = new List <CreateConfigScrptData>(); #region 遍历所有配置导出单个proto文件 foreach (System.IO.FileInfo fileInfo in serverFileInfos) { if (fileInfo.Name.StartsWith("~")) { continue; } if (Excel2ProtoTool.ingoreList.Contains(fileInfo.Name)) { continue; } string name = fileInfo.Name.Replace(".xlsx", ""); if (!fileInfo.Name.EndsWith(".xlsx")) { Debug.Log("跳过文件 " + name + " 因为它不是一个表文件"); continue; } //单个配置相关数据 CreateConfigScrptData scriptData = new CreateConfigScrptData(); scriptDataList.Add(scriptData); scriptData.excelName = name; excelNames.Add(name); if (selectList != null && !selectList.Contains(fileInfo.Name)) { continue; } Debug.Log("build Proto:" + name); var start = Time.realtimeSinceStartup; FileStream stream = File.Open(serverConfigProtoPath + "/" + fileInfo.Name, FileMode.Open, FileAccess.Read); ExcelPackage excelReader = new ExcelPackage(stream); ExcelWorkbook result = excelReader.Workbook; ExcelWorksheet workSheet = result.Worksheets.First(); int columns = workSheet.Dimension.End.Column; int rows = workSheet.Dimension.End.Row; if (rows < 3) { Debug.LogError("选择的excel表行数小于4"); return; } string SaveValue = "package " + PackageName + ";\n\n"; SaveValue += "message " + name + "Config{\n"; for (int j = 0; j <= columns; j++) { if (j == 0) { continue; } if (string.IsNullOrEmpty(workSheet.GetValue <string>(1, j))) { continue; } string valueName = workSheet.GetValue <string>(3, j); if (string.IsNullOrEmpty(valueName)) { Debug.LogError(fileInfo.Name + "第" + (j + 1) + "列变量名为空"); return; } valueName = valueName.TrimEnd(' '); string explain = workSheet.GetValue <string>(1, j); string type = workSheet.GetValue <string>(2, j); //保存第一个字段的类型以及变量名 if (j == 1) { scriptData.VariableName = valueName; scriptData.TypeName = type; } if (type == "int") { type = "int32"; } else if (type == "long") { type = "int64"; } SaveValue += "\trequired " + type + " " + valueName + " = " + (j) + ";\t\t//" + explain + "\n"; } SaveValue += "}\n\n"; SaveValue += "message " + name + "ConfigData{\n"; SaveValue += "\trepeated " + name + "Config config = 1;\n"; SaveValue += "}\n"; System.IO.FileStream Fstream = System.IO.File.Create(Application.dataPath + "/" + scriptsProtoConfigProto + "/" + name + ".proto"); char[] data = SaveValue.ToCharArray(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(Fstream); bw.Write(data); bw.Close(); Fstream.Close(); var end = Time.realtimeSinceStartup; Debug.LogFormat("Build,Start:{0}s end:{1}s duration:{2}s name:{3}", start, end, end - start, name); } #endregion #region 创建一个总表proto文件 string protoNewValue = "package " + PackageName + ";\r\n\r\n"; foreach (string str in excelNames) { protoNewValue += " import \"" + str + ".proto\";\r\n"; } protoNewValue += "\r\nmessage ConfigDatabase {\r\n"; for (int i = 0; i < excelNames.Count; i++) { protoNewValue += "\trequired " + excelNames[i] + "ConfigData m_" + excelNames[i] + "_data = " + (i + 1) + ";\r\n"; } protoNewValue += "}\r\n"; System.IO.FileStream Fstream2 = System.IO.File.Create(Application.dataPath + "/" + scriptsProtoConfigProto + "/ConfigDatabaseFile.proto"); char[] data2 = protoNewValue.ToCharArray(); System.IO.BinaryWriter bw2 = new System.IO.BinaryWriter(Fstream2); bw2.Write(data2); bw2.Close(); Fstream2.Close(); #endregion #region 自动补齐初始化代码 CreateConfigScrpt(scriptDataList); #endregion }
void IBinarySerialize.Write(System.IO.BinaryWriter w) { w.Write(_delimiter); w.Write(_accumulator.ToString()); }
public byte[] CommitTransaction(SortedSet <BaseDataObjectVersion> objects) { System.IO.MemoryStream MS = new System.IO.MemoryStream(); System.IO.MemoryStream MSRP = new System.IO.MemoryStream(); System.IO.BinaryWriter MSBW = new System.IO.BinaryWriter(MS); SortedSet <byte[]> dependencies = new SortedSet <byte[]> (BD2.Core.ByteSequenceComparer.Shared); ChunkHeaderv1 ch = new ChunkHeaderv1(DateTime.UtcNow, ""); MSBW.Write(ch.Version); byte[] chbytes = ch.Serialize(); MSBW.Write(chbytes.Length); MSBW.Write(chbytes); MSBW.Write(1); Console.WriteLine("{0} sections", 1); int n = 0; //foreach (var tup in data) { MSBW.Write(1); Console.WriteLine("Section version is {0}", 1); System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode <BaseDataObjectVersion> > ss = new System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode <BaseDataObjectVersion> > (); System.Collections.Generic.LinkedList <BaseDataObjectVersion> ll = new LinkedList <BaseDataObjectVersion> (); foreach (BaseDataObjectVersion bdo in objects) { if (!ss.ContainsKey(bdo)) { ss.Add(bdo, ll.AddLast(bdo)); } foreach (BaseDataObjectVersion dependency in bdo.GetDependenies()) { byte[] dep = dependency.ChunkID; if (dep == null) { if (ss.ContainsKey(bdo)) { } else { ss.Add(dependency, ll.AddBefore(ss [bdo], dependency)); } } else { if (!dependencies.Contains(dependency.ChunkID)) { dependencies.Add(dependency.ChunkID); } } } } foreach (BaseDataObjectVersion bdo in ll) { n++; System.IO.MemoryStream MST = new System.IO.MemoryStream(); MST.Write(bdo.ObjectType.ToByteArray(), 0, 16); bdo.Serialize(MST, encryptedStorageManager); byte[] bytes = MST.ToArray(); //Console.WriteLine ("Object of type {0} serialized to {1} bytes.", bdo.GetType ().FullName, bytes.Length); { System.IO.MemoryStream MSC = new System.IO.MemoryStream(); System.IO.BinaryWriter BWC = new System.IO.BinaryWriter(MSC); BWC.Write(bytes.Length); MSRP.Write(MSC.ToArray(), 0, 4); } MSRP.Write(bytes, 0, bytes.Length); } byte[] encoded = MSRP.ToArray(); Console.WriteLine("{0} objects encoded in {1} bytes", objects.Count, encoded.Length); MSBW.Write(encoded.Length); MSBW.Write(encoded); //} if (n == 0) { Console.WriteLine("No objects to save, nothing to do"); return(null); } System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(); Console.WriteLine("{0} dependencies", dependencies.Count); byte[][] deps = new byte [dependencies.Count][]; int depid = 0; foreach (byte[] dep in dependencies) { deps [depid++] = dep; } Console.WriteLine("Writing {0} bytes representing {1} objects to backend", MS.Length, n); byte[] buf = MS.ToArray(); byte[] chunkID = sha.ComputeHash(buf); dataStorage [DefaultStorage].Push(chunkID, buf, deps, userStorage.Sign(chunkID)); foreach (var bdo in objects) { bdo.SetChunkID(chunkID); } return(chunkID); }
static void ExportExcelConfigAll() { string m_ExcelPath = ExcelPath; if (string.IsNullOrEmpty(m_ExcelPath)) { Debug.Log("没有设置服务器SNV目录"); return; } #region 设置好需要导出数据的配置表相关信息(因为变量名是驼峰命名,所以提前存起来) DirectoryInfo serverDirectoryInfo = new DirectoryInfo(m_ExcelPath); System.IO.FileInfo[] serverFileInfos = serverDirectoryInfo.GetFiles("*.xlsx", SearchOption.TopDirectoryOnly); Dictionary <string, string> dicPath = new Dictionary <string, string>(); Dictionary <string, string> classNameDic = new Dictionary <string, string>(); foreach (System.IO.FileInfo fileInfo in serverFileInfos) { string name = fileInfo.Name; name = name.Replace(".xlsx", ""); classNameDic[name] = name; dicPath[name] = m_ExcelPath + "/" + fileInfo.Name; } #endregion #region 实例化总表数据 Type AllConfigType = SysUtil.GetTypeByName(PackageName + ".ConfigDatabase"); if (AllConfigType == null) { return; } System.Object AllConfigData = Activator.CreateInstance(AllConfigType); #endregion #region 遍历总表属性,把对应的数据赋值到总表实例里面(通过属性设值) System.Reflection.PropertyInfo[] fields = AllConfigType.GetProperties(); foreach (System.Reflection.PropertyInfo f in fields) { if (f.Name.EndsWith("data")) { var start = Time.realtimeSinceStartup;//System.DateTime.Now.Ticks; string name = f.Name.Substring(2, f.Name.Length - 2); name = name.Substring(0, f.Name.Length - 7); if (!dicPath.ContainsKey(name)) { continue; } string filePath = dicPath[name]; System.Object tempData = CreateData(dicPath[name], classNameDic[name]); if (null == tempData) { continue; } f.SetValue(AllConfigData, tempData, null); } } #endregion System.IO.MemoryStream MstreamConfig = new System.IO.MemoryStream(); ProtoBuf.Serializer.Serialize(MstreamConfig, AllConfigData); byte[] dataConfig = MstreamConfig.ToArray(); var pathConfig = string.Format("{0}/{1}.bytes", ExportBytesPath, "ConfigDatabase"); System.IO.FileStream FstreamConfig = System.IO.File.Create(pathConfig); System.IO.BinaryWriter bwConfig = new System.IO.BinaryWriter(FstreamConfig); bwConfig.Write(dataConfig); FstreamConfig.Close(); bwConfig.Close(); MstreamConfig.Close(); AssetDatabase.Refresh(); }
//获取媒体帧对应字节数组 public byte[] GetBytes() { var ms = new System.IO.MemoryStream(); var bw = new System.IO.BinaryWriter(ms); bw.Write(MediaFrameVersion); bw.Write(nEx); bw.Write(nIsKeyFrame); bw.Write(nTimetick); bw.Write(nIsAudio); bw.Write(nSize); int _tOffset = nOffset;// 重置偏移量 nOffset = 0; bw.Write(nOffset); if (MediaFrameVersion == 1) { bw.Write(nEncoder); if (nIsAudio == 0) { bw.Write(nSPSLen); bw.Write(nPPSLen); bw.Write(nWidth); bw.Write(nHeight); } else { bw.Write(nFrequency); bw.Write(nChannel); bw.Write(nAudioFormat); bw.Write(nSamples); } } bw.Write(Data, _tOffset, nSize); nOffset = _tOffset; return(ms.ToArray()); }
/// <summary> /// Write a set of input files to a torrent7z archive (assuming the same output archive name) /// </summary> /// <param name="inputFiles">Input files to be moved</param> /// <param name="outDir">Output directory to build to</param> /// <param name="rom">DatItem representing the new information</param> /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param> /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param> /// <returns>True if the archive was written properly, false otherwise</returns> public override bool Write(List <string> inputFiles, string outDir, List <Rom> roms, bool date = false, bool romba = false) { bool success = false; string tempFile = Path.Combine(outDir, "tmp" + Guid.NewGuid().ToString()); // If either list of roms is null or empty, return if (inputFiles == null || roms == null || inputFiles.Count == 0 || roms.Count == 0) { return(success); } // If the number of inputs is less than the number of available roms, return if (inputFiles.Count < roms.Count) { return(success); } // If one of the files doesn't exist, return foreach (string file in inputFiles) { if (!File.Exists(file)) { return(success); } } // Get the output archive name from the first rebuild rom string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".7z") ? "" : ".7z")); // Set internal variables SevenZipBase.SetLibraryPath("7za.dll"); SevenZipExtractor oldZipFile; SevenZipCompressor zipFile; try { // If the full output path doesn't exist, create it if (!Directory.Exists(Path.GetDirectoryName(archiveFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName)); } // If the archive doesn't exist, create it and put the single file if (!File.Exists(archiveFileName)) { zipFile = new SevenZipCompressor() { ArchiveFormat = OutArchiveFormat.SevenZip, CompressionLevel = CompressionLevel.Normal, }; // Map all inputs to index Dictionary <string, int> inputIndexMap = new Dictionary <string, int>(); for (int i = 0; i < inputFiles.Count; i++) { inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), i); } // Sort the keys in TZIP order List <string> keys = inputIndexMap.Keys.ToList(); keys.Sort(ZipFile.TorrentZipStringCompare); // Create the temp directory string tempPath = Path.Combine(outDir, Guid.NewGuid().ToString()); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } // Now add all of the files in order foreach (string key in keys) { string newkey = Path.Combine(tempPath, key); File.Move(inputFiles[inputIndexMap[key]], newkey); zipFile.CompressFiles(tempFile, newkey); File.Move(newkey, inputFiles[inputIndexMap[key]]); // After the first file, make sure we're in append mode zipFile.CompressionMode = CompressionMode.Append; } Utilities.CleanDirectory(tempPath); Utilities.TryDeleteDirectory(tempPath); } // Otherwise, sort the input files and write out in the correct order else { // Open the old archive for reading using (oldZipFile = new SevenZipExtractor(archiveFileName)) { // Map all inputs to index Dictionary <string, int> inputIndexMap = new Dictionary <string, int>(); for (int i = 0; i < inputFiles.Count; i++) { // If the old one contains the new file, then just skip out if (oldZipFile.ArchiveFileNames.Contains(roms[i].Name.Replace('\\', '/'))) { continue; } inputIndexMap.Add(roms[i].Name.Replace('\\', '/'), -(i + 1)); } // Then add all of the old entries to it too for (int i = 0; i < oldZipFile.FilesCount; i++) { inputIndexMap.Add(oldZipFile.ArchiveFileNames[i], i); } // If the number of entries is the same as the old archive, skip out if (inputIndexMap.Keys.Count <= oldZipFile.FilesCount) { success = true; return(success); } // Otherwise, process the old zipfile zipFile = new SevenZipCompressor() { ArchiveFormat = OutArchiveFormat.SevenZip, CompressionLevel = CompressionLevel.Normal, }; // Get the order for the entries with the new file List <string> keys = inputIndexMap.Keys.ToList(); keys.Sort(ZipFile.TorrentZipStringCompare); // Copy over all files to the new archive foreach (string key in keys) { // Get the index mapped to the key int index = inputIndexMap[key]; // If we have the input file, add it now if (index < 0) { FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]); // Create a stream dictionary Dictionary <string, Stream> dict = new Dictionary <string, Stream>(); dict.Add(key, inputStream); // Now add the stream zipFile.CompressStreamDictionary(dict, tempFile); } // Otherwise, copy the file from the old archive else { Stream oldZipFileEntryStream = new MemoryStream(); oldZipFile.ExtractFile(index, oldZipFileEntryStream); oldZipFileEntryStream.Seek(0, SeekOrigin.Begin); // Create a stream dictionary Dictionary <string, Stream> dict = new Dictionary <string, Stream>(); dict.Add(oldZipFile.ArchiveFileNames[index], oldZipFileEntryStream); // Now add the stream zipFile.CompressStreamDictionary(dict, tempFile); oldZipFileEntryStream.Dispose(); } // After the first file, make sure we're in append mode zipFile.CompressionMode = CompressionMode.Append; } } } success = true; } catch (Exception ex) { Console.WriteLine(ex); success = false; } // If the old file exists, delete it and replace if (File.Exists(archiveFileName)) { Utilities.TryDeleteFile(archiveFileName); } File.Move(tempFile, archiveFileName); // Now make the file T7Z // TODO: Add ACTUAL T7Z compatible code BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName)); bw.Seek(0, SeekOrigin.Begin); bw.Write(Constants.Torrent7ZipHeader); bw.Seek(0, SeekOrigin.End); using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName))) { // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4) byte[] tempsig = Constants.Torrent7ZipSignature; if (oldZipFile.FilesCount > 1) { tempsig[16] = 0x2; } else { tempsig[16] = 0; } bw.Write(tempsig); bw.Flush(); bw.Dispose(); } return(true); }
private void WriteFramesToFfmpeg() { Bytable curFrame = null; byte[] buf = null; System.IO.BinaryWriter dataPipe = m_dataWriter; try { while (!m_shouldExit) { while (!m_shouldPause) { // Wait for the next frame to arrive. m_frameReady.WaitOne(); m_frameWritten.Reset(); // Grab the frame. curFrame = Interlocked.Exchange(ref m_frame, curFrame); if (curFrame == null || curFrame.Length == 0) { // This really shouldn't happen. UnityEngine.Debug.LogWarning("FfmpegPipe recieved invalid frame"); m_frameWritten.Set(); continue; } curFrame.ToBytes(ref buf); dataPipe.Write(buf); if (ReleaseFrame != null) { ReleaseFrame(curFrame); } m_frameCount++; m_frameWritten.Set(); // It's safe to throw this memory away, because Unity is transferring ownership. curFrame = null; } // Wait for the next frame m_ready.WaitOne(); } dataPipe.Flush(); dataPipe.Close(); } catch (System.Threading.ThreadInterruptedException) { // This is fine, the render thread sent an interrupt. dataPipe.Flush(); dataPipe.Close(); } catch (System.Exception e) { UnityEngine.Debug.LogWarning(m_outputFile); UnityEngine.Debug.LogException(e); } }
public override void Save(System.IO.BinaryWriter outStream) { outStream.Write(MetadataStringOffset); outStream.Write(NameStringOffset); outStream.Write(AnimatedObjectStringOffset); outStream.Write(ActorStringOffset); outStream.Write(BaseMaxLife); outStream.Write(BaseMaxMana); outStream.Write(WeaponSpeed); outStream.Write(MinDamage); outStream.Write(MaxDamage); outStream.Write(MaxAttackDistance); outStream.Write(IconStringOffset); outStream.Write(U06); outStream.Write(BaseStrength); outStream.Write(BaseDexterity); outStream.Write(BaseIntelligence); outStream.Write(KnownSkillsListLength); outStream.Write(KnownSkillsListOffset); outStream.Write(DescriptionStringOffset); outStream.Write(StartingGemKey); outStream.Write(U13); outStream.Write(U14); outStream.Write(U15); outStream.Write(U16); outStream.Write(U17); outStream.Write(AudioStringOffset); }