Beispiel #1
0
 public static void SaveFile()
 {
     try
     {
         System.IO.FileStream stream = new System.IO.FileStream("\\lastfiles.dat", System.IO.FileMode.Create);
         System.Runtime.Serialization.Formatters.Binary.BinaryFormatter  formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         formatter.Serialize( stream, recentProjects );
         formatter.Serialize( stream, recentFiles );
         stream.Flush();
         stream.Close();
     }
     catch{}
 }
 /// <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();
 }
        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;
            }
        }
        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");
        }
 ///  <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();
 }
Beispiel #6
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();
   }
 }
        /// <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 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 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);
                }
            }
        }
Beispiel #10
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;
        }
Beispiel #11
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);
 }
Beispiel #12
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();

        }
Beispiel #13
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());
            }
        }
Beispiel #14
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");
                }
            }
        }
 /// <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;
             }
         }
     }
 }
Beispiel #16
0
		public static void WriteToBinaryFile()
		{
			using (Stream stream = File.Open(MainActivity.vysledkyPath,FileMode.Create))
			{
				var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
				binaryFormatter.Serialize(stream, seznam);
			}
		}
Beispiel #17
0
 void NewPopulationHandler(object sender, NewPopulationEventArgs e)        
 {
     IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     Stream stream = new FileStream(filenameBase + count + filenameExt, FileMode.Create, FileAccess.Write, FileShare.None);
     formatter.Serialize(stream, e.NewPopulation);
     stream.Close();
     count++;
 }
Beispiel #18
0
 public void ShouldBeSerializable()
 {
     var e = new Example(new ExampleColumns(new[] { "a" }), new Dictionary<string, string> { { "a", "a" } });
     var ser = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     using (var ms = new MemoryStream())
         ser.Serialize(ms, e);
     Assert.IsTrue(true, "Serialization succeded");
 }
Beispiel #19
0
 public static void SaveState(GameState state)
 {
     using (Stream stream = File.Open("myFile.txt", FileMode.Create))
     {
         var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         binaryFormatter.Serialize(stream, state);
     }
 }
Beispiel #20
0
 public static string Serialize(List<UserInfo> userList)
 {
     MemoryStream memoryStream=new MemoryStream();
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     bf.Serialize(memoryStream, userList);
     StreamReader sr = new StreamReader(memoryStream);
     memoryStream.Seek(0, SeekOrigin.Begin);
     return sr.ReadToEnd();
 }
Beispiel #21
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);
 }
Beispiel #22
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;
 }
        // Write to the file
        private void UpdatePersistedRegistry()
        {
            using (Stream stream = new FileStream(cRegistryFile, FileMode.Create, FileAccess.Write, FileShare.Write))
            {

                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(stream, sSubscriptions);
            }
        }
Beispiel #24
0
 /// <summary>
 /// Sortuje listę wyników topScoreList oraz zapisuje do pliku
 /// </summary>
 private void WriteTopScoreList()
 {
     topScoreList.Add(new HighScore() { Score = Score, PlayerName = PlayerName });
     topScoreList = topScoreList.OrderByDescending(s => s.Score).ToList(); //sortowanie po najwyższych wynikach
     using (Stream stream = File.Open(@"TopScoreTable.bin", FileMode.Create))
     {
         var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         binaryFormatter.Serialize(stream, topScoreList);
     }
 }
Beispiel #25
0
        private void BackUp(List<CurrencyInfo> items)
        {
            var file = @"\fialed\" + Guid.NewGuid() + ".dat";

            using (var fs = new FileStream(file, FileMode.OpenOrCreate))
            {
                var fm = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                fm.Serialize(fs, items);
            }
        }
Beispiel #26
0
        public void zapiszHasla()
        {
            //serialize
            using (Stream stream = File.Open(serializationFile, FileMode.OpenOrCreate))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                bformatter.Serialize(stream, hasla);
            }
        }
Beispiel #27
0
 /// <summary>
 /// 序列化参数设定
 /// </summary>
 /// <param name="request">要序列化的对象</param>
 /// <param name="strFileName">序列化文件名</param>
 public static void SerializeBinary(object request, string strFileName)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
     new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     //System.IO.MemoryStream memStream = new System.IO.MemoryStream();
     FileStream fileStream = new FileStream(strFileName, FileMode.OpenOrCreate);
     serializer.Serialize(fileStream, request);
     fileStream.Close();
     //return memStream.GetBuffer();
 }
		public void SerializationDemo(){
			ArgumentException ex = new ArgumentException("blahblah");
			System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
				new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			using (MemoryStream ms = new MemoryStream()) {
				bf.Serialize(ms, ex);
				SevenZipCompressor cmpr = new SevenZipCompressor();
				cmpr.CompressStream(ms, File.Create(createTempFileName()));
			}
		}
		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);
		}
 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);
     }
 }
Beispiel #31
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            speechEngine.AudioLevelUpdated -= new EventHandler <AudioLevelUpdatedEventArgs>(sr_audioLevelUpdated);
            speechEngine.SpeechRecognized  -= new EventHandler <SpeechRecognizedEventArgs>(sr_speechRecognized);

            string dir = @"";
            string serializationFile    = Path.Combine(dir, "profiles.vd");
            string xmlSerializationFile = Path.Combine(dir, "profiles_xml.vc");

            try {
                Stream stream     = File.Open(serializationFile, FileMode.Create);
                var    bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bformatter.Serialize(stream, profileList);
                stream.Close();

                try {
                    Stream xmlStream = File.Open(xmlSerializationFile, FileMode.Create);
                    System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(List <Profile>));
                    writer.Serialize(xmlStream, profileList);
                    xmlStream.Close();
                }
                catch (Exception ex) {
                    DialogResult res = MessageBox.Show("Le fichier profiles_xml.vc est en cours d'utilisation par un autre processus. Voulez vous quitter sans sauvegarder ?", "Impossible de sauvegarder", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    if (res == DialogResult.No)
                    {
                        e.Cancel = true;
                    }
                }
            }
            catch (Exception exception) {
                DialogResult res = MessageBox.Show("Le fichier profiles.vd est en cours d'utilisation par un autre processus. Voulez vous quitter sans sauvegarder ?", "Impossible de sauvegarder", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (res == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }
Beispiel #32
0
        /// <summary>
        /// Save the catalog to disk by BINARY serializing the object graph as a *.DAT file.
        /// </summary>
        /// <remarks>
        /// For 'reference', the method also saves XmlSerialized copies of the Catalog (which
        /// can get quite large) and just the list of Words that were found. In production, you
        /// would probably comment out/remove the Debugging code.
        ///
        /// You may also wish to use a difficult-to-guess filename for the serialized data,
        /// or else change the .DAT file extension to something that will be not be served by
        /// IIS (so that other people can't download your catalog).
        /// </remarks>
        public void Save()
        {
            // XML
            if (Preferences.InMediumTrust)
            {
                // TODO: Maybe use to save as ZIP - save space on disk? http://www.123aspx.com/redir.aspx?res=31602
                string xmlFileName = Path.GetDirectoryName(Preferences.CatalogFileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(Preferences.CatalogFileName) + ".xml";
                Kelvin <Catalog> .ToXmlFile(this, xmlFileName);

                //XmlSerializer serializerXmlCatalog = new XmlSerializer(typeof(Catalog));
                //System.IO.TextWriter writer = new System.IO.StreamWriter(xmlFileName);
                //serializerXmlCatalog.Serialize(writer, this);
                //writer.Close();
                return;
            }

            // BINARY http://www.dotnetspider.com/technology/kbpages/454.aspx
            System.IO.Stream stream = new System.IO.FileStream(Preferences.CatalogFileName, System.IO.FileMode.Create);
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            formatter.Serialize(stream, this);
            stream.Close();

            #region Debugging Serialization - these are only really useful for looking at; they're not re-loaded
            if (Preferences.DebugSerializeXml)
            {
                //Kelvin<Catalog>.ToBinaryFile(this, Path.GetFileNameWithoutExtension(Preferences.CatalogFileName) + "_Kelvin" + Path.GetExtension(Preferences.CatalogFileName));
                //Kelvin<Catalog>.ToXmlFile(this, Path.GetFileNameWithoutExtension(Preferences.CatalogFileName) + "_Kelvin.xml");
                Kelvin <string[]> .ToXmlFile(this.Dictionary, Path.GetFileNameWithoutExtension(Preferences.CatalogFileName) + "_debugwords.xml");

                // XML http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=236
                //XmlSerializer serializerXmlWords = new XmlSerializer(typeof(string[]));
                //System.IO.TextWriter writerW = new System.IO.StreamWriter(Path.GetFileNameWithoutExtension(Preferences.CatalogFileName) + "_words.xml");
                //serializerXmlWords.Serialize(writerW, this.Dictionary);
                //writerW.Close();
            }
            #endregion
        }
Beispiel #33
0
        /// <summary>
        /// 处理保存角色信息到文件
        /// </summary>
        private unsafe void ProcessSaveRcdToFile()
        {
            string     sSaveFileName;
            FileStream nFileHandle;

            fixed(sbyte *buff = m_ChrRcd.Data.sChrName)
            {
                SaveDialog.FileName = HUtil32.SBytePtrToString(buff, m_ChrRcd.Data.ChrNameLen);
            }

            SaveDialog.InitialDirectory = ".\\";
            if (SaveDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            sSaveFileName = SaveDialog.FileName;
            if (File.Exists(sSaveFileName))
            {
                nFileHandle = File.Open(sSaveFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            }
            else
            {
                nFileHandle = File.Create(sSaveFileName);
            }
            if (nFileHandle == null)
            {
                MessageBox.Show("保存文件出现错误!!!", "错误信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
                return;
            }
            //@ Unsupported function or procedure: 'FileWrite'
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter format = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            format.Serialize(nFileHandle, m_ChrRcd);
            //nFileHandle.Write(m_ChrRcd, 0, sizeof(THumDataInfo));
            //FileWrite(nFileHandle, m_ChrRcd, sizeof(THumDataInfo));
            nFileHandle.Close();
            MessageBox.Show("人物数据导出成功!!!", "提示信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
        }
Beispiel #34
0
        private static void TestComparerSerialization <T>(SCG.IEqualityComparer <T> equalityComparer, string internalTypeName = null)
        {
            var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            var s  = new MemoryStream();

            var dict = new Dictionary <T, T>(equalityComparer);

            Assert.Same(equalityComparer, dict.EqualityComparer);

            bf.Serialize(s, dict);
            s.Position = 0;
            dict       = (Dictionary <T, T>)bf.Deserialize(s);

            if (internalTypeName == null)
            {
                Assert.IsType(equalityComparer.GetType(), dict.EqualityComparer);
            }
            else
            {
                Assert.Equal(internalTypeName, dict.EqualityComparer.GetType().ToString());
            }

            Assert.True(equalityComparer.Equals(dict.EqualityComparer));
        }
 public void SaveQuestions(String fileName)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         using (System.IO.Stream stream = System.IO.File.Open(fileName, System.IO.FileMode.Create))
         {
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             bformatter.Serialize(stream, m_questions);
         }
         using (System.IO.Stream stream = System.IO.File.Open(fileName + "p", System.IO.FileMode.Create))
         {
             var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
             bformatter.Serialize(stream, m_passage);
         }
     }
     catch (Exception e)
     {
         Cursor.Current = Cursors.Default;
         MessageBox.Show("failed to save the file \"" + fileName + "\"\n\r" + e.Message, "Question Editor", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     Cursor.Current = Cursors.Default;
     MessageBox.Show("The question set was successfuly saved to \"" + fileName + "\"", "Question Editor", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
Beispiel #36
0
        public static bool BinarySerialize(string FilePath, Object ObjectToSerialize)
        {
            bool status = true;

            if (Directory.Exists(Path.GetDirectoryName(FilePath)) && ObjectToSerialize != null)
            {
                try
                {
                    System.IO.FileStream fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Create);
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bf.Serialize(fs, ObjectToSerialize);
                    fs.Close();
                }
                catch
                {
                    status = false;
                }
            }
            else
            {
                status = false;
            }
            return(status);
        }
        /// <summary>
        /// 生成证书文件
        /// </summary>
        /// <param name="data">注册信息</param>
        /// <param name="fileName">证书文件路径</param>
        /// <param name="key"></param>
        public void BuildLicFile(string data, string fileName, string key, string iv = null)
        {
            string str = string.Empty;

            if (string.IsNullOrEmpty(iv))
            {
                str = Cryptor.DESEncrypt(str, key);
            }
            else
            {
                str = Cryptor.DESEncrypt(data, key, iv);
            }

            IFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            if (str != null)
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    binaryFormatter.Serialize(fileStream, str);
                    fileStream.Close();
                }
            }
        }
Beispiel #38
0
        public void TestRuntimeSerialize3()
        {
            MCvPoint3D32f[] data = new MCvPoint3D32f[] { new MCvPoint3D32f() };

            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);

            Matrix <float> mat = new Matrix <float>(data.GetLength(0), 1, 3, handle.AddrOfPinnedObject(), sizeof(float) * 3);

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

            Byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, mat);
                bytes = ms.GetBuffer();
            }
            using (MemoryStream ms2 = new MemoryStream(bytes))
            {
                Matrix <float> mat2 = (Matrix <float>)formatter.Deserialize(ms2);
                EmguAssert.IsTrue(mat.Equals(mat2));
            }
            handle.Free();
        }
        //Write to file functions
        public static long WriteToBinaryFile <T>(string filePath, T objectToWrite, FileMode mode, long moveToOffset = -1, bool before = true)
        {
            long offset = 0;

            using (Stream stream = File.Open(filePath, mode))
            {
                if (moveToOffset != -1)
                {
                    stream.Position = moveToOffset;
                }
                if (before)
                {
                    offset = stream.Position;
                }

                var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                binaryFormatter.Serialize(stream, objectToWrite);
                if (!before)
                {
                    offset = stream.Position;
                }
            }
            return(offset);
        }
Beispiel #40
0
 public bool SaveBook()
 {
     if (this.isHasSaved)
     {
         return(true);
     }
     if (this.book == null)
     {
         return(false);
     }
     try
     {
         Stream stream = File.Open(this.book.LocalFolder + "\\" + this.book.NovelName + ".ECB", FileMode.Create, FileAccess.ReadWrite);
         //SoapFormatter formatter = new SoapFormatter();
         //formatter.Serialize(stream, this.book);
         IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
         formatter.Serialize(stream, this.book);
         stream.Close();
         return(true);
     }
     catch { return(false); }
     finally
     { }
 }
Beispiel #41
0
        public void CanBeSerializedCorrectly()
        {
            PropertyPageException exInner = new PropertyPageException("inner");
            PropertyPageException ex1     = new PropertyPageException("foo", "link", exInner);

            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(PropertyPageException));
            PropertyPageException ex2 = (PropertyPageException)o;

            Assert.AreEqual(ex1.Data.Count, ex2.Data.Count);
            Assert.AreEqual(ex1.InnerException != null, ex2.InnerException != null);
            Assert.AreEqual(ex1.Message, ex2.Message);
            Assert.AreEqual(ex1.HelpLink, ex2.HelpLink);
            Assert.AreEqual(ex1.StackTrace, ex2.StackTrace);
            Assert.AreEqual(ex1.ToString(), ex2.ToString());
        }
Beispiel #42
0
        private void SaveState()
        {
            Dictionary <string, object> additional = new Dictionary <string, object>();

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter;

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

            MemoryStream stream = new MemoryStream();

            formatter.Serialize(stream, Job.Optimizer.State.Random);

            additional["random"] = stream.ToArray();
            stream.Close();

            SavePairs(null, Job.Optimizer.State.Settings.All(), "state", additional, delegate(object o, out string name, out object val) {
                KeyValuePair <string, object> data = (KeyValuePair <string, object>)o;

                name = "_s_" + data.Key;
                val  = data.Value;

                return(true);
            });
        }
Beispiel #43
0
        //private void testSubgraphToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    string[] molecules = {"COP(OC)OC",
        //        "CCOP(C)OCC",
        //        "COP(C1=CC=CC=C1)C2=CC=CC=C2",
        //        "P(c1ccccc1)(c1ccccc1)c1ccccc1",
        //        "CCN(CC)P(OC)OC",
        //        "CC(C)N(C(C)C)P(N(C(C)C)C(C)C)OCCC#N",
        //        "O(P(N(C)C)C)C",
        //        "C(COP(O)S)NC(=O)CS",
        //        "CCOP(SC)SC(C)C",
        //        "COP(=O)(OC)OC",
        //        "COP(=O)(C)OC",
        //        "CCOP(=O)(C1=CC=CC=C1)C2=CC=CC=C2",
        //        "P(c1ccccc1)(c1ccccc1)(c1ccccc1)=O",
        //        "CCOP(=O)(N)OCC",
        //        "CCOP(=O)(N(C)C)N(C)C",
        //        "CN(C)P(=O)(N(C)C)N(C)C",
        //        "CCCc1ccccc1NP(=O)(C)Oc1ccccc1CC",
        //        "P(c1ccccc1)(c1ccccc1)(N)=O",
        //        "CCOP(=S)(OCC)OCC",
        //        "CCOP(=S)(OCC)SCC",
        //        "CN(C)P(=O)(C)N(C)C"};
        //    string[] groups = {"OP(O)O",
        //        "OP(C)O",
        //        "OP(C)C",
        //        "CP(C)C",
        //        "NP(O)O",
        //        "NP(N)O",
        //        "OP(N)C",
        //        "OP(O)S",
        //        "OP(S)S",
        //        "OP(=O)(O)O",
        //        "OP(=O)(O)C",
        //        "OP(=O)(C)C",
        //        "CP(=O)(C)C",
        //        "OP(=O)(N)O",
        //        "OP(=O)(N)N",
        //        "NP(=O)(N)N",
        //        "NP(=O)(C)O",
        //        "NP(=O)(C)C",
        //        "OP(=S)(O)O",
        //        "OP(=S)(O)S",
        //        "NP(=O)(C)N"};
        //    DateTime start = DateTime.Now;
        //    ChemInfo.Molecule m = null;
        //    int[] indices = null;
        //    foreach (string molecule in molecules)
        //    {
        //        m = new ChemInfo.Molecule(molecule);
        //        bool found = false;
        //        int numFound = 0;
        //        foreach (string smart in groups)
        //        {
        //            if (m.FindSmarts(smart, ref indices))
        //            {
        //                found = true;
        //                numFound++;
        //            }
        //            //if (m.FindSmarts2(smart, ref temp)) found = true;
        //        }
        //        if (!found || numFound > 1)
        //        {
        //            MessageBox.Show(molecule);
        //        }
        //    }
        //    MessageBox.Show("Time Required is: " + (double)DateTime.Now.Subtract(start).Milliseconds + " milliseconds", "Test Completed Successfully");
        //}

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.IO.Directory.CreateDirectory(documentPath);
            System.IO.FileStream fs = new System.IO.FileStream(documentPath + "\\references.dat", System.IO.FileMode.Create);
            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            try
            {
                formatter.Serialize(fs, m_References);
            }
            catch (System.Runtime.Serialization.SerializationException ex)
            {
                Console.WriteLine("Failed to serialize. Reason: " + ex.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }

            var json = new System.Web.Script.Serialization.JavaScriptSerializer();

            System.IO.File.WriteAllText(documentPath + "\\FunctionalGroups.json", json.Serialize(fGroups));
        }
Beispiel #44
0
        private void btnAddLinija_Click(object sender, EventArgs e)
        {
            DodadiLinija dodadi = new DodadiLinija();

            if (dodadi.ShowDialog() == DialogResult.OK)
            {
                Prevoznik s = lstPrevoznici.SelectedItem as Prevoznik;
                s.Linii.Add(dodadi.linija as Linija);
                lstLinii.Items.Clear();
                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();
        }
Beispiel #45
0
 /// <summary>
 /// exports the pointcloud to a file so it can be loaded again later
 /// </summary>
 public void exportPointCloud()
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     System.IO.FileStream stream = null;
     if (!System.IO.File.Exists(@"config\referenceCloud.dat"))
     {
         System.IO.Directory.CreateDirectory(@"config\");
     }
     try
     {
         using (stream = new System.IO.FileStream(@"config\referenceCloud.dat", System.IO.FileMode.Create))
         {
             formatter.Serialize(stream, this);
             stream.Flush();
             stream.Close();
         }
     }
     catch (Exception ex) { Log.LogManager.writeLog("ERROR: " + ex.Message); }
     finally { if (stream != null)
               {
                   stream.Close(); stream.Dispose();
               }
     }
 }
Beispiel #46
0
        private void saveList()
        {
            //serialize
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string serializationFile = Path.Combine(dir, "people.bin");


            try {
                if (this.person_list.Count == 0)
                {
                    return;
                }

                using (Stream stream = File.Open(serializationFile, FileMode.Create)) {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bformatter.Serialize(stream, this.person_list);
                }
            } catch {
                MessageBox.Show("Error occured while saving list!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("File saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
Beispiel #47
0
        // Perform a deep Copy of the source object.
        public static T DeepClone <T>(T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            // Don't serialize a null object, simply return the default for that object
            if (Object.ReferenceEquals(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));
            }
        }
Beispiel #48
0
        private void serializeButton_Click(object sender, EventArgs e)
        {
            string inputPath  = inputFolderTextBox.Text;
            string outputPath = "content.bin";

            string[] dirs  = Directory.GetDirectories(inputPath, "*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
            string[] files = Directory.GetFiles(inputPath, "*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();

            Folder folder = new Folder(dirs, files);

            using (Stream stream = File.Open(outputPath, FileMode.Create))
            {
                var bFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                try
                {
                    bFormatter.Serialize(stream, folder);
                    MessageBox.Show("Success! Result binary file is: " + outputPath, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #49
0
        /// <summary>Adds all selected mission craft into the current library group.</summary>
        private void cmdAddToLibrary_Click(object sender, EventArgs e)
        {
            int group = lstLibraryGroup.SelectedIndex;

            if (group < 0 || group >= _groupList.Count)
            {
                return;
            }
            foreach (int si in lstMissionCraft.SelectedIndices)
            {
                using (MemoryStream ms = new MemoryStream(2048))
                {
                    System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    formatter.Serialize(ms, getFlightGroupObjectFromCollection(si));
                    ms.Position = 0;
                    object fg = formatter.Deserialize(ms);

                    lstLibraryCraft.Items.Add(lstMissionCraft.Items[si]);
                    _groupList[group].Add(fg);
                    _isDirty = true;
                }
            }
            refreshGroupCraftCount();
        }
Beispiel #50
0
        public void TestRuntimeSerialize2()
        {
            Random r = new Random();

            double[,,] data = new double[100, 80, 2];
            for (int i = 0; i < data.GetLength(0); i++)
            {
                for (int j = 0; j < data.GetLength(1); j++)
                {
                    for (int k = 0; k < data.GetLength(2); k++)
                    {
                        data[i, j, k] = r.NextDouble();
                    }
                }
            }

            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);

            Matrix <Double> mat = new Matrix <Double>(data.GetLength(0), data.GetLength(1), data.GetLength(2), handle.AddrOfPinnedObject(), sizeof(double) * data.GetLength(1) * data.GetLength(2));

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

            Byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, mat);
                bytes = ms.GetBuffer();
            }
            using (MemoryStream ms2 = new MemoryStream(bytes))
            {
                Matrix <Double> mat2 = (Matrix <double>)formatter.Deserialize(ms2);
                EmguAssert.IsTrue(mat.Equals(mat2));
            }
            handle.Free();
        }
Beispiel #51
0
        /*public new object DeepCopy()
         * {
         *  Magazine someMag = new Magazine();
         *  someMag.Name = new String(Name);
         *  someMag.Freq = new Frequency();
         *  someMag.Freq = Freq;
         *  someMag.Date = new System.DateTime(Date.Year, Date.Month, Date.Day, Date.Hour, Date.Minute, Date.Second);
         *  someMag.Amount = Amount;
         *  for (int i = 0; i < artList.Count; i++)
         *  {
         *      someMag.ArtList.Add(artList[i]);
         *  }
         *  for (int i = 0; i < personList.Count; i++)
         *  {
         *      someMag.PersonList.Add(PersonList[i]);
         *  }
         *  return someMag;
         * }*/
        public static Magazine DeepCopy(Magazine someMag)
        {
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            formatter.Serialize(ms, someMag);
            ms.Position = 0;
            return((Magazine)formatter.Deserialize(ms));

            /*Magazine someMag = new Magazine();
             * someMag.Name = new String(Name);
             * someMag.Freq = new Frequency();
             * someMag.Freq = Freq;
             * someMag.Date = new System.DateTime(Date.Year, Date.Month, Date.Day, Date.Hour, Date.Minute, Date.Second);
             * someMag.Amount = Amount;
             * for (int i = 0; i < artList.Count; i++)
             * {
             *  someMag.ArtList.Add(artList[i]);
             * }
             * for (int i = 0; i < personList.Count; i++)
             * {
             *  someMag.PersonList.Add(PersonList[i]);
             * }
             * return someMag;*/
        }
Beispiel #52
0
        public static T CreateCloneSerial <T>(T source)
        {
            // like CreateCloneT but uses serialization.
            // serializer can offer more depth and honors serialization attributes.

            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }

            if (Object.ReferenceEquals(source, null))
            {
                return(default(T));
            }

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

            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return((T)formatter.Deserialize(stream));
            }
        }
        private void btnKupiGuest_Click(object sender, EventArgs e)
        {
            KupiBilet_Guest forma = new KupiBilet_Guest();

            if (forma.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (Prevoznik p in LogIn.Prevoznici)
                {
                    if (p == tekoven)
                    {
                        foreach (Linija l in p.Linii)
                        {
                            if (l == tekovna)
                            {
                                l.SlobodniMesta = KupiBilet_Guest.slobodniMesta;
                            }
                        }
                    }
                }

                LiniiRefresh();
                zaPlakjanje         += KupiBilet_Guest.vkupnaCena;
                vkupnoBileti        += KupiBilet_Guest.brBileti;
                txtVkupnoBileti.Text = vkupnoBileti.ToString();
                txtVkupnoCena.Text   = zaPlakjanje.ToString() + " ден.";
            }

            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();
        }
Beispiel #54
0
        private void sauvegardeComptesOGSpy()
        {
            FileStream fs = null;

            try
            {
                String dossierParametres = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                dossierParametres += @"\Mackila\OgameFarmingInterface";
                System.IO.Directory.CreateDirectory(dossierParametres);
                fs = new FileStream(dossierParametres + @"\comptes.param", FileMode.Create);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(fs, this.listeDesComptes);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
        private static void SaveSettings()
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            System.IO.Stream stream;

            lock (CacheSettings.SyncRoot)
            {
                if (CacheLocation == null)
                {
                    return;
                }

                stream = new FileStream(Path.Combine(CacheLocation, "cacheSettings.bin"), FileMode.OpenOrCreate, FileAccess.Write);
                try
                {
                    formatter.Serialize(stream, CacheSettings);
                }
                finally
                {
                    stream.Close();
                }
            }
        }
Beispiel #56
0
        public static byte[] ObjectToByteArray(object _Object)
        {
            try
            {
                // create new memory stream
                System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();

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

                // Serializes an object, or graph of connected objects, to the given stream.
                _BinaryFormatter.Serialize(_MemoryStream, _Object);

                // convert stream to byte array and return
                return(_MemoryStream.ToArray());
            }
            catch
            {
            }

            // Error occured, return null
            return(null);
        }
Beispiel #57
0
        /// <summary>
        /// Clones the object - object must have Serialized attribute.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public static object CloneObject(object item)
        {
            // HACK: handler AssemblyResolve udalosti zamezi vyjimce, ktera vyskakuje
            // pokud se deserializuje objekt tridy dynamicky nactene assembly
            ResolveEventHandler resolveHandler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            AppDomain.CurrentDomain.AssemblyResolve += resolveHandler;

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

                using (Stream stream = new MemoryStream())
                {
                    formatter.Serialize(stream, item);
                    stream.Seek(0, SeekOrigin.Begin);
                    return(formatter.Deserialize(stream));
                }
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= resolveHandler;
            }
        }
Beispiel #58
0
        private void SaveSnowflakeData()
        {
            //create the save dialog

            string         saveFilename = null;
            SaveFileDialog saveDialog   = saveFileDialog1;

            saveDialog.DefaultExt = "*.txt";
            saveDialog.Filter     = "Snowflake data files|*.snowflake";

            DialogResult dr = saveFileDialog1.ShowDialog();


            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                // this could fail so we need a try catch block around it


                try
                {
                    saveFilename = saveFileDialog1.FileName;

                    //this is the net recipe for saving an list of serializable objects
                    //serializable means able to be sent to a filestream

                    System.IO.FileStream s = new System.IO.FileStream(saveFilename, System.IO.FileMode.Create);
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter f = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    f.Serialize(s, sfp);
                    s.Close();
                }
                catch (System.IO.IOException ex)
                {
                    MessageBox.Show(ex.Message, "File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #59
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              IOptions <SenparcSetting> senparcSetting,
                              IOptions <SenparcWeixinSetting> senparcWeixinSetting, IHubContext <ReloadPageHub> hubContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"node_modules")),
                RequestPath  = new PathString("/node_modules")
            });


            app.UseCookiePolicy();

            app.UseMvc();

            #region CO2NET

            // 启动 CO2NET 全局注册,必须!
            IRegisterService register = RegisterService.Start(env, senparcSetting.Value)
                                        //关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore/Startup.cs
                                        .UseSenparcGlobal();

            #region 全局缓存配置(按需)

            //当同一个分布式缓存同时服务于多个网站(应用程序池)时,可以使用命名空间将其隔离(非必须)
            register.ChangeDefaultCacheNamespace("SCFCache");

            #region 配置和使用 Redis

            //配置全局使用Redis缓存(按需,独立)
            var redisConfigurationStr = senparcSetting.Value.Cache_Redis_Configuration;
            var useRedis = !string.IsNullOrEmpty(redisConfigurationStr) && redisConfigurationStr != "Redis配置";
            if (useRedis) //这里为了方便不同环境的开发者进行配置,做成了判断的方式,实际开发环境一般是确定的,这里的if条件可以忽略
            {
                /* 说明:
                 * 1、Redis 的连接字符串信息会从 Config.SenparcSetting.Cache_Redis_Configuration 自动获取并注册,如不需要修改,下方方法可以忽略
                 * /* 2、如需手动修改,可以通过下方 SetConfigurationOption 方法手动设置 Redis 链接信息(仅修改配置,不立即启用)
                 */
                Senparc.CO2NET.Cache.Redis.Register.SetConfigurationOption(redisConfigurationStr);

                //以下会立即将全局缓存设置为 Redis
                Senparc.CO2NET.Cache.Redis.Register.UseKeyValueRedisNow(); //键值对缓存策略(推荐)
                //Senparc.CO2NET.Cache.Redis.Register.UseHashRedisNow();//HashSet储存格式的缓存策略

                //也可以通过以下方式自定义当前需要启用的缓存策略
                //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisObjectCacheStrategy.Instance);//键值对
                //CacheStrategyFactory.RegisterObjectCacheStrategy(() => RedisHashSetObjectCacheStrategy.Instance);//HashSet
            }
            //如果这里不进行Redis缓存启用,则目前还是默认使用内存缓存

            #endregion

            #region 注册日志(按需,建议)

            register.RegisterTraceLog(ConfigTraceLog); //配置TraceLog

            #endregion

            #endregion

            #endregion

            #region Weixin 设置

            /* 微信配置开始
             *
             * 建议按照以下顺序进行注册,尤其须将缓存放在第一位!
             */

            //注册开始

            #region 微信缓存(按需,必须在 register.UseSenparcWeixin () 之前)

            //微信的 Redis 缓存,如果不使用则注释掉(开启前必须保证配置有效,否则会抛错)
            if (useRedis)
            {
                app.UseSenparcWeixinCacheRedis();
            }

            #endregion

            //开始注册微信信息,必须!
            register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value)
            //注意:上一行没有 ; 下面可接着写 .RegisterXX()
            #region 注册公众号或小程序(按需)

            //注册公众号(可注册多个)
            .RegisterMpAccount(senparcWeixinSetting.Value, "SCF")
            .RegisterMpAccount("", "", "Senparc_Template")

            //注册多个公众号或小程序(可注册多个)
            //.RegisterWxOpenAccount(senparcWeixinSetting.Value, "【盛派网络小助手】小程序")
            //注册第三方平台(可注册多个)
            #region 注册第三方平台

            .RegisterOpenComponent(senparcWeixinSetting.Value,
                                   //getComponentVerifyTicketFunc
                                   async componentAppId =>
            {
                var dir = Path.Combine(ServerUtility.ContentRootMapPath("~/App_Data/OpenTicket"));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId));
                using (var fs = new FileStream(file, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        var ticket = await sr.ReadToEndAsync();
                        return(ticket);
                    }
                }
            },

                                   //getAuthorizerRefreshTokenFunc
                                   async(componentAppId, auhtorizerId) =>
            {
                var dir = Path.Combine(ServerUtility.ContentRootMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                if (!System.IO.File.Exists(file))
                {
                    return(null);
                }

                using (Stream fs = new FileStream(file, FileMode.Open))
                {
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var result    = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs);
                    return(result.authorizer_refresh_token);
                }
            },

                                   //authorizerTokenRefreshedFunc
                                   (componentAppId, auhtorizerId, refreshResult) =>
            {
                var dir = Path.Combine(ServerUtility.ContentRootMapPath("~/App_Data/AuthorizerInfo/" + componentAppId));
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
                using (Stream fs = new FileStream(file, FileMode.Create))
                {
                    var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    binFormat.Serialize(fs, refreshResult);
                    fs.Flush();
                }
            }, "【盛派网络】开放平台")

            #endregion
            //除此以外,仍然可以在程序任意地方注册公众号或小程序:
            //AccessTokenContainer.Register(appId, appSecret, name);//命名空间:Senparc.Weixin.MP.Containers

            #endregion

            #region 注册微信支付(按需)

            //注册最新微信支付版本(V3)(可注册多个)
            .RegisterTenpayV3(senparcWeixinSetting.Value, "SCF")     //记录到同一个 SenparcWeixinSettingItem 对象中

            #endregion

            ;

            #endregion

            #region .NET Core默认不支持GB2312

            //http://www.mamicode.com/info-detail-2225481.html
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            #endregion

            #region Senparc.Core 设置

            //用于解决HttpContext.Connection.RemoteIpAddress为null的问题
            //https://stackoverflow.com/questions/35441521/remoteipaddress-is-always-null
            app.UseHttpMethodOverride(new HttpMethodOverrideOptions
            {
                //FormFieldName = "X-Http-Method-Override"//此为默认值
            });

            app.UseSenparcMvcDI();

            //Senparc.Scf.Core.Config.SiteConfig.SenparcCoreSetting = senparcCoreSetting.Value;//网站设置

            //提供网站根目录
            if (env.ContentRootPath != null)
            {
                Senparc.Scf.Core.Config.SiteConfig.ApplicationPath = env.ContentRootPath;
                Senparc.Scf.Core.Config.SiteConfig.WebRootPath     = env.WebRootPath;
            }

            #endregion

            #region 异步线程

            {
                ////APM Ending 数据统计
                //var utility = new APMNeuralDataThreadUtility();
                //Thread thread = new Thread(utility.Run) { Name = "APMNeuralDataThread" };
                //SiteConfig.AsynThread.Add(thread.Name, thread);
            }

            SiteConfig.AsynThread.Values.ToList().ForEach(z =>
            {
                z.IsBackground = true;
                z.Start();
            }); //全部运行

            #endregion
        }
Beispiel #60
0
        public static bool Attach(bool noAutoExit)
        {
            lock (_syncRoot) {
                NativeMethods.FileSafeHandle handle = null;
                bool isFirstInstance = false;
                try {
                    _mtxFirstInstance = new Mutex(true, MutexName, out isFirstInstance);
                    if (isFirstInstance == false)   //we need to contact previous instance.
                    {
                        _mtxFirstInstance = null;

                        byte[] buffer;
                        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, new NewInstanceEventArgs(System.Environment.CommandLine, System.Environment.GetCommandLineArgs()));
                            ms.Flush();
                            buffer = ms.GetBuffer();
                        }

                        //open pipe
                        if (!NativeMethods.WaitNamedPipe(NamedPipeName, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT))
                        {
                            throw new System.InvalidOperationException(Resources.ExceptionWaitNamedPipeFailed);
                        }
                        handle = NativeMethods.CreateFile(NamedPipeName, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, System.IntPtr.Zero, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_ATTRIBUTE_NORMAL, System.IntPtr.Zero);
                        if (handle.IsInvalid)
                        {
                            throw new System.InvalidOperationException(Resources.ExceptionCreateFileFailed);
                        }

                        //send bytes
                        uint             written    = 0;
                        NativeOverlapped overlapped = new NativeOverlapped();
                        if (!NativeMethods.WriteFile(handle, buffer, (uint)buffer.Length, ref written, ref overlapped))
                        {
                            throw new System.InvalidOperationException(Resources.ExceptionWriteFileFailed);
                        }
                        if (written != buffer.Length)
                        {
                            throw new System.InvalidOperationException(Resources.ExceptionWriteFileWroteUnexpectedNumberOfBytes);
                        }
                    }
                    else      //there is no application already running.

                    {
                        _thread              = new Thread(Run);
                        _thread.Name         = "Medo.Application.SingleInstance.0";
                        _thread.IsBackground = true;
                        _thread.Start();
                    }
                } catch (System.Exception ex) {
                    System.Diagnostics.Trace.TraceWarning(ex.Message + "  {Medo.Application.SingleInstance}");
                } finally {
                    //if (handle != null && (!(handle.IsClosed || handle.IsInvalid))) {
                    //    handle.Close();
                    //}
                    if (handle != null)
                    {
                        handle.Dispose();
                    }
                }

                if ((isFirstInstance == false) && (noAutoExit == false))
                {
                    System.Diagnostics.Trace.TraceInformation("Exit(E_ABORT): Another instance is running.  {Medo.Application.SingleInstance}");
                    System.Environment.Exit(unchecked ((int)0x80004004)); //E_ABORT(0x80004004)
                }

                return(isFirstInstance);
            }
        }