Deserialize() public method

public Deserialize ( Stream serializationStream ) : object
serializationStream Stream
return object
        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, true);
                        _instrFiles = (Dictionary<string, string>)formatter.Deserialize(writerStream);
                        _studFiles = (Dictionary<string, string>)formatter.Deserialize(writerStream);
                        foreach (var file in _instrFiles)
                        {
                            FilesGrid.Items.Add(new FileRow(file.Key, "Викладач"));
                        }
                        foreach (var file in _studFiles)
                        {
                            FilesGrid.Items.Add(new FileRow(file.Key, "Студент"));
                        }
                    }
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Помилка додавання файлу");
            }
        }
		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;
		}
 private void UpdateSpecialities()
 {
     SpecialityGrid.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_SPECIALITIES;
                 BinaryFormatter formatter = new BinaryFormatter();
                 formatter.Serialize(writerStream, message);
                 if ((bool)formatter.Deserialize(writerStream))
                 {
                     _specialityCollection = (List<Speciality>)formatter.Deserialize(writerStream);
                 }
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
     foreach (var speciality in _specialityCollection)
     {
         SpecialityGrid.Items.Add(speciality);
     }
 }
 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 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 ();
        }
Exemplo n.º 6
0
 public void Setup()
 {
     IFormatter formatter = new BinaryFormatter();
     _scrapeOne = (Scrape)formatter.Deserialize(GetResourceStream("QualityBot.Test.Tests.TestData.FakeAncestryDevScrape.bin"));
     _scrapeTwo = (Scrape)formatter.Deserialize(GetResourceStream("QualityBot.Test.Tests.TestData.FakeAncestryStageScrape.bin"));
     _comparer = new Comparer();
 }
Exemplo n.º 7
0
        public void Resume()
        {
            string fileName = "";
            if (sign == '$')
                fileName = "food.ser";
            if (sign == 'o')
                fileName = "snake.ser";
            if (sign == '#')
                fileName = "wall.ser";
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            BinaryFormatter bf = new BinaryFormatter();
            try
            {
                if (sign == '$')
                    Game.food = bf.Deserialize(fs) as Food;
                if (sign == '#')
                    Game.wall = bf.Deserialize(fs) as Wall;

                if (sign == 'o')
                    Game.snake = bf.Deserialize(fs) as Snake;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                fs.Close();
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            Ohjelma ohj1 = new Ohjelma { nimi = "muumit", kanava = "TV2", alkuaika = 8, loppuaika = 9, info = "muumit seikkailee" };
            Ohjelma ohj2 = new Ohjelma { nimi = "jattipotti", kanava = "MTV3", alkuaika = 8, loppuaika = 23, info = "voita tsiljoona euroa soita nyt heti" };
            List<Ohjelma> ohjelmat = new List<Ohjelma>();
            ohjelmat.Add(ohj1);
            ohjelmat.Add(ohj2);
            IFormatter formatter = new BinaryFormatter();
            foreach (Ohjelma o in ohjelmat)
            {
                Stream writeStream = new FileStream(o.nimi+".bin", FileMode.Create, FileAccess.Write, FileShare.None);
                
                formatter.Serialize(writeStream, o);
                writeStream.Close();
            }


            Stream readStream = new FileStream("jattipotti.bin", FileMode.Open, FileAccess.Read, FileShare.None);
            Ohjelma jattipotti = (Ohjelma) formatter.Deserialize(readStream);

            Console.WriteLine("nimi: {0}, kanava: {1}, alkuaika: {2}, loppuaika: {3}, info: {4}", jattipotti.nimi, jattipotti.kanava, 
                jattipotti.alkuaika, jattipotti.loppuaika, jattipotti.info);

            readStream = new FileStream("muumit.bin", FileMode.Open, FileAccess.Read, FileShare.None);
            Ohjelma muumit = (Ohjelma)formatter.Deserialize(readStream);

            Console.WriteLine("nimi: {0}, kanava: {1}, alkuaika: {2}, loppuaika: {3}, info: {4}", muumit.nimi, muumit.kanava,
                muumit.alkuaika, muumit.loppuaika, muumit.info);

        }
Exemplo n.º 9
0
 public void Load(String filename)
 {
     FileStream fs = new FileStream(filename, FileMode.Open);
     BinaryFormatter f = new BinaryFormatter();
     simulation = (Common.Motion.Simulation)f.Deserialize(fs);
     zombieSimulation = (Common.Motion.Simulation)f.Deserialize(fs);
 }
Exemplo n.º 10
0
        public void Resume()
            // чтобы вернуться в предыдущее место делаем десериализатор
        {
            string fileName = "";
            if (sign == '*')
                fileName = "food.dat";
            if (sign == '#')

                fileName = "wall.dat";
            if (sign == 'o')
                fileName = "snake.dat";
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            BinaryFormatter bf = new BinaryFormatter();

            if (sign == '*')
                Game.food = bf.Deserialize(fs) as Food;
            if (sign == '#')
                Game.wall = bf.Deserialize(fs) as Wall;

            if (sign == 'o')
                Game.snake = bf.Deserialize(fs) as Snake;

            fs.Close();

        }
Exemplo n.º 11
0
        public void Resume()
        {
            string fname = "snake.ser";
            if (sign == '@')
                fname = "food.ser";
            if (sign == '#')
                fname = "wall.ser";
            string path = @"C:\Users\Zhandos\Documents\Visual Studio 2012\Projects\mySnake\Snake\Snake\ser\" + fname;
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

            if (sign == 'O')
            {
                updateConsole(color, ' ', ref Game.snake.body);
                Game.snake.body.Clear();
                Game.snake = bf.Deserialize(fs) as Snake;
                updateConsole(color, sign, ref Game.snake.body);
            }
            if (sign == '#')
            {
                updateConsole(color, ' ', ref Game.wall.body);
                Game.wall.body.Clear();
                Game.wall = bf.Deserialize(fs) as Wall;
                updateConsole(color, sign, ref Game.wall.body);
            }
            if (sign == '@')
            {
                updateConsole(color,' ', ref Game.food.body);
                Game.food.body.Clear();
                Game.food = bf.Deserialize(fs) as Food;
                updateConsole(color, sign, ref Game.food.body);
            }
            fs.Close();
        }
Exemplo n.º 12
0
        public FileCacheItem Deserialize(Stream stream)
        {
            var surrogateSelector = new AnonymousTypeSurrogateSelector();
            surrogateSelector.AddSurrogate(typeof(CacheItemPolicy), new StreamingContext(StreamingContextStates.All), new CacheItemPolicySurrogate());

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.SurrogateSelector = surrogateSelector;
            formatter.Binder = _binder;

            FileCacheItem item = null;

            try
            {
                string key = (string)formatter.Deserialize(stream);
                CacheItemPolicy policy = (CacheItemPolicy)formatter.Deserialize(stream);
                object payload = formatter.Deserialize(stream);

                item = new FileCacheItem(key, policy, payload);
            }
            catch (SerializationException)
            {

            }

            return item;
        }
 public async Task<Stream> Get(string endpoint, object args, string expectedContentType)
 {
     var cacheFileName = Path.Combine(_cacheDir, string.Concat((endpoint + "_" + args).Replace(" ", "").Split(Path.GetInvalidFileNameChars())));
     if (endpoint == "accounts/login")
     {
         if (File.Exists(cacheFileName))
         {
             using (var stream = File.OpenRead(cacheFileName))
             {
                 var formatter = new BinaryFormatter();
                 Cookies = (CookieContainer) formatter.Deserialize(stream);
                 _headers = (NameValueCollection) formatter.Deserialize(stream);
             }
             return Stream.Null;
         }
         return await _decorated.Get(endpoint, args, expectedContentType);
     }
     if (!File.Exists(cacheFileName))
     {
         using (var source = await _decorated.Get(endpoint, args, expectedContentType))
         using (var destination = File.OpenWrite(cacheFileName))
         {
             source.CopyTo(destination);
         }
     }
     return File.OpenRead(Path.Combine(_cacheDir, cacheFileName));
 }
Exemplo n.º 14
0
        public IEnumerable<Event> EventsFor(Guid aggregateRootId)
        {
            var idpair = new KeyValuePair<string, object>("@AggregateRootId", aggregateRootId);

            var snapshots = readRepository.All("SELECT * FROM [Snapshots] WHERE [AggregateRootId] = @AggregateRootId ORDER BY [DateTime] DESC", new[] { idpair });
            var snapshot = snapshots.FirstOrDefault();
            var date = epoch;
            if (snapshot != null)
                date = snapshot.DateTime;

            var events = readRepository.All("SELECT * FROM [Events] WHERE [AggregateRootId] = @AggregateRootId AND [DateTime] > @Date ORDER BY [DateTime]", new[] { idpair, new KeyValuePair<string, object>("@Date", date) });

            var formatter = new BinaryFormatter();

            if (date > epoch)
                yield return formatter.Deserialize(new MemoryStream((byte[])snapshot.Snapshot)) as Event;

            foreach (var @event in events)
            {
//Console.WriteLine("deserializing: " + @event.Id);
                var stream = new MemoryStream((byte[])@event.Event);

                yield return formatter.Deserialize(stream) as Event;
            }
        }
Exemplo n.º 15
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 Dictionary<string, int> InitSubjectsTable()
 {
     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_SUBJECTS;
                 BinaryFormatter formatter = new BinaryFormatter();
                 formatter.Serialize(writerStream, message);
                 bool fl = (bool)formatter.Deserialize(writerStream);
                 if (fl)
                 {
                     _subjectsCollection = (Dictionary<string, int>)formatter.Deserialize(writerStream);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Помилка", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     return _subjectsCollection;
 }
Exemplo n.º 17
0
        public void TestTeardDown()
        {
            foreach (Process oldProcess in processes) {
                while (!oldProcess.HasExited)
                    oldProcess.CloseMainWindow ();

                //System.Threading.Thread.Sleep (5000);

                // Print values to make sure if something changed
                Console.WriteLine ("ProcessId: {0}", oldProcess.Id);

                BinaryFormatter bf = new BinaryFormatter ();
                FileStream retrieveStream = new FileStream (string.Format("{0}.0.bin", oldProcess.Id), FileMode.Open);
                ArrayList oldArraylist = (ArrayList) bf.Deserialize(retrieveStream);              
                retrieveStream.Close ();
                retrieveStream.Dispose ();
                File.Delete(string.Format ("{0}.0.bin", oldProcess.Id));
                //
                retrieveStream = new FileStream (string.Format ("{0}.1.bin", oldProcess.Id), FileMode.Open);
                ArrayList newArrayList = (ArrayList) bf.Deserialize (retrieveStream);
                retrieveStream.Close ();
                retrieveStream.Dispose ();
                File.Delete (string.Format ("{0}.1.bin", oldProcess.Id));

                // If we fail here is because we *did* change something
                for (int index = 0; index < oldArraylist.Count; index++)
                    Assert.IsTrue (object.Equals(oldArraylist[index], newArrayList[index]),
                        string.Format("elements at index {0} are not equal", index));
            }
        }
Exemplo n.º 18
0
      public void Load()
      {
         // Load preferencies
         FileStream fs;
         try
         {
            fs = new FileStream(GetUserDataPath(), FileMode.Open, FileAccess.Read);
            BinaryFormatter b = new BinaryFormatter();
            fs.Seek(0, SeekOrigin.Begin);

            Nick = (string)b.Deserialize(fs);
            Host = (string)b.Deserialize(fs);
            Port = (string)b.Deserialize(fs);
            TextColor = (Color)b.Deserialize(fs);

            AutoRun = (bool)b.Deserialize(fs);
            AutoConnect = (bool)b.Deserialize(fs);
            RunMinimized = (bool)b.Deserialize(fs);

            fs.Close();
         }
         catch (Exception)
         {
            // No preferencies, use default
            Nick = "Your nick";
            Host = "localhost";
            Port = "14242";
            TextColor = Color.Black;

            AutoRun = false;
            AutoConnect = false;
            RunMinimized = false;
         }
      }
Exemplo n.º 19
0
Arquivo: Program.cs Projeto: sbst/code
        public static void DoAcceptTcpClientCallback(IAsyncResult ar)
        {
            Thread.Sleep(0);
            Byte[] bytes = new Byte[1024];
            String data = null;
            TcpListener listener = (TcpListener)ar.AsyncState;
            TcpClient client = listener.EndAcceptTcpClient(ar);
            Console.WriteLine("Client connect completed");

            data = null;
            NetworkStream stream = client.GetStream();

            BinaryFormatter outformat = new BinaryFormatter();

            string name;
            name = outformat.Deserialize(stream).ToString();
            FileStream fs = new FileStream("D:\\" + name, FileMode.OpenOrCreate);
            BinaryWriter bw = new BinaryWriter(fs);
            int count;
            count = int.Parse(outformat.Deserialize(stream).ToString());
            int i = 0;
            for (; i < count; i += 1024)
            {

                byte[] buf = (byte[])(outformat.Deserialize(stream));
                bw.Write(buf);
            }
            Console.WriteLine("Successfully read in D:\\" + name);
            bw.Close();
            fs.Close();
            tcpClientConnected.Set();
        }
Exemplo n.º 20
0
        static void LoadConsts(Stream fs) {
            var bf = new BinaryFormatter();

            GTA5Constants.PC_AES_KEY = (byte[]) bf.Deserialize(fs);
            GTA5Constants.PC_NG_KEYS = (byte[][]) bf.Deserialize(fs);
            GTA5Constants.PC_NG_DECRYPT_TABLES = (byte[][]) bf.Deserialize(fs);
            GTA5Constants.PC_LUT = (byte[]) bf.Deserialize(fs);
        }
Exemplo n.º 21
0
 public static void Deserialize(byte[] buffer, 
     out int messageKind, out MessageBase msg)
 {
     MemoryStream ms = new MemoryStream(buffer);
     BinaryFormatter formatter = new BinaryFormatter();
     messageKind = (int)formatter.Deserialize(ms);
     msg = (MessageBase)formatter.Deserialize(ms);
 }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();

            FileStream inPut = new FileStream("C:\\Users\\DEVELOPER4\\Desktop\\savefile\\lolblackjagged.yup", FileMode.Open, FileAccess.Read);
            States state = new States();

            state.gridSize = (Size)bFormatter.Deserialize(inPut);

            state.innerRectColor = (Color[][])bFormatter.Deserialize(inPut);
            state.innerShapeColor = (Color[][])bFormatter.Deserialize(inPut);
            state.rectColor = (Color[][])bFormatter.Deserialize(inPut);
            state.shapeColor = (Color[][])bFormatter.Deserialize(inPut);
            state.types = (int[][])bFormatter.Deserialize(inPut);
            state.rotation = (int[][])bFormatter.Deserialize(inPut);
            state.values = (int[][])bFormatter.Deserialize(inPut);
            state.circleGrid = (Rectangle[][])bFormatter.Deserialize(inPut);
            state.rectangleGrid = (Rectangle[][])bFormatter.Deserialize(inPut);
            state.lvls = Converter.ToJagged(new int[state.gridSize.Height,state.gridSize.Width]);
            state.owned = new List<Location>[4];

            for (int i = 0; i < state.owned.Length; i++) {
                state.owned[i] = new List<Location>();
            }

            inPut.Close();

            Console.WriteLine("Number of Players?");
            state.numOfPlayers = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Total Value?");
            state.totalValue = Convert.ToInt32(Console.ReadLine());

            //ICommandBoardService proxy;
            using (ServiceHost host = new ServiceHost(typeof(CommandBoardServiceLibrary.CommandBoardService)))
            {
                NetTcpBinding ntb = new NetTcpBinding();
                NetTcpSecurity nts = new NetTcpSecurity();
                nts.Mode = SecurityMode.None;
                ntb.Security = nts;

                host.AddServiceEndpoint(typeof(
                    CommandBoardServiceLibrary.ICommandBoardService),
                    new NetTcpBinding(),"net.tcp://localhost:9000/commandboard");
                host.Open();

                ICommandBoardService proxy = ChannelFactory<ICommandBoardService>.CreateChannel(
                             new NetTcpBinding(),
                            new EndpointAddress("net.tcp://localhost:9000/commandboard"));

                proxy.setState(state);

                Console.WriteLine("Good to go");
                Console.ReadLine();

            }
        }
Exemplo n.º 23
0
 private static void Load(string path, Script script)
 {
     var formatter = new BinaryFormatter();
     using (var stream = File.OpenRead(path))
     {
         script.RootBranches.AddRange((List<ScriptedRootBranch>)formatter.Deserialize(stream));
         script.Changesets.AddRange((List<ScriptedChangeset>)formatter.Deserialize(stream));
     }
 }
Exemplo n.º 24
0
 public void GetMove(NetworkStream ns, View view, Game game )
 {
     BinaryFormatter formatter = new BinaryFormatter();
     Position from = (Position)formatter.Deserialize(ns);
     Position to = (Position)formatter.Deserialize(ns);
     // view
     view.Invoke(new Action(
         () => { game.Cell_Click(from); Thread.Sleep(100); game.Cell_Click(to); }));
 }
Exemplo n.º 25
0
        private LegacyDataLibrary(Stream file)
        {
            var formatter = new BinaryFormatter();

            trainingLibrary = (List<Tuple<string, List<int>>>)formatter.Deserialize(file);
            listOfIndicies = (List<List<int>>)formatter.Deserialize(file);
            listOfIndexLabels = (List<string>)formatter.Deserialize(file);

            ReferenceSet = new InMemoryReferenceSet(trainingLibrary.Select(t => new ReferenceItem(t.Item1, t.Item2)));
        }
Exemplo n.º 26
0
 public void Resume()
 {
     Type t = GetType();
     FileStream fs = new FileStream(string.Format("{0}.dat", t.Name), FileMode.Open, FileAccess.Read);
     BinaryFormatter bf = new BinaryFormatter();
     if (t == typeof(Wall)) Game.wall = bf.Deserialize(fs) as Wall;
     if (t == typeof(Snake)) Game.snake = bf.Deserialize(fs) as Snake;
     if (t == typeof(Food)) Game.food = bf.Deserialize(fs) as Food;
     fs.Close();
 }
Exemplo n.º 27
0
 public void Load()
 {
     var bf = new BinaryFormatter();
     var file = File.Open(Application.persistentDataPath + "\\" + gameObject.name + "statdata.bin", FileMode.Open);
     var file2 = File.Open(Application.persistentDataPath + "\\" + gameObject.name + "chardata.bin", FileMode.Open);
     Stats = (ModifiableStatistic[])bf.Deserialize(file);
     Characteristics = (Characteristic[])bf.Deserialize(file);
     file.Close();
     file2.Close();
 }
Exemplo n.º 28
0
 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();
     }
 }
Exemplo n.º 29
0
        public void Resume2()
        {
            Type t = GetType();
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = new FileStream(string.Format(@"C:\Users\Home\Source\Repos\labwork1\lab3_zmeika\lab3_zmeika\bin\Debug\{0}.dat", t.Name), FileMode.Open, FileAccess.Read);
            //BinaryFormatter bf = new BinaryFormatter();

            if (t == typeof(Wall)) Game.wall = bf.Deserialize(fs) as Wall;
            if (t == typeof(Snake)) Game.snake = bf.Deserialize(fs) as Snake;
            if (t == typeof(Food)) Game.food = bf.Deserialize(fs) as Food;
            fs.Close();
         }
Exemplo n.º 30
0
 protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
 {
     Stream incomingData = objectProvider.GetData();
     BinaryFormatter formatter = new BinaryFormatter();
     string name = (string)formatter.Deserialize(incomingData);
     Bitmap pixeldata = (Bitmap)formatter.Deserialize(incomingData);
     using (BitmapForm form = new BitmapForm()) {
         form.Text = name;
         form.Bitmap = pixeldata;
         windowService.ShowDialog(form);
     }
 }
Exemplo n.º 31
0
        public object DeserializeBinary(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                Log.W("DeserializeBinary Without Valid Path.");
                return(null);
            }

            var fileInfo = new FileInfo(path);

            if (!fileInfo.Exists)
            {
                Log.W("DeserializeBinary File Not Exit.");
                return(null);
            }

            using (var fs = fileInfo.OpenRead())
            {
                var bf =
                    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                var data = bf.Deserialize(fs);

                return(data);
            }
        }
Exemplo n.º 32
0
        private T DeserializeMessage <T>(ZMessage msg) where T : class
        {
            T             t         = null;
            ByteArrayPool _bytePool = new ByteArrayPool();

            byte[] tmp = _bytePool.Malloc((int)(msg[1].Length));
            msg[1].Read(tmp, 0, (int)(msg[1].Length));
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(tmp))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter fmt = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                t = fmt.Deserialize(stream) as T;
            }
            _bytePool.Free(tmp);
            //try
            //{
            //    t = CommonUtils.FromJSON<T>(msg[1].ReadString());
            //}
            //catch (Exception ex)
            //{
            //    Program.logger.LogRunning("反序列化市场数据失败!\r\n  Message:{0}\r\n  StackTrace:{1}", ex.Message, ex.StackTrace);
            //}

            msg.Dispose();
            return(t);
        }
Exemplo n.º 33
0
        /// <summary>
        /// 自二進制陣列轉換為名稱對應檔案
        /// </summary>
        /// <param name="binary">二進制陣列</param>
        /// <returns>名稱對應陣列</returns>
        public static NameMapping[] FromBinary(byte[] binary)
        {
            var          binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            MemoryStream stream          = new MemoryStream(binary);

            return((NameMapping[])binaryFormatter.Deserialize(stream));
        }
Exemplo n.º 34
0
 /// <summary>
 /// 讀取檔案
 /// </summary>
 /// <param name="file">路徑</param>
 /// <returns>名稱對應陣列</returns>
 public static NameMapping[] Load(string file)
 {
     using (Stream stream = File.Open(file, FileMode.Open)) {
         var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         return((NameMapping[])binaryFormatter.Deserialize(stream));
     }
 }
Exemplo n.º 35
0
        public void DeserializeGracefullyFailsOnDataError()
        {
            TestSerializableObject obj = new TestSerializableObject();

            string originalValue = "original value 123";

            obj.Test = originalValue;
            TestCacheSerializer.Serialize(obj);

            //2. Delete the cachePath
            AppContext.StreamManager.CloseStream(TmpCachePath); //disposes and removes cache stream

            using (BinaryWriter writer = new BinaryWriter(new FileStream(TmpCachePath, FileMode.Open)))
            {
                string foo = "foo";
                writer.Write(foo);
                writer.Flush();
            }

            // Now that it is closed, we should be able to repeat the process and successfully delete the bad cache file.
            obj = TestCacheSerializer.Deserialize <TestSerializableObject>();
            Assert.IsNotNull(obj);
            Assert.AreEqual(originalValue, obj.Test);
            Assert.IsTrue(File.Exists(TmpCachePath));

            // Deserializing it should have forced the cache file back to the correct data.
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (Stream stream = new FileStream(TmpCachePath, FileMode.Open))
            {
                obj = (TestSerializableObject)formatter.Deserialize(stream);
            }

            Assert.AreEqual(originalValue, obj.Test);
        }
Exemplo n.º 36
0
    void load_data()
    {
        int cant_players = 1;

        if (File.Exists(Application.persistentDataPath + "/gamedata.dat"))
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/gamedata.dat", FileMode.Open); //Generamos lectura del archivo
            cant_players = (int)bf.Deserialize(file);
            //Todas las lineas de lectura (importante orden)
            file.Close();

            for (int i = 0; i < cant_players; i++)
            {
                vidas_j[i] = 0; //Le asigno 2 vidas a la cantidad de players que se haya seleccionado
            }
        }

        spawn_j1(); //Siempre spawnea al menos al jugador 1

        if (cant_players > 1)
        {
            spawn_j2();
        }

        for (int i = 0; i < cant_players; i++)
        {
            actualizar_puntos(i + 1);
        }
    }
Exemplo n.º 37
0
        private bool loadRecord()
        {
            var raw = readRawData();

            if (raw != null)
            {
                byte[] cipher = Convert.FromBase64String(raw);

                using (Stream stream = new MemoryStream(cipher))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    object records = bformatter.Deserialize(stream);
                    if (records is AccountRecords)
                    {
                        accountRecords = Records.Change(records);
                    }
                    else
                    {
                        accountRecords = (Records)records;
                    }
                }
            }
            accRecInit();

            return(true);
        }
Exemplo n.º 38
0
        public bool importRecord(string raw)
        {
            try
            {
                byte[] cipher = Convert.FromBase64String(raw);

                using (Stream stream = new MemoryStream(cipher))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    object records = bformatter.Deserialize(stream);
                    if (records is AccountRecords)
                    {
                        accountRecords = Records.Change(records);
                    }
                    else
                    {
                        accountRecords = (Records)records;
                    }
                }
                accRecInit();
                storeRecord();
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 39
0
        public static T ToObject <T>(this byte[] _ByteArray) where T : class
        {
            try
            {
                // convert byte array to memory stream
                System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);

                // create new BinaryFormatter
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
                    = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                // set memory stream position to starting point
                _MemoryStream.Position = 0;

                // Deserializes a stream into an object graph and return as a object.
                return(_BinaryFormatter.Deserialize(_MemoryStream) as T);
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            // Error occured, return null
            return(null);
        }
Exemplo n.º 40
0
    static T FromBytes <T>(byte[] Data)
    {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        System.IO.MemoryStream MS = new System.IO.MemoryStream(Data);

        return((T)BF.Deserialize(MS));
    }
Exemplo n.º 41
0
        private void Button_History(object sender, RoutedEventArgs e)
        {
            CalcHistory history = new CalcHistory();
            String      message = "";

            try
            {
                using (Stream streamLoad = File.Open("MyFile.bin", FileMode.Open))
                {
                    var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    history = (CalcHistory)binaryFormatter.Deserialize(streamLoad);
                }
            }
            catch (FileNotFoundException errorMessage)
            {
                Console.WriteLine(@"file not there", errorMessage);
            }
            catch (SerializationException errorMesage)
            {
                Console.WriteLine(@"File empty", errorMesage);
            }
            List <String> historyList;

            historyList = history.GetList();
            for (int i = 0; i < historyList.Count; i++)
            {
                message += historyList.ElementAt(i) + "\n";
            }
            MessageBox.Show(message);
        }
Exemplo n.º 42
0
        private void buttonLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog opd = new OpenFileDialog();

            opd.Title  = "Open Image File";
            opd.Filter = "sav|*.sav";

            if (opd.ShowDialog() == System.Windows.Forms.DialogResult.OK && opd.FileName != null)
            {
                using (Stream stream = File.Open(opd.FileName, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    dataList = (List <data>)bformatter.Deserialize(stream);
                }

                // dataList = changeToData(saveDataList);

                if (dataList.Count == 0)
                {
                    return;
                }
                dataGridViewShow.Rows.Clear();
                foreach (data i in dataList)
                {
                    dataGridViewShow.Rows.Add(i.title, i.des, i.imageData);
                }
            }
        }
        private bool LoadConfigFileBF(string filePath)
        {
            if (File.Exists(filePath))
            {
                Debug.WriteLine("Accessed BF TGC Reader...");

                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                try
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    mConfig = (IndexerConfig)bf.Deserialize(fs);
                    return(true);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    fs.Close();
                    return(false);
                }
                finally
                {
                    fs.Close();
                }
            }
            return(false);
        }
Exemplo n.º 44
0
        //Get called when opening a document with persisted stream.
        protected override void OnLoad(Stream inStrm)
        {
            // Override OnLoad and uses a binary formatter to deserialize the log.
            var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            _log = (Dictionary <string, string>)bf.Deserialize(inStrm);
        }
Exemplo n.º 45
0
    private void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/Inventory.dat"))
        {
            //BinaryFormatter bf = new BinaryFormatter ();
            //FileStream file = File.Open (Application.persistentDataPath + "/Inventory.dat",FileMode.Open);
            using (Stream stream = File.Open(Application.persistentDataPath + "/Inventory.dat", FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                Loadeditems = (List <Item>)bformatter.Deserialize(stream);
            }

            foreach (Item Myitem in Loadeditems)
            {
                if (Myitem.ID == -1)
                {
                    Debug.Log(Myitem.ID);
                    continue;
                }
                Debug.Log(Myitem.ID);
                AddItem(Myitem.ID);
            }
            Debug.Log("File Exists");
        }
    }
Exemplo n.º 46
0
        /// <summary>
        /// 从磁盘加载Cookie
        /// </summary>
        private static void LoadCookiesFromDisk()
        {
            cc = new CookieContainer();
            string cookieFile = System.Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\HttpClient.cookie";

            if (!System.IO.File.Exists(cookieFile))
            {
                return;
            }
            FileStream fs = null;

            try
            {
                fs = new FileStream(cookieFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                cc = (CookieContainer)formater.Deserialize(fs);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                }
            }
        }
Exemplo n.º 47
0
 public T FromBinary <T>(byte[] binary) where T : class
 {
     using (MemoryStream memory = new MemoryStream(binary))
     {
         var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         return(formatter.Deserialize(memory) as T);
     }
 }
Exemplo n.º 48
0
 /// <summary>
 /// Reads an object instance from a binary file.
 /// </summary>
 /// <typeparam name="T">The type of object to read from the binary file.</typeparam>
 /// <param name="filePath">The file path to read the object instance from.</param>
 /// <returns>Returns a new instance of the object read from the binary file.</returns>
 public static T ReadFromBinaryFile <T>(string filePath)
 {
     using (Stream stream = File.Open(filePath, FileMode.Open))
     {
         var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         return((T)binaryFormatter.Deserialize(stream));
     }
 }
Exemplo n.º 49
0
 /// <summary>
 /// DesSerializador de Hashtable
 /// </summary>
 /// <param name="_fileName">Nome do ficheiro</param>
 /// <returns></returns>
 public static Hashtable DeserializeHashtable(string _fileName)
 {
     using (Stream stream = File.Open(_fileName, FileMode.Open))
     {
         var serializador = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         return((Hashtable)serializador.Deserialize(stream));
     }
 }
Exemplo n.º 50
0
 /// <summary>
 /// Deserializa un objeto a partir del contenido de un archivo binario
 /// </summary>
 /// <param name="fileName">Archivo desde donde toma los bytes que se
 /// encuentran serializados</param>
 /// <returns>objeto deserializado</returns>
 public static object DeserializeFromBin(string fileName)
 {
     using (System.IO.FileStream ds = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
     {
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         return(bf.Deserialize(ds));
     }
 }
Exemplo n.º 51
0
        public static VariableMgr Import(byte[] data)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(data, false);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            VariableMgr mgr = b.Deserialize(stream) as VariableMgr;

            return(mgr);
        }
Exemplo n.º 52
0
        private void button5_Click(object sender, EventArgs e)
        {
            //czyszczenie list grafu
            using (var g = Graphics.FromImage(pictureBox1.Image))
            {
                g.Clear(Color.White);
                pictureBox1.Refresh();
            }
            Nodes.Clear();
            Edges.Clear();

            string dir = "C:\\Graph\\";
            string serializationFileEdge = Path.Combine(dir, "edges.bin");

            using (Stream stream = File.Open(serializationFileEdge, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                Edges = (List <Edge>)bformatter.Deserialize(stream);

                foreach (Edge ed in Edges)
                {
                    Console.WriteLine(ed);
                }
            }

            string serializationFileNode = Path.Combine(dir, "nodes.bin");

            using (Stream stream = File.Open(serializationFileNode, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                Nodes = (List <Node>)bformatter.Deserialize(stream);

                foreach (Node n in Nodes)
                {
                    Console.WriteLine(n);
                }
            }

            using (var g = Graphics.FromImage(pictureBox1.Image))
            {
                Brush aBrush = (Brush)Brushes.Black;
                Pen   pen    = new Pen(Color.Black, 1);

                // rysowanie wezlow i krawedzi
                for (int i = 0; i < Nodes.Count; i++)
                {
                    g.FillRectangle(aBrush, Nodes[i].Point.X, Nodes[i].Point.Y, 5, 5);
                }

                for (int i = 0; i < Edges.Count; i++)
                {
                    g.DrawLine(pen, Edges[i].StartNode.Point.X, Edges[i].StartNode.Point.Y, Edges[i].EndNode.Point.X, Edges[i].EndNode.Point.Y);
                }
                pictureBox1.Refresh();
            }
        }
Exemplo n.º 53
0
        private List <CSOMaster> LoadItemWiseSales()
        {
            List <CSOMaster> oListSOMaster = new List <CSOMaster>();

            CSOBO    oCSOBO  = new CSOBO();
            CResult  oResult = new CResult();
            DateTime date    = dtpDate.Value.Date;

            oResult = oCSOBO.ReadSalesItemWise(dtpDateFrom2.Value.Date, dtpDateTo2.Value.Date, ddlRptBranch3.SelectedValue.ToString().Trim(), cmbItemName.SelectedValue.ToString(), ddlExportedBranch.SelectedValue.ToString().Trim());

            if (oResult.IsSuccess)
            {
                oListSOMaster = (List <CSOMaster>)oResult.Data;
            }
            else
            {
                MessageBox.Show(oResult.ErrMsg.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                oListSOMaster = null;
            }

            // Advance Start
            if (!defaultUserMode)
            {
                string m_sAdvanceConfigFileName = "AdvanceConfigAndLogFile.config";

                List <CSOMaster> oListSOMaster2 = new List <CSOMaster>();

                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                if (File.Exists(m_sAdvanceConfigFileName))
                {
                    using (Stream stream = new FileStream(m_sAdvanceConfigFileName, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        byte[]       baKey        = { 51, 208, 75, 59, 223, 134, 241, 155, 170, 229, 177, 160, 246, 71, 77, 141, 66, 7, 223, 103, 97, 80, 235, 82, 94, 107, 226, 190, 76, 94, 31, 43 };
                        byte[]       baIV         = { 142, 96, 41, 14, 206, 132, 173, 19, 12, 50, 124, 121, 42, 27, 35, 9 };
                        Rijndael     rijndael     = Rijndael.Create();
                        CryptoStream cryptoStream = new CryptoStream(stream, rijndael.CreateDecryptor(baKey, baIV), CryptoStreamMode.Read);
                        //
                        oListSOMaster2 = (List <CSOMaster>)formatter.Deserialize(cryptoStream);

                        //
                        cryptoStream.Close();
                    }
                }
                if (oListSOMaster2.Count > 0)
                {
                    foreach (CSOMaster oSOMaster in oListSOMaster2)
                    {
                        if (oSOMaster.SOMstr_Date.ToShortDateString() == dtpDate.Value.Date.ToShortDateString())
                        {
                            oListSOMaster.Add(oSOMaster);
                        }
                    }
                }
            }
            // Advance End

            return(oListSOMaster);
        }
Exemplo n.º 54
0
        public static Message BytesToMessage(byte[] bytes)
        {
            var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            using (var stream = new System.IO.MemoryStream(bytes))
            {
                return((Message)formatter.Deserialize(stream));
            }
        }
Exemplo n.º 55
0
        public static object DeSerializebinary(MemoryStream memStream)//二进制流反序列化为对象
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new
                                                                                          System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            object newobj = deserializer.Deserialize(memStream);   //创建一个内存流存储区

            memStream.Close();                                     //关闭内存流 并释放
            return(newobj);
        }
Exemplo n.º 56
0
    public static List <string> load()
    {
        using (Stream stream = File.Open("save.dat", FileMode.Open))
        {
            var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            return((List <string>)bformatter.Deserialize(stream));
        }
    }
Exemplo n.º 57
0
    void loadItemFile()
    {
        using (Stream stream = File.Open("save5.dat", FileMode.Open))
        {
            var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            idShop = (List <int>)bformatter.Deserialize(stream);
        }
    }
Exemplo n.º 58
0
        /// <summary>
        /// Deserializes an object from a byte array.
        /// </summary>
        /// <param name="data">The array of bytes that contains the serialization of the object.</param>
        /// <returns>An object that has been deserialized from the data.</returns>
        protected object BinaryDeSerialize(byte[] data)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            object result = formatter.Deserialize(ms);

            ms.Close();
            return(result);
        }
Exemplo n.º 59
0
 public int CaptureLoad(string path)
 {
     try
     {
         sb.BinaryFormatter bf = new sb.BinaryFormatter();
         using (io.FileStream fs = io.File.OpenRead(path))
         {
             captureDraw      = (List <ilGraphCaptureDraw>)bf.Deserialize(fs);
             captureDrawPoint = (List <ilGraphCaptureDrawPoint>)bf.Deserialize(fs);
             captureFill      = (List <ilGraphCaptureFill>)bf.Deserialize(fs);
             captureFillPoint = (List <ilGraphCaptureFillPoint>)bf.Deserialize(fs);
         }
     }
     catch (Exception e)
     {
         return(1);
     }
     return(0);
 }
        public Mark_Attendance_Form()
        {
            InitializeComponent();
            loadcourses  = new Linked_List <Course>();
            student_list = new Linked_List <Student>();

            string serializationFile = "course_file.bin";

            using (Stream stream = File.Open(serializationFile, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                loadcourses = (Linked_List <Course>)bformatter.Deserialize(stream);
            }
            for (ListNode <Course> temp = loadcourses.getHead(); temp != null; temp = temp.next)
            {
                courseBox.Items.Add(temp.val.get_String());
            }

            courseBox.Text = "Subject";
            idLabel.Text   = "";


            string studentfile = "student_file.bin";

            using (Stream stream = File.Open(studentfile, FileMode.Open))
            {
                var bformatter = new BinaryFormatter();

                student_list = (Linked_List <Student>)bformatter.Deserialize(stream);
            }

            face = new HaarCascade("haarcascade_frontalface_default.xml");
            //eye = new HaarCascade("haarcascade_eye.xml");
            try
            {
                //Load of previus trainned faces and labels for each image
                string   Labelsinfo = File.ReadAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt");
                string[] Labels     = Labelsinfo.Split('%');
                NumLabels = Convert.ToInt16(Labels[0]);
                ContTrain = NumLabels;
                string LoadFaces;

                for (int tf = 1; tf < NumLabels + 1; tf++)
                {
                    LoadFaces = "face" + tf + ".bmp";
                    trainingImages.Add(new Image <Gray, byte>(Application.StartupPath + "/TrainedFaces/" + LoadFaces));
                    labels.Add(Labels[tf]);
                }
            }
            catch
            {
                MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }