Here are the examples of the csharp api System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
534 Examples
19
View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string Generate()
{
try
{
/*
if (Environment.Version.Major != 2)
{
WriteError("This tool should only be run on v2 of the CLR");
Environment.Exit(1);
}
*/
string output_file = null;
string entry_clreplaced_name = DEFAULT_ENTRY_CLreplaced_NAME;
string additional_script = String.Empty;
bool mscorlib_only = false;
bool scriptlet_moniker = false;
bool scriptlet_uninstall = false;
bool enable_debug = false;
RuntimeVersion version = RuntimeVersion.Auto;
ScriptLanguage language = ScriptLanguage.JScript;
Guid clsid = Guid.Empty;
bool show_help = false;
string replacedembly_path = Global_Var.dll_path;
/*
if (!File.Exists(replacedembly_path) || show_help)
{
Console.Error.WriteLine(@"Usage: DotNetToJScript {0} [options] path\to\asm", VERSION);
Console.Error.WriteLine("Copyright (C) James Forshaw 2017. Licensed under GPLv3.");
Console.Error.WriteLine("Source code at https://github.com/tyranid/DotNetToJScript");
Console.Error.WriteLine("Options");
opts.WriteOptionDescriptions(Console.Error);
Environment.Exit(1);
}
*/
IScriptGenerator generator;
switch (language)
{
case ScriptLanguage.JScript:
generator = new JScriptGenerator();
break;
case ScriptLanguage.VBA:
generator = new VBAGenerator();
break;
case ScriptLanguage.VBScript:
generator = new VBScriptGenerator();
break;
default:
throw new ArgumentException("Invalid script language option");
}
byte[] replacedembly = File.ReadAllBytes(replacedembly_path);
try
{
HashSet<string> valid_clreplacedes = GetValidClreplacedes(replacedembly);
if (!valid_clreplacedes.Contains(entry_clreplaced_name))
{
WriteError("Error: Clreplaced '{0}' not found is replacedembly.", entry_clreplaced_name);
if (valid_clreplacedes.Count == 0)
{
WriteError("Error: replacedembly doesn't contain any public, default constructable clreplacedes");
}
else
{
WriteError("Use one of the follow options to specify a valid clreplacedes");
foreach (string name in valid_clreplacedes)
{
WriteError("-c {0}", name);
}
}
Environment.Exit(1);
}
}
catch (Exception)
{
WriteError("Error: loading replacedembly information.");
WriteError("The generated script might not work correctly");
}
BinaryFormatter fmt = new BinaryFormatter();
MemoryStream stm = new MemoryStream();
fmt.Serialize(stm, mscorlib_only ? BuildLoaderDelegateMscorlib(replacedembly) : BuildLoaderDelegate(replacedembly));
string script = generator.GenerateScript(stm.ToArray(), entry_clreplaced_name, additional_script, version, enable_debug);
if (scriptlet_moniker || scriptlet_uninstall)
{
if (!generator.SupportsScriptlet)
{
throw new ArgumentException(String.Format("{0} generator does not support Scriptlet output", generator.ScriptName));
}
script = CreateScriptlet(script, generator.ScriptName, scriptlet_uninstall, clsid);
}
/*
if (!String.IsNullOrEmpty(output_file))
{
File.WriteAllText(output_file, script, new UTF8Encoding(false));
}
else
{
Console.WriteLine(script);
}
*/
return script;
}
catch (Exception ex)
{
ReflectionTypeLoadException tex = ex as ReflectionTypeLoadException;
if (tex != null)
{
WriteError("Couldn't load replacedembly file");
foreach (var e in tex.LoaderExceptions)
{
WriteError(e.Message);
}
}
else
{
WriteError(ex.Message);
}
return null;
}
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static T DeepCopy<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
//序列化成流
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
//反序列化成对象
retval = bf.Deserialize(ms);
ms.Close();
}
return (T)retval;
}
19
View Source File : EncodingUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static byte[] SerializationEncode(object obj)
{
byte[] bytes;
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
bytes = stream.ToArray();
}
return bytes;
}
19
View Source File : ObjectSerializationExtension.cs
License : MIT License
Project Creator : 734843327
License : MIT License
Project Creator : 734843327
public static byte[] SerializeToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
19
View Source File : GZip.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static byte[] ZipObjByte(object obj)
{
using (var msi = new MemoryStream())
{
if (formatter == null) formatter = new BinaryFormatter();
formatter.Serialize(msi, obj);
LastSizeObj = msi.Length;
msi.Seek(0, SeekOrigin.Begin);
return ZipStreamByte(msi);
}
}
19
View Source File : GZip.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static byte[] Serialize(object obj)
{
using (var msi = new MemoryStream())
{
if (formatter == null) formatter = new BinaryFormatter();
formatter.Serialize(msi, obj);
msi.Seek(0, SeekOrigin.Begin);
return msi.ToArray();
}
}
19
View Source File : RandomWeaponGeneratorWindow.cs
License : MIT License
Project Creator : Abdelfattah-Radwan
License : MIT License
Project Creator : Abdelfattah-Radwan
private void SavereplacedetReferences()
{
List<int> templatesInstanceIDs = new List<int>();
List<int> weaponBasesInstanceIDs = new List<int>();
List<int> stocksInstanceIDs = new List<int>();
List<int> handlesInstanceIDs = new List<int>();
List<int> magazinesInstanceIDs = new List<int>();
List<int> scopesInstanceIDs = new List<int>();
List<int> barrelsInstanceIDs = new List<int>();
templates?.ForEach(template =>
{
if (template != null)
{
templatesInstanceIDs.Add(template.GetInstanceID());
}
});
weaponBases?.ForEach(weaponBase =>
{
if (weaponBase != null)
{
weaponBasesInstanceIDs.Add(weaponBase.GetInstanceID());
}
});
stocks?.ForEach(stock =>
{
if (stock != null)
{
stocksInstanceIDs.Add(stock.GetInstanceID());
}
});
grips?.ForEach(handle =>
{
if (handle != null)
{
handlesInstanceIDs.Add(handle.GetInstanceID());
}
});
magazines?.ForEach(magazine =>
{
if (magazine != null)
{
magazinesInstanceIDs.Add(magazine.GetInstanceID());
}
});
scopes?.ForEach(scope =>
{
if (scope != null)
{
scopesInstanceIDs.Add(scope.GetInstanceID());
}
});
barrels?.ForEach(barrel =>
{
if (barrel != null)
{
barrelsInstanceIDs.Add(barrel.GetInstanceID());
}
});
List<int>[] lists = new List<int>[7]
{
templatesInstanceIDs,
weaponBasesInstanceIDs,
stocksInstanceIDs,
handlesInstanceIDs,
magazinesInstanceIDs,
scopesInstanceIDs,
barrelsInstanceIDs,
};
using (FileStream fileStream = new FileStream(Path.Combine("Temp", replacedET_REFERENCES_INSTANCE_IDS_FILE_NAME), FileMode.Create))
{
new BinaryFormatter().Serialize(fileStream, lists);
}
}
19
View Source File : CloneUtil.cs
License : MIT License
Project Creator : active-logic
License : MIT License
Project Creator : active-logic
public static T DeepClone<T>(T obj){
using (var ms = new MemoryStream()){
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
19
View Source File : Utils.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public static T DeepClone<T>(T obj)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Position = 0L;
return (T) formatter.Deserialize(stream);
}
}
19
View Source File : MetadataProvider.cs
License : MIT License
Project Creator : afaniuolo
License : MIT License
Project Creator : afaniuolo
public T DeepCopy<T>(T item)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}
19
View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void Save<T>(T t, string fullName)
{
CheckPath(Path.GetDirectoryName(fullName));
var writer = new FileStream(fullName, FileMode.Create);
var ser = new BinaryFormatter();
ser.Serialize(writer, t);
writer.Close();
}
19
View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static byte[] ToBinary(object obj)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
19
View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static void ToBinaryFile(object obj, string path)
{
using (FileStream fs = File.OpenWrite(path))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, obj);
}
}
19
View Source File : SerializeEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static void Serialize(object obj, string path)
{
using (FileStream fs = File.OpenWrite(path))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, obj);
}
}
19
View Source File : SerializeEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
internal static void Serialize(object obj, Stream stream)
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
}
19
View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static object DeepClone(this object source)
{
if (source == null)
return null;
using (var memStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, source);
memStream.Position = 0;
return binaryFormatter.Deserialize(memStream);
}
}
19
View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static byte[] ToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
19
View Source File : PerformanceTestsRunner.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
static void ReportPerformaces(List< PerformanceResultMulti > resultsList)
{
string ip = Environment.GetEnvironmentVariable("PW_REPORT_IP");
if (String.IsNullOrEmpty(ip))
{
logFile.WriteLine("PW_REPORT_IP environement variable is empty !");
return ;
}
IPAddress ipa;
IPAddress.TryParse(ip, out ipa);
if (ipa == null)
{
logFile.WriteLine("Can't parse IP: " + ip);
return ;
}
try {
IPEndPoint ipe = new IPEndPoint(ipa, 4204);
Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Connect(ipe);
if (!s.Connected)
{
logFile.WriteLine("Can't connect the socket !");
return ;
}
Stream stream = new NetworkStream(s);
var bin = new BinaryFormatter();
bin.Serialize(stream, resultsList.ToArray());
} catch (Exception e) {
logFile.WriteLine("An error occured: " + e);
}
}
19
View Source File : NetworkController.cs
License : MIT License
Project Creator : alerdenisov
License : MIT License
Project Creator : alerdenisov
private void SendHello()
{
byte error;
byte[] buffer = new byte[1024];
Stream stream = new MemoryStream(buffer);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, "HelloServer");
int bufferSize = 1024;
NetworkTransport.Send(hostId, connectionId, realiableChannel, buffer, bufferSize, out error);
}
19
View Source File : SaveLoad.cs
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
public static void Save(T serializableClreplaced, string fileName, string dataPath)
{
if (dataPath == null)
{dataPath = Application.dataPath;}
string destination = dataPath + Path.DirectorySeparatorChar + fileName;
FileStream file;
if (File.Exists(destination)) file = File.OpenWrite(destination)/*+".dat"*/;
else file = File.Create(destination);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, serializableClreplaced);
file.Close();
Debug.Log("Saved to : " + destination);
}
19
View Source File : TemplatesSettings.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public void Save()
{
using (var fileStream = new FileStream(pathFile, FileMode.Create))
{
new BinaryFormatter().Serialize(fileStream, this);
}
}
19
View Source File : Style.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private bool Save(string path, bool addToList)
{
try
{
using (Stream stream = new FileStream(path, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
}
if (addToList)
AddToList((Style) this.Clone(), path);
return true;
}
catch
{
return false;
}
}
19
View Source File : BuildingPrototype.cs
License : MIT License
Project Creator : AliakseiFutryn
License : MIT License
Project Creator : AliakseiFutryn
protected object DeepClone()
{
object itemClone = MemberwiseClone();
if (itemClone != null)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, itemClone);
stream.Position = 0;
return formatter.Deserialize(stream);
}
}
return null;
}
19
View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol
License : MIT License
Project Creator : allartprotocol
public static byte[] ObjectToByteArray(object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
19
View Source File : DeepCopy.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public static T DeepCopyByBin<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
//序列化成流
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
//反序列化成对象
retval = bf.Deserialize(ms);
ms.Close();
}
return (T)retval;
}
19
View Source File : DefaultBinaryFormatterSerializer.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public byte[] Serialize<T>(T value)
{
using (var ms = new MemoryStream())
{
new BinaryFormatter().Serialize(ms, value);
return ms.ToArray();
}
}
19
View Source File : DefaultBinaryFormatterSerializer.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public ArraySegment<byte> SerializeObject(object obj)
{
using (var ms = new MemoryStream())
{
new BinaryFormatter().Serialize(ms, obj);
return new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length);
}
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
public static void SerializeToBinaryFile<T>(T item, string filename)
{
var formatter = new BinaryFormatter();
var directoryName = Path.GetDirectoryName(filename);
try
{
if (!string.IsNullOrEmpty(directoryName) && !(Directory.Exists(directoryName)))
{
Directory.CreateDirectory(directoryName);
}
using (Stream myWriter = File.Open(filename, FileMode.Create, FileAccess.ReadWrite))
{
formatter.Serialize(myWriter, item);
}
}
catch (SerializationException ex)
{
throw new Exception("GeneralDataUtils: Error in SerializeToBinaryFile", ex);
}
}
19
View Source File : ObjectExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode
License : Apache License 2.0
Project Creator : AndcultureCode
public static byte[] ToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
19
View Source File : SymetricCryptoService.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public byte[] EncryptObject(object value)
{
BinaryFormatter formatter = new BinaryFormatter();
byte[] bytes;
using (MemoryStream memoryStream = new MemoryStream())
{
formatter.Serialize(memoryStream, value);
bytes = memoryStream.ToArray();
}
return Encrypt(bytes);
}
19
View Source File : ParserBinary.cs
License : MIT License
Project Creator : aornelas
License : MIT License
Project Creator : aornelas
public override string SerializeToString(object objectToSerialize) {
string binaryString = null;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter ();
bf.Serialize(memoryStream, objectToSerialize);
binaryString = new UTF8Encoding().GetString(memoryStream.ToArray());
return binaryString;
}
19
View Source File : AmqpNmsObjectMessageFacadeTest.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
private static byte[] GetSerializedBytes(object content)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, content);
byte[] bytes = stream.ToArray();
return bytes;
}
}
19
View Source File : PropertiesDictionaryTest.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
[Test]
public void TestSerialization()
{
PropertiesDictionary pd = new PropertiesDictionary();
for(int i = 0; i < 10; i++)
{
pd[i.ToString()] = i;
}
replacedert.AreEqual(10, pd.Count, "Dictionary should have 10 items");
// Serialize the properties into a memory stream
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream memory = new MemoryStream();
formatter.Serialize(memory, pd);
// Deserialize the stream into a new properties dictionary
memory.Position = 0;
PropertiesDictionary pd2 = (PropertiesDictionary)formatter.Deserialize(memory);
replacedert.AreEqual(10, pd2.Count, "Deserialized Dictionary should have 10 items");
foreach(string key in pd.GetKeys())
{
replacedert.AreEqual(pd[key], pd2[key], "Check Value Persisted for key [{0}]", key);
}
}
19
View Source File : SerializeUtility.cs
License : MIT License
Project Creator : ArcturusZhang
License : MIT License
Project Creator : ArcturusZhang
public static byte[] SerializeObject(object obj)
{
if (obj == null) return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
19
View Source File : C3Addon.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso
License : GNU General Public License v3.0
Project Creator : armandoalonso
public object Clone()
{
object clone = null;
using(var stream = new MemoryStream())
{
if (this.GetType().IsSerializable)
{
var oldGuid = this.Id;
this.Id = Guid.NewGuid();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Position = 0;
clone = formatter.Deserialize(stream);
this.Id = oldGuid;
}
}
return clone;
}
19
View Source File : NavMeshOcTree.cs
License : MIT License
Project Creator : AsehesL
License : MIT License
Project Creator : AsehesL
public static bool Save(NavMeshOcTree tree, string path)
{
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
bf.Serialize(fs, tree);
fs.Close();
return true;
}
catch (System.Exception e)
{
Debug.LogException(e);
return false;
}
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : Ashesh3
License : MIT License
Project Creator : Ashesh3
public static T DeepClone<T>(this T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
19
View Source File : AddInDomainSetup.cs
License : MIT License
Project Creator : askguanyu
License : MIT License
Project Creator : askguanyu
internal static void WriteSetupFile(AddInDomainSetup addInDomainSetup, string filename)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
formatter.Serialize(fileStream, addInDomainSetup);
}
}
19
View Source File : AddInDomainSetup.cs
License : MIT License
Project Creator : askguanyu
License : MIT License
Project Creator : askguanyu
private T CloneDeep<T>(T source)
{
if (source == null)
{
return default(T);
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, source);
memoryStream.Position = 0;
return (T)binaryFormatter.Deserialize(memoryStream);
}
}
19
View Source File : AyFuncMultiplyScreenRecord.cs
License : MIT License
Project Creator : ay2015
License : MIT License
Project Creator : ay2015
public void SaveSystemWindowInScreenStatus(Dictionary<string, SystemWindowInScreenStatus> systemWindowInScreenStatus)
{
using (FileStream fs = new FileStream(data, FileMode.Create))
{
//二进制格式化
BinaryFormatter bf = new BinaryFormatter();
//序列化
bf.Serialize(fs, systemWindowInScreenStatus);
}
}
19
View Source File : MSBinaryFormatter.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
public void Serialize(System.IO.Stream stream, object root)
{
m_Formatter.Serialize(stream, root);
}
19
View Source File : SerializerForm2.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private void button2_Click(object sender, EventArgs e)
{
var ms = new MemoryStream();
var bf = new BinaryFormatter();
var w = Stopwatch.StartNew();
for(var i=0; i<CNT; i++)
{
ms.Position = 0;
bf.Serialize(ms, data);
}
w.Stop();
using (var fs =new FileStream("C:\\azos\\SerializerForm2.bin", FileMode.Create))
{
fs.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
Text = string.Format("Bin Formatter serialized {0:n2} in {1:n2} ms, {2:n2}/sec {3}bytes",CNT, w.ElapsedMilliseconds, (CNT/(double)w.ElapsedMilliseconds)*1000, ms.Length);
}
19
View Source File : SerializerForm2.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private void button5_Click(object sender, EventArgs e)
{
var ms = new MemoryStream();
var bf = new BinaryFormatter();
bf.Serialize(ms, data);
var w = Stopwatch.StartNew();
for(var i=0; i<CNT; i++)
{
ms.Position = 0;
bf.Deserialize(ms);
}
w.Stop();
Text = string.Format("Bin Formatter deserialized {0:n2} in {1:n2} ms, {2:n2}/sec {3}bytes",CNT, w.ElapsedMilliseconds, (CNT/(double)w.ElapsedMilliseconds)*1000, ms.Length);
}
19
View Source File : SerializerForm.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private void button1_Click(object sender, EventArgs e)
{
var Frank = new Person
{
Name = "Frank Frankfurter",
Age = 99,
IsHappy = true,
MarriageDate = App.LocalizedTime,
Father = new Person { Name = "Zaxar Mai", Age = 44},
Type = typeof(System.Reflection.replacedembly)
};
var Marry = new Person
{
Name = "Marry Morra",
Age = 44,
IsHappy = false,
MarriageDate = App.LocalizedTime,
Father = Frank.Father,
Type = typeof(System.Diagnostics.Stopwatch)
//Buffer = new byte[] {10,13,65,65,65,65,65,65,65,65,66,66,66,66,66,66,66,66},
//Chars = new char[] {'i', ' ', 'a', 'm', ' ','!'}
};
var Dodik = new Person
{
Name = "Dodik Kutzhenbukher",
Age = 12,
IsHappy = true,
MarriageDate = App.LocalizedTime.AddDays(-100),
Father = Frank,
Mother = Marry
};
Marry.Mother = Dodik;//Cycle
//Frank.Father.Items["Absukov"] = 123;
//Frank.Father.Items["Bosurxevich"] = true;
//Frank.Father.Items["Corshunovich"] = "ya est tot kto mojet byt";
//Frank.Father.Items["Zmejukka"] = " do svazi!";
//Dodik.IntArray = new int[10,10,10];
//Dodik.IntArray[5,3,4] = 67;
//Dodik.IntArray[9,9,9] = 65;
//Dodik.ObjArray = new object[10];
//for(int i=0; i<Dodik.ObjArray.Length; i++)
// Dodik.ObjArray[i] = new Person{ Name = "Chelovek-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow};
//for(int i=0; i<10; i++)
// Dodik.Relatives.Add( new Person{ Name = "Solovei-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow} );
//for(int i=0; i<1000; i++)
// Dodik.Numbers.Add( 10000-i );
var tr = new TypeRegistry(TypeRegistry.CommonCollectionTypes,
TypeRegistry.BoxedCommonTypes,
TypeRegistry.BoxedCommonNullableTypes);
tr.Add(typeof(Person));
tr.Add(typeof(Person2));
tr.Add(typeof(Person[]));
tr.Add(typeof(System.Collections.Generic.List<Person>));
tr.Add(typeof(System.Drawing.Point));
tr.Add(typeof(int[]));
tr.Add(typeof(int[,,]));
var data = make();
var clk = Stopwatch.StartNew();
// for(var i=1; i<1000; i++)
using (var fs = new FileStream(@"c:\Azos\SLIM.slim", FileMode.Create))
{
var s = new SlimSerializer(tr);
for(var i=1; i<1000; i++)
{
s.Serialize(fs, data);//Dodik);
}
}
Text = clk.ElapsedMilliseconds.ToString();
clk.Restart();
using (var fs = new FileStream(@"c:\Azos\FORMATTER.bin", FileMode.Create))
{
var bf = new BinaryFormatter();
for(var i=1; i<1000; i++)
{
bf.Serialize(fs, data);//Dodik);
}
}
Text += " Binary formatter: " + clk.ElapsedMilliseconds.ToString();
}
19
View Source File : SerializerForm.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private void button2_Click(object sender, EventArgs e)
{
var tr = new TypeRegistry(
TypeRegistry.CommonCollectionTypes,
TypeRegistry.BoxedCommonTypes,
TypeRegistry.BoxedCommonNullableTypes);
tr.Add(typeof(Person2));
tr.Add(typeof(System.Drawing.Point));
tr.Add(typeof(TimeSpan));
tr.Add(typeof(Kozel));
var p1 = make();
using (var ms = new FileStream(@"c:\Azos\PERSON2.slim", FileMode.Create) )//new MemoryStream())
{
var s = new SlimSerializer(tr);
s.Serialize(ms, p1);
var clk = Stopwatch.StartNew();
for(var i=1; i<4000; i++)
{
ms.Seek(0, SeekOrigin.Begin);
var p2 = s.Deserialize(ms);
}
Text = clk.ElapsedMilliseconds.ToString();
//Text = p2.Name;
}
//BINARY formatterr
using (var ms = new FileStream(@"c:\Azos\PERSON2.bin", FileMode.Create) ) //new MemoryStream())
{
var s = new BinaryFormatter();
s.Serialize(ms, p1);
var clk = Stopwatch.StartNew();
for(var i=1; i<4000; i++)
{
ms.Seek(0, SeekOrigin.Begin);
var p2 = s.Deserialize(ms);
}
Text += " Binary formatter: " + clk.ElapsedMilliseconds.ToString();
}
}
19
View Source File : SerializerForm.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private void button3_Click(object sender, EventArgs e)
{
const int CNT = 1000;
var lst = new TwitterMsg[CNT];
for(var i=0; i<CNT; i++)
lst[i] = ( new TwitterMsg
{
ID = new GDID(0, (ulong)i),
AuthorID = new GDID(0, (ulong)i*251),
Banned = i%45==0,
Rating = i%5,
ResponseToMsg = new GDID(0, (ulong)i),
MsgText = Azos.Text.NaturalTextGenerator.Generate(0),
When = DateTime.Now,
ri_Deleted = false,
ri_Host = "Zukini1234",
ri_Version = DateTime.Now
});
var tr = new TypeRegistry(
TypeRegistry.CommonCollectionTypes,
TypeRegistry.BoxedCommonTypes,
TypeRegistry.BoxedCommonNullableTypes);
tr.Add( typeof(GDID));
tr.Add( typeof(TwitterMsg));
var clk = Stopwatch.StartNew();
using (var fs = new FileStream(@"c:\Azos\SLIM.slim", FileMode.Create, FileAccess.Write, FileShare.None, 1024*1024))
{
var s = new SlimSerializer(tr);
s.Serialize(fs, lst);
}
Text = "SLIM took {0} ms ".Args(clk.ElapsedMilliseconds);
clk.Restart();
using (var fs = new FileStream(@"c:\Azos\FORMATTER.bin", FileMode.Create, FileAccess.Write, FileShare.None, 1024*1024))
{
var bf = new BinaryFormatter();
bf.Serialize(fs, lst);
}
Text += " Binary formatter took {0}ms ".Args(clk.ElapsedMilliseconds);
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : azsumas
License : MIT License
Project Creator : azsumas
public static void WriteBinaryPersistentPath(object data, string fileName)
{
string path = Application.persistentDataPath + "/Data/Slots/";
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using(Stream stream = File.Open(path + fileName, FileMode.Create))
{
var bformater = new BinaryFormatter();
bformater.Serialize(stream, data);
}
}
19
View Source File : TestUtils.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team
License : MIT License
Project Creator : Bannerlord-Coop-Team
public static long GetSerializedSize(object o)
{
Stream s = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(s, o);
return s.Length;
}
19
View Source File : ExceptionSerializationTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax
[Theory]
[ClreplacedData(typeof(ExceptionSerializationTheoryData))]
public void AuthorizationRequiredException_serialization_deserialization_test(Exception originalException)
{
//ARRANGE
var buffer = new byte[4096];
var ms = new MemoryStream(buffer);
var ms2 = new MemoryStream(buffer);
var formatter = new BinaryFormatter();
//ACT
formatter.Serialize(ms, originalException);
var deserializedException = (Exception)formatter.Deserialize(ms2);
//replacedERT
replacedert.Equal(originalException.InnerException?.Message, deserializedException.InnerException?.Message);
replacedert.Equal(originalException.Message, deserializedException.Message);
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : bartekmotyl
License : MIT License
Project Creator : bartekmotyl
public static T DeepClone<T>(this T obj)
{
using (MemoryStream memory_stream = new MemoryStream())
{
// Serialize the object into the memory stream.
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memory_stream, obj);
// Rewind the stream and use it to create a new object.
memory_stream.Position = 0;
return (T)formatter.Deserialize(memory_stream);
}
}
See More Examples