Serialize() public method

public Serialize ( Stream serializationStream, object graph ) : void
serializationStream Stream
graph object
return void
Example #1
0
        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();
        }
		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;
		}
        /// <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 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 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;
            }
        }
        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 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 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 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 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 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 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;
            }
        }
Example #13
0
        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();
        }
Example #14
0
        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();
        }
        /// <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;
                }
            }
        }
        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();
        }
Example #17
0
 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;
 }
		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)
		{
			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)
		{
			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();
		}
Example #21
0
 public void Save(string path)
 {
     var formatter = new BinaryFormatter();
     using (var stream = File.Create(path))
     {
         formatter.Serialize(stream, RootBranches);
         formatter.Serialize(stream, Changesets);
     }
 }
Example #22
0
 /// <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);
     }
 }
Example #23
0
        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();
        }
Example #24
0
 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();
 }
Example #25
0
		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();
		}
Example #26
0
 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();
 }
Example #27
0
 public static void Save(Stream stream, BinaryFormatter formatter)
 {
     try
     {
         formatter.Serialize(stream, UseLocalIP);
         formatter.Serialize(stream, ServerIP);
         formatter.Serialize(stream, ServerPort);
     }
     catch
     {
     }
 }
Example #28
0
 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);
     }
 }
Example #29
0
        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 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();
     }
 }