private const string PATH_TO_DAT_FILE = "./joueurs.dat"; //Répertoire courrant.

        #endregion Fields

        #region Methods

        /// <summary>
        /// Charge un fichier contenant tous les joueurs.
        /// </summary>
        /// <returns>La liste de joueurs s'il y en a, sinon null.</returns>
        public static List<Joueur> Load()
        {
            List<Joueur> joueurs = null;

            if (File.Exists(PATH_TO_DAT_FILE))
            {
                try
                {
                    using (Stream stream = File.Open(PATH_TO_DAT_FILE, FileMode.Open))
                    {
                        stream.Position = 0;
                        var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        joueurs = (List<Joueur>)bformatter.Deserialize(stream);
                    }
                }
                catch (ArgumentException)
                {
                    MessageBox.Show("Le fichier est invalide.");
                }
                catch (DirectoryNotFoundException)
                {
                    MessageBox.Show("Répertoire introuvable");
                }
                catch (FileNotFoundException)
                {
                    MessageBox.Show("Le fichier n'existe pas.");
                }
                catch (IOException)
                {
                    MessageBox.Show("Problème lors de la lecture du fichier.");
                }
            }

            return joueurs;
        }
Esempio n. 2
0
        public static byte[] Compress(System.Runtime.Serialization.ISerializable obj)
        {

            //    infile.Length];
            IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, obj);
            byte[] buffer = ms.ToArray();
            //Stream stream = new MemoryStream();

            //    FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
            //MyObject obj = (MyObject)formatter.Deserialize(stream);
            //stream.Close();



            // Use the newly created memory stream for the compressed data.
            MemoryStream msOutput = new MemoryStream();
            GZipStream compressedzipStream = new GZipStream(msOutput, CompressionMode.Compress, true);

            compressedzipStream.Write(buffer, 0, buffer.Length);
            // Close the stream.
            compressedzipStream.Close();
            return msOutput.ToArray();

        }
        /// <summary>
        /// Sauvegarde tous les joueurs.
        /// </summary>
        /// <param name="joueurs">La liste de joueurs a sauvegarder</param>
        public static void Save(List<Joueur> joueurs)
        {
            try
            {
                using (Stream stream = File.Open(PATH_TO_DAT_FILE, FileMode.Create))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    if (joueurs.Any())
                    {
                        bformatter.Serialize(stream, joueurs);
                    }
                }
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Le fichier est invalide.");
            }
            catch (DirectoryNotFoundException)
            {
                MessageBox.Show("Répertoire introuvable");
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("Le fichier n'existe pas.");
            }
            catch (IOException)
            {
                MessageBox.Show("Problème lors de la lecture du fichier.");
            }
            catch (System.Runtime.Serialization.SerializationException e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public SettingManager()
        {
            _cookieFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            _imageHashSerializer = new System.Xml.Serialization.XmlSerializer(typeof(HashSet<string>));

            //設定ファイル読み込み
            EmailAddress = GPlusImageDownloader.Properties.Settings.Default.EmailAddress;
            Password = GPlusImageDownloader.Properties.Settings.Default.Password;
            ImageSaveDirectory = new System.IO.DirectoryInfo(
                string.IsNullOrEmpty(GPlusImageDownloader.Properties.Settings.Default.ImageSaveDirectory)
                ? Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\testFolder"
                : GPlusImageDownloader.Properties.Settings.Default.ImageSaveDirectory);
            Cookies = DeserializeCookie();
            ImageHashList = DeserializeHashes();

            if (!ImageSaveDirectory.Exists)
                try
                {
                    ImageSaveDirectory.Create();
                    ImageSaveDirectory.Refresh();
                }
                catch (System.IO.IOException)
                { IsErrorNotFoundImageSaveDirectory = !ImageSaveDirectory.Exists; }
            else
                IsErrorNotFoundImageSaveDirectory = false;
        }
        public void TestBulkDeletionResultsSerializable()
        {
            var successfulObjects = new[] { "/container/object1", "/container/object2" };
            var failedObjects =
                new[]
                {
                    new BulkDeletionFailedObject("/badContainer/object3", new Status((int)HttpStatusCode.BadRequest, "invalidContainer")),
                    new BulkDeletionFailedObject("/container/badObject", new Status((int)HttpStatusCode.BadRequest, "invalidName"))
                };
            BulkDeletionResults results = new BulkDeletionResults(successfulObjects, failedObjects);
            BinaryFormatter formatter = new BinaryFormatter();
            using (Stream stream = new MemoryStream())
            {
                formatter.Serialize(stream, results);
                stream.Position = 0;
                BulkDeletionResults deserialized = (BulkDeletionResults)formatter.Deserialize(stream);
                Assert.IsNotNull(deserialized);

                Assert.IsNotNull(deserialized.SuccessfulObjects);
                Assert.AreEqual(successfulObjects.Length, deserialized.SuccessfulObjects.Count());
                for (int i = 0; i < successfulObjects.Length; i++)
                    Assert.AreEqual(successfulObjects[i], deserialized.SuccessfulObjects.ElementAt(i));

                Assert.IsNotNull(deserialized.FailedObjects);
                Assert.AreEqual(failedObjects.Length, deserialized.FailedObjects.Count());
                for (int i = 0; i < failedObjects.Length; i++)
                {
                    Assert.IsNotNull(deserialized.FailedObjects.ElementAt(i));
                    Assert.AreEqual(failedObjects[i].Object, deserialized.FailedObjects.ElementAt(i).Object);
                    Assert.IsNotNull(deserialized.FailedObjects.ElementAt(i).Status);
                    Assert.AreEqual(failedObjects[i].Status.Code, deserialized.FailedObjects.ElementAt(i).Status.Code);
                    Assert.AreEqual(failedObjects[i].Status.Description, deserialized.FailedObjects.ElementAt(i).Status.Description);
                }
            }
        }
Esempio n. 6
0
		/// <summary> Initializes all readonly configuration values </summary>
		static Configuration()
		{
			// Serializer:
			Binary = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			Binary.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
			Binary.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
			Binary.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded;

			// DEFUALT FORMATTING
			FORMAT_DEFAULT		= LogUtils.PrepareFormatString("[{ManagedThreadId:D2}] {Level,8} - {Message}");// <- this can NOT contain expressions
			FORMAT_METHOD		= LogUtils.PrepareFormatString("{MethodType:%s.}{MethodName}{MethodArgs:(%s)}");
			FORMAT_LOCATION		= LogUtils.PrepareFormatString("{LogCurrent:   executing %s}{Method:   at %s@}{IlOffset:?}{FileLocation}");
			FORMAT_FILELINE		= LogUtils.PrepareFormatString("{FileName: in %s:line }{FileLine:?}");
			FORMAT_FULLMESSAGE	= LogUtils.PrepareFormatString("{Message}{Location}{Exception}");
			FormatProvider = new EventDataFormatter();

			CSharpTest.Net.Utils.ProcessInfo info = new CSharpTest.Net.Utils.ProcessInfo();
			ProcessId = info.ProcessId;
			ProcessName = info.ProcessName;
			AppDomainName = info.AppDomainName;
			EntryAssembly = info.EntryAssembly.GetName().Name;
			IsDebugging = info.IsDebugging;

			DefaultLogFile = info.DefaultLogFile.Insert(info.DefaultLogFile.LastIndexOf('.'), "{0}");
		}
Esempio n. 7
0
        // Pelaajien lataaminen tiedostosta
        public List<Pelaaja> Load(string filepath)
        {
            // palautusarvo
            List<Pelaaja> players = new List<Pelaaja>();
            // haetaan pääte
            string ext = Path.GetExtension(filepath);

            using (Stream stream = File.Open(filepath, FileMode.Open))
            {
                // tarkastetaan tiedostopäätteen perusteella
                // miten sitä käsitellään
                // HOX HUONO TAPA, tiedostopäätteellä ei oikeasti ole merkitystä
                switch (ext)
                {
                    case ".xml":
                        XmlSerializer serializer = new XmlSerializer(typeof(List<Pelaaja>));
                        players = (List<Pelaaja>)serializer.Deserialize(stream);
                        break;

                    case ".bin":
                        var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        players = (List<Pelaaja>)bformatter.Deserialize(stream);
                        break;

                    default:
                        throw new Exception("Extension \"" + ext + "\" is not supported");
                }
            }

            return players;
        }
Esempio n. 8
0
 public void SyncFolderPairs(string ConfigFileName, int index, bool previewOnly)
 {
     SyncToy.SyncEngineConfig SEConfig = null;
     ArrayList EngineConfigs = new ArrayList();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     try
     {
         using (StreamReader sr = new StreamReader(ConfigFileName))
         {
             do
             {
                 SEConfig = (SyncToy.SyncEngineConfig)bf.Deserialize(sr.BaseStream);
                 EngineConfigs.Add(SEConfig);
             }
             while (sr.BaseStream.Position < sr.BaseStream.Length);
             sr.Close();
         }
         if (index != -1)
         {
             SyncFolderPair((SyncToy.SyncEngineConfig)EngineConfigs[index], previewOnly);
         }
         else
         {
             foreach (SyncToy.SyncEngineConfig Config in EngineConfigs)
             {
                 SyncFolderPair(Config, previewOnly);
             }
         }
        }
     catch (Exception ex)
     {
         Console.WriteLine("SyncFolderPairs Exception -> {0}", ex.Message);
     }
 }
		public void TestSerializeSchemaPropertyValueCollection()
		{
			System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			System.IO.MemoryStream ms = new System.IO.MemoryStream();
			SchemaPropertyValueCollection obj1 = new SchemaPropertyValueCollection();

			SCGroup group = SCObjectGenerator.PrepareGroupObject();

			foreach (string key in group.Properties.GetAllKeys())
			{
				obj1.Add(group.Properties[key]);
			}

			bf.Serialize(ms, obj1);
			ms.Seek(0, System.IO.SeekOrigin.Begin);

			var obj2 = (SchemaPropertyValueCollection)bf.Deserialize(ms);

			Assert.AreEqual(obj1.Count, obj2.Count);

			var keys1 = obj1.GetAllKeys();

			foreach (var key in keys1)
			{
				Assert.IsTrue(obj2.ContainsKey(key));
				Assert.AreEqual(obj1[key].StringValue, obj2[key].StringValue);
			}
		}
Esempio n. 10
0
 public MapFormatter()
 {
   serial = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
   serial.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
   serial.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways;
   serial.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
 }
Esempio n. 11
0
        public static double[] GetSimilarity(double[] a, double[] b)
        {
            if (s_simi == null)
            {
                s_simi = new SimilarityAnalysis();
                s_simi.setOptions(new string[] { "-T", "first-1", "-e", "20", "-r", "3", "-f", "false" });

                if (System.IO.File.Exists(CacheFileName))
                {
                    using (var file = System.IO.File.Open(CacheFileName, System.IO.FileMode.Open))
                    {
                        var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        m_cache = bf.Deserialize(file) as Dictionary<double[], double[]>;
                    }
                }
                else
                {
                    m_cache = new Dictionary<double[], double[]>();
                }
            }

            //double[] c = new double[a.Length + b.Length];
            //a.CopyTo(c, 0);
            //b.CopyTo(c, a.Length);
            //if (m_cache.ContainsKey(c))
            //    return m_cache[c];

            Instances instance = CreateInstanceOnFly(a, b);
            s_simi.analyze(instance);

            double[] ret = new double[] { s_simi.m_distancesFreq[1][0], s_simi.m_distancesTime[1][0] };
            //m_cache[c] = ret;

            return ret;
        }
 ///  <summary>  
 ///  序列化为二进制字节数组  
 ///  </summary>  
 ///  <param  name="request">要序列化的对象 </param>  
 ///  <returns>字节数组 </returns>  
 public static byte[] SerializeBinary(object request)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     System.IO.MemoryStream memStream = new System.IO.MemoryStream();
     serializer.Serialize(memStream, request);
     return memStream.GetBuffer();
 }
Esempio n. 13
0
 public void Write(string key, LocationCacheRecord lcr)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     formatter.Serialize(ms, lcr);
     cache.Write(key, ms.ToArray(), true);
 }
Esempio n. 14
0
        ///<summary>
        ///Forwards incoming clientdata to PacketHandler.
        ///</summary>
        public void handler()
        {
            clientStream = new SslStream(tcpClient.GetStream(), true);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Kettler_X7_Lib.Objects.Packet pack = null;

            X509Certificate serverCertificate = serverControl.getCertificate();

            try
            {
                clientStream.AuthenticateAsServer(serverCertificate,false, SslProtocols.Tls, false);
            }
            catch (Exception)
            {
                Console.WriteLine("Authentication failed");
                disconnect();
            }

            for (; ; )
            {
                try
                {
                    pack = formatter.Deserialize(clientStream) as Kettler_X7_Lib.Objects.Packet;
                    PacketHandler.getPacket(serverControl, this, pack);
                }
                catch
                {
                    disconnect();
                }

                Thread.Sleep(10);
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            //if (System.IO.Directory.Exists(cardPath) == false)
            //{
            //    System.IO.Directory.CreateDirectory(cardPath);
            //}
            if (System.IO.File.Exists(cardPath + "cardList") == false)
            {
                DownloadAllCardSet();
            }
            else
            {
                try
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter reader = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    System.IO.FileStream file = System.IO.File.OpenRead(cardPath + "cardList");
                    card.cardList = (List<card>)reader.Deserialize(file);
                    file.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Your card database seems to be corrupted, we will redownload it");
                    DownloadAllCardSet();
                }

            }
            if (System.IO.File.Exists(cardPath + "cardCollection") == true)
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter reader = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                System.IO.FileStream file = System.IO.File.OpenRead(cardPath + "cardCollection");
                card.MyCollection = (List<card>)reader.Deserialize(file);
                file.Close();
            }
        }
Esempio n. 16
0
        public static bool SerializeBin(string filePath, object target)
        {
            if (target == null)
            {
                return false;
            }
            if (string.IsNullOrEmpty(filePath))
            {
                return false;
            }

            try
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate);
                formatter.Serialize(stream, target);
                stream.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
Esempio n. 17
0
        public void TestBooleanQuerySerialization()
        {
            Lucene.Net.Search.BooleanQuery lucQuery = new Lucene.Net.Search.BooleanQuery();

            lucQuery.Add(new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("field", "x")), Occur.MUST);

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bf.Serialize(ms, lucQuery);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            Lucene.Net.Search.BooleanQuery lucQuery2 = (Lucene.Net.Search.BooleanQuery)bf.Deserialize(ms);
            ms.Close();

            Assert.AreEqual(lucQuery, lucQuery2, "Error in serialization");

            Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir, true);

            int hitCount = searcher.Search(lucQuery, 20).TotalHits;

            searcher.Close();
            searcher = new Lucene.Net.Search.IndexSearcher(dir, true);

            int hitCount2 = searcher.Search(lucQuery2, 20).TotalHits;

            Assert.AreEqual(hitCount, hitCount2, "Error in serialization - different hit counts");
        }
Esempio n. 18
0
 public LocationCacheRecord Read(string key)
 {
     byte[] buffer = cache.Read(key);
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     LocationCacheRecord lcr = (LocationCacheRecord)formatter.Deserialize(new System.IO.MemoryStream(buffer));
     return lcr;
 }
Esempio n. 19
0
        public static Message Deserialize(NetworkStream ns)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            object obj = bf.Deserialize(ns);
            return (Message)obj;
        }
Esempio n. 20
0
        public void RecreateBinFiles()
        {
            DataTable testOutput;

            using (
                var connection =
                    new SqlConnection("Server=localhost;Database=AdventureWorks2012;Trusted_Connection=True;"))
            {
                var qryText = new StringBuilder();
                qryText.AppendLine(QRY);
                testOutput = new DataTable();
                using (var command = connection.CreateCommand())
                {
                    command.Connection.Open();
                    command.CommandType = CommandType.Text;
                    command.CommandText = qryText.ToString();

                    using (var da = new SqlDataAdapter { SelectCommand = command })
                        da.Fill(testOutput);
                    command.Connection.Close();
                }
            }

            var binSer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            using (var ms = new MemoryStream())
            {
                binSer.Serialize(ms, testOutput);
                using (var binWtr = new BinaryWriter(File.Open(@"C:\Projects\31g\trunk\Code\NoFuture.Tests\Sql\DataTable.Person.bin", FileMode.Create)))
                    binWtr.Write(ms.GetBuffer());
            }
        }
Esempio n. 21
0
        // Pelaajien tallennus tiedostoon
        public void Save(string filepath, List<Pelaaja> players)
        {
            // Haetaan tiedostopääte
            string ext = Path.GetExtension(filepath);

            // käynnistetään stream
            using (Stream stream = File.Open(filepath, FileMode.Create))
            {
                // tarkastetaan tiedostopäätteen perusteella
                // missä muodossa se halutaan tallentaa
                switch (ext)
                {
                    case ".xml":
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Pelaaja>));
                        xmlSerializer.Serialize(stream, players);
                        break;

                    case ".bin":
                        var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        bformatter.Serialize(stream, players);
                        break;

                    default:
                        throw new Exception("Extension \"" + ext + "\" is not supported");
                }
            }
        }
Esempio n. 22
0
 /// <summary>
 /// Update a business object.
 /// </summary>
 /// <param name="request">The request parameter object.</param>
 public byte[] Update(byte[] req)
 {
   var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
   Csla.Server.Hosts.WcfBfChannel.UpdateRequest request;
   using (var buffer = new System.IO.MemoryStream(req))
   {
     request = (Csla.Server.Hosts.WcfBfChannel.UpdateRequest)formatter.Deserialize(buffer);
   }
   Csla.Server.DataPortal portal = new Csla.Server.DataPortal();
   object result;
   try
   {
     result = portal.Update(request.Object, request.Context);
   }
   catch (Exception ex)
   {
     result = ex;
   }
   var response = new WcfResponse(result);
   using (var buffer = new System.IO.MemoryStream())
   {
     formatter.Serialize(buffer, response);
     return buffer.ToArray();
   }
 }
 /// <summary>
 /// 扩展方法:将二进制byte[]数组反序列化为对象-通过系统提供的二进制流来完成反序列化
 /// </summary>
 /// <param name="SerializedObj">待反序列化的byte[]数组</param>
 /// <param name="ThrowException">是否抛出异常</param>
 /// <returns>返回结果</returns>
 public static object ByteArrayToObject(this byte[] SerializedObj, bool ThrowException)
 {
     if (SerializedObj == null)
     {
         return null;
     }
     else
     {
         try
         {
             System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             System.IO.MemoryStream stream = new System.IO.MemoryStream(SerializedObj);
             object obj = formatter.Deserialize(stream);
             return obj;
         }
         catch (System.Exception ex)
         {
             if (ThrowException)
             {
                 throw ex;
             }
             else
             {
                 return null;
             }
         }
     }
 }
Esempio n. 24
0
 public static void LoadFields()
 {
     IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     Stream stream = new FileStream("FieldList.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
     FieldList = (List<Field>)formatter.Deserialize(stream);
     stream.Close();
 }
 /// <summary>
 /// 扩展方法:将对象序列化为二进制byte[]数组-通过系统提供的二进制流来完成序列化
 /// </summary>
 /// <param name="Obj">待序列化的对象</param>
 /// <param name="ThrowException">是否抛出异常</param>
 /// <returns>返回结果</returns>
 public static byte[] ObjectToByteArray(this object Obj, bool ThrowException)
 {
     if (Obj == null)
     {
         return null;
     }
     else
     {
         try
         {
             System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             System.IO.MemoryStream stream = new System.IO.MemoryStream();
             formatter.Serialize(stream, Obj);
             return stream.ToArray();
         }
         catch (System.Exception ex)
         {
             if (ThrowException)
             {
                 throw ex;
             }
             else
             {
                 return null;
             }
         }
     }
 }
Esempio n. 26
0
        //void global_asax_AcquireRequestState(object sender, EventArgs e)
        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            // get the security cookie
            HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);

            if (cookie != null)
            {
                // we got the cookie, so decrypt the value
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                if (ticket.Expired)
                {
                    // the ticket has expired - force user to login
                    FormsAuthentication.SignOut();
                    //Response.Redirect("~/Security/Login.aspx");
                }
                else
                {
                    // ticket is valid, set HttpContext user value
                    System.IO.MemoryStream buffer = new System.IO.MemoryStream(Convert.FromBase64String(ticket.UserData));
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    HttpContext.Current.User = (System.Security.Principal.IPrincipal)formatter.Deserialize(buffer);
                }
            }
        }
 /// <summary>
 /// Uses the System formatters to save the MapXtreme objects in the session state as a binary blob.
 /// </summary>
 /// <param name="ser">A serializable object.</param>
 /// <remarks>If you simply send it to the Session state it will automatically extract itself the next time the user accesses the site. This allows you to deserialize certain objects when you want them. This method takes an object and saves it's binary stream.</remarks>
 /// <returns>A byte array to hold binary format version of object you passed in.</returns>
 public static byte[] BinaryStreamFromObject(object ser)
 {
     System.IO.MemoryStream memStr = new System.IO.MemoryStream();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     formatter.Serialize(memStr, ser);
     return memStr.GetBuffer();
 }
Esempio n. 28
0
        private void LoadGrammar_ToolButton_Click( object sender, EventArgs e )
        {
            if( this.LoadGrammar_Dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK )
            {
                try
                {
                    SyntacticAnalysis.Grammar grammar;
                    using( var stream = System.IO.File.OpenRead(this.LoadGrammar_Dialog.FileName) )
                    {
                        var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        grammar = (SyntacticAnalysis.Grammar)bf.Deserialize(stream);
                    }

                    this.Editor.Grammar = grammar;
                }
                catch( Exception ex )
                {
                    MessageBox.Show(
                        this,
                        ex.Message,
                        "Hiba nyelvtan betöltése közben",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
        }
 public void LoadQuestions(String fileName)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         using (System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Open))
         {
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_questions = (List<Question>)bformatter.Deserialize(stream);
         }
         using (System.IO.Stream stream = System.IO.File.Open(fileName+"p", System.IO.FileMode.Open))
         {
             Passage p = new Passage();
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             m_passage = (Passage)bformatter.Deserialize(stream);
         }
     }
     catch (Exception e)
     {
         Cursor.Current = Cursors.Default;
         MessageBox.Show("failed to load the file \"" + fileName + "\"\n\r" + e.Message, "Question Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     m_currentPage = 0;
     m_totalPages = m_questions.Count / m_questionsPerPage;
     this.RefreshQuestions();
     Cursor.Current = Cursors.Default;
 }
Esempio n. 30
0
        public Stock GetStock(StockName stockName, DateTime startDate, DateTime endDate)
        {
            string dir = String.Format(@"..\..\StockData\Yahoo");
            string filename = String.Format("{0}.stock", stockName);
            var fullPath = Path.Combine(dir, filename);

            List<IStockEntry> rates;
            if (!File.Exists(fullPath))
            {
                rates = GetStockFromRemote(stockName, startDate, endDate);
                Directory.CreateDirectory(dir);
                using (Stream stream = File.Open(fullPath, FileMode.Create))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bformatter.Serialize(stream, rates);
                }

            }
            else
            {
                using (Stream stream = File.Open(fullPath, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    rates = (List<IStockEntry>) bformatter.Deserialize(stream);
                }
            }
            var stock = new Stock(stockName, rates);
            return stock;
        }
Esempio n. 31
0
        /// <summary>
        /// Creates a unique 'clone' of an item. Used to create unique clones of commands when changing/updating new parameters.
        /// </summary>
        public static T Clone <T>(T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            if (source == null)
            {
                return(default(T));
            }

            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Stream stream = new MemoryStream();

            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return((T)formatter.Deserialize(stream));
            }
        }
        public void CanBeSerializedCorrectly()
        {
            XamlReadWriteException ex1 = new XamlReadWriteException("foo");

            MemoryStream ms = new MemoryStream();

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new
                                                                                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(ms, ex1);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            Object o = bf.Deserialize(ms);

            Assert.IsInstanceOfType(o, typeof(XamlReadWriteException));
            XamlReadWriteException ex2 = (XamlReadWriteException)o;

            Assert.AreEqual(ex1.Data.Count, ex2.Data.Count);
            Assert.AreEqual(ex1.InnerException, ex2.InnerException);
            Assert.AreEqual(ex1.Message, ex2.Message);
            Assert.AreEqual(ex1.StackTrace, ex2.StackTrace);
            Assert.AreEqual(ex1.ToString(), ex2.ToString());
        }
Esempio n. 33
0
        /// <summary> Perform a deep Copy of the object. Binary Serialization is used to perform the copy </summary>
        /// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
        /// <typeparam name="T">The type of object being copied </typeparam>
        /// <param name="source">The object instance to copy </param>
        /// <returns>The copied object </returns>
        public static T Clone <T>(this T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new System.ArgumentException("The type must be serializable.", "source");
            }

            // Don't serialize a null object, simply return the default for that object
            if (UnityEngine.Object.ReferenceEquals(source, null))
            {
                return(default(T));
            }

            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.Stream stream = new System.IO.MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                return((T)formatter.Deserialize(stream));
            }
        }
    static void Main(string[] args)
    {
        employees.Add(1, "Fred");
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        var fi = new System.IO.FileInfo(@"employees.bin");

        using (var binaryFile = fi.Create())
        {
            binaryFormatter.Serialize(binaryFile, employees);
            binaryFile.Flush();
        }
        Dictionary <int, string> readBack;

        using (var binaryFile = fi.OpenRead())
        {
            readBack = (Dictionary <int, string>)binaryFormatter.Deserialize(binaryFile);
        }
        foreach (var kvp in readBack)
        {
            Console.WriteLine($"{kvp.Key}\t{kvp.Value}");
        }
    }
Esempio n. 35
0
        public MainWindowForm()
        {
            //This tries to read the settings from "settings.bin", if it failes the settings stay at default values.
            try
            {
                IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                Stream     stream    = new FileStream("settings.bin", FileMode.Open, FileAccess.Read);
                oSettings = (KinectSettings)formatter.Deserialize(stream);
                stream.Close();
            }
            catch (Exception)
            {
            }

            oServer = new KinectServer(oSettings);
            oServer.eSocketListChanged += new SocketListChangedHandler(UpdateListView);
            oTransferServer             = new TransferServer();
            oTransferServer.lVertices   = lAllVertices;
            oTransferServer.lColors     = lAllColors;

            InitializeComponent();
        }
Esempio n. 36
0
        /// <summary>
        /// GetCookieStatus()で取得した値を渡すことで状態を復元する
        /// </summary>
        /// <param name="cookieStatusBase64"></param>
        /// <returns></returns>
        public bool SetCookieStatus(string cookieStatusBase64)
        {
            try
            {
                byte[]     bs        = System.Convert.FromBase64String(cookieStatusBase64);
                IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                using (Stream stream = new MemoryStream(bs.Length))
                {
                    stream.Position = 0;
                    stream.Write(bs, 0, bs.Length);
                    stream.Position = 0;
                    CookieStatus    = formatter.Deserialize(stream) as Hal.CookieGetterSharp.CookieStatus;
                }
                this.RefreshBrowser();
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Esempio n. 37
0
        /// <summary>
        /// Connette ad un host remoto e manda i file
        /// </summary>
        /// <param name="server">Dati dell'utente a cui connettersi</param>
        /// <param name="filesToSend">Lista dei file da mandare</param>
        /// <param name="ct">Usato per fermare la trasmissione dei file</param>
        /// <returns></returns>
        public async Task TransferRequestSender(User server, List <string> filesToSend, CancellationToken ct)
        {
            try
            {
                TcpClient client = new TcpClient(server.userAddress.ToString(), server.TcpPortTo);
                using (NetworkStream ns = client.GetStream())
                {
                    //TODO Send Info

                    //Serialize user
                    IFormatter   formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    MemoryStream ms        = new MemoryStream();
                    formatter.Serialize(ms, Configuration.CurrentUser);
                    byte[] data = ms.ToArray();
                    //Send size of serialized data
                    int    sizeFormatted = IPAddress.HostToNetworkOrder(data.Length);
                    byte[] sizeBuf       = BitConverter.GetBytes(sizeFormatted);
                    ns.Write(sizeBuf, 0, sizeBuf.Length);
                    //Send serialized data
                    ns.Write(data, 0, data.Length);

                    //TODO Send number of elements to send
                    int    numFiles = IPAddress.HostToNetworkOrder(filesToSend.Count);
                    byte[] nElemBuf = BitConverter.GetBytes(numFiles);
                    ns.Write(nElemBuf, 0, nElemBuf.Length);
                    Console.WriteLine("Sent " + filesToSend.Count.ToString());
                    //TODO Wait for ok



                    //TODO For each element send type, fileNameSize, fileName and transfer it
                }
            }
            catch (SocketException e)
            {
                //Error connecting to client
                //TODO Print error message
            }
        }
Esempio n. 38
0
        private void btnRemoveLinija_Click(object sender, EventArgs e)
        {
            Potvrda potvrda = new Potvrda();

            if (potvrda.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Prevoznik s = lstPrevoznici.SelectedItem as Prevoznik;
                s.Linii.Remove(lstLinii.SelectedItem as Linija);
                LiniiRefresh();


                LogIn.objekt = new Ser(LogIn.Prevoznici);
                System.Runtime.Serialization.IFormatter fmt = new
                                                              System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                FileStream strm = new FileStream("avtobuska.db", FileMode.Create,
                                                 FileAccess.Write, FileShare.None);
                fmt.Serialize(strm, LogIn.objekt);
                strm.Close();
            }

            VkupnoRefresh();
        }
Esempio n. 39
0
        private void btnAddPrevoznik_Click(object sender, EventArgs e)
        {
            DodadiPrevoznik_Admin dodadi = new DodadiPrevoznik_Admin();

            if (dodadi.ShowDialog() == DialogResult.OK)
            {
                Prevoznik a = dodadi.prevoznik;
                LogIn.Prevoznici.Add(a);
                lstPrevoznici.Items.Clear();
                PrevozniciRefresh();
            }
            LogIn.objekt = new Ser(LogIn.Prevoznici);
            System.Runtime.Serialization.IFormatter fmt = new
                                                          System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            FileStream strm = new FileStream("avtobuska.db", FileMode.Create,
                                             FileAccess.Write, FileShare.None);

            fmt.Serialize(strm, LogIn.objekt);
            strm.Close();

            VkupnoRefresh();
        }
Esempio n. 40
0
        /// <summary>
        /// 深拷贝对象副本
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepCopy <T>(this T obj)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            T copy = default(T);

            try
            {
                formatter.Serialize(ms, obj);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                copy = (T)formatter.Deserialize(ms);
            }
            catch (Exception ex)
            {
                throw new Exception("深拷贝对象实例出错", ex);
            }
            finally
            {
                ms.Close();
            }
            return(copy);
        }
Esempio n. 41
0
        public void WriteUser(User user)
        {
            System.IO.FileStream fs = null;
            try
            {
                if (System.IO.Directory.Exists(dbpath + "Save") == false)
                {
                    System.IO.Directory.CreateDirectory(dbpath + "Save");
                }
                if (System.IO.Directory.Exists(dbpath + "Save/Accounts") == false)
                {
                    System.IO.Directory.CreateDirectory(dbpath + "Save/Accounts");
                }
                fs = new System.IO.FileStream(dbpath + "Save/Accounts/" + user.Name + ".dat", System.IO.FileMode.Create);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter xs = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                xs.Serialize(fs, user);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: can't Write User in database");
                throw new Exception(ex.Message + "\r\n" + ex.StackTrace);
            }
            finally
            {
                try
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }

                catch (Exception ex)
                {
                    Console.WriteLine("Error: can't write User in database");
                    throw new Exception(ex.Message + "\r\n" + ex.StackTrace);
                }
            }
        }
Esempio n. 42
0
        public void Save()
        {
            _dimensions = _dim;
            IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Stream     toStream  = null;

            try
            {
                toStream = new FileStream(AppPath + "\\settings.dat", FileMode.Create, FileAccess.Write, FileShare.None);
                formatter.Serialize(toStream, this);
            }
            catch
            {
            }
            finally
            {
                if (toStream != null)
                {
                    toStream.Close();
                }
            }
        }
Esempio n. 43
0
 private void save()
 {
     try
     {
         using (System.Windows.Forms.SaveFileDialog dialog = new SaveFileDialog())
         {
             if (dialog.ShowDialog() == DialogResult.OK)
             {
                 using (Stream st = File.Open(dialog.FileName, FileMode.Create))
                 {
                     var binfor = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                     binfor.Serialize(st, G);
                     MessageBox.Show("Se ha guardado de manera correcta");
                 }
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Esempio n. 44
0
 /// <summary>
 /// Serialize object to path
 /// </summary>
 /// <param name="path">Target path</param>
 /// <param name="sObject">Serialize object</param>
 private static void serializeObject(string path, object sObject)
 {
     try
     {
         FileInfo fileInfo = new FileInfo(path);
         if (!fileInfo.Directory.Exists)
         {
             Directory.CreateDirectory(fileInfo.Directory.FullName);
         }
         //Open or create stream
         using (FileStream fs = new FileStream(path, FileMode.Truncate, FileAccess.ReadWrite, FileShare.Write))
         {
             //Use BinaryFormatter to write and save data
             System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             bf.Serialize(fs, sObject);
         }
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e.Message + " Line 34, SerializeHelper.cs");
     }
 }
Esempio n. 45
0
        static private Bundle FileToBundle(string file)
        {
            // Generate file name based on configuration and name of the wixpdb
            long position = 0;
            // create a new formatter instance
            var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            // read the animal as position back
            Bundle installable = null;

            using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                if (position < stream.Length)
                {
                    stream.Seek(position, SeekOrigin.Begin);
                    installable = (Bundle)formatter.Deserialize(stream);
                    position    = stream.Position;
                }
            }
            formatter = null;
            return(installable);
        }
Esempio n. 46
0
        /// <summary>
        /// Loads a listView from a file
        /// </summary>
        /// <param name="filePath">the path of the load file</param>
        /// <param name="loadTo">the ListView to load to</param>
        public static void LoadFile(string filePath, ListView loadTo)
        {
            if (File.Exists(filePath))
            {
                VideoData[] items = null;

                using (FileStream fs = File.OpenRead(filePath))
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    items = (VideoData[])bf.Deserialize(fs);
                }

                loadTo.Items.Clear();
                foreach (VideoData item in items)
                {
                    if (File.Exists(item.URL))
                    {
                        loadTo.Items.Add(item);
                    }
                }
            }
        }
Esempio n. 47
0
        public void TestRuntimeSerialize()
        {
            Mat img = new Mat(100, 80, DepthType.Cv8U, 3);

            using (MemoryStream ms = new MemoryStream())
            {
                //img.SetRandNormal(new MCvScalar(100, 100, 100), new MCvScalar(50, 50, 50));
                //img.SerializationCompressionRatio = 9;
                CvInvoke.SetIdentity(img, new MCvScalar(1, 2, 3));
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
                    formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(ms, img);
                Byte[] bytes = ms.GetBuffer();

                using (MemoryStream ms2 = new MemoryStream(bytes))
                {
                    Object o    = formatter.Deserialize(ms2);
                    Mat    img2 = (Mat)o;
                    EmguAssert.IsTrue(img.Equals(img2));
                }
            }
        }
Esempio n. 48
0
        public MainWindow()
        {
            InitializeComponent();

            TestClass testClass = new TestClass()
            {
                Property1 = 1,
                Property2 = "test",
                Property3 = DateTime.Now,
                Child     = new Child()
                {
                    Property1 = "test",
                }
            };

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            formatter.Serialize(memoryStream, testClass);

            memoryStream.Position = 0;
            TestClass deserialized = formatter.Deserialize(memoryStream) as TestClass;
        }
Esempio n. 49
0
        public static bool SerializeBinary(string path, object obj)
        {
            if (string.IsNullOrEmpty(path))
            {
                Log.W("SerializeBinary Without Valid Path.");
                return(false);
            }

            if (obj == null)
            {
                Log.W("SerializeBinary obj is Null.");
                return(false);
            }

            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
                    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bf.Serialize(fs, obj);
                return(true);
            }
        }
Esempio n. 50
0
        private void SendTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            if (!this.IsBroadcasting)
            {
                return;
            }

            var hgd = new BroadcasterHostedGameData();

            hgd.ProcessId  = Process.GetCurrentProcess().Id;
            hgd.GameGuid   = State.Instance.Engine.Game.GameId;
            hgd.GameName   = State.Instance.Engine.Game.GameName;
            hgd.GameStatus = State.Instance.Handler.GameStarted
                ? EHostedGame.GameInProgress
                : EHostedGame.StartedHosting;
            hgd.GameVersion = State.Instance.Engine.Game.GameVersion;
            hgd.HasPassword = State.Instance.Engine.Game.HasPassword;
            hgd.Name        = State.Instance.Engine.Game.Name;
            hgd.Port        = State.Instance.Engine.Game.HostUri.Port;
            hgd.Source      = State.Instance.Engine.IsLocal ? HostedGameSource.Lan : HostedGameSource.Online;
            hgd.TimeStarted = State.Instance.StartTime;
            hgd.Username    = State.Instance.Engine.Game.HostUserName;
            hgd.Id          = State.Instance.Engine.Game.Id;
            hgd.Spectator   = State.Instance.Engine.Game.Spectators;

            using (var ms = new MemoryStream())
            {
                var ser = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                ser.Serialize(ms, hgd);
                ms.Flush();

                ms.Position = 0;
                var bytes = ms.ToArray();
                var mess  = new List <byte>();
                mess.AddRange(BitConverter.GetBytes((Int32)bytes.Length));
                mess.AddRange(bytes);
                this.Client.Send(mess.ToArray(), mess.Count, new IPEndPoint(IPAddress.Broadcast, BroadcastPort));
            }
        }
Esempio n. 51
0
        static Settings()
        {
            try
            {
                if (System.IO.File.Exists(filename))
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    f.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
                    using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                    {
                        dic = (System.Collections.Generic.Dictionary <string, object>)f.Deserialize(fs);
                        fs.Close();
                    }
                }
            }
            catch {}

            if (dic == null)
            {
                dic = new System.Collections.Generic.Dictionary <string, object>();
            }
        }
Esempio n. 52
0
        static MatchInput MatchFromBin(byte[] rawInput, LogWatch watch = null)
        {
            if (null == watch)
            {
                watch = new LogWatch(true);
            }
            MatchInput input = null;

            using (var ms = new System.IO.MemoryStream(rawInput))
            {
                var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                input = bf.Deserialize(ms) as MatchInput;
            }
            if (null == input)
            {
                return(null);
            }
            watch.LogCostTime(string.Format("Home:{0}[{1}] vs Away:{2}[{3}]. Start)",
                                            input.HomeManager.Mid, input.HomeManager.Name,
                                            input.AwayManager.Mid, input.AwayManager.Name));
            return(input);
        }
Esempio n. 53
0
        /// <summary>
        /// Loads polls saved to bin file into current polls
        /// </summary>
        /// <returns></returns>
        public static List <Poll> LoadPolls()
        {
            string parentDir         = Environment.CurrentDirectory.ToString();
            string serializationFile = Path.Combine(parentDir, "polls.bin");

            if (File.Exists(serializationFile))
            {
                Console.Write(File.Exists(serializationFile));
                using (Stream stream = File.Open(serializationFile, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    stream.Position = 0;
                    List <Poll> pollList = (List <Poll>)bformatter.Deserialize(stream);
                    //foreach (Poll poll in pollList) { GetLastMessage(poll); }
                    return(pollList);
                }
            }
            else
            {
                return(new List <Poll>());
            }
        }
Esempio n. 54
0
        private void loadNetworks()
        {
            String dataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ZeroTier\\One";
            String dataFile = Path.Combine(dataPath, "networks.dat");

            if (File.Exists(dataFile))
            {
                List <ZeroTierNetwork> netList;

                using (Stream stream = File.Open(dataFile, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    netList = (List <ZeroTierNetwork>)bformatter.Deserialize(stream);
                    stream.Close();
                }

                lock (_knownNetworks)
                {
                    _knownNetworks = netList;
                }
            }
        }
Esempio n. 55
0
        private Auto leer(string name)
        {
            // Instaciamos el formatiador de tipo Binary
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter fomatiador
                = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            // Creamos el stream
            System.IO.Stream stream =
                new System.IO.FileStream(
                    name,
                    System.IO.FileMode.Open,
                    System.IO.FileAccess.Read,
                    System.IO.FileShare.None);

            // Deserealizamos
            Auto auto = (Auto)fomatiador.Deserialize(stream);

            // Cerramos la conexion
            stream.Close();

            return(auto);
        }
Esempio n. 56
0
        /// <summary>
        /// Guarda objecto que contém a lista em binário
        /// </summary>
        protected override void WriteFile()
        {
            // Declaração de variáveis locais
            string FilePath;
            Stream stream;

            // Definir caminho absoluto onde o ficheiro de texto será criado e escrito
            FilePath = Environment.CurrentDirectory + "//" + DATAFILE;

            // Inicializar stream de escrita através da criação do ficheiro onde serão guardados
            // Caso o ficheiro já exista, será reescrito
            stream = File.Create(FilePath);

            // Inicializar classe responsável por serializar os dados em binário
            var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            // Serializar objecto que contém os dados em binário
            serializer.Serialize(stream, UserList);

            // Fechar stream de escrita de modo a libertar os recursos do sistema
            stream.Close();
        }
Esempio n. 57
0
        /// <summary>
        /// Десериализуем класс SceneManager,чтобы получить
        /// сохранненные сцены...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManagerView_Load(object sender, EventArgs e)
        {
            try
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binFormat =
                    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                using (Stream fStream = new FileStream("user.dat",
                                                       FileMode.Open))
                {
                    sManager = (SceneManager)binFormat.Deserialize(fStream);
                    SceneManager.SM(sManager);
                    fStream.Close();
                }
            }
            catch
            {
                MessageBox.Show("Файл сохранений не найден или же он пуст...");
            }

            nameForm = this.Text;
        }
Esempio n. 58
0
        public bool SaveSearch(string path, bool compressed)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializeResults = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            if (!compressed)
            {
                FileStream resultFile = new FileStream(path, FileMode.Create);
                serializeResults.Serialize(resultFile, sSize);
                resultFile.Close();
                return(true);
            }

            ZipOutputStream resultStream = new ZipOutputStream(path);

            resultStream.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
            resultStream.PutNextEntry("ResList");

            serializeResults.Serialize(resultStream, sSize);
            resultStream.Close();
            resultStream.Dispose();
            return(true);
        }
Esempio n. 59
0
        public static void Add <T>(string key, T value, DateTime expity)
        {
            if (value == null)
            {
                return;
            }

            if (expity <= DateTime.Now)
            {
                Remove(key);

                return;
            }

            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //定义BinaryFormatter以序列化DataSet对象
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();                                                                 //创建内存流对象
                            formatter.Serialize(ms, value);                                                                                           //把DataSet对象序列化到内存流
                            byte[] buffer = ms.ToArray();                                                                                             //把内存流对象写入字节数组
                            ms.Close();                                                                                                               //关闭内存流对象
                            ms.Dispose();                                                                                                             //释放资源
                            r.Set(key, buffer, expity - DateTime.Now);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }
        }
        private void low_alerts()
        {
            string column1, column2, column3;

            //deserialize bin file so it can be read into the List object
            using (Stream stream = File.Open(path, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                items = (List <Item>)bformatter.Deserialize(stream);
            }

            for (int i = 0; i < items.Count(); i++)
            {
                if (Int32.Parse(items[i].getcount()) < 5)
                {
                    column1 = "Status: Low Stock";
                    column2 = "Item: " + items[i].getitem();
                    column3 = "Count: " + items[i].getcount();
                    AlertListBox.Items.Add(String.Format("{0} {1} {2}", column1.PadRight(24), column2.PadRight(19), column3.PadRight(10)));
                }
            }
        }