示例#1
0
        private static XmlDocument Save(object data)
        {
            var stream   = new MemoryStream();
            var settings = new SharpSerializerXmlSettings();

            settings.AdvancedSettings.PropertiesToIgnore.Add(typeof(Class2BeSerialized), "NameRule");
            settings.AdvancedSettings.PropertiesToIgnore.Add(typeof(Class2BeSerialized), "ComplexRule");

            settings.AdvancedSettings.PropertyTypesToIgnore.Add(typeof(Class2BeIgnored));

            settings.AdvancedSettings.AttributesToIgnore.Add(typeof(MyExcludeAttribute));
            // this does not work
            //settings.AdvancedSettings.PropertiesToIgnore.Add(null, "NameRule");
            //settings.AdvancedSettings.PropertiesToIgnore.Add(null, "ComplexRule");
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(data, stream);

            stream.Position = 0;

            XmlDocument doc = new XmlDocument();

            doc.Load(stream);

            return(doc);
        }
        private static void serialize(object source, SharpSerializer serializer, Func<byte[], byte[]> dataCallback)
        {
            byte[] data;

            // Serializing
            using (var stream = new MemoryStream())
            {
                // serialize
                serializer.Serialize(source, stream);

                data = stream.ToArray();
            }

            // Modifying data
            if (dataCallback!=null)
            {
                data = dataCallback(data);
            }

            // Deserializing
            using (var stream = new MemoryStream(data))
            {
                // deserialize
                var result = serializer.Deserialize(stream);

                // it comes never here
            }
        }
示例#3
0
        public void XmlSerial_ShouldSerializeDateTimeOffset()
        {
            var parent = new ClassWithDateTimeOffset
            {
                Date          = DateTimeOffset.Now,
                DateTimeLocal = new DateTime(2021, 12, 11, 10, 9, 8, DateTimeKind.Local),
                DateTimeUtc   = new DateTime(2021, 12, 11, 10, 9, 8, DateTimeKind.Utc)
            };

            var stream     = new MemoryStream();
            var settings   = new SharpSerializerXmlSettings();
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(parent, stream);

            stream.Position = 0;
            XmlDocument doc = new XmlDocument();

            doc.Load(stream);
            System.Console.WriteLine(doc.InnerXml);

            serializer      = new SharpSerializer(settings);
            stream.Position = 0;
            ClassWithDateTimeOffset loaded = serializer.Deserialize(stream) as ClassWithDateTimeOffset;

            Assert.AreEqual(parent.Date, loaded.Date);

            // Additional tests concerning
            // https://github.com/polenter/SharpSerializer/issues/17#issuecomment-994484009
            Assert.AreEqual(parent.DateTimeLocal, loaded.DateTimeLocal);
            Assert.AreEqual(parent.DateTimeLocal.Kind, loaded.DateTimeLocal.Kind);
            Assert.AreEqual(parent.DateTimeUtc, loaded.DateTimeUtc);
            Assert.AreEqual(parent.DateTimeUtc.Kind, loaded.DateTimeUtc.Kind);
        }
示例#4
0
        public void XmlSerial_ShouldSerializeGuid()
        {
            var parent = new ClassWithGuid()
            {
                Guid = Guid.NewGuid(),
            };

            var stream     = new MemoryStream();
            var settings   = new SharpSerializerXmlSettings();
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(parent, stream);

            stream.Position = 0;
            XmlDocument doc = new XmlDocument();

            doc.Load(stream);
            System.Console.WriteLine(doc.InnerXml);

            serializer      = new SharpSerializer(settings);
            stream.Position = 0;
            ClassWithGuid loaded = serializer.Deserialize(stream) as ClassWithGuid;

            Assert.AreEqual(parent.Guid, loaded.Guid, "same guid");
        }
示例#5
0
        public void BinSerial_TwoIdenticalChildsShouldBeSameInstance()
        {
            var parent = new ParentChildTestClass()
            {
                Name = "parent",
            };

            var child = new ParentChildTestClass()
            {
                Name   = "child",
                Father = parent,
                Mother = parent,
            };

            Assert.AreSame(child.Father, child.Mother, "Precondition: Saved Father and Mother are same instance");

            var stream     = new MemoryStream();
            var settings   = new SharpSerializerBinarySettings(BinarySerializationMode.SizeOptimized);
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(child, stream);

            serializer      = new SharpSerializer(settings);
            stream.Position = 0;
            ParentChildTestClass loaded = serializer.Deserialize(stream) as ParentChildTestClass;

            Assert.AreSame(loaded.Father, loaded.Mother, "Loaded Father and Mother are same instance");
        }
示例#6
0
        public void BinSerial_ShouldSerializeDateTimeOffset()
        {
            var parent = new ClassWithDateTimeOffset
            {
                Date          = DateTimeOffset.Now,
                DateTimeLocal = new DateTime(2021, 12, 11, 10, 9, 8, DateTimeKind.Local),
                DateTimeUtc   = new DateTime(2021, 12, 11, 10, 9, 8, DateTimeKind.Utc)
            };

            var stream     = new MemoryStream();
            var settings   = new SharpSerializerBinarySettings(BinarySerializationMode.SizeOptimized);
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(parent, stream);


            serializer      = new SharpSerializer(settings);
            stream.Position = 0;
            ClassWithDateTimeOffset loaded = serializer.Deserialize(stream) as ClassWithDateTimeOffset;

            Assert.AreEqual(parent.Date, loaded.Date, "same date");
            // Additional tests concerning
            // https://github.com/polenter/SharpSerializer/issues/17#issuecomment-994484009
            // DateTimeKind is not deserialized as expected.
            // A suggested workaround is using DateTimeOffset or a complex object instead of DateTime.
            Assert.AreEqual(parent.DateTimeLocal, loaded.DateTimeLocal);
            Assert.AreEqual(DateTimeKind.Unspecified, loaded.DateTimeLocal.Kind);
            Assert.AreEqual(parent.DateTimeUtc, loaded.DateTimeUtc);
            Assert.AreEqual(DateTimeKind.Unspecified, loaded.DateTimeUtc.Kind);
        }
示例#7
0
        static public void Closing(object sender, FormClosingEventArgs e)
        {
            Form form       = (Form)sender;
            var  serializer = new Polenter.Serialization.SharpSerializer();

            serializer.Serialize(form, fileName(form));
        }
示例#8
0
 /// <summary>
 ///   Reads a string value from the Octgn registry
 /// </summary>
 /// <param name="valName"> The name of the value </param>
 /// <returns> A string value </returns>
 public static string ReadValue(string valName)
 {
     try
     {
         if (File.Exists(GetPath()))
         {
             var serializer = new SharpSerializer();
             var config = (Hashtable)serializer.Deserialize(GetPath());
             if (config.ContainsKey(valName))
             {
                 return config[valName].ToString();
             }
         }
     }
     catch(Exception e)
     {
         Trace.WriteLine("[SimpleConfig]ReadValue Error: " + e.Message);
         try
         {
             File.Delete(GetPath());
         }
         catch (Exception)
         {
             Trace.WriteLine("[SimpleConfig]ReadValue Error: Couldn't delete the corrupt config file.");
         }
     }
     return null;
 }
示例#9
0
        private static void serialize(object source, SharpSerializer serializer, Func <byte[], byte[]> dataCallback)
        {
            byte[] data;

            // Serializing
            using (var stream = new MemoryStream())
            {
                // serialize
                serializer.Serialize(source, stream);

                data = stream.ToArray();
            }


            // Modifying data
            if (dataCallback != null)
            {
                data = dataCallback(data);
            }

            // Deserializing
            using (var stream = new MemoryStream(data))
            {
                // deserialize
                var result = serializer.Deserialize(stream);

                // it comes never here
            }
        }
示例#10
0
        public void CanDeserializeClassWithPrivateConstructor()
        {
            var child = new ClassWithPrivateConstructor("child");

            var data = new ClassWithPrivateConstructor("MyName")
            {
                Complex = child
            };

            var settings   = new SharpSerializerXmlSettings();
            var serializer = new SharpSerializer(settings);

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(data, stream);

                stream.Position = 0;

                var deserialized = serializer.Deserialize(stream) as ClassWithPrivateConstructor;

                Assert.IsNotNull(deserialized);
                Assert.AreEqual(data.Name, deserialized.Name);
                Assert.AreEqual(data.Complex.Name, deserialized.Complex.Name);
            }
        }
示例#11
0
        /// <summary>
        /// Check GitHub for the current published version
        /// </summary>
        /// <returns>
        /// 0 - No update available
        /// 1 - Update available</returns>
        public int CheckForUpdate()
        {
            FastMoveUpdateInfoVariables UpdateVariables;
            string downloadString = "";
            WebClient client = new WebClient();
            try
            {
                downloadString = client.DownloadString("https://raw.githubusercontent.com/j-b-n/Fastmove/master/update.xml");
            }
            catch(Exception)
            {

            }

            //writeOnlineUpdateInfo();

            var serializer = new SharpSerializer(false);

            using (Stream s = GenerateStreamFromString(downloadString))
            {
                UpdateVariables = (FastMoveUpdateInfoVariables)serializer.Deserialize(s);
                string runningVersion = GetRunningVersion();

                if (UpdateVariables.version != runningVersion)
                {
                    //New version available!
                    return 1;
                }

            }
            return 0;
        }
        public void BinSerial_TwoIdenticalChildsShouldBeSameInstance()
        {
            var parent = new ParentChildTestClass()
            {
                Name = "parent",
            };

            var child = new ParentChildTestClass()
            {
                Name = "child",
                Father = parent,
                Mother = parent,
            };

            Assert.AreSame(child.Father, child.Mother, "Precondition: Saved Father and Mother are same instance");

            var stream = new MemoryStream();
            var settings = new SharpSerializerBinarySettings(BinarySerializationMode.SizeOptimized);
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(child, stream);

            serializer = new SharpSerializer(settings);
            stream.Position = 0;
            ParentChildTestClass loaded = serializer.Deserialize(stream) as ParentChildTestClass;

            Assert.AreSame(loaded.Father, loaded.Mother, "Loaded Father and Mother are same instance");
        }
        public void serializeSizeOptimizedBinary_Click(object sender, EventArgs e)
        {
            // create fake obj
            var obj = RootContainer.CreateFakeRoot();

            // create instance of sharpSerializer
            var serializer = new SharpSerializer(true);

            // *************************************************************************************
            // For advanced serialization you create SharpSerializer with an overloaded constructor
            //
            //  SharpSerializerBinarySettings settings = createBinarySettings();
            //  serializer = new SharpSerializer(settings);
            //
            // Scroll the page to the createBinarySettings() method for more details
            // *************************************************************************************

            // set the filename
            var filename = "sharpSerializerExample.sizeOptimized";

            // serialize
            SerializationMessage = serialize(obj, serializer, filename);

            //IKI: iOS UIAlertView
            ShowMessageAlert(this, null);

            return;
        }
示例#14
0
文件: Cacher.cs 项目: Quertz/Ocell
        public static IEnumerable<TwitterStatus> GetFromCache(TwitterResource resource)
        {
            string fileName = GetCacheName(resource);
            var serializer = new SharpSerializer(SerializerSettings);
            Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName);
            IEnumerable<TwitterStatus> statuses = null;

            if (mutex.WaitOne(1000))
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        statuses = serializer.Deserialize(stream) as IEnumerable<TwitterStatus>;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }

            mutex.Dispose();
            return statuses ?? new List<TwitterStatus>();
        }
        private void StartEstudio_Load(object sender, EventArgs e)
        {
            try
            {
                var serializer = new SharpSerializer();
                Console.WriteLine(Path);
                estudioAbierto = (Estudio)serializer.Deserialize(Path);
                Console.WriteLine(estudioAbierto.ProjectName);
                lblProjectName.Text = estudioAbierto.ProjectName;
                listaItemsEstudio = estudioAbierto.ListaItemsEstudio;
                iNeutral = estudioAbierto.NeutralImage;
                foreach (ItemsEstudio item in listaItemsEstudio)
                {
                    string[] row = new string[] {""+ item.Numero,item.Nombre,item.Tipo };

                    tablaTimeline.Rows.Add(row);
                }

            }
            catch (Exception es)
            {
                Console.WriteLine("No Jala");
                Console.WriteLine(es);
            }
        }
示例#16
0
文件: Cacher.cs 项目: Quertz/Ocell
        public static void SaveToCache(TwitterResource resource, IEnumerable<TwitterStatus> list)
        {
            string fileName = GetCacheName(resource);

            var serializer = new SharpSerializer(SerializerSettings);
            Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName);

            if (mutex.WaitOne(1000))
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        serializer.Serialize(list.Distinct().OfType<TwitterStatus>().ToList(), stream);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }

            mutex.Dispose();
        }
示例#17
0
        public static IEnumerable<TwitterStatus> GetFromCache(TwitterResource resource)
        {
            string fileName = GetCacheName(resource);
            var serializer = new SharpSerializer(SerializerSettings);

            IEnumerable<TwitterStatus> statuses = null;

            MutexUtil.DoWork("OCELL_FILE_MUTEX" + fileName, () =>
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        if (stream.Length != 0)
                            statuses = serializer.Deserialize(stream) as IEnumerable<TwitterStatus>;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            });

            return statuses ?? new List<TwitterStatus>();
        }
 public SharpSerializer() // TODO: Is it possible to assigh Type to serializer, so it could speed up?
 {
     var settings = new Polenter.Serialization.SharpSerializerBinarySettings
     {
         Mode = BinarySerializationMode.Burst
     };
     _serializer = new Polenter.Serialization.SharpSerializer(settings);
 }
示例#19
0
 public static void Serialize(SyncHistory history, string path)
 {
     SharpSerializerXmlSettings settings = new SharpSerializerXmlSettings();
     settings.IncludeAssemblyVersionInTypeName = false;
     settings.IncludePublicKeyTokenInTypeName = false;
     SharpSerializer serializer = new SharpSerializer(settings);
     serializer.Serialize(history, path);
 }
示例#20
0
        private static object Deserialize(Stream streamObject)
        {
            if (streamObject == null)
                return null;

            // true - binary serialization, default - xml ser.
            var serializer = new SharpSerializer(true);
            return serializer.Deserialize(streamObject);
        }
示例#21
0
 public SharpSerializer(TestingSystem context, IConfigSectionNode conf)
     : base(context, conf)
 {
     var settings = new Polenter.Serialization.SharpSerializerBinarySettings
       {
           Mode = BinarySerializationMode.Burst
       };
     m_Serializer = new Polenter.Serialization.SharpSerializer(settings);
 }
示例#22
0
        public SharpSerializer() // TODO: Is it possible to assigh Type to serializer, so it could speed up?
        {
            var settings = new Polenter.Serialization.SharpSerializerBinarySettings
            {
                Mode = BinarySerializationMode.Burst
            };

            _serializer = new Polenter.Serialization.SharpSerializer(settings);
        }
示例#23
0
        public SharpSerializer(TestingSystem context, IConfigSectionNode conf)
            : base(context, conf)
        {
            var settings = new Polenter.Serialization.SharpSerializerBinarySettings
            {
                Mode = BinarySerializationMode.Burst
            };

            m_Serializer = new Polenter.Serialization.SharpSerializer(settings);
        }
示例#24
0
        static public void Load(object sender, EventArgs e)
        {
            Form form = (Form)sender;

            if (File.Exists(fileName(form)))
            {
                var serializer = new Polenter.Serialization.SharpSerializer();
                form = (Form)serializer.Deserialize(fileName(form));
            }
        }
示例#25
0
文件: Store.cs 项目: slieser/sandbox
 public void Save(IEnumerable<Datensatz> datensätze) {
     using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
         using (var file = appStorage.OpenFile(Filename, FileMode.OpenOrCreate)) {
             using (var writer = new StreamWriter(file)) {
                 var serializer = new SharpSerializer();
                 serializer.Serialize(datensätze, writer.BaseStream);
             }
         }
     }
 }
示例#26
0
 /// <summary>
 ///   Writes a string value to the Octgn registry
 /// </summary>
 /// <param name="valName"> Name of the value </param>
 /// <param name="value"> String to write for value </param>
 public static void WriteValue(string valName, string value)
 {
     var serializer = new SharpSerializer();
     var config = new Hashtable();
     if (File.Exists(GetPath()))
     {
         config = (Hashtable) serializer.Deserialize(GetPath());
     }
     config[valName] = value;
     serializer.Serialize(config, GetPath());
 }
示例#27
0
 public static IList<TrackBranch> Deserialize(string path, DXVcsWrapper vcsWrapper)
 {
     if (!File.Exists(path)) {
         Log.Error($"Track branch config with path {path} was not found.");
         return new List<TrackBranch>();
     }
     SharpSerializer serializer = new SharpSerializer();
     var branches = (IList<TrackBranch>)serializer.Deserialize(path);
     ProcessTrackItems(branches, vcsWrapper);
     return branches;
 }
示例#28
0
文件: Store.cs 项目: slieser/sandbox
 public IEnumerable<Datensatz> Load() {
     using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
         using (var file = appStorage.OpenFile(Filename, FileMode.OpenOrCreate)) {
             using (var reader = new StreamReader(file)) {
                 var serializer = new SharpSerializer();
                 var verbrauchswerte = serializer.Deserialize(reader.BaseStream);
                 return (IEnumerable<Datensatz>)verbrauchswerte;
             }
         }
     }
 }
示例#29
0
 public static SyncHistory Deserialize(string path)
 {
     try {
         SharpSerializer serializer = new SharpSerializer();
         return (SyncHistory)serializer.Deserialize(path);
     }
     catch (Exception ex) {
         Log.Error($"Loading history from {path} failed", ex);
         return new SyncHistory();
     }
 }
示例#30
0
        public void GenerateTestConfig()
        {
            List<TrackItem> items = new List<TrackItem>();
            items.Add(new TrackItem() { Path = @"$/Sandbox/litvinov/XPF/DevExpress.Xpf.Core", ProjectPath = "DevExpress.Xpf.Core" });
            TrackBranch branch = new TrackBranch("2015.2", "$/Sandbox/litvinov/XPF/track2015.2.config", "$/Sandbox/litvinov/XPF", items);

            SharpSerializerXmlSettings settings = new SharpSerializerXmlSettings();
            settings.IncludeAssemblyVersionInTypeName = false;
            settings.IncludePublicKeyTokenInTypeName = false;
            SharpSerializer serializer = new SharpSerializer(settings);
            serializer.Serialize(new List<TrackBranch>() { branch }, @"c:\1\trackconfig_testxpf.config");
        }
示例#31
0
 public static void Load()
 {
     SharpSerializer serializer = new SharpSerializer();
     OrusTheGame loadedGame = serializer.Deserialize("save.xml") as OrusTheGame;
     if(loadedGame != null)
     {
         if (loadedGame.GameInformation.Character != null && !loadedGame.GameInformation.GameMenu.CharacterSelectionInProgress)
         {
             UpdateGameProperties(loadedGame);
         }
     }
 }
示例#32
0
 /// <summary>
 ///   Reads a string value from the Octgn registry
 /// </summary>
 /// <param name="valName"> The name of the value </param>
 /// <returns> A string value </returns>
 public static string ReadValue(string valName)
 {
     if (File.Exists(GetPath()))
     {
         var serializer = new SharpSerializer();
         var config = (Hashtable) serializer.Deserialize(GetPath());
         if (config.ContainsKey(valName))
         {
             return config[valName].ToString();
         }
     }
     return null;
 }
示例#33
0
 List<SyncProfile> IProfileMapper.Load()
 {
     List<SyncProfile> p;
     if (File.Exists(Filename))
     {
         SharpSerializer s = new SharpSerializer();
         p = (List<SyncProfile>)s.Deserialize(Filename);
     }
     else
     {
         p = new List<SyncProfile>();
     }
     return p;
 }
示例#34
0
 /// <summary>
 /// Returns the fully rehydrated object based upon the given byte array.
 /// </summary>
 /// <param name="data">The byte array that represents the object.</param>
 /// <returns>Fully rehydrated object.</returns>
 public static object DeserializeFromBinary(byte[] data)
 {
     using (var memStream = new MemoryStream(data))
     {
         var settings = new SharpSerializerBinarySettings
         {
             IncludeAssemblyVersionInTypeName = true,
             IncludeCultureInTypeName = true,
             IncludePublicKeyTokenInTypeName = true
         };
         SharpSerializer ser = new SharpSerializer(settings);
         return ser.Deserialize(memStream);
     }
 }
示例#35
0
 /// <summary>
 /// Returns the fully rehydrated object based upon the given XML.
 /// </summary>
 /// <param name="xml">The xml that represents object.</param>
 /// <returns>Fully rehydrated object.</returns>
 public static object DeserializeFromXml(string xml)
 {
     using (var memStream = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
     {
         var settings = new SharpSerializerXmlSettings
         {
             IncludeAssemblyVersionInTypeName = true,
             IncludeCultureInTypeName = true,
             IncludePublicKeyTokenInTypeName = true
         };
         SharpSerializer ser = new SharpSerializer(settings);
         return ser.Deserialize(memStream);
     }
 }
示例#36
0
        public void XmlSerial_TwoIdenticalChildsShouldBeSameInstance()
        {
            var parent = new ParentChildTestClass()
            {
                Name = "parent",
            };

            var child = new ParentChildTestClass()
            {
                Name   = "child",
                Father = parent,
                Mother = parent,
            };

            Assert.AreSame(child.Father, child.Mother, "Precondition: Saved Father and Mother are same instance");

            var stream     = new MemoryStream();
            var settings   = new SharpSerializerXmlSettings();
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(child, stream);

            /*
             *  <Complex name="Root" type="Polenter.Serialization.XmlSerialisationTests+ParentChildTestClass, SharpSerializer.Tests">
             *          <Properties>
             *                  <Simple name="Name" value="child" />
             *                  <Complex name="Mother" id="1">
             *                          <Properties>
             *                                  <Simple name="Name" value="parent" />
             *                                  <Null name="Mother" />
             *                                  <Null name="Father" />
             *                          </Properties>
             *                  </Complex>
             *                  <ComplexReference name="Father" id="1" />
             *          </Properties>
             *  </Complex>
             */
            stream.Position = 0;
            XmlDocument doc = new XmlDocument();

            doc.Load(stream);
            System.Console.WriteLine(doc.InnerXml);

            serializer      = new SharpSerializer(settings);
            stream.Position = 0;
            ParentChildTestClass loaded = serializer.Deserialize(stream) as ParentChildTestClass;

            Assert.AreSame(loaded.Father, loaded.Mother, "Loaded Father and Mother are same instance");
        }
示例#37
0
 void GenerateRepoConfig(string branch, string taskName, string watchTaskName, string defaultService, bool allowTesting = false,  string[] testConfigs = null)
 {
     RepoConfig config = new RepoConfig() {
         Name = branch,
         FarmTaskName = watchTaskName,
         FarmSyncTaskName = taskName,
         DefaultServiceName = defaultService,
         SupportsTesting = allowTesting,
     };
     SharpSerializerXmlSettings settings = new SharpSerializerXmlSettings();
     settings.IncludeAssemblyVersionInTypeName = false;
     settings.IncludePublicKeyTokenInTypeName = false;
     SharpSerializer serializer = new SharpSerializer(settings);
     serializer.Serialize(config, @"z:\gitconfig.config");
 }
示例#38
0
        /// <summary>
        ///   Reads a string value from the Octgn registry
        /// </summary>
        /// <param name="valName"> The name of the value </param>
        /// <returns> A string value </returns>
        public static string ReadValue(string valName, string def)
        {
            lock (lockObject)
            {
                var ret = def;
                Stream f = null;
                try
                {
                    if (File.Exists(GetPath()))
                    {
                        var serializer = new SharpSerializer();

                        Hashtable config = new Hashtable();
                        if (OpenFile(GetPath(), FileMode.OpenOrCreate, FileShare.None, TimeSpan.FromSeconds(2), out f))
                        {
                            config = (Hashtable)serializer.Deserialize(f);
                        }
                        if (config.ContainsKey(valName))
                        {
                            return config[valName].ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    Trace.WriteLine("[SimpleConfig]ReadValue Error: " + e.Message);
                    try
                    {
                        File.Delete(GetPath());
                    }
                    catch (Exception)
                    {
                        Trace.WriteLine("[SimpleConfig]ReadValue Error: Couldn't delete the corrupt config file.");
                    }
                }
                finally
                {
                    if (f != null)
                    {
                        f.Close();
                        f = null;
                    }
                }
                return ret;
            }
        }
示例#39
0
 public static void Save(object sender = null, object args = null)
 {
     if(OrusTheGame.Instance.GameInformation.Character != null)
     {
         SharpSerializer serializer = new SharpSerializer();
         //Decide which properties to ignore
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "Content");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "Components");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "LaunchParameters");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "Services");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "TargetElapsedTime");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "QuestFont");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "NameFont");
         serializer.PropertyProvider.PropertiesToIgnore.Add(typeof(OrusTheGame), "AllCharacters");
         serializer.Serialize(OrusTheGame.Instance, "save.xml");
     }
 }
示例#40
0
 /// <summary>
 ///   Writes a string value to the Octgn registry
 /// </summary>
 /// <param name="valName"> Name of the value </param>
 /// <param name="value"> String to write for value </param>
 public static void WriteValue(string valName, string value)
 {
     try
     {
         var serializer = new SharpSerializer();
         var config = new Hashtable();
         if (File.Exists(GetPath()))
         {
             config = (Hashtable) serializer.Deserialize(GetPath());
         }
         config[valName] = value;
         serializer.Serialize(config, GetPath());
     }
     catch(Exception e)
     {
         Trace.WriteLine("[SimpleConfig]WriteValue Error: " + e.Message);
     }
 }
        public void BinSerial_ShouldSerializeGuid()
        {
            var parent = new ClassWithGuid()
            {
                Guid = Guid.NewGuid(),
            };

            var stream = new MemoryStream();
            var settings = new SharpSerializerBinarySettings(BinarySerializationMode.SizeOptimized);
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(parent, stream);

            serializer = new SharpSerializer(settings);
            stream.Position = 0;
            ClassWithGuid loaded = serializer.Deserialize(stream) as ClassWithGuid;

            Assert.AreEqual(parent.Guid, loaded.Guid, "same guid");
        }
示例#42
0
        public static void SaveToCache(TwitterResource resource, IEnumerable<TwitterStatus> list)
        {
            string fileName = GetCacheName(resource);

            var serializer = new SharpSerializer(SerializerSettings);
            MutexUtil.DoWork("OCELL_FILE_MUTEX" + fileName, () =>
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        serializer.Serialize(list.Distinct().OfType<TwitterStatus>().ToList(), stream);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            });
        }
示例#43
0
        public void BinSerial_ShouldSerializeGuid()
        {
            var parent = new ClassWithGuid()
            {
                Guid = Guid.NewGuid(),
            };

            var stream     = new MemoryStream();
            var settings   = new SharpSerializerBinarySettings(BinarySerializationMode.SizeOptimized);
            var serializer = new SharpSerializer(settings);

            serializer.Serialize(parent, stream);


            serializer      = new SharpSerializer(settings);
            stream.Position = 0;
            ClassWithGuid loaded = serializer.Deserialize(stream) as ClassWithGuid;

            Assert.AreEqual(parent.Guid, loaded.Guid, "same guid");
        }
示例#44
0
        public void CannotDeserializeClassWithoutParameterlessConstructor()
        {
            var child = new ClassWithoutParameterlessConstructor("child");

            var data = new ClassWithoutParameterlessConstructor("MyName")
            {
                Complex = child
            };

            var settings   = new SharpSerializerXmlSettings();
            var serializer = new SharpSerializer(settings);

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(data, stream);

                stream.Position = 0;

                serializer.Deserialize(stream);
            }
        }
示例#45
0
        private static void serialize(HelloWorldTestCase testCase, SharpSerializer serializer)
        {
            using (var stream = new MemoryStream())
            {
                // serialize
                serializer.Serialize(testCase.Source, stream);

                // reset stream
                stream.Position = 0;

                // deserialize
                var result = serializer.Deserialize(stream);

                // reset stream to test if it is not closed
                // the stream will be closed by the user
                stream.Position = 0;

                // Fix assertions
                Assert.AreEqual(testCase.Source.GetType(), result.GetType());

                // Custom assertions
                testCase.MakeAssertion(result);
            }
        }