public Serialize ( Stream serializationStream, object graph ) : void | ||
serializationStream | Stream | |
graph | object | |
return | void |
public Constants.LoginStatus logon(User user) { Constants.LoginStatus retval = Constants.LoginStatus.STATUS_SERVERNOTREACHED; byte[] message = new byte[Constants.WRITEBUFFSIZE]; byte[] reply; MemoryStream stream = new MemoryStream(message); try { //Serialize data in memory so you can send them as a continuous stream BinaryFormatter serializer = new BinaryFormatter(); NetLib.insertEntropyHeader(serializer, stream); serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGIN); serializer.Serialize(stream, user.ringsInfo[0].ring.ringID); serializer.Serialize(stream, user.ringsInfo[0].userName); serializer.Serialize(stream, user.ringsInfo[0].password); serializer.Serialize(stream, user.node.syncCommunicationPoint); reply = NetLib.communicate(Constants.SERVER2,message, true); stream.Close(); stream = new MemoryStream(reply); NetLib.bypassEntropyHeader(serializer, stream); Constants.MessageTypes replyMsg = (Constants.MessageTypes)serializer.Deserialize(stream); switch(replyMsg) { case Constants.MessageTypes.MSG_OK: ulong sessionID = (ulong)serializer.Deserialize(stream); uint numRings = (uint)serializer.Deserialize(stream); uint ringID; Ring ring; for(uint ringCounter = 0; ringCounter < numRings; ringCounter++) { LordInfo lordInfo = (LordInfo)serializer.Deserialize(stream); ring = RingInfo.findRingByID(user.ringsInfo, lordInfo.ringID); ring.lords = lordInfo.lords; } user.loggedIn = true; retval = Constants.LoginStatus.STATUS_LOGGEDIN; break; case Constants.MessageTypes.MSG_NOTAMEMBER: retval = Constants.LoginStatus.STATUS_NOTAMEMBER; break; case Constants.MessageTypes.MSG_ALREADYSIGNEDIN: retval = Constants.LoginStatus.STATUS_ALREADYSIGNEDIN; break; default: break; } } catch (Exception e) { int x = 2; } return retval; }
public static void ShowStudentInfo(int id, string ip, int port) { Student student = null; TcpClient eClient = new TcpClient(); try { eClient = new TcpClient(ip, port); using (NetworkStream writerStream = eClient.GetStream()) { MSG message = new MSG(); message.stat = STATUS.GET_ACCOUNT_BY_ID; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(writerStream, message); formatter.Serialize(writerStream, id); student = (Student)formatter.Deserialize(writerStream); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { eClient.Close(); } if (student == null) { throw new ArgumentException(string.Format("Студента з id = {0} не iснує", id)); } StudentInfoWindow sw = new StudentInfoWindow(string.Format("{0} {1} {2}", student.Lastname, student.Firstname, student.Patronymic), student.Group, student.Faculty, student.PhoneNumber, student.Email, student.Address, student.AverageMark); sw.ShowDialog(); }
public static void Main() { //Tworzenie Obiektów do serializacji Klasa ob = new Klasa ("ob1", 1); Klasa ob2 = new Klasa ("ob2", 5); Console.WriteLine ("Przed serializacją"); ob.print (); ob2.print (); BinaryFormatter Formater = new BinaryFormatter(); FileStream str = new FileStream ("Serial.bin", FileMode.Create, FileAccess.Write); //Serializowanie do strumienia Formater.Serialize (str, ob); Formater.Serialize (str, ob2); str.Close (); //Deserializacja str = new FileStream ("Serial.bin", FileMode.Open, FileAccess.Read); Klasa w = (Klasa)Formater.Deserialize (str); Klasa w2 = (Klasa)Formater.Deserialize (str); Console.WriteLine ("Po serializacji"); w.print (); w2.print (); Console.ReadKey (); }
public Dictionary<GroupRow, int> InitGroupTable() { _groupsCollection.Clear(); foreach (var faculty in EnumDecoder.StringToFaculties) { try { Configuration config = (App.Current as App).config; using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port)) { using (NetworkStream writerStream = eClient.GetStream()) { MSG message = new MSG(); message.stat = STATUS.GET_GROUP_BY_FACULTY; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(writerStream, message); formatter.Serialize(writerStream, faculty.Value); bool fl = (bool)formatter.Deserialize(writerStream); if (fl) { foreach (var group in (Dictionary<string, int>)formatter.Deserialize(writerStream)) { _groupsCollection.Add(new GroupRow(group.Key, faculty.Key), group.Value); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Помилка", MessageBoxButton.OK, MessageBoxImage.Error); } } return _groupsCollection; }
public async Task Post(string endpoint, object data, NameValueCollection headers) { if (endpoint == "accounts/login") { var cacheFileName = Path.Combine(_cacheDir, "accountslogin_"); if (!File.Exists(cacheFileName)) { await _decorated.Post(endpoint, data, headers); using (var stream = File.OpenWrite(cacheFileName)) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, Cookies); formatter.Serialize(stream, headers); } } else if (headers != null) { foreach (string key in _headers) { headers[key] = _headers[key]; } } } else { Debug.WriteLine("Skip POST to " + endpoint); } }
public void trainSystem(string fileDirectory, string dbFile) { //Eğitim veritabanını oluştur Stream fileStream = new FileStream(dbFile, FileMode.Create, FileAccess.Write); IFormatter formatter = new BinaryFormatter(); //Eğitim dizinindeki bütün bitmap dosyalarını listele string[] filePaths = getFiles(fileDirectory, "*.gif|*.jpg|*.png|*.bmp", SearchOption.AllDirectories); Int32 numOfImages = filePaths.Length; formatter.Serialize(fileStream, numOfImages); //Görüntü sayısını dosyaya yaz Bitmap bm; //Her dosya için 64bin histogram ve dosya isminden oluşan bir nesne oluştur //Oluşturulan nesneyi serileştirerek dosyaya kaydet for (int i=0; i<filePaths.Length; i++) { bm = (Bitmap)Bitmap.FromFile(filePaths[i]); ImageRecord newRecord = new ImageRecord(); newRecord.histogram = generate64binHistogram(bm); newRecord.fileName = filePaths[i]; formatter.Serialize(fileStream,newRecord); progressBar1.Value = i*100/filePaths.Length; } fileStream.Close(); }
public void sendAndReceiveHello(Peer neighbor, Ring ring) { byte[] message = new byte[Constants.WRITEBUFFSIZE]; byte[] reply = new byte[Constants.READBUFFSIZE]; MemoryStream stream; try { User user = User.getInstance(); BinaryFormatter serializer = new BinaryFormatter(); stream = new MemoryStream(message); NetLib.insertEntropyHeader(serializer, stream); RingInfo ringInfo = user.findRingInfo(ring.ringID); serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO); serializer.Serialize(stream, ring.ringID); serializer.Serialize(stream, ringInfo.token); serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE)); reply = NetLib.communicate(neighbor.node.syncCommunicationPoint, message, true); Debug.Assert(reply != null, "Neighbor did not reply to Hello"); BinaryFormatter deserializer = new BinaryFormatter(); stream = new MemoryStream(reply); NetLib.bypassEntropyHeader(deserializer, stream); Constants.MessageTypes replyMsg = (Constants.MessageTypes)deserializer.Deserialize(stream); switch(replyMsg) { case Constants.MessageTypes.MSG_HELLO: uint ringID = (uint)deserializer.Deserialize(stream); if(ringID != ring.ringID) return; ulong token = (ulong)deserializer.Deserialize(stream); Peer peer = (Peer)deserializer.Deserialize(stream); IPEndPoint neighborIPEndPoint = peer.node.syncCommunicationPoint; if(!neighborIPEndPoint.Address.Equals(neighbor.node.syncCommunicationPoint.Address)) //REVISIT: alert security system return; neighbor.node.syncCommunicationPoint = neighborIPEndPoint; neighbor.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint; neighbor.IE = peer.IE; break; case Constants.MessageTypes.MSG_DISCONNECT: neighbor.IE = null; break; default: neighbor.IE = null; break; } } catch (Exception e) { int x = 2; } }
/// <summary> /// Calls method with one parameter and result. Deserializes parameter and serialize result. /// </summary> /// <param name="type">Type containing method</param> /// <param name="methodName">Name of method to call</param> /// <param name="pipeName">Name of pipe to pass parameter and result</param> static void InvokeFunc(Type type, string methodName, string pipeName) { using (var pipe = new NamedPipeClientStream(pipeName)) { pipe.Connect(); var formatter = new BinaryFormatter(); ProcessThreadParams pars; var lengthBytes = new byte[4]; pipe.Read(lengthBytes, 0, 4); var length = BitConverter.ToInt32(lengthBytes, 0); var inmemory = new MemoryStream(length); var buf = new byte[1024]; while (length != 0) { var red = pipe.Read(buf, 0, buf.Length); inmemory.Write(buf, 0, red); length -= red; } inmemory.Position = 0; try { AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { return type.Assembly; }; pars = (ProcessThreadParams)formatter.Deserialize(inmemory); var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null); if (method == null) throw new InvalidOperationException("Method is not found: " + methodName); if (pars.Pipe != null) { var auxPipe = new NamedPipeClientStream(pars.Pipe); auxPipe.Connect(); for (int i = 0; i < pars.Parameters.Length; i++) if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe; } object result = method.Invoke(pars.Target, pars.Parameters); var outmemory = new MemoryStream(); formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result)); outmemory.WriteTo(pipe); } catch (TargetInvocationException e) { formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException)); throw e.InnerException; } catch (Exception e) { formatter.Serialize(pipe, ProcessThreadResult.Exception(e)); throw; } } }
static void Main(string[] args) { Insect i = new Insect("Meadow Brow", 12); Stream sw = File.Create("Insects.bin"); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(sw, i); sw.Close(); ArrayList box = new ArrayList(); box.Add(new Insect("Marsh Fritillarry", 34)); box.Add(new Insect("Speckled Wood", 56)); box.Add(new Insect("Milkweed", 78)); sw = File.Open("Insects.bin", FileMode.Append); bf.Serialize(sw, box); sw.Close(); Stream sr = File.OpenRead("Insects.bin"); Insect j = (Insect)bf.Deserialize(sr); Console.WriteLine(j); ArrayList bag = (ArrayList)bf.Deserialize(sr); sr.Close(); foreach (Insect k in bag) { Console.WriteLine(k); } Console.ReadLine(); }
/// <summary> /// This method is called from the QueryVisualizer to copy the following data to the stream: /// 1. The query expression as string /// 2. SQL query text(s) / parameters /// 3. Connection string /// </summary> /// <param name="query"> The query exression to visualize </param> /// <param name="outgoingData"> The stream used for marshalling to the visualizer </param> /// public static void StreamQueryInfo(DataContext dataContext, IQueryable query, Stream outgoingData) { BinaryFormatter formatter = new BinaryFormatter(); if (dataContext == null) { formatter.Serialize(outgoingData, "None"); formatter.Serialize(outgoingData, "No datacontext provided."); return; } Expression expr = query.Expression; if (expr == null) { formatter.Serialize(outgoingData, "None"); formatter.Serialize(outgoingData, "Expression of the query is empty."); return; } formatter.Serialize(outgoingData, expr.ToString()); try { SqlQueryInfo qi = new SqlQueryInfo(GetFullQueryInfo(dataContext, query)); qi.serialize(outgoingData); } catch (Exception ex) { outgoingData.Position = 0; formatter.Serialize(outgoingData, "None"); formatter.Serialize(outgoingData, string.Format(CultureInfo.CurrentUICulture, "Exception while serializing the query:\r\n{0}", ex.Message)); return; } IDbConnection conn = dataContext.Connection; string connectionString = conn.ConnectionString; //Need to check for |DataDirectory| token in the connection string and replace with absolute path to allow if (connectionString.Contains("|DataDirectory|")) { connectionString = conn.ConnectionString.Replace(@"|DataDirectory|\", AppDomain.CurrentDomain.BaseDirectory); } //the Linq To Sql Query Visualizer to use the same connection string. formatter.Serialize(outgoingData, connectionString); }
public void receiveAndSendHello(RingInfo ringInfo, Peer peer, Neighbor neighbor, BinaryWriter writer) { if(!peer.node.syncCommunicationPoint.Address.Equals(neighbor.peer.node.syncCommunicationPoint.Address)) //REVISIT: alert security system return; neighbor.peer.node.syncCommunicationPoint = peer.node.syncCommunicationPoint; neighbor.peer.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint; neighbor.peer.IE = peer.IE; byte[] message = new byte[Constants.WRITEBUFFSIZE]; MemoryStream stream; try { User user = User.getInstance(); BinaryFormatter serializer = new BinaryFormatter(); stream = new MemoryStream(message); NetLib.insertEntropyHeader(serializer, stream); serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO); serializer.Serialize(stream, ringInfo.ring.ringID); serializer.Serialize(stream, ringInfo.token); serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE)); writer.Write(message); writer.Flush(); } catch (Exception e) { int x = 2; } }
static void Main(string[] args) { string data = "This must be stored in a file."; FileStream fs = new FileStream("SerializedString.Data", FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, data); fs.Close(); fs = new FileStream("SerializedDate.Data", FileMode.Create); bf.Serialize(fs, DateTime.Now); fs.Close(); fs = new FileStream("SerializedDate.Data", FileMode.Open); DateTime output = (DateTime)bf.Deserialize(fs); Console.WriteLine(output); fs.Close(); }
public void logoff(User user) { byte[] message = new byte[Constants.WRITEBUFFSIZE]; MemoryStream stream = null; if(!loggedIn) return; try { //Serialize data in memory so you can send them as a continuous stream BinaryFormatter serializer = new BinaryFormatter(); stream = new MemoryStream(message); serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGOFF); serializer.Serialize(stream, this.loginCallbackTable.getSessionID()); serializer.Serialize(stream, user.publicUserInfo); serializer.Serialize(stream, user.privateUserInfo); serializer.Serialize(stream, user.node); NetLib.communicate(Constants.SERVER,message, false); stream.Close(); } catch { return; } finally { loggedIn = false; } }
private void ReReadFiles() { FilesGrid.Items.Clear(); try { Configuration config = (App.Current as App).config; using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port)) { using (NetworkStream writerStream = eClient.GetStream()) { MSG message = new MSG(); message.stat = STATUS.GET_FILES; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(writerStream, message); formatter.Serialize(writerStream, _eventId); formatter.Serialize(writerStream, false); _files = (Dictionary<string, string>)formatter.Deserialize(writerStream); foreach (var file in _files) { FilesGrid.Items.Add(new FileRow(file.Key, "Викладач")); } } } } catch (Exception) { MessageBox.Show("Помилка додавання файлу"); } }
public int Store(string fileName) { int errors = 0; Stream str = null; try { str = File.Open(fileName, FileMode.Create, FileAccess.Write); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(str, _package.Header); foreach (var item in _package.Content) { _package.Header.SetPosition(item.Key, str.Position); formatter.Serialize(str, item.Value); } str.Seek(0, SeekOrigin.Begin); //rewrite header with real positions formatter.Serialize(str, _package.Header); str.Close(); } catch (Exception e) { throw new Exception("Error writing Xbim file", e); } finally { if (str != null) str.Close(); } return errors; }
private void RegisterButton_Click(object sender, RoutedEventArgs e) { try { if (PasswordBox.Password != PasswordRepeatBox.Password) throw new Exception("Паролі не співпадають"); Instructor instructor = new Instructor(LoginBox.Text, PasswordBox.Password, FirstNameBox.Text, LastNameBox.Text, SecondNameBox.Text); Configuration config = (App.Current as App).config; using (TcpClient eClient = new TcpClient(config.IP.ToString(), config.Port)) { using (NetworkStream writerStream = eClient.GetStream()) { MSG message = new MSG(); message.stat = STATUS.ADD_INSTRUCTOR; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(writerStream, message); formatter.Serialize(writerStream, instructor); bool fl = (bool)formatter.Deserialize(writerStream); if (!fl) MessageBox.Show("Помилка додавання облікового запису"); else { NavigationService nav = NavigationService.GetNavigationService(this); nav.Navigate(new System.Uri("StartPage.xaml", UriKind.RelativeOrAbsolute)); } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public override void GetData(object target, Stream outgoingData) { Pixmap pixmap = target as Pixmap; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(outgoingData, pixmap.ToString()); formatter.Serialize(outgoingData, pixmap.MainLayer.ToBitmap()); outgoingData.Flush(); }
public override void GetData(object target, Stream outgoingData) { Pixmap.Layer layer = target as Pixmap.Layer; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(outgoingData, string.Format("Layer {0}x{1}", layer.Width, layer.Height)); formatter.Serialize(outgoingData, layer.ToBitmap()); outgoingData.Flush(); }
public override void GetData(object target, Stream outgoingData) { Bitmap bitmap = target as Bitmap; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(outgoingData, string.Format("Bitmap {0}x{1}", bitmap.Width, bitmap.Height)); formatter.Serialize(outgoingData, bitmap); outgoingData.Flush(); }
public byte[] GetBytes() { BinaryFormatter formatter = new BinaryFormatter(); byte[] bytes = new byte[100]; //may need to work this out formatter.Serialize(new MemoryStream(bytes, 0, 2), ContentCode); formatter.Serialize(new MemoryStream(bytes, 2, 98), Content); return bytes; }
/// <summary> /// Saves the grid to file /// </summary> /// <param name="path">Path to file</param> /// <param name="grid">Instance of grid</param> public static void Save(string path, Grid grid) { using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate,FileAccess.Write, FileShare.None)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(fileStream, grid.Parameters); binaryFormatter.Serialize(fileStream, grid.Cells); } }
public void Save(string path) { var formatter = new BinaryFormatter(); using (var stream = File.Create(path)) { formatter.Serialize(stream, RootBranches); formatter.Serialize(stream, Changesets); } }
public static byte[] Serialize(int messageKind, MessageBase msg) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf1 = new BinaryFormatter(); bf1.Serialize(ms, messageKind); bf1.Serialize(ms, msg); return ms.ToArray(); }
public void Save() { var bf = new BinaryFormatter(); var file = File.Create(Application.persistentDataPath + "\\" + gameObject.name + "statdata.bin"); var file2 = File.Create(Application.persistentDataPath + "\\" + gameObject.name + "chardata.bin"); bf.Serialize(file, Stats); bf.Serialize(file2, Characteristics); file.Close(); file2.Close(); }
public override void GetData(object target, Stream outgoingData) { Texture texture = target as Texture; PixelData layer = texture.GetPixelData(); Bitmap bitmap = layer.ToBitmap(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(outgoingData, texture.ToString()); formatter.Serialize(outgoingData, bitmap); outgoingData.Flush(); }
private void Login_Click(object sender, RoutedEventArgs e) { Configuration config = (App.Current as App).config; TcpClient eClient = new TcpClient(); try { eClient = new TcpClient(config.IP.ToString(), config.Port); using (NetworkStream writerStream = eClient.GetStream()) { MSG message = new MSG(); message.stat = STATUS.LOGIN; BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(writerStream, message); formatter.Serialize(writerStream, LoginBox.Text); formatter.Serialize(writerStream, PasswordBox.Password); bool fl = (bool)formatter.Deserialize(writerStream); if (fl) { Account ac = (Account)formatter.Deserialize(writerStream); if (ac != null) { Instructor st; if (ac is Instructor) { st = (Instructor)ac; config.Login = LoginBox.Text; config.Password = PasswordBox.Password; (App.Current as App).SaveConfig(); (App.Current as App).instr = st; NavigationService nav = NavigationService.GetNavigationService(this); nav.Navigate(new System.Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute)); } else { MessageBox.Show("Невірний тип облікового запису"); } } } else { MessageBox.Show("Невірна комбінація"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { eClient.Close(); } }
private void TestBinaryFormatter() { Student std = new Student() { Name = "Mark", Age = 20 }; Teacher ter = new Teacher() { Name = "Jim", Age = 21 }; using (FileStream fs =new FileStream(@"Student.dat", FileMode.Create)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs,std); bf.Serialize(fs,ter); } }
private void btnSaveAll_Click(object sender, EventArgs e) { IFormatter formatter = new BinaryFormatter(); // Сериализация контактов Stream stream = new FileStream("Contacts.org", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, Contacts); stream.Close(); // Сериализация заметок stream = new FileStream("Notes.org", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, Notes); stream.Close(); }
public static void SerializeFields(object source, Stream stream, Func<FieldInfo, bool> predicate) { var formatter = new BinaryFormatter(); foreach (var field in source.GetType() .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(predicate)) { object value = field.GetValue(source) ?? NullToken.Instance; formatter.Serialize(stream, field.Name); formatter.Serialize(stream, value); } }
public static void Save(Stream stream, BinaryFormatter formatter) { try { formatter.Serialize(stream, UseLocalIP); formatter.Serialize(stream, ServerIP); formatter.Serialize(stream, ServerPort); } catch { } }
public static void TestBinarySerializationUnzipped(int len) { DateTime t1; TimeSpan dt; double[] arr = new double[len]; for (int i = 0; i < arr.Length; i++) { arr[i] = Math.PI * Math.Sqrt(i); } FileStream fs = new FileStream(@"C:\TEMP\testbinformat.bin", FileMode.Create); // Construct a BinaryFormatter and use it to serialize the data to the stream. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); t1 = DateTime.Now; try { formatter.Serialize(fs, arr); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Flush(); fs.Close(); } dt = DateTime.Now - t1; Console.WriteLine("Duration: {0}", dt); }
public static void WriteBinaryToFile <T>(string path, T target, FileMode fileMode = FileMode.Create) { using (Stream stream = File.Open(path, fileMode)) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, target); } }
public void SetCookieDomain(string cookiename, object cookievalue, int hour) { try { System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); string result = string.Empty; //将字符串进行base64编码,解决中文问题。然后进行序列化化,将shopcart保存至cookie using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { bf.Serialize(ms, cookievalue); byte[] byt = new byte[ms.Length]; byt = ms.ToArray(); result = System.Convert.ToBase64String(byt); ms.Flush(); } HttpCookie hc = new HttpCookie(cookiename); hc.Value = result; hc.HttpOnly = false; if (hour != 0) { hc.Expires = DateTime.Now.AddHours(hour); //设置过期时间 } else { hc.Expires = DateTime.MaxValue; } hc.Domain = CFun.GetAppStr("webDomain"); HttpContext.Current.Response.Cookies.Add(hc); } catch { } }
/// <summary> /// Serialize /// DataTable을 byte[]로 시리얼라이즈 한다. /// </summary> /// <param name="dt"></param> /// <returns></returns> public static byte[] Serialize(DataTable dt) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, dt); return(stream.ToArray()); }
public static MemoryStream getStream(Object obj) { var stream = new MemoryStream(); var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(stream, obj); return(stream); }
public static byte[] Export(VariableMgr mgr) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); b.Serialize(stream, mgr); return(stream.ToArray()); }
private void ItemsSave(string filename) { using (System.IO.FileStream str = new System.IO.FileStream(filename, System.IO.FileMode.Create)) { BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); serializer.Serialize(str, _items); } }
public static void writeGene(string path, Gene gene) { Stream stream = File.Create(path); var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); serializer.Serialize(stream, gene); stream.Close(); }
public static void WriteToBinaryFile <T>(T objectToWrite, bool append = false) { using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create)) { var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binaryFormatter.Serialize(stream, objectToWrite); } }
private void btnSerialize_Click(object sender, RoutedEventArgs e) { System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); Stream stream = new FileStream(@"D:\pelaajat.bin", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, pelaajat); stream.Close(); }
/// <summary> /// Serializa uma hashtable e grava em ficheiro /// </summary> /// <param name="list">Hashtable a serializar</param> /// <param name="fileName">Nome do ficheiro a gravar</param> public static void SerializeHashtable(this Hashtable _list, string _fileName) { var serializador = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); Stream stream = new FileStream(_fileName, FileMode.Create, FileAccess.Write, FileShare.None); serializador.Serialize(stream, _list); stream.Close(); }
public int CaptureSave(string path) { try { sb.BinaryFormatter bf = new sb.BinaryFormatter(); using (io.FileStream fs = io.File.OpenWrite(path)) { bf.Serialize(fs, captureDraw); bf.Serialize(fs, captureDrawPoint); bf.Serialize(fs, captureFill); bf.Serialize(fs, captureFillPoint); } } catch (Exception e) { return(1); } return(0); }
public void Save(string filename, List <Entity> entities) { using (Stream stream = File.Open(filename, FileMode.Create)) { var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binaryFormatter.SurrogateSelector = _surrogateSelector; binaryFormatter.Serialize(stream, entities); } }
public byte[] ToBinary <T>(T data) where T : class { using (MemoryStream memory = new MemoryStream()) { var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(memory, data); return(memory.ToArray()); } }
public static MemoryStream Serializebinary(object request)//对象序列化为二进制流 { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); MemoryStream menStream = new MemoryStream(); //创建一个内存流存储区 serializer.Serialize(menStream, request); //将对象序列化为二进制流 return(menStream); }
/// <summary> /// Serializa un objeto a un archivo binario. /// </summary> /// <param name="fileName">Ruta del archivo en el cual depositar los bytes</param> /// <param name="objToSerialize">Objeto en memoria a transformar en bytes</param> public static void SerializeToBin(string fileName, object objToSerialize) { using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); b.Serialize(fs, objToSerialize); fs.Close(); } }
public string MD5() { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, this); ms.Position = 0; byte[] hv = System.Security.Cryptography.HashAlgorithm.Create("MD5").ComputeHash(ms); return(BitConverter.ToString(hv)); }
void save_data() { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/gamedata.dat", FileMode.Create); bf.Serialize(file, data_g.players); //Guardo este dato //Si tuviera mas datos los guardo aca, importante el orden porque se leeran en mismo orden file.Close(); }
public override string ToString() { System.Runtime.Serialization.IFormatter format = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { format.Serialize(stream, this); using (System.IO.StreamReader sr = new System.IO.StreamReader(stream)) return(sr.ReadToEnd()); } }
public void gravarEstoque(List <Produto> Prds) { string serializationFile = "Estoque.bin"; using (Stream stream = File.Open(serializationFile, FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, Prds); } }
public void gravarClientes(List <Cliente> Clts) { string serializationFile = "Clientes.bin"; using (Stream stream = File.Open(serializationFile, FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, Clts); } }
//Get called when saving document. protected override void OnSave(Stream outStrm) { // Override OnSave and uses a binary formatter to serialize the log. Dictionary <string, string> log = new Dictionary <string, string>(); log.Add("userName", Environment.UserName); log.Add("time", DateTime.Now.ToLongTimeString()); var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(outStrm, log); }
public byte[] Serialize() { byte[] data; using (var ms = new System.IO.MemoryStream()) { var formatter = new Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(ms, this); data = ms.ToArray(); } return(data); }
/// <summary> /// Creates a deep copy of specified object, by serializing and deserialziing it. /// </summary> /// <param name="objectToCopy"></param> /// <returns></returns> public static Object createDeepCopyBySerialization(Object objectToCopy) { // Create a deep copy of the current sequence file, by serializing and then deserializing. A clever trick. using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, objectToCopy); ms.Position = 0; return(bf.Deserialize(ms)); } }
public object Clone() { MemoryStream ms = new MemoryStream(); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, this); ms.Position = 0; object obj = bf.Deserialize(ms); ms.Close(); return(obj); }
public override void InputListofCustomer() { base.InputListofCustomer(); string pathsave = @"D:\"; string serializationFile = Path.Combine(pathsave, "CUSTOMER.bin"); using (Stream stream = File.Open(serializationFile, FileMode.Create)) { var fformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); fformatter.Serialize(stream, ListofCustomer); } }
public static void SaveCookie() { if (gCookies != null) { string path = System.IO.Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "cookie.bin"); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.Stream stream = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { formatter.Serialize(stream, gCookies); } } }
// This is a legacy reader static public void ReadLondonData() { List <Target> targetList = new List <Target>(); List <Instrument> instrumentList = new List <Instrument>(); String initialPath = "http://www.londonstockexchange.com/exchange/searchengine/all/json/search.html?q="; int counter = 0; string line; string savePathCurrent = Program.root + ".html"; System.IO.StreamReader file = new System.IO.StreamReader(Program.root + @"StocksToCheck.txt"); // Going over each of the stocks mentioned,line by line while ((line = file.ReadLine()) != null) { using (WebClient client = new WebClient()) { client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " + "(compatible; MSIE 6.0; Windows NT 5.1; " + ".NET CLR 1.1.4322; .NET CLR 2.0.50727)"; var jsonfile = client.DownloadString(initialPath + line); JsonTextReader reader = new JsonTextReader(new StringReader(jsonfile)); bool continueLoop = true; // In the json file, take the value of symbol to targetList while (continueLoop == true) { reader.Read(); if (reader.Value != null) { if (String.Equals(reader.Value.ToString(), "symbol1")) { reader.Read(); targetList.Add(new Target(line, reader.Value.ToString(), StockName.London)); Console.WriteLine("{0},{1}", reader.Value, line); continueLoop = false; } } } } counter++; } //Save to a seralizable file using (Stream stream = File.Open(Program.root + "ListInterpreted.txt", FileMode.Create)) { var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, targetList); } // At this point targetList contains the keys required to get into the file.Close(); }
public static byte[] ObjectToByteArray(this System.Object obj) { if (obj == null) { return(null); } System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { bf.Serialize(ms, obj); return(ms.ToArray()); } }
/// <summary> /// Serialize /// Object을 byte[]로 시리얼라이즈 한다. /// </summary> /// <param name="type">Serialize Type</param> /// <param name="obj"></param> /// <returns></returns> public static byte[] Serialize(SerializeType type, Object obj) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); switch (type) { case SerializeType.DataSet: DataSet ds = (DataSet)obj; ds.RemotingFormat = SerializationFormat.Binary; formatter.Serialize(stream, ds); break; case SerializeType.DataTable: DataTable dt = (DataTable)obj; dt.RemotingFormat = SerializationFormat.Binary; formatter.Serialize(stream, dt); break; } return(stream.ToArray()); }