public MessageSystemClient() { client = new TcpClient(); WebApiConfiguration webApiConfigurationFile = BinarySerialization.ReadFromBinaryFile <WebApiConfiguration>(@".\WebApiConfig.cfg"); serverEndPoint = new IPEndPoint(IPAddress.Parse(webApiConfigurationFile.Server), 3000); }
public unsafe void SerializeAndDeserialize_MultidimensionalArray() { var src = new ClassWithMultidimensionalArray { MultidimensionalArrayInt32 = new[, ] { { 1, 2 }, { 3, 4 } } }; var parameters = new BinarySerializationParameters { UserDefinedAdapters = new List <IBinaryAdapter> { new Array2Adapter <int>() } }; using (var stream = new UnsafeAppendBuffer(16, 4, Allocator.Temp)) { BinarySerialization.ToBinary(&stream, src, parameters); var reader = stream.AsReader(); var dst = BinarySerialization.FromBinary <ClassWithMultidimensionalArray>(&reader, parameters); Assert.That(dst.MultidimensionalArrayInt32, Is.EqualTo(new[, ] { { 1, 2 }, { 3, 4 } })); } }
private void Init() { try { mijnenOverzicht = BinarySerialization.ReadFromBinaryFile <MijnenOverzicht>("mijnenoverzicht.bin"); } catch (Exception) { Foutmelding.Content = "Fout bij lezen oude gegevens"; } try { reportValues = BinarySerialization.ReadFromBinaryFile <ReportValues>("reportValues.bin"); } catch (Exception) { Foutmelding.Content = "Fout bij lezen oude configuratie"; reportValues.ijzerWaarde = 19.00m; reportValues.steenWaarde = 14.00m; reportValues.kleiWaarde = 4.00m; reportValues.loon1uur = 2.04m; reportValues.loon1uurmob = 1.22m; reportValues.loon2uur = 2.72m; reportValues.loon2uurmob = 2.18m; reportValues.loon6uur = 5.52m; reportValues.loon10uur = 7.84m; reportValues.loon22uur = 15.00m; } InitMijnen(); RapportDatum.SelectedDate = DateTime.Today.AddDays(-1); }
public void ClientConnection(object s) { Socket s_Client = (Socket)s; byte[] buffer; User user; try { while (true) { buffer = new byte[1024]; s_Client.Receive(buffer); user = (User)BinarySerialization.Deserializate(buffer); if (user.user == "admin" && user.password == "admin") { byte[] toSend = Encoding.ASCII.GetBytes("success"); s_Client.Send(toSend); } else { byte[] toSend = Encoding.ASCII.GetBytes("fail"); s_Client.Send(toSend); } Console.WriteLine("User Recieved:" + user.user); Console.WriteLine("Password Recieved:" + user.password); } } catch (SocketException ex) { Console.WriteLine("Simulator Disconnected : {0}", ex.Message); } }
private void Receive() { var client = new UdpClient(_port); var data = string.Empty; IPEndPoint remoteIpEndPoint = null; while (!data.Equals(EndCommand)) { try { var bytesData = client.Receive(ref remoteIpEndPoint); data = BinarySerialization.GetString(bytesData); if (data.Equals(EndCommand)) { break; } var dataPrice = JsonSerialization.GetObject <DataPrice>(data); lock (_sync) { _dataDump.Data.Add(dataPrice.DateTime, dataPrice); } } catch (Exception e) { Console.WriteLine(e); } } client.Close(); }
private static byte[] GetBytes(Price obj) { var strData = JsonSerialization.ToString(obj); var byteData = BinarySerialization.ToByteArray(strData); return(byteData); }
public void RecieveAction(int lockStepTurn, int playerID, byte[] actionAsBytes) { //Debug.Log("Recieved Player " + playerID + "'s action for turn " + lockStepTurn + " on turn " + _lockStepTurnID); Action action = BinarySerialization.DeserializeObject <Action>(actionAsBytes); if (action == null) { Debug.Log("Sending action failed"); //TODO: Error handle invalid actions recieve } else { _pendingActions.AddAction(action, Convert.ToInt32(playerID), _lockStepTurnID, lockStepTurn); //send confirmation if (_confirmedActions.IsConfirmedActionsEnabled()) { if (Network.isServer) { //we don't need an rpc call if we are the server ConfirmActionServer(lockStepTurn, _localPlayerIndex, playerID); } else { _networkInterface.CallConfirmActionServer(lockStepTurn, _localPlayerIndex, playerID); } } } }
public int Run(OptionGroup_ToJson args) { Console.WriteLine("Reading UE4 SaveGame file."); GvasFormat.Gvas save; using (var stream = File.Open(args.In, FileMode.Open, FileAccess.Read, FileShare.Read)) { save = BinarySerialization.ReadGvas(stream); } Console.WriteLine("Reading done."); Console.WriteLine("Converting to json."); using (var fs = File.Create(args.Out)) { GvasFormat.Serialization.Json.JsonSerialization.WriteGvas(fs, save, args.Compact); } Console.WriteLine("Converting done."); if (args.Compact) { Console.WriteLine("Note! I can not convert compact json back to gvas because type informations are not included."); } if (args.PrintStatistics) { Console.WriteLine("Printing statistics."); string dir = Path.GetDirectoryName(Path.GetFullPath(args.Out)); Statistic.PrintToFile_EnumTypeSet(dir); Statistic.PrintToFile_GenericStructTypeSet(dir); Statistic.PrintToFile_UETypeSet(dir); Statistic.PrintToFile_TypeStringSet(dir); Console.WriteLine("Printing done."); } return(0); }
public static MethodCallInfo ToMethodCall(this ValueSet set) { string b64 = set[FuncMethodBase64Key] as string; var method = BinarySerialization.FromBase64BinaryString <MethodCallInfo>(b64); return(method); }
public View_page() { InitializeComponent(); Person person = BinarySerialization.ReadFromBinaryFile <Person>("C:/Users/186173.KIP/source/repos/WpfApp4/WpfApp4/data.bin"); InitPersonItemBox(person); }
public void ImageListStreamer_RoundTripAndExchangeWithNet() { string netBlob; using (var imageList = new ImageList() { ImageSize = new Size(16, 16), TransparentColor = Color.White }) { imageList.Images.Add(new Bitmap(16, 16)); netBlob = BinarySerialization.ToBase64String(imageList.ImageStream); } // ensure we can deserialise NET serialised data and continue to match the payload ValidateResult(netBlob); // ensure we can deserialise NET Fx serialised data and continue to match the payload ValidateResult(ClassicImageListStreamer); void ValidateResult(string blob) { using ImageListStreamer result = BinarySerialization.EnsureDeserialize <ImageListStreamer>(blob); using (NativeImageList nativeImageList = result.GetNativeImageList()) { Assert.True(ComCtl32.ImageList.GetIconSize(new HandleRef(this, nativeImageList.Handle), out int x, out int y).IsTrue()); Assert.Equal(16, x); Assert.Equal(16, y); var imageInfo = new ComCtl32.IMAGEINFO(); Assert.True(ComCtl32.ImageList.GetImageInfo(new HandleRef(this, nativeImageList.Handle), 0, ref imageInfo).IsTrue()); Assert.False(imageInfo.hbmImage.IsNull); } } }
public void ListViewGroup_RoundTripAndExchangeWithNet() { var listViewGroup = new ListViewGroup("Header", HorizontalAlignment.Center) { Tag = "Tag", Name = "GroupName", }; listViewGroup.Items.Add(new ListViewItem("Item")); var netBlob = BinarySerialization.ToBase64String(listViewGroup); // ensure we can deserialise NET serialised data and continue to match the payload ValidateResult(netBlob); // ensure we can deserialise NET Fx serialised data and continue to match the payload ValidateResult(ClassicListViewGroup); void ValidateResult(string blob) { ListViewGroup result = BinarySerialization.EnsureDeserialize <ListViewGroup>(blob); Assert.Equal("Header", result.Header); Assert.Equal(HorizontalAlignment.Center, result.HeaderAlignment); Assert.Equal("Tag", result.Tag); Assert.Equal("GroupName", result.Name); var item = Assert.Single(result.Items) as ListViewItem; Assert.NotNull(item); Assert.Equal("Item", item.Text); } }
private void SaveToFile() { WebApiConfiguration.Instance.Server = Server; WebApiConfiguration.Instance.Port = Port; BinarySerialization.WriteToBinaryFile(@".\WebApiConfig.cfg", WebApiConfiguration.Instance); //NotificationMessages.ShowSuccess(message: "Einstellungen wurden erfolgreich gespeichert."); }
private void sendCB_CheckedChanged(object sender, EventArgs e) { int l = 0; FTP f; try { f = BinarySerialization.DeserializeFTP(BinarySerialization.FTP_SETTINGS); l = f.GetHost().Length; } catch (Exception) { } if (l == 0 && sendCB.Checked == true && !isFTPConnectionOpen) { sendCB.Checked = false; MessageBox.Show("You need to set up a valid server connection first!", "MySQLBackUpFTP_ADOPSE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); new FTPConnection(); isFTPConnectionOpen = true; } MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.sendBackup = sendCB.Checked; MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.Save(); if (sendCB.Checked) { deleteFilesCB.Enabled = true; } else { deleteFilesCB.Enabled = false; deleteFilesCB.Checked = false; MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.deleteFiles = deleteFilesCB.Checked; MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.Save(); } }
/// <summary> /// Writes <paramref name="model"/> to this context. /// </summary> /// <param name="baseName">The base name to use for asset files, without extension.</param> /// <param name="model">The <see cref="SCHEMA2"/> to write.</param> public void WriteBinarySchema2(string baseName, SCHEMA2 model) { Guard.NotNullOrEmpty(baseName, nameof(baseName)); Guard.NotNull(model, nameof(model)); model = this._PreprocessSchema2(model, this.ImageWriting == ResourceWriteMode.BufferView, true); Guard.NotNull(model, nameof(model)); var ex = BinarySerialization.IsBinaryCompatible(model); if (ex != null) { throw ex; } model._PrepareBuffersForInternalWriting(); model._PrepareImagesForWriting(this, baseName, ResourceWriteMode.Embedded); _ValidateBeforeWriting(model); using (var m = new MemoryStream()) { using (var w = new BinaryWriter(m)) { BinarySerialization.WriteBinaryModel(w, model); } WriteAllBytesToEnd($"{baseName}.glb", m.ToArraySegment()); } model._AfterWriting(); }
private void btnSaveChar_Click(object sender, EventArgs e) { if (MessageBox.Show("Do you want to save this character?", "Save Character", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { BinarySerialization.WriteToBinaryFile <Character>(@"C:\Users\Tau\Desktop\CompSci\Visual Studio Projects\character.bin", newChar); } }
/// <summary> /// Reads from the binary stream and returns the next object. /// </summary> /// <remarks> /// The type is given as a hint to the serializer to avoid writing root type information. /// </remarks> /// <param name="type">The root type.</param> /// <returns>The deserialized object value.</returns> public object ReadObject(Type type) { var parameters = m_Params; parameters.SerializedType = type; return(BinarySerialization.FromBinary <object>(m_Stream, parameters)); }
private void Exit() { if (operations != 0) { MessageBox.Show("Some operations are still in progress. Please wait.", "MySQLBackUpFTP_ADOPSE", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { ArrayList databases = BinarySerialization.DeserializeArrayList(BinarySerialization.DATABASES_ARRAYLIST); if (databases != null) { for (int i = 0; i < myDatabasesCLB.Items.Count; i++) { for (int j = 0; j < databases.Count; j++) { Database database = (Database)databases[j]; if (myDatabasesCLB.Items[i].Equals(database.GetAlias())) { database.SetWillDoBackup(myDatabasesCLB.GetItemChecked(i)); databases[j] = database; break; } } } BinarySerialization.Serialize(databases, BinarySerialization.DATABASES_ARRAYLIST); } Application.ExitThread(); } }
private void LoadWebApiConfigurationFromFile() { WebApiConfiguration webApiConfigurationFile = BinarySerialization.ReadFromBinaryFile <WebApiConfiguration>(@".\WebApiConfig.cfg"); WebApiConfiguration.Instance.Server = webApiConfigurationFile.Server; WebApiConfiguration.Instance.Port = webApiConfigurationFile.Port; }
private unsafe VkPipelineShaderStageCreateInfo[] CreateShaderStages(PipelineStateDescription pipelineStateDescription, out Dictionary <int, string> inputAttributeNames) { var stages = pipelineStateDescription.EffectBytecode.Stages; var nativeStages = new VkPipelineShaderStageCreateInfo[stages.Length]; inputAttributeNames = null; for (int i = 0; i < stages.Length; i++) { var shaderBytecode = BinarySerialization.Read <ShaderInputBytecode>(stages[i].Data); if (stages[i].Stage == ShaderStage.Vertex) inputAttributeNames = shaderBytecode.InputAttributeNames; fixed(byte *entryPointPointer = &defaultEntryPoint[0]) { // Create stage nativeStages[i] = new VkPipelineShaderStageCreateInfo { sType = VkStructureType.PipelineShaderStageCreateInfo, stage = VulkanConvertExtensions.Convert(stages[i].Stage), pName = entryPointPointer, }; vkCreateShaderModule(GraphicsDevice.NativeDevice, shaderBytecode.Data, null, out nativeStages[i].module); } } ; return(nativeStages); }
public void AxHostState_RoundTripAndExchangeWithNet() { string coreBlob; using (var stream = new MemoryStream(256)) { var bytes = Encoding.UTF8.GetBytes("abc"); using (var writer = new BinaryWriter(stream)) { writer.Write(bytes.Length); writer.Write(bytes); stream.Seek(0, SeekOrigin.Begin); var state = new AxHost.State(stream, 1, true, "licenseKey"); coreBlob = BinarySerialization.ToBase64String(state); } } Assert.Equal(ClassicAxHostState, coreBlob); var result = BinarySerialization.EnsureDeserialize <AxHost.State>(coreBlob); Assert.Null(result.GetPropBag()); Assert.Equal(1, result.Type); Assert.True(result._GetManualUpdate()); Assert.Equal("licenseKey", result._GetLicenseKey()); var streamOut = result.GetStream() as Interop.Ole32.GPStream; Assert.NotNull(streamOut); Stream bufferStream = streamOut.GetDataStream(); byte[] buffer = new byte[3]; bufferStream.Read(buffer, 0, buffer.Length); Assert.Equal("abc", Encoding.UTF8.GetString(buffer)); }
public void TreeNodeAndPropertyBag_RoundTripAndExchangeWithNet() { var children = new TreeNode[] { new TreeNode("node2"), new TreeNode("node3") }; TreeNode treeNodeIn = new TreeNode("node1", 1, 2, children) { ToolTipText = "tool tip text", Name = "node1", SelectedImageKey = "key", Checked = true, BackColor = Color.Yellow, // Colors and Font are serialized into the property bag. ForeColor = Color.Green, NodeFont = new Font(FontFamily.GenericSansSerif, 9f) }; var coreBlob = BinarySerialization.ToBase64String(treeNodeIn); Assert.Equal(ClassicTreeNode, coreBlob); var result = BinarySerialization.EnsureDeserialize <TreeNode>(coreBlob); Assert.Equal("node1", result.Text); Assert.Equal(-1, result.ImageIndex); // No image list Assert.Equal("key", result.SelectedImageKey); Assert.Equal(2, result.childCount); Assert.Equal("node2", result.FirstNode.Text); Assert.Equal("node3", result.LastNode.Text); Assert.Equal("tool tip text", result.ToolTipText); Assert.Equal("node1", result.Name); Assert.True(result.Checked); Assert.Equal(Color.Yellow, result.BackColor); Assert.Equal(Color.Green, result.ForeColor); Assert.Equal(FontFamily.GenericSansSerif.Name, result.NodeFont.FontFamily.Name); }
/// <summary> /// Enviar un objeto al cliente /// </summary> /// <param name="s">Socket del cliente</param> /// <param name="o">Objeto para enviar</param> private void Send(Socket s, object o) //Recibir y enviar informacion { byte[] buffer = new byte[1024]; //enviar un paquete de cierto tamaño, en este caso puse el 1024 bytes (se puede modificar) byte[] obj = BinarySerialization.Serializate(o); Array.Copy(obj, buffer, obj.Length); s.Send(buffer); }
public void ListViewSubItemAndSubItemStyle_RoundTripAndExchangeWithNet() { string coreBlob; using (var font = new Font(FontFamily.GenericSansSerif, 9f)) { var listViewSubItem = new ListViewSubItem( new ListViewItem(), "SubItem1", foreColor: Color.White, backColor: Color.Black, font) { Tag = "UserData" }; coreBlob = BinarySerialization.ToBase64String(listViewSubItem); } Assert.Equal(ClassicListViewSubItem, coreBlob); var result = BinarySerialization.EnsureDeserialize <ListViewSubItem>(coreBlob); Assert.Equal("SubItem1", result.Text); Assert.True(result.CustomStyle); Assert.True(result.CustomForeColor); Assert.True(result.CustomBackColor); Assert.True(result.CustomFont); Assert.Equal(Color.White, result.ForeColor); Assert.Equal(Color.Black, result.BackColor); Assert.Equal(FontFamily.GenericSansSerif.Name, result.Font.FontFamily.Name); Assert.Null(result.Tag); // UserData is wiped on deserialization }
/// <summary> /// Writes the given boxed object to the binary stream. /// </summary> /// <remarks> /// Any <see cref="UnityEngine.Object"/> references are added to the object table and can be retrieved by calling <see cref="GetUnityObjects"/>. /// </remarks> /// <param name="obj">The object to serialize.</param> public void WriteObject(object obj) { var parameters = m_Params; parameters.SerializedType = obj?.GetType(); BinarySerialization.ToBinary(m_Stream, obj, parameters); }
public PhysicsDebugEffect(GraphicsDevice graphicsDevice) : base(graphicsDevice, bytecode ?? (bytecode = BinarySerialization.Read <EffectBytecode>(binaryBytecode))) { Color = new Color4(1.0f); WorldViewProj = Matrix.Identity; UseUv = true; }
public void TrainNetwork(List <float> result) { for (var i = 0; i < 10; i++) { for (var j = 0; j < result.Count; j++) { if (float.IsNaN(OutputLayer[j].GetValue())) { MessageBox.Show("Undefinierter Wert"); break; } OutputLayer[j].Err += Neuron.Neuron.SigmoidDerivate(OutputLayer[j].GetValue()) * (result[j] - OutputLayer[j].GetValue()); OutputLayer[j].AdjustWeights(); } foreach (var hidden in HiddenLayer) { if (float.IsNaN(hidden.GetValue())) { MessageBox.Show("Undefinierter Wert"); break; } var test1 = Neuron.Neuron.SigmoidDerivate(hidden.GetValue()); foreach (var output in OutputLayer) { hidden.Err += test1 * output.Err * output.Connections[output.Connections.FindIndex(p => p.EntNeur == hidden)].Wei; } hidden.AdjustWeights(); } } Invalidate(); BinarySerialization.WriteToBinaryFile("C:\\dev\\Projects\\Tests\\SentenceSplitterTest\\SentenceSplitterWithForms\\Store\\NetStore.bin", this); }
private bool ValidateUserToken(ResponseModel response, byte[] userToken, out string userName) { userName = null; var user = BinarySerialization.ReadFromBytes <TokenRequestModel>(userToken); var userlist = UserLoginState.FindAllByToken(user.Token); if (userlist.Count == 0) { response.Status = -2; response.Message = "用户未登录"; return(false); } if (userlist[0].ExpireDate < DateTime.Now) { response.Status = -3; response.Message = "用户登录已过期,请重新登录"; userlist[0].Delete(); return(false); } userName = userlist[0].UserName; if (userlist.Count > 1) { userlist.RemoveAt(0); userlist.Delete(); } return(true); }
public void RecieveAction(int lockStepTurn, string playerID, byte[] actionAsBytes) { //log.Debug ("Recieved Player " + playerID + "'s action for turn " + lockStepTurn + " on turn " + LockStepTurnID); IAction action = BinarySerialization.DeserializeObject <IAction>(actionAsBytes); if (action == null) { log.Debug("Sending action failed"); //TODO: Error handle invalid actions recieve } else { pendingActions.AddAction(action, Convert.ToInt32(playerID), LockStepTurnID, lockStepTurn); //send confirmation if (Network.isServer) { //we don't need an rpc call if we are the server ConfirmActionServer(lockStepTurn, Network.player.ToString(), playerID); } else { nv.RPC("ConfirmActionServer", RPCMode.Server, lockStepTurn, Network.player.ToString(), playerID); } } }
private void Awake() { //persistent singleton if (instance == null) { instance = this; DontDestroyOnLoad(this); } else { if (this != instance) { Destroy(this.gameObject); } } if (BinarySerialization.LoadFromPlayerPrefs(SavingKeysContainer.SAVE1_ID) == null) { BinarySerialization.SaveToPlayerPrefs(SavingKeysContainer.SAVE1_ID, false); } if (BinarySerialization.LoadFromPlayerPrefs(SavingKeysContainer.SAVE2_ID) == null) { BinarySerialization.SaveToPlayerPrefs(SavingKeysContainer.SAVE2_ID, false); } if (BinarySerialization.LoadFromPlayerPrefs(SavingKeysContainer.SAVE3_ID) == null) { BinarySerialization.SaveToPlayerPrefs(SavingKeysContainer.SAVE3_ID, false); } }
public void Serialize(Stream stream, BinarySerialization.Endianness endianness, BinarySerializationContext context) { var writer = new BinaryWriter(stream); var value = Value; do { var lower7Bits = (byte) (value & 0x7f); value >>= 7; if (value > 0) lower7Bits |= 128; writer.Write(lower7Bits); } while (value > 0); }
public void Deserialize(Stream stream, BinarySerialization.Endianness endianness, BinarySerializationContext context) { var reader = new BinaryReader(stream); bool more = true; int shift = 0; Value = 0; while (more) { int b = reader.ReadByte(); if (b == -1) throw new InvalidOperationException("Reached end of stream before end of varuint."); var lower7Bits = (byte)b; more = (lower7Bits & 128) != 0; Value |= (uint)((lower7Bits & 0x7f) << shift); shift += 7; } }
public void Deserialize(Stream stream, BinarySerialization.Endianness endianness, BinarySerializationContext serializationContext) { }
/// <summary> /// 加载Cookie /// </summary> /// <returns>返回加载的Cookie</returns> public static CookieContainer LoadCookie() { BinarySerialization<CookieContainer> bs = new BinarySerialization<CookieContainer>(cookie); cookie = bs.DeSerialization("cookie.dat"); if (cookie == null) cookie = new CookieContainer(); return cookie; }
/// <summary> /// 保存Cookie /// </summary> /// <returns>返回是否正确保存Cookie结果</returns> public static bool SaveCookie() { BinarySerialization<CookieContainer> bs = new BinarySerialization<CookieContainer>(cookie); return bs.Serialization("cookie.dat"); }
public void Serialize(Stream stream, BinarySerialization.Endianness endianness, BinarySerializationContext serializationContext) { // TODO check context }