Пример #1
0
 public static void LoadFile()
 {
     try
     {
         recentProjects=new System.Collections.ArrayList(4);
         recentFiles=new System.Collections.ArrayList(4);
         System.IO.FileStream stream = new System.IO.FileStream("\\lastfiles.dat", System.IO.FileMode.Open);
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         recentProjects = (System.Collections.ArrayList)formatter.Deserialize( stream );
         recentFiles = (System.Collections.ArrayList)formatter.Deserialize( stream );
         stream.Close();
     }
     catch{}
 }
Пример #2
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;
        }
Пример #3
0
 /// <summary>
 /// Get an existing business object.
 /// </summary>
 /// <param name="request">The request parameter object.</param>
 public byte[] Fetch(byte[] req)
 {
   var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
   Csla.Server.Hosts.WcfBfChannel.FetchRequest request;
   using (var buffer = new System.IO.MemoryStream(req))
   {
     request = (Csla.Server.Hosts.WcfBfChannel.FetchRequest)formatter.Deserialize(buffer);
   }
   Csla.Server.DataPortal portal = new Csla.Server.DataPortal();
   object result;
   try
   {
     result = portal.Fetch(request.ObjectType, request.Criteria, 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();
   }
 }
Пример #4
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;
 }
Пример #5
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 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;
 }
        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);
                }
            }
        }
Пример #8
0
        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;
        }
Пример #9
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 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();
            }
        }
 /// <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;
             }
         }
     }
 }
Пример #12
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;
        }
Пример #13
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();
 }
Пример #14
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");
        }
Пример #15
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;
        }
Пример #16
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);
                }
            }
        }
Пример #17
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;
        }
Пример #18
0
		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);
			}
		}
 public void LoadData()
 {
     IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     System.IO.Stream stream = new System.IO.FileStream(path + "/SimpleRandDef.rand", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
     SaveData saveData = (SaveData) formatter.Deserialize(stream);
     stream.Close();
     categories = saveData.categories;
 }
Пример #20
0
 /// <summary>
 /// Wczytuje listę wyników z pliku do topScoreList
 /// </summary>
 private void LoadTopScoreList()
 {
     using (Stream stream = File.Open(@"TopScoreTable.bin", FileMode.Open))
     {
         var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         topScoreList = (List<HighScore>)binaryFormatter.Deserialize(stream);
     }
 }
Пример #21
0
 /// <summary>
 /// 将内存流反序列为对像
 /// </summary>
 /// <param name="memStream">内存流</param>
 /// <returns></returns>
 public static object DeSerializeMemoryStream(System.IO.MemoryStream memStream)
 {
     memStream.Position = 0;
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     object newobj = deserializer.Deserialize(memStream);
     memStream.Close();
     return newobj;
 }
Пример #22
0
 public static List<UserInfo> Deserialize(string userString)
 {
     byte[] userBytes = ASCIIEncoding.ASCII.GetBytes(userString.ToCharArray());
     MemoryStream memoryStream = new MemoryStream(userBytes);
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     memoryStream.Seek(0, SeekOrigin.Begin);
     return (List<UserInfo>)bf.Deserialize(memoryStream);
 }
Пример #23
0
 public OrderPackage Clone()
 {
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     formatter.Serialize(memoryStream, this);
     memoryStream.Position = 0;
     OrderPackage newPackage = (OrderPackage)formatter.Deserialize(memoryStream);
     return newPackage;
 }
Пример #24
0
 private static List<ColumnInfo> DeserializeColumnInfo(string code)
 {
     using (System.IO.MemoryStream stream = new System.IO.MemoryStream(Convert.FromBase64String(code)))
     {
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
             new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         return (List<ColumnInfo>)bf.Deserialize(stream);
     }
 }
Пример #25
0
 public ImageRecord Clone()
 {
     System.IO.MemoryStream m = new System.IO.MemoryStream();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b =
         new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     b.Serialize(m, this);
     m.Position = 0;
     return (ImageRecord)b.Deserialize(m);
 }
Пример #26
0
 /// <summary>
 /// 【通用函数】字节数组转换成对象,自动判断isDbNull,返回null
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static object BytesToObj(byte[] data)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     using (MemoryStream rems = new MemoryStream(data))
     {
         rems.Position = 0;
         return formatter.Deserialize(rems);
     }
 }
Пример #27
0
 /// <summary>
 /// 反序列化参数设定
 /// </summary>
 /// <param name="strFileName">反序列化文件名</param>
 /// <returns>返回对象</returns>
 public static object DeserializeBinary(string strFileName)
 {
     //System.IO.MemoryStream memStream = new MemoryStream(buf);
     //memStream.Position = 0;
     System.IO.FileStream fileStream = new FileStream(strFileName, FileMode.Open);
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     object newobj = deserializer.Deserialize(fileStream);
     fileStream.Close();
     return newobj;
 }   
Пример #28
0
		public void Serializable() {
			var store = new StoreRequest();
			store.Attributes.Add("http://someAttribute", "val1", "val2");
			var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			var ms = new MemoryStream();
			formatter.Serialize(ms, store);
			ms.Position = 0;
			var store2 = formatter.Deserialize(ms);
			Assert.AreEqual(store, store2);
		}
Пример #29
0
 public static SerializedObject DeSerialize(string messageBody)
 {
     byte[] bytes = Convert.FromBase64String(messageBody);
     System.IO.MemoryStream stream = new System.IO.MemoryStream();
     stream.Write(bytes, 0, bytes.Length);
     stream.Flush();
     stream.Position = 0;
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     object result = f.Deserialize(stream);
     return (SerializedObject)result;
 }
 public static Object createDeepCopyBySerialization(Object objectToCopy)
 {
     // Create a deep copy of the current sequence file, by serializing and then deserializing. A clever trick.
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         bf.Serialize(ms, objectToCopy);
         ms.Position = 0;
         return bf.Deserialize(ms);
     }
 }
Пример #31
0
        public ObservableCollection <Check> ReadChecks(DateTime dateTime)
        {
            string destPath1 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Racuni", $"{dateTime.Year}_{dateTime.Month}_{dateTime.Day}_{racuni}");

            try
            {
                var f_fileStream      = File.OpenRead(destPath1);
                var f_binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                ObservableCollection <Check> checks = (ObservableCollection <Check>)f_binaryFormatter.Deserialize(f_fileStream);
                f_fileStream.Close();
                return(checks);
            }
            catch (Exception exe)
            {
                Console.WriteLine($"neuspesna deserijalizacija zbog {exe.Message}");
                return(null);
            }
        }
Пример #32
0
        public static object DeserializeBinary(Stream stream)
        {
            if (stream == null)
            {
                Log.W("DeserializeBinary Failed!");
                return(null);
            }

            using (stream)
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
                    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                var data = bf.Deserialize(stream);

                // TODO:这里没风险嘛?
                return(data);
            }
        }
Пример #33
0
        public ObservableCollection <Table> ReadTables()
        {
            string destPath1 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, stolovi);

            try
            {
                var f_fileStream      = File.OpenRead(destPath1);
                var f_binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                ObservableCollection <Table> stolovi = (ObservableCollection <Table>)f_binaryFormatter.Deserialize(f_fileStream);
                f_fileStream.Close();
                return(stolovi);
            }
            catch (Exception exe)
            {
                Console.WriteLine($"neuspesna deserijalizacija zbog {exe.Message}");
                return(null);
            }
        }
Пример #34
0
        public PriceList ReadPriceList()
        {
            string destPath1 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cenovnik);

            try
            {
                var       f_fileStream      = File.OpenRead(destPath1);
                var       f_binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                PriceList priceList         = (PriceList)f_binaryFormatter.Deserialize(f_fileStream);
                f_fileStream.Close();
                return(priceList);
            }
            catch (Exception exe)
            {
                Console.WriteLine($"neuspesna deserijalizacija zbog {exe.Message}");
                return(null);
            }
        }
Пример #35
0
 /// <summary>
 /// 反序列化XML文件
 /// </summary>
 /// <param name="FileFullPath">文件全路径</param>
 /// <returns></returns>
 public static bool DeserializeXmlFile(string FileFullPath)
 {
     try
     {
         System.Data.DataSet DS = new System.Data.DataSet();
         FileStream          FS = new FileStream(FileFullPath, FileMode.Open);
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter FT = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         ((System.Data.DataSet)FT.Deserialize(FS)).WriteXml(FileFullPath + ".tmp");
         FS.Close();
         DeleteFile(FileFullPath);
         File.Move(FileFullPath + ".tmp", FileFullPath);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Пример #36
0
        public void NotificationObjectShouldBeSerializable()
        {
            var  serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            var  stream     = new System.IO.MemoryStream();
            bool invoked    = false;

            var testObject = new TestNotificationObject();

            testObject.PropertyChanged += (o, e) => { invoked = true; };

            serializer.Serialize(stream, testObject);

            stream.Seek(0, System.IO.SeekOrigin.Begin);

            var reconstitutedObject = serializer.Deserialize(stream) as TestNotificationObject;

            Assert.IsNotNull(reconstitutedObject);
        }
Пример #37
0
        private void OpenFile_Click(object sender, EventArgs e)
        {
            int          size   = -1;
            var          FD     = new System.Windows.Forms.OpenFileDialog();
            DialogResult result = FD.ShowDialog(); // Show the dialog.

            if (result == DialogResult.OK)         // Test result.
            {
                string file = FD.FileName;
                try
                {
                    using (Stream stream = File.Open(file, FileMode.Open))
                    {
                        var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                        dataList = (List <Data>)bformatter.Deserialize(stream);
                    }
                    PulseLB.Text          = dataList[0].pulse;
                    RPMLB.Text            = dataList[0].rpm;
                    SpeedLB.Text          = dataList[0].speed;
                    DistanceLB.Text       = dataList[0].distance;
                    RequestedPowerLB.Text = dataList[0].requestedPower;
                    EnergyLB.Text         = dataList[0].energy;
                    ElepsedTimeLB.Text    = dataList[0].elapsedTime;
                    ActualPowerLB.Text    = dataList[0].actualpower;

                    HistoryChart.Series.Add("speed");
                    HistoryChart.Series["speed"].ChartType           = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                    HistoryChart.ChartAreas[0].AxisX.IsMarginVisible = false;
                    HistoryChart.Invoke(new Action(() =>
                    {
                        foreach (Data data in dataList)
                        {
                            HistoryChart.Series["speed"].Points.AddY(data.speed);
                        }
                    }));
                }
                catch (IOException)
                {
                }
            }
            Console.WriteLine(size);   // <-- Shows file size in debugging mode.
            Console.WriteLine(result); // <-- For debugging use.
        }
Пример #38
0
        //read binary data from external file (image-object.dat) and convert byte array into object, in this case it's an image object, and show the image in picturebox
        //pictureBox2.Image = (Image)FileToObject("c:\\image-object.dat");
        public object ConvertFileToObject(string _FileName)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                byte[] _ByteArray = _BinaryReader.ReadBytes((Int32)_TotalBytes);

                // close file reader and do some cleanup
                _FileStream.Close();
                _FileStream.Dispose();
                _FileStream = null;
                _BinaryReader.Close();

                // 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));
            }
            catch (Exception _Exception)
            {
                // Error
                _Exception.ToString();
            }

            // Error occured, return null
            return(null);
        }
Пример #39
0
        //****************************************************************************************
        //
        //****************************************************************************************

        public bool Deserialize(Stream stream, BinaryFormatter formatter)
        {
            if (stream == null)
            {
                return(false);
            }

            if (formatter == null)
            {
                return(false);
            }

            int nbEntries = ( int )formatter.Deserialize(stream);

            for (int entry = 0; entry < nbEntries; ++entry)
            {
                Entry pEntry = new Entry();

                pEntry.Deserialize(stream, formatter);

                m_entries.Add(pEntry);
            }


            System.Type type = typeof(T);

            System.Reflection.BindingFlags bindingFlags = (System.Reflection.BindingFlags)(-1);

            for (int entry = 0; entry < m_entries.Count; ++entry)
            {
                string fieldname = m_entries[entry].fieldname;

                System.Reflection.FieldInfo fieldinfo = type.GetField(fieldname, bindingFlags);

                if (fieldinfo == null)
                {
                    Debug.Log("Field: " + fieldname + " no longer exist in class " + type.ToString() + " current implementation");
                }

                m_entries[entry].fieldinfo = fieldinfo;
            }

            return(true);
        }
Пример #40
0
        /// <summary>
        /// Opens the configuration.
        /// </summary>
        /// <returns><c>true</c>, if configuration was opened, <c>false</c> otherwise.</returns>
        /// <param name="path">Path.</param>
        public bool OpenConfiguration(string path)
        {
            if (File.Exists(path))
            {
                try {
                    Stream stream    = File.Open(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.Write);
                    var    formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    var config = formatter.Deserialize(stream);

                    Configuration = (BoardConfiguration)config;

                    stream.Close();

                    if (LastConfigurationLocations.Contains(path))
                    {
                        LastConfigurationLocations.Remove(path);
                        LastConfigurationLocations.Reverse();
                        LastConfigurationLocations.Add(path);
                        LastConfigurationLocations.Reverse();
                    }
                    else
                    {
                        LastConfigurationLocations.Reverse();
                        LastConfigurationLocations.Add(path);
                        LastConfigurationLocations.Reverse();
                    }
                    WritePreferences();

                    if (OnOnfigurationLoaded != null)
                    {
                        OnOnfigurationLoaded.Invoke(this, new ConfigurationLoadedArgs(path, true));
                    }
                } catch (Exception) {
                    throw;
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #41
0
        public void LoadRememberMe()
        {
            if (!new System.IO.FileInfo(this.SerializationFullPathFile).Exists)
            {
                return;
            }

            System.IO.FileStream fs = null;

            try
            {
                // Create the stream
                fs = new System.IO.FileStream(SerializationFullPathFile, System.IO.FileMode.Open);

                // Create the formatter
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
                    new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                // Create the temp user
                Users u = new Users();

                //deserialize
                u = (Users)bf.Deserialize(fs);

                // Close the stream
                fs.Close();

                this.UserID    = u.UserID;
                this.Username  = u.Username;
                this.Password  = u.Password;
                this.FirstName = u.FirstName;
                this.LastName  = u.LastName;
                this.IsAdmin   = u.IsAdmin;
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }

                return;
            }
        }
Пример #42
0
        /// <summary>
        /// Clone object to new object
        /// </summary>
        /// <returns></returns>
        public virtual object Clone()
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(ms, this);
            ms.Position = 0;
            object obj = bf.Deserialize(ms);

            ms.Close();

            NZBaseObject baseObject = obj as NZBaseObject;

            if (baseObject != null)
            {
                baseObject.m_owner = this.Owner;
            }

            return(obj);
        }
Пример #43
0
        public static List <T> DosyaOku()
        {
            List <T> list = new List <T>();
            string   dir  = HttpRuntime.AppDomainAppPath;
            string   serializationFile = Path.Combine(dir, typeof(T).Name + ".bin");

            if (!File.Exists(serializationFile))
            {
                return(null);
            }
            using (Stream stream = File.Open(serializationFile, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                list = (List <T>)bformatter.Deserialize(stream);
            }

            return(list);
        }
        private void printReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Stream stream = File.Open(path, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                items = (List <Item>)bformatter.Deserialize(stream);
            }
            File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "report.txt"), String.Empty);
            int index = 0;

            while (index < items.Count())
            {
                string[] values = { items[index].getsku(), items[index].getcategory(), items[index].getitem(), items[index].getcount(), items[index].getprice(), items[index].getdate(), items[index].getexpire(), items[index].getpromo(), items[index].getdiscount() };

                for (int i = 0; i < values.Length; i++)
                {
                    File.AppendAllText(Path.Combine(Directory.GetCurrentDirectory(), "report.txt"), (values[i] + " "));
                }
                File.AppendAllText(Path.Combine(Directory.GetCurrentDirectory(), "report.txt"), Environment.NewLine);
                index++;
            }


            fileToPrint = new System.IO.StreamReader(Path.Combine(Directory.GetCurrentDirectory(), "report.txt"));
            printFont   = new System.Drawing.Font("Arial", 10);

            //File.WriteAllText("inventory.txt");

            PrintDialog pdi = new PrintDialog();

            pdi.Document = printDocument1;
            if (pdi.ShowDialog() == DialogResult.OK)
            {
                printDocument1.Print();
            }
            else
            {
                MessageBox.Show("Print Cancelled");
            }
            //printDocument1.Print();
            fileToPrint.Close();
        }
Пример #45
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "Red Circles file (*.rcrls)|*.rcrls";
            openFileDialog1.Title  = "Open a Red Circle File";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileName = openFileDialog1.FileName;
                System.Runtime.Serialization.IFormatter fmt = new
                                                              System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                FileStream strm = new FileStream(FileName, FileMode.Open,
                                                 FileAccess.Read, FileShare.None);
                circleDoc = (RedCircles)fmt.Deserialize(strm);
                strm.Close();
            }
            Invalidate(true);
            isChanged = false;
        }
Пример #46
0
        public static T ReadFromFile <T>(string fileName)
        {
            T      lst      = default(T);
            string filePath = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Directory.ToString();

            fileName = filePath + @"\" + fileName;
            if (File.Exists(fileName))
            {
                using (Stream stream = File.Open(fileName, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    if (stream.Length > 0)
                    {
                        lst = (T)bformatter.Deserialize(stream);
                    }
                }
            }
            return(lst);
        }
        private void Load_User_accounts()
        {
            string column1, column2;

            //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();
                current_account = (List <Accounts>)bformatter.Deserialize(stream);
            }

            // Gets firstname & lastname & ID & Username of current accounts
            for (int i = 0; i < current_account.Count(); i++)
            {
                column1 = (current_account[i].getfirstName() + " " + current_account[i].getlastName() + "\t");
                column2 = (" \tID: " + current_account[i].getempID());
                UserListBox.Items.Add(String.Format("{0} {1}", column1.PadRight(20), column2.PadRight(20)));
            }
        }
Пример #48
0
        public List <Submission> LoadSubmissionsFromFile()
        {
            List <Submission> submissionList;

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

                submissionList = (List <Submission>)bformatter.Deserialize(stream);
            }
            //using (StreamReader streamReader = new StreamReader(_submissionsFileName))
            //{
            //    while ((line = streamReader.ReadLine()) != null)
            //    {
            //        submissionList.Add(line);
            //    }
            //}
            return(submissionList);
        }
        /// <summary>
        /// Deserialize a Byte Array to T object
        /// </summary>
        /// <param name="frozen">Array of <see cref="System.Byte"/> containing a previously serialized object</param>
        /// <returns>T instance or null</returns>
        public static T FromBinary(Byte[] frozen)
        {
            if (frozen.Length <= 0)
            {
                throw new ArgumentOutOfRangeException("frozenObject", "Cannot thaw a zero-length Byte[] array");
            }

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter
                = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.Stream stream = new System.IO.MemoryStream(frozen);
            try
            {
                return((T)formatter.Deserialize(stream));
            }
            finally
            {
                stream.Close();
            }
        }
Пример #50
0
        public static T ReadFromDisk <T>(string fileName)
        {
#if UNITY_5_4_OR_NEWER
            var userData = GetStoredData();
            return(JsonUtility.FromJson <T>(userData));
#else
            string path         = Application.persistentDataPath + "/" + fileName + ".dat";
            T      returnObject = default(T);
            if (File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Open);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                fs.Seek(0, SeekOrigin.Begin);
                returnObject = (T)bf.Deserialize(fs);
                fs.Close();
            }
            return(returnObject);
#endif
        }
Пример #51
0
 /*
  * загрузить задачу по идентификатору
  * Входные данные: целое число(id задачи).
  * Выходные данные: экземпляр класса Task
  * Побочные эффекты:
  * Отсутствуют
  */
 public Task loadTask(int taskId)
 {
     try
     {
         if (taskId == -1)
         {
             return(null);
         }
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         Stream fStream = new FileStream(basePath + "/task/" + taskId.ToString() + ".bin", FileMode.Open);
         Task   tmp     = (Task)binFormat.Deserialize(fStream);
         fStream.Close();
         return(tmp);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Пример #52
0
        private void abrirAnimacionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String resultado = "";

            try
            {
                using (System.Windows.Forms.OpenFileDialog dialogo =
                           new System.Windows.Forms.OpenFileDialog())
                {
                    if (dialogo.ShowDialog() ==
                        System.Windows.Forms.DialogResult.OK)
                    {
                        using (Stream st = File.Open(
                                   dialogo.FileName, FileMode.Open))
                        {
                            var binfor = new System.Runtime.
                                         Serialization.Formatters.
                                         Binary.BinaryFormatter();
                            LinkedList <Efecto> obj = (LinkedList <Efecto>)binfor.Deserialize(st);
                            dibujador.listaDeEfectos = obj;
                            actualizarListaDeEfectos();
                            resultado     = "ABIERTO CORRECTAMENTE";
                            objetoInicial = new Objeto(dibujador.objeto);
                            grabando      = false;
                            timer.Enabled = false;
                        }
                    }
                    else
                    {
                        resultado = "OPERACION CANCELADA";
                    }
                }
            }
            catch (Exception ex)
            {
                resultado = "ERROR AL ABRIR EL ARCHIVO : " + ex.Message;
                MessageBox.Show("ERROR AL ABRIR EL ARCHIVO : " + ex.Message);
            }
            finally
            {
                aviso.Text = resultado;
            }
        }
Пример #53
0
        public void ZipApiException_SerialisesAndDeserialisesCorrectly()
        {
            var inner = new InvalidOperationException("Test");
            var ex    = new ZipApiException("Test message", inner);

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

            using (var stream = new System.IO.MemoryStream())
            {
                formatter.Serialize(stream, ex);

                stream.Seek(0, System.IO.SeekOrigin.Begin);

                var deserialisedEx = formatter.Deserialize(stream) as ZipApiException;

                Assert.AreEqual("Test message", deserialisedEx.Message);
                Assert.IsTrue(deserialisedEx.InnerException is InvalidOperationException);
            }
        }
Пример #54
0
        public static object DeserializeObject <T>(string filePath)
        {
            try
            {
                //deserialize
                object obj = null;
                using (Stream stream = File.Open(filePath, FileMode.Open))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    obj = (T)bformatter.Deserialize(stream);
                }
                return(obj);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("DeserializeObject():" + ex.Message);
            }
        }
Пример #55
0
        /// <summary>
        /// Serve il client appena connesso
        /// </summary>
        /// <param name="cliSock">Socket del client</param>
        /// <param name="ct"></param>
        private void ServeClient(TcpClient cliSock, CancellationToken ct)
        {
            using (NetworkStream ns = cliSock.GetStream())
            {
                ns.ReadTimeout = Configuration.TCPConnectionTimeoutMilliseconds;

                //Get size of serialized counterpart data
                byte[] sizeBuf  = new byte[sizeof(int)];
                int    bytesRed = ns.Read(sizeBuf, 0, sizeBuf.Length);
                if (bytesRed < 0)
                {
                    MessageBox.Show("Cannot receive data from counterpart. Please check connection to the LAN and try again");
                    return;
                }
                int size = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(sizeBuf, 0));

                //Get client parameters (Identity and security)
                byte[] formattedUser = new byte[size];
                ns.Read(formattedUser, 0, formattedUser.Length);

                IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                User       counterpart;
                using (MemoryStream ms = new MemoryStream(formattedUser)) {
                    counterpart = (User)formatter.Deserialize(ms);
                }


                //TODO Get number of elements
                byte[] nElemBuf = new byte[sizeof(int)];
                bytesRed = ns.Read(nElemBuf, 0, nElemBuf.Length);
                if (bytesRed < 0)
                {
                    MessageBox.Show("Cannot receive data from user " + counterpart.NickName != ""?counterpart.NickName:counterpart.Name + ". Please check connection to the LAN and try again");
                    return;
                }
                int nElem = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(nElemBuf, 0));

                //TODO Ask user for confermation if necessary
                MessageBox.Show("User " + counterpart.NickName != "" ? counterpart.NickName : counterpart.Name + " wants to send " + nElem.ToString() + " files/folders. Accept?");

                //TODO For each element get type, fileNameSize, fileName and transfer it
            }
        }
Пример #56
0
 /// <summary>
 /// 将缓存文件系列化为T(此处T为字典类型)
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="cacheFileName"></param>
 /// <returns></returns>
 private static T _DeSerializeFromBin <T>(string cacheFileName) where T : new()
 {
     if (File.Exists(cacheFileName))
     {
         T ret = new T();
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         using (FileStream fs = new FileStream(cacheFileName, FileMode.Open, FileAccess.Read))
         {
             ret = (T)bf.Deserialize(fs);
         }
         return(ret);
     }
     else
     {
         //return new T();
         return(default(T)); //返回null;
         //throw new FileNotFoundException(string.Format("file {0} does not exist", cacheFileName));
     }
 }
        private void search_case(int num, string user_search_input)
        {
            //deserialize bin file
            using (Stream stream = File.Open(path, FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

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


            DataTable dt = new DataTable();

            foreach (string c in columnnames)
            {
                dt.Columns.Add(c);
            }

            // Search according to user selection and updates
            int index = 0;

            while (index < items.Count())
            {
                DataRow dr = dt.NewRow();

                if (items[index].getValue(num) == user_search_input)
                {
                    string[] values = { items[index].getsku(), items[index].getcategory(), items[index].getitem(), items[index].getcount(), items[index].getprice(), items[index].getdate(), items[index].getexpire(), items[index].getpromo(), items[index].getdiscount() };
                    for (int i = 0; i < values.Length; i++)
                    {
                        dr[i] = values[i];
                    }

                    dt.Rows.Add(dr);
                }
                else
                {
                    string[] values = { " ", " ", " ", " ", " ", " ", " ", " ", " " };
                }
                ++index;
            }
            dataGridView1.DataSource = dt;
        }
Пример #58
0
        /// <summary>
        /// 对象深度拷贝,复制相同数据,但指向内存位置不一样的数据
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">值</param>
        /// <returns></returns>
        public static T DeepClone <T>(this T obj) where T : class
        {
            if (obj == null)
            {
                return(default(T));
            }

            if (!typeof(T).HasAttribute <SerializableAttribute>(true))
            {
                throw new NotSupportedException($"当前对象未标记特性“{typeof(SerializableAttribute)}”,无法进行DeepClone操作");
            }
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, obj);
                ms.Seek(0, SeekOrigin.Begin);
                return((T)formatter.Deserialize(ms));
            }
        }
Пример #59
0
        private List <Entree> ReadInBin(string S_path)
        {
            string path = S_path;

            if (!System.IO.File.Exists(path))
            {
                return(new List <Entree>());
            }
            List <Entree> Out = new List <Entree>();

            if (System.IO.File.Exists(path))
            {
                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                System.IO.Stream stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                Out = (List <Entree>)formatter.Deserialize(stream);
                stream.Close();
            }
            return(Out);
        }
Пример #60
0
        public object DeepClone(object ldc)
        {
            object clonedObj = null;

            try
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                Formatter.Serialize(stream, ldc);
                stream.Position = 0;
                clonedObj       = Formatter.Deserialize(stream);
                stream.Close();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return(clonedObj);
        }