Example #1
0
        public void FromXml_Xml_ReturnsObjectFromXml()
        {
            string xml     = File.ReadAllText("books.xml");
            var    catalog = XSerializer.FromXml <Catalog>(xml);

            Assert.IsNotNull(catalog);
        }
Example #2
0
        /// <summary>
        /// Serializes object of specified type with Xml Serializer
        /// </summary>
        /// <typeparam name="ObjetType">Type of serialized object</typeparam>
        /// <param name="data">Object to serialize</param>
        /// <returns>Returns object serialized into string.</returns>
        public static string Serialize <T>(T data, string rootAttribute = null)
        {
            XmlSerializer XSerializer;

            if (System.String.IsNullOrEmpty(rootAttribute))
            {
                XSerializer = new XmlSerializer(typeof(T));
            }
            else
            {
                XSerializer = new XmlSerializer(typeof(T), rootAttribute);
            }

            StringWriter  SWriter  = new StringWriter();
            XmlTextWriter XTWriter = new XmlTextWriter(SWriter);

            XTWriter.Formatting = Formatting.Indented;
            XSerializer.Serialize(XTWriter, data);
            string output = SWriter.ToString();

            XTWriter.Close();
            SWriter.Close();

            return(output);
        }
Example #3
0
        public void BuildXmlSerializer_ArrayType_ReturnsXmlSerializer()
        {
            var           arr = Helper.GeStringArray();
            XmlSerializer ser = XSerializer.BuildXmlSerializer(arr);

            Assert.IsNotNull(ser);
        }
Example #4
0
        /// <summary>
        /// Deserializes object from isolated storage file.
        /// </summary>
        /// <typeparam name="T">Type of object.</typeparam>
        /// <param name="fileName">Path to isolated storage file.</param>
        /// <returns></returns>
        public static T Deserialize <T>(string subDirectory, string fileName)
        {
            try
            {
                // Open isolated storage.
                using (var storageManager = new IsolatedStorageManager())
                {
                    fileName = Prepare(storageManager, subDirectory, fileName);

                    if (storageManager.FileExists(fileName))
                    {
                        // Open file from storage.
                        using (var stream = storageManager.OpenFile(fileName, IO.OpenFileMode.Open))
                        {
                            XFile file = XFile.LoadBinary(stream, fileName);

                            var serializer = new XSerializer(file);

                            return(serializer.Deserialize <T>("Data"));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(default(T));
        }
Example #5
0
        /// <summary>
        /// Serializes object to isolated storage file.
        /// </summary>
        /// <param name="fileName">file name.</param>
        /// <param name="obj">Object to serialize.</param>
        public static void Serialize(string subDirectory, string fileName, Object obj)
        {
            // Open isolated storage.
            using (var storageManager = new IsolatedStorageManager())
            {
                fileName = Prepare(storageManager, subDirectory, fileName);

                // Open file from storage.
                using (Stream stream = storageManager.OpenFile(fileName, IO.OpenFileMode.Create))
                {
                    XFile file = XFile.Create(fileName);

                    XNode fileNode = file;

                    var node = new XNode(file, "Serializator");
                    ((XNode)file).Nodes.Add(node);

                    // Create serializer for type.
                    var serializer = new XSerializer(node);
                    serializer.Serialize("Data", obj);

                    file.WriteBinary(stream);
                }
            }
        }
Example #6
0
        public void ToXml_ValidCollection_ReturnsXmlString()
        {
            ICollection <string> catalog = Helper.GeStringArray();

            string xml = XSerializer.ToXml(catalog);

            Assert.IsTrue(xml.Length > 0);
        }
Example #7
0
        public void BuildXmlSerializer_ObjectType_ReturnsXmlSerializer()
        {
            SimpleFake fake = new SimpleFake();

            XmlSerializer ser = XSerializer.BuildXmlSerializer(fake);

            Assert.IsNotNull(ser);
        }
Example #8
0
        public void BuildXmlSerializer_CollectionType_ReturnsXmlSerializer()
        {
            ICollection <string> col = Helper.GeStringArray();

            XmlSerializer ser = XSerializer.BuildXmlSerializer(col);

            Assert.IsNotNull(ser);
        }
Example #9
0
 public static T ToObject <T>(this string text)
 {
     if (text.IsNullOrEmpty())
     {
         return(default(T));
     }
     return(XSerializer.Deserialize <T>(text));
 }
Example #10
0
        public static string ToXml <T>(this T instance, bool omitXmlDeclaration)
        {
            if (instance == null)
            {
                return(string.Empty);
            }

            return(XSerializer.Serialize(instance, omitXmlDeclaration));
        }
Example #11
0
        public static string ToXml <T>(this T instance)
        {
            if (instance == null)
            {
                return(string.Empty);
            }

            return(XSerializer.Serialize(instance));
        }
Example #12
0
 public GOC()
 {
     _webServiceCache = new WebServiceClientCache();
     _loggerStandard  = new Logger();
     _xSerializer     = new XSerializer();
     _jSerializer     = new JSerializer();
     _csvSerializer   = new CsvSerializer();
     _encoding        = Encoding.Default;
 }
Example #13
0
 public GOCWindows()
 {
     _settingsCache   = new SettingsCache();
     _webServiceCache = new WebServiceClientCache();
     _databaseCache   = new DatabaseCacheWindows();
     _logger          = new LoggerWindows();
     _xSerializer     = new XSerializer();
     _jSerializer     = new JSerializer();
     _csvSerializer   = new CsvSerializer();
     _encoding        = Encoding.Default;
 }
Example #14
0
        private void SaveGame()
        {
            mDirector.GetStoryManager.SaveAchievements();
            var saveName = DateTime.Now;

            XSerializer.Save(mDirector.GetStoryManager.Level,
                             saveName.ToString(CultureInfo.CurrentCulture).Replace(':', '_') + ".xml",
                             false);
            Console.WriteLine("Game Saved");
            sSaved = true;
        }
Example #15
0
 public void Write(XSerializer value)
 {
     Fragment[] fragments;
     byte[]     buffer = value.GetBuffer(out fragments);
     if (fragments != null)
     {
         foreach (Fragment _framment in fragments)
         {
             WriteBytes(buffer, _framment.begin, _framment.length);
         }
     }
 }
Example #16
0
        public void BuildXmlSerializer_StructType_ReturnsXmlSerializer()
        {
            var stru = new SampleStruct
            {
                Count     = 5,
                FirstName = "Bob",
                LastName  = "Marly",
                Time      = DateTime.Now,
            };

            XmlSerializer ser = XSerializer.BuildXmlSerializer(stru);

            Assert.IsNotNull(ser);
        }
Example #17
0
        public void ToXml_ValidStruct_ReturnsXmlString()
        {
            var catalog = new SampleStruct
            {
                Count     = 50,
                FirstName = "Pablo",
                LastName  = "Duartes",
                Time      = DateTime.Now
            };

            string xml = XSerializer.ToXml(catalog);

            Assert.IsTrue(xml.IndexOf("SampleStruct") > 0);
        }
Example #18
0
        private void LoadConfig()
        {
            var configuration = XSerializer.Load(@"Config.xml", true);

            if (configuration.IsPresent())
            {
                mInstance = (GlobalVariablesInstance)configuration.Get();
            }
            else
            {
                mInstance = new GlobalVariablesInstance();
            }

            mInstance.LoadToStatic();
        }
Example #19
0
        /// <summary>
        /// The Method to load the Achievements. The Achievements file has to be at %USERPROFILE%\Saved Games\Singularity\Achievements. If no one like this exists
        /// it will just create a new one.
        /// </summary>
        internal void LoadAchievements()
        {
            var achievements = XSerializer.Load(@"Achievements.xml", true);

            if (achievements.IsPresent())
            {
                mAchievements = (AchievementInstance)achievements.Get();
            }
            else
            {
                mAchievements = new AchievementInstance();
            }

            mAchievements.LoadToStatic();
        }
Example #20
0
        public RequestBuilder(XSerializer serializer, ILogger logger)
        {
            if (serializer == null)
            {
                throw new ArgumentNullException(nameof(serializer));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _serializer = serializer;
            _logger     = logger;
        }
Example #21
0
        }         // enum LegalStatus

        public TargetResults(string targetData)
        {
            OutStr  = targetData;
            Targets = new List <CompanyInfo>();

            try
            {
                foreach (var business in XElement.Parse(targetData).Element("REQUEST").Elements("DT11"))
                {
                    var bi = XSerializer.Deserialize <CompanyInfo>(business);
                    Targets.Add(bi);
                }                 // for each business

                if (Targets.Any())
                {
                    foreach (var t in Targets)
                    {
                        t.BusName = string.IsNullOrEmpty(t.BusName)
                                                        ? string.Empty
                                                        : System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(t.BusName.ToLower());
                        t.AddrLine1 = string.IsNullOrEmpty(t.AddrLine1)
                                                        ? string.Empty
                                                        : System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(t.AddrLine1.ToLower());
                        t.AddrLine2 = string.IsNullOrEmpty(t.AddrLine2)
                                                        ? string.Empty
                                                        : System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(t.AddrLine2.ToLower());
                        t.AddrLine3 = string.IsNullOrEmpty(t.AddrLine3)
                                                        ? string.Empty
                                                        : System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(t.AddrLine3.ToLower());
                        t.AddrLine4 = string.IsNullOrEmpty(t.AddrLine4)
                                                        ? string.Empty
                                                        : System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(t.AddrLine4.ToLower());
                    }                     // for each

                    if (Targets.Count > 1)
                    {
                        Targets.Add(new CompanyInfo {
                            BusName = "Company not found", BusRefNum = "skip"
                        });
                    }
                }                 // if
            }
            catch
            {
            } // try
        }     // constructor
Example #22
0
        /// <summary>
        /// Initialize the template from the informations contained in the given object.
        /// </summary>
        /// <param name="pObject">The object initializing the template.</param>
        /// <param name="pSerializer">The serializer</param>
        /// <returns>True if the type of the given object is the same or inherits the templated type.</returns>
        bool IXTemplate.InitializeFrom(object pObject, XSerializer pSerializer)
        {
            try
            {
                if (pObject != null && this.BaseTemplatedType.IsAssignableFrom(pObject.GetType()))
                {
                    return(this.InitializeFrom((TObject)pObject, pSerializer));
                }

                return(false);
            }
            catch
            (Exception /*lEx*/)
            {
                return(false);
            }
        }
Example #23
0
        public void ToXml_ValidObject_ReturnsXmlString()
        {
            var catalog = new Catalog();
            var book    = new Book();
            var book2   = new Book();

            Dummy.Populate(book);
            Dummy.Populate(book2);
            Dummy.Populate(catalog);

            catalog.BookList.Add(book);
            catalog.BookList.Add(book2);

            string xml = XSerializer.ToXml(catalog);

            Assert.IsTrue(xml.Length > 0);
        }
Example #24
0
        public bool KeyTyped(KeyEvent keyevent)
        {
            // b key is used to convert the settler unit into a command center
            var keyArray = keyevent.CurrentKeys;

            foreach (var key in keyArray)
            {
                // if key b has been pressed and the settler unit is selected and its not moving
                // --> send out event that deletes settler and adds a command center
                if (key == Keys.Q)
                {
                    mDirector.GetStoryManager.SaveAchievements();
                    XSerializer.Save(this, "Quicksave.xml", false);
                    return(false);
                }
            }

            return(true);
        }
Example #25
0
        /// <summary>
        /// Deserializes data string with Xml Serializer
        /// </summary>
        /// <typeparam name="ObjetType">Type of returned object</typeparam>
        /// <param name="data">serialized data</param>
        /// <returns>returns deserialized object of specified type</returns>
        public static T Deserialize <T>(string data, string rootAttribute = null)//this string data
        {
            XmlSerializer XSerializer;

            if (System.String.IsNullOrEmpty(rootAttribute))
            {
                XSerializer = new XmlSerializer(typeof(T));
            }
            else
            {
                XSerializer = new XmlSerializer(typeof(T), rootAttribute);
            }

            StringReader SReader = new StringReader(data);
            T            output  = (T)XSerializer.Deserialize(SReader);

            SReader.Close();

            return(output);
        }
Example #26
0
        /// <summary>
        /// Initialize the template from the informations contained in the given object.
        /// </summary>
        /// <param name="pObject">The object initializing the template.</param>
        /// <param name="pSerializer">The serializer</param>
        /// <returns>True if the type of the given object is the same or inherits the templated type.</returns>
        public virtual bool InitializeFrom(TObject pObject, XSerializer pSerializer)
        {
            if (pObject != null)
            {
                this.Editor        = pObject;
                this.TemplatedType = pObject.GetType();

                if (pSerializer != null)
                {
                    this.mTemplateNode = pSerializer.Serialize(pObject);
                }
                else
                {
                    XSerializer lSerializer = new XSerializer();
                    this.mTemplateNode = lSerializer.Serialize(pObject);
                }

                return(this.mTemplateNode != null);
            }

            return(false);
        }
        /// <summary>
        /// This method creates the specified element.
        /// </summary>
        /// <param name="pParentElement">The parent element.</param>
        /// <param name="pSerializationContext">The serialization context.</param>
        /// <returns>The created object.</returns>
        public virtual object Create(XElement pParentElement, IXSerializationContext pSerializationContext)
        {
            XAttribute lAttribute         = this.mTargetElement.Attribute(XConstants.EXTERNAL_REFERENCE_ATTRIBUTE);
            string     lExternalReference = lAttribute.Value;
            string     lFullExternalReference;
            bool       lIsRelative;

            if (Path.IsPathRooted(lExternalReference))
            {
                lFullExternalReference = lExternalReference;
                lIsRelative            = false;
            }
            else
            {
                lFullExternalReference = pSerializationContext.CurrentDirectory.FullName + Path.DirectorySeparatorChar + lExternalReference;
                lIsRelative            = true;
            }
            XSerializer lDeserializer = new XSerializer(pSerializationContext.ExternalReferenceResolver);
            object      lResult       = lDeserializer.Deserialize(lFullExternalReference);

            pSerializationContext.ExternalReferenceResolver.RegisterExternalReference(lResult, lFullExternalReference, lIsRelative);
            return(lResult);
        }
Example #28
0
        /// <summary>
        /// Create an instance of the template type.
        /// </summary>
        /// <returns>The instance is the creation succed, default value otherwise.</returns>
        public virtual TObject Create(XSerializer pSerializer)
        {
            try
            {
                if (this.mTemplateNode == null)
                {
                    return(default(TObject));
                }

                if (pSerializer != null)
                {
                    return((TObject)pSerializer.Deserialize(this.mTemplateNode));
                }
                else
                {
                    XSerializer lSerializer = new XSerializer();
                    return((TObject)lSerializer.Deserialize(this.mTemplateNode));
                }
            }
            catch (Exception /*lEx*/)
            {
                return(default(TObject));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SerializationContractDecorator" /> class.
 /// </summary>
 /// <param name="pDecoratedContract">The p decorated contract.</param>
 /// <param name="pXSerializer">The calling x serializer.</param>
 public SerializationContractDecorator(IXSerializationContract pDecoratedContract, XSerializer pXSerializer)
 {
     this.DecoratedContract = pDecoratedContract;
     this.XSerializer = pXSerializer;
 }
Example #30
0
        public void ToXml_String_ThrowsInvalidOperation()
        {
            string catalog = File.ReadAllText("Books.xml");

            Assert.Throws <InvalidOperationException>(() => XSerializer.ToXml(catalog));
        }
Example #31
0
        public void ToXml_EmptyString_ThrowsArgumentException()
        {
            string catalog = "";

            Assert.Throws <ArgumentException>(() => XSerializer.ToXml(catalog));
        }
        /// <summary>
        /// This method creates the specified element.
        /// </summary>
        /// <param name="pParentElement">The parent element.</param>
        /// <param name="pSerializationContext">The serialization context.</param>
        /// <returns>The created object.</returns>
        public virtual object Create(XElement pParentElement, IXSerializationContext pSerializationContext)
        {
            XAttribute lAttribute = this.mTargetElement.Attribute(XConstants.EXTERNAL_REFERENCE_ATTRIBUTE);
            string lExternalReference = lAttribute.Value;
            string lFullExternalReference;
            bool lIsRelative;
            if (Path.IsPathRooted(lExternalReference))
            {
                lFullExternalReference = lExternalReference;
                lIsRelative = false;
            }
            else
            {
                lFullExternalReference = pSerializationContext.CurrentDirectory.FullName + Path.DirectorySeparatorChar + lExternalReference;
                lIsRelative = true;

            }
            XSerializer lDeserializer = new XSerializer(pSerializationContext.ExternalReferenceResolver);
            object lResult = lDeserializer.Deserialize(lFullExternalReference);
            pSerializationContext.ExternalReferenceResolver.RegisterExternalReference(lResult, lFullExternalReference, lIsRelative);
            return lResult;
        }