Inheritance: IRemotingFormatter, IFormatter
Example #1
2
 /// <summary>
 /// 将一个对象序列化为字节数组
 /// </summary>
 /// <param name="data">要序列化的对象</param>
 /// <returns>序列化好的字节数组</returns>
 public static byte[] ToBytes(Object data)
 {
     MemoryStream ms = new MemoryStream();
     BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(ms, data);
     return ms.ToArray();
 }
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider provider)
        {
            using (Form form1 = new Form())
            {
                form1.Text = "FormCollection Visualizer";
                form1.StartPosition = FormStartPosition.WindowsDefaultLocation;
                form1.SizeGripStyle = SizeGripStyle.Auto;
                form1.ShowInTaskbar = false;
                form1.ShowIcon = false;

                DataTable dt;

                using (Stream stream = provider.GetData())
                {
                    BinaryFormatter bformatter = new BinaryFormatter();

                    dt = (DataTable)bformatter.Deserialize(stream);

                    stream.Close();
                }

                DataGridView gridView = new DataGridView();
                gridView.Dock = DockStyle.Fill;

                form1.Controls.Add(gridView);

                gridView.DataSource = dt;

                windowService.ShowDialog(form1);
            }
        }
Example #3
0
        /// <summary>
        /// Opens a bin-file and converts it to a SaveFile that gets returned.
        /// </summary>
        public SaveFile LoadState()
        {

            SaveFile tmpFile = new SaveFile();

            Stream fileStreamer;
            BinaryFormatter bf;

            try
            {
                using(fileStreamer = File.Open("state.bin", FileMode.Open))
                {
                    bf = new BinaryFormatter();
                    var tmpState = bf.Deserialize(fileStreamer);
                    tmpFile = (SaveFile)tmpState;

                    return tmpFile;
                }
            }

            catch
            {
                return tmpFile;
            }       
        }
 public static MemoryStream SerializeToStream(object o)
 {
     MemoryStream stream = new MemoryStream();
     IFormatter formatter = new BinaryFormatter();
     formatter.Serialize(stream, o);
     return stream;
 }
Example #5
0
        public void TestVFSException()
        {
            var e1 = new VFSException();
            Assert.IsTrue(e1.Message.Contains("VFSException"));

            var e2 = new VFSException("a");
            Assert.AreEqual("a", e2.Message);

            var e3 = new VFSException("a", new Exception("x"));
            Assert.AreEqual("a", e3.Message);
            Assert.AreEqual("x", e3.InnerException.Message);

            using (var ms = new MemoryStream())
            {
                var serializer = new BinaryFormatter();
                serializer.Serialize(ms, e3);
                ms.Seek(0, SeekOrigin.Begin);

                var e4 = serializer.Deserialize(ms) as VFSException;

                Assert.IsNotNull(e4);
                Assert.AreEqual("a", e4.Message);
                Assert.AreEqual("x", e4.InnerException.Message);
            }
        }
Example #6
0
        /// <summary>
        /// Creates the crash dump.
        /// </summary>
        public static void CreateCrashDump()
        {
            if (!Directory.Exists("Dumps"))
                Directory.CreateDirectory("Dumps");

            Log.Info("Creating crash dump...");

            try
            {
                using (var fs =
                    File.Open(
                        Path.Combine(Environment.CurrentDirectory, "Dumps",
                                     string.Format("{0}.acd", DateTime.Now.ToString("yyyy_MM_dd_HH_mm"))),
                        FileMode.Create))
                {

                    var formatter = new BinaryFormatter();

                    var bot = AlarisBot.Instance;

                    formatter.Serialize(fs, bot);

                }
            }
            catch(Exception x)
            {
                Log.Fatal("Failed to write crash dump. ({0})", x);
                return;
            }

            Log.Info("Crash dump created.");
        }
        public void TestRoundTripElementSerialisation()
        {
            // Use a BinaryFormatter or SoapFormatter.
            IFormatter formatter = new BinaryFormatter();
            //IFormatter formatter = new SoapFormatter();

            // Create an instance of the type and serialize it.
            var elementId = new SerializableId
            {
                IntID = 42,
                StringID = "{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"
            };

            //Serialise to a test memory stream
            var m = new MemoryStream();
            formatter.Serialize(m, elementId);
            m.Flush();

            //Reset the stream
            m.Seek(0, SeekOrigin.Begin);

            //Readback
            var readback = (SerializableId)formatter.Deserialize(m);

            Assert.IsTrue(readback.IntID == 42);
            Assert.IsTrue(readback.StringID.Equals("{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"));
        }
		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;
		}
Example #9
0
 public void Save(string path)
 {
     BinaryFormatter binaryFormatter = new BinaryFormatter();
     FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
     binaryFormatter.Serialize(fileStream, this);
     fileStream.Close();
 }
Example #10
0
 public bool talk()
 {
     try
     {
         if (null != sendPro)
         {
             TcpClient client = new TcpClient();
             client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)),
                 int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort)));
             NetworkStream ns = client.GetStream();
             IFormatter formatter = new BinaryFormatter();
             formatter.Serialize(ns, sendPro);
             reseivePro = (Protocol)formatter.Deserialize(ns);
             client.Close();
         }
         else
         {
             return false;
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
 public void LoadFromFile(string aPath)
 {
     using (Stream stream = File.Open(aPath, FileMode.Open))
     {
         Clear();
         BinaryFormatter bin = new BinaryFormatter();
         Configuration deserialized = bin.Deserialize(stream) as Configuration;
         foreach (var prof in deserialized.Professors)
         {
             Professors.Add(prof);
         }
         foreach (var room in deserialized.Rooms)
         {
             Rooms.Add(room);
         }
         foreach (var group in deserialized.Groups)
         {
             Groups.Add(group);
         }
         foreach (var course in deserialized.Courses)
         {
             Courses.Add(course);
         }
         foreach (var constraint in deserialized.Constraints)
         {
             Constraints.Add(constraint);
         }
         foreach (var classcont in deserialized.Classes)
         {
             Classes.Add(classcont.Key, classcont.Value);
         }
     }
 }
        private bool SetValue(object currentValue, out object newValue)
        {
            DTE dte = this.GetService<DTE>(true);
            IDictionaryService dictionaryService = (IDictionaryService)ServiceHelper.GetService(this, typeof(IDictionaryService));

            try
            {
                if (!string.IsNullOrEmpty(RecipeArgument))
                {

                    string argumentvalue = dictionaryService.GetValue(RecipeArgument).ToString();
                    Version v = new Version(argumentvalue);
                    if (v != null)
                    {
                        byte[] bytes;
                        long length = 0;
                        MemoryStream ws = new MemoryStream();
                        BinaryFormatter sf = new BinaryFormatter();
                        sf.Serialize(ws, v);
                        length = ws.Length;
                        bytes = ws.GetBuffer();
                        newValue = Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
                        return true;
                    }
                }
            }
            catch { }
            //string projectId = currentProject.

            newValue = "";
            return false;
        }
Example #13
0
        public override void OnSaveData()
        {
            LoggerUtilities.Log("Saving road names");

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();

            try
            {
                RoadContainer[] roadNames = RoadNameManager.Instance().Save();

                if (roadNames != null)
                {
                    binaryFormatter.Serialize(memoryStream, roadNames);
                    serializableDataManager.SaveData(dataKey, memoryStream.ToArray());
                    LoggerUtilities.Log("Road names have been saved!");
                }
                else
                {
                    LoggerUtilities.LogWarning("Couldn't save road names, as the array is null!");
                }
            }
            catch (Exception ex)
            {
                LoggerUtilities.LogException(ex);
            }
            finally
            {
                memoryStream.Close();
            }
        }
 /// <summary>
 /// Save the specified object.
 /// </summary>
 /// <param name="filename">The filename to save to.</param>
 /// <param name="obj">The object to save.</param>
 public static void Save(string filename, object obj)
 {
     Stream s = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
     var b = new BinaryFormatter();
     b.Serialize(s, obj);
     s.Close();
 }
 /// <summary>
 /// Encode value into a stream
 /// </summary>
 /// <param name="value">Value to encode</param>
 /// <param name="destination">Stream to write the serialized object to.</param>
 public void Encode(object value, Stream destination)
 {
     if (value == null) throw new ArgumentNullException("value");
     if (destination == null) throw new ArgumentNullException("destination");
     var formatter = new BinaryFormatter();
     formatter.Serialize(destination, value);
 }
Example #16
0
        public void Constructor_InitializesSerializer()
        {
            serializer = new BinaryFormatter();

            Assert.IsTrue(serverStream.IsConnected);
            Assert.IsTrue(clientStream.IsConnected);
        }
        public void Save(TelemetryLap lap, string fileName)
        {
            try
            {

                if (lap == null)
                    return;

                if (File.Exists(fileName))
                    File.Delete(fileName);

                using (Stream stream = File.Open(fileName, FileMode.Create))
                {
                    var binFormatter = new BinaryFormatter();
                    binFormatter.Serialize(stream, lap);
                    stream.Close();
                }
            } catch (Exception ex)
            {
                #if DEBUG
                logger.Error("Count not save binary telemetry lap", ex);
            #endif
                throw ex;
            }
        }
Example #18
0
        public int Run()
        {
            try
            {
                Stream codeStream = LocateCode();
                var formatter = new BinaryFormatter();
                var reader = new ScriptEngine.Compiler.ModulePersistor(formatter);
                var moduleHandle = reader.Read(codeStream);
                var engine = new HostedScriptEngine();
                var src = new BinaryCodeSource(moduleHandle);

                var process = engine.CreateProcess(this, moduleHandle, src);
                return process.Start();
                
            }
            catch (ScriptInterruptionException e)
            {
                return e.ExitCode;
            }
            catch (Exception e)
            {
                this.ShowExceptionInfo(e);
                return 1;
            }

        }
Example #19
0
 public static void saveToFile(Mesh mesh, string _filename)
 {
     Stream stream = File.Open(_filename, FileMode.Create);
     BinaryFormatter bFormatter = new BinaryFormatter();
     bFormatter.Serialize(stream, mesh);
     stream.Close();
 }
Example #20
0
        public ManufacturersForm(GXManufacturerCollection manufacturers, string selectedManufacturer)
        {
            InitializeComponent();
            NameCH.Width = -2;
            UpdateValues();
            InactivityModeTB.Enabled = StartProtocolTB.Enabled = NameTB.Enabled = ManufacturerIdTB.Enabled = UseLNCB.Enabled = UseIEC47CB.Enabled = false;
            ManufacturersOriginal = manufacturers;

            //Create clone from original items.
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, manufacturers);
            ms.Position = 0;
            Manufacturers = (GXManufacturerCollection)bf.Deserialize(ms);
            ms.Close();
            bool bSelected = false;
            foreach (GXManufacturer it in Manufacturers)
            {
                if (!it.Removed)
                {
                    ListViewItem item = AddManufacturer(it);
                    if (it.Identification == selectedManufacturer)
                    {
                        bSelected = item.Selected = true;
                    }
                }
            }
            //Select first item
            if (ManufacturersList.Items.Count != 0 && !bSelected)
            {
                ManufacturersList.Items[0].Selected = true;
            }
        }
Example #21
0
 private static Object DeserializeFromMemory(Stream stream)
 {
     //构造一个序列化格式化器来做所有辛苦的工作
     BinaryFormatter formatter = new BinaryFormatter();
     //告诉格式化器从流中反序列化对象
     return formatter.Deserialize(stream);
 }
Example #22
0
        public Base GetCompletedWork(Guid jobGuid)
        {
            if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager");

            while (true)
            {
                Packet p = new Packet(1100);
                p.Add(jobGuid.ToByteArray(),true);
                _ConnectionToManager.SendPacket(p);
                Stopwatch sendTime = new Stopwatch();
                sendTime.Start();
                while (sendTime.ElapsedMilliseconds < _CommsTimeout)
                {
                    if (_ConnectionToManager.GetPacketsToProcessCount() > 0)
                    {
                        foreach (Packet packet in _ConnectionToManager.GetPacketsToProcess())
                        {
                            switch (packet.Type)
                            {
                                case 1101:
                                    return null;
                                case 1102:
                                    Object[] packetObjects = packet.GetObjects();
                                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                                    return (Base) binaryFormatter.Deserialize(new MemoryStream((Byte[]) packetObjects[0]));
                            }
                        }
                        Thread.Sleep(100);
                    }
                }
                if (_ConnectionToManager.IsConnected())_ConnectionToManager.Disconnect();
                _ConnectionToManager.Connect(_IpAddress, _Port, 204800);
            }
            return null;
        }
Example #23
0
        //Méthode statique pour l'envoi et la réception
        public void Send(Paquet paquet, NetworkStream stream)
        {
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(stream, paquet);
            stream.Flush();
        }
Example #24
0
        public Guid SendJob(Base activity)
        {
            if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager");

            while (true)
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                MemoryStream datastream = new MemoryStream();
                binaryFormatter.Serialize(datastream, activity);
                Packet p = new Packet(1000);
                Byte[] data= datastream.ToArray();
                p.Add(data,true);
                _ConnectionToManager.SendPacket(p);
                Stopwatch sendTime = new Stopwatch();
                sendTime.Start();
                while (sendTime.ElapsedMilliseconds < _CommsTimeout)
                {
                    if (_ConnectionToManager.GetPacketsToProcessCount() > 0)
                    {
                        foreach (Guid jobGuid in from packet in _ConnectionToManager.GetPacketsToProcess() where packet.Type == 1001 select new Guid((Byte[]) packet.GetObjects()[0]))
                        {

                            return jobGuid;
                        }
                    }
                    Thread.Sleep(1);
                }
                if (_ConnectionToManager.IsConnected()) _ConnectionToManager.Disconnect();
                _ConnectionToManager.Connect(_IpAddress, _Port, 20480 * 1024);
            }
            throw new Exception("Mananger unavailable or busy");
        }
 public static object DeserializeFromStream(MemoryStream stream)
 {
     IFormatter formatter = new BinaryFormatter();
     stream.Seek(0, SeekOrigin.Begin);
     object o = formatter.Deserialize(stream);
     return o;
 }
 public void Save()
 {
     Stream stream = File.Open(filepath, FileMode.Create);
     BinaryFormatter bFormatter = new BinaryFormatter();
     bFormatter.Serialize(stream, this);
     stream.Close();
 }
 static MethodEvaluator()
 {
     BinaryFormatter formatter = new BinaryFormatter {
         AssemblyFormat = FormatterAssemblyStyle.Simple
     };
     s_Formatter = formatter;
 }
Example #28
0
 public static void LoadFromFile(string filePath, object options)
 {
     FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
     BinaryFormatter bf = new BinaryFormatter();
     options = bf.Deserialize(fs);
     fs.Close();
 }
Example #29
0
 // Serialize and Save all Template list
 private void SerializeAndSave(string fileName, Template templejt)
 {
     System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Truncate);
     BinaryFormatter bFormatter = new BinaryFormatter();
     bFormatter.Serialize(stream, templejt);
     stream.Close();
 }
Example #30
0
 static void Main(string[] args)
 {
     string quit = "n";
     while (quit == "n")
     {
         ITransport transport = TcpTransport.CreateTransport(45459);
         if (transport != null)
         {
             IEvent e = new TcpEvent((int)EventId.Media, null);
             BinaryFormatter bf = new BinaryFormatter();
             MemoryStream mem = new MemoryStream();
             bf.Serialize(mem, e);
             transport.Send(mem.GetBuffer());
             Console.WriteLine("Quit?(y/n)");
             quit = Console.ReadLine();
             transport.Close();
             //if (quit != "n")
             //{
             //    Console.WriteLine("send disconned event to Server to close the server");
             //    IEvent d = new TcpEvent((int)EventId.Disconnect, null);
             //    BinaryFormatter bfd = new BinaryFormatter();
             //    MemoryStream memd = new MemoryStream();
             //    bfd.Serialize(memd, d);
             //    transport.Send(memd.GetBuffer());
             //    transport.Close();
             //}
         }
     }
 }