Exemplo n.º 1
0
        private string SerializeGame([NotNull] MGM.Game.Game game)
        {
            var memoryStream = new MemoryStream();

            Serializer.WriteObject(memoryStream, game);
            return(Encoding.UTF8.GetString(memoryStream.ToArray()));
        }
Exemplo n.º 2
0
        private void Store(string fileName, object graph)
        {
            XmlWriter writer = null;

            try {
                if (File.Exists(fileName))
                {
                    File.Copy(fileName, GetBackupFileName(fileName), true);
                    File.Delete(fileName);
                }

                writer = XmlWriter.Create(fileName);
                //writer = new XmlTextWriter(fileName, Encoding.UTF8);
                //writer.Formatting = Formatting.Indented;
                //writer.Namespaces = false;

                NetDataContractSerializer ser = new NetDataContractSerializer();
                ser.AssemblyFormat = FormatterAssemblyStyle.Simple;
                //DataContractSerializer ser = new DataContractSerializer(typeof (ArrayList));

                ser.WriteObject(writer, graph);
            }
            catch (Exception) {
                throw;
            }
            finally {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
        private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
        {
            XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();

            netDataContractSerializer.WriteObject(fs, job);
            fs.Flush();
        }
Exemplo n.º 4
0
        public static string Serialize(object value)
        {
            if (value == null)
            {
                return(String.Empty);
            }
            else
            {
                using (var m = new MemoryStream())
                {
                    var w = XmlTextWriter.Create(
                        m,
                        new XmlWriterSettings()
                    {
                        Indent            = true,
                        Encoding          = Encoding.Unicode,
                        NamespaceHandling = NamespaceHandling.OmitDuplicates,
                    });

                    var s = new NetDataContractSerializer();

                    s.WriteObject(w, value);
                    w.Flush();
                    w.Close();

                    // Don't forget to skip byte order mark
                    var buffer = m.ToArray();
                    var prelen = Encoding.Unicode.GetPreamble().Length;
                    return(System.Text.Encoding.Unicode.GetString(buffer, prelen, buffer.Length - prelen));
                }
            }
        }
Exemplo n.º 5
0
 public static void WriteObject <T>(T data, string fileName, ExceptionHandler exceptionHandler)
 {
     try
     {
         using (var fs = new FileStream(fileName, FileMode.Create))
         {
             var settings = new XmlWriterSettings {
                 Indent = true
             };
             using (var writer = XmlWriter.Create(fs, settings))
             {
                 var ser = new NetDataContractSerializer();
                 ser.WriteObject(writer, data);
                 writer.Close();
             }
         }
     }
     catch (Exception exc)
     {
         if (exceptionHandler != null)
         {
             exceptionHandler($"{nameof(XmlIO)}.{nameof(ReadObject)}<{typeof(T).Name}>", exc);
         }
         else
         {
             throw;
         }
     }
 }
Exemplo n.º 6
0
        static void DeserializeAndReserialize(string path)
        {
            Console.WriteLine(
                "Deserializing new version to old version");
            FileStream fs = new FileStream(path,
                                           FileMode.Open);
            XmlDictionaryReader reader = XmlDictionaryReader.
                                         CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            // Create the serializer.
            NetDataContractSerializer ser =
                new NetDataContractSerializer();
            // Deserialize version 1 of the data.
            PurchaseOrder PO_V1 =
                (PurchaseOrder)ser.ReadObject(reader, false);

            Console.WriteLine("Order Date:{0}",
                              PO_V1.PurchaseDate.ToLongDateString());
            fs.Close();

            Console.WriteLine(
                "Reserialize the object with extension data intact");
            // First change the order date.
            DateTime newDate = PO_V1.PurchaseDate.AddDays(10);

            PO_V1.PurchaseDate = newDate;

            // Create a new FileStream to write with.
            FileStream writer = new FileStream(path, FileMode.Create);

            // Serialize the object with changed data.
            ser.WriteObject(writer, PO_V1);
            writer.Close();
        }
Exemplo n.º 7
0
        public static void SaveToDevice <T>(T obj, String path, Action userCallback) where T : class
        {
            if (_storageDevice == null)
            {
                Console.WriteLine("Storage Device was null");
                if (userCallback != null)
                {
                    userCallback();
                }
                return;
            }
            _storageDevice.BeginOpenContainer(Constants.Locations.ContainerName, openResult => {
                using (var sd = _storageDevice.EndOpenContainer(openResult)) {
                    var serializer     = new NetDataContractSerializer();
                    var writerSettings = new XmlWriterSettings {
                        Indent = true, CloseOutput = true
                    };

                    using (var writer = XmlWriter.Create(sd.CreateFile(path), writerSettings)) {
                        serializer.WriteObject(writer, obj);
                    }

                    if (userCallback != null)
                    {
                        userCallback();
                    }
                }
            }, null);
        }
Exemplo n.º 8
0
    static void Main(string[] args)
    {
        // create a new Person object
        Person myPerson = new Person("Adam Freeman", "London");

        // open the stream to the file we want to store the data in
        Stream myStream = new MemoryStream();

        // create the serialize
        NetDataContractSerializer serializer = new NetDataContractSerializer();

        // serialize the Person object
        serializer.WriteObject(myStream, myPerson);

        // reset the cursor on the stream and read the serialized data
        myStream.Seek(0, SeekOrigin.Begin);
        StreamReader myReader = new StreamReader(myStream);

        Console.WriteLine(myReader.ReadToEnd());

        // reset the cursor and deserialize the object
        myStream.Seek(0, SeekOrigin.Begin);
        Person myDeserializedPerson = (Person)serializer.ReadObject(myStream);

        // wait for input before exiting
        Console.WriteLine("Press enter to finish");
        Console.ReadLine();
    }
Exemplo n.º 9
0
        private bool TryNetDataContractSerializer(Type type)
        {
            using (var m = new MemoryStream())
            {
                var w = XmlTextWriter.Create(
                    m,
                    new XmlWriterSettings()
                {
                    Indent            = true,
                    Encoding          = Encoding.Unicode,
                    NamespaceHandling = NamespaceHandling.OmitDuplicates,
                });

                var s = new NetDataContractSerializer(
                    new StreamingContext(),
                    int.MaxValue,
                    false,
                    System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
                    null);

                var o = Activator.CreateInstance(type, true);

                s.WriteObject(w, o);
                w.Flush();
                w.Close();

                // Don't forget to skip byte order mark
                var buffer = m.ToArray();
                var prelen = Encoding.Unicode.GetPreamble().Length;
                var xml    = System.Text.Encoding.Unicode.GetString(buffer, prelen, buffer.Length - prelen);
            }

            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// /// <summary>
        /// Serialization routines used only to mimic SQL persistance to ensure there are no errors during unit testing of the in memory store.
        /// Obtained from https://referencesource.microsoft.com/#System.Activities.DurableInstancing/System/Activities/DurableInstancing/SerializationUtilities.cs,6929c9045420df05
        /// </summary>
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="propertyBag"></param>
        void DefaultSerializePropertyBag(Stream stream, Dictionary <XName, object> propertyBag)
        {
            using (XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, null, null, false))
            {
                dictionaryWriter.WriteStartElement("Properties");

                foreach (KeyValuePair <XName, object> property in propertyBag)
                {
                    dictionaryWriter.WriteStartElement("Property");

                    try
                    {
                        serializer.WriteObject(dictionaryWriter, property);
                    }
                    catch (System.Runtime.Serialization.InvalidDataContractException ex)
                    {
                        throw new SerializationFailedException("This can be caused by many issues. Ensure you have a default constructor and check the inner exception for more info. See also: https://stackoverflow.com/questions/10077121/datacontract-exception-cannot-be-serialized", ex);
                    }

                    dictionaryWriter.WriteEndElement();
                }

                dictionaryWriter.WriteEndElement();
            }
        }
 public void WriteXml(XmlWriter writer)
 {
     if (this.Value != null)
     {
         NetDataContractSerializer serializer = this.CreateSerializer();
         serializer.WriteObject(writer, this.Value);
     }
 }
Exemplo n.º 12
0
 public void Save(string path, IShape shape)
 {
     using (var f = File.OpenWrite(path))
     {
         var s = new NetDataContractSerializer();
         s.WriteObject(f, shape);
     }
 }
Exemplo n.º 13
0
        private static void SaveStatusToFile(ScheduledJob job, FileStream fs)
        {
            StatusInfo          statusInfo = new StatusInfo(job.InstanceId, job.Name, job.Location, job.Command, job.StatusMessage, job.JobStateInfo.State, job.HasMoreData, job.PSBeginTime, job.PSEndTime, job.Definition);
            XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();

            netDataContractSerializer.WriteObject(fs, statusInfo);
            fs.Flush();
        }
Exemplo n.º 14
0
 public void WriteProducts(ICollection<Product> products)
 {
     var serializer = new NetDataContractSerializer();
     using (FileStream fs = new FileStream(path, FileMode.Create))
     {
         serializer.WriteObject(fs, products);
     }
 }
Exemplo n.º 15
0
        public void Write(ICollection <Film> films)
        {
            var serializer = new NetDataContractSerializer();

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                serializer.WriteObject(fs, films);
            }
        }
Exemplo n.º 16
0
        public static byte[] Serialize(object value)
        {
            var ns = new NetDataContractSerializer();

            using (var s = new MemoryStream())
            {
                ns.WriteObject(s, value);
                return(s.ToArray());
            }
        }
        public string Serialize(T obj)
        {
            var ser = new NetDataContractSerializer();

            using (var stream = new MemoryStream())
            {
                ser.WriteObject(stream, obj);
                return(Encoding.ASCII.GetString(stream.ToArray()));
            }
        }
Exemplo n.º 18
0
        public static void Save(Plugin plg)
        {
            MySerialization oMainFormSerialize = new MySerialization(plg);

            NetDataContractSerializer dcs = new NetDataContractSerializer();

            using (Stream oStream = File.Create(plg.SerializePath)) {
                dcs.WriteObject(oStream, oMainFormSerialize);
            }
        }
Exemplo n.º 19
0
        static void Serialize7(Root r, Stream fs, Stopwatch sw)
        {
            NetDataContractSerializer ser = new NetDataContractSerializer();
            XmlDictionaryWriter       xw  = XmlDictionaryWriter.CreateTextWriter(fs);

            sw.Start();
            ser.WriteObject(xw, r);
            sw.Stop();
            xw.Close();
        }
Exemplo n.º 20
0
        /// <summary>
        /// Serializes the specified object to XML.
        /// </summary>
        /// <param name="item">The object to serialize. Must have <see cref="DataContractAttribute" /> applied.</param>
        /// <returns>An <see cref="XElement" /> representing the specified object.</returns>
        /// <exception cref="InvalidDataContractException"><paramref name="item" /> is not a valid data contract.</exception>
        public static XElement Serialize(object item)
        {
            NetDataContractSerializer serializer = CreateSerializer(Enumerable.Empty <SerializerProxyMap>());
            XDocument doc = new XDocument();

            using (XmlWriter writer = doc.CreateWriter())
            {
                serializer.WriteObject(writer, item);
            }
            return(doc.Root);
        }
            public XElement ToElement(object val, Func <Type, XNamespace> getNamespace)
            {
                var serializer = new NetDataContractSerializer();

                using (var ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, val);
                    ms.Seek(0, SeekOrigin.Begin);
                    return(XElement.Load(new XmlTextReader(ms)));
                }
            }
Exemplo n.º 22
0
        /// <summary>
        /// Serializes the specified object to a complete XML document.</summary>
        /// <typeparam name="T">
        /// The type of the object to serialize.</typeparam>
        /// <param name="obj">
        /// The object to serialize.</param>
        /// <returns>
        /// A <see cref="String"/> containing the complete XML document resulting from the
        /// serialization of <paramref name="obj"/>.</returns>
        /// <exception cref="SerializationException">
        /// <paramref name="obj"/> could not be serialized.</exception>
        /// <remarks>
        /// <b>Serialize</b> uses a <see cref="NetDataContractSerializer"/> and an <see
        /// cref="XmlWriter"/> using the settings returned by <see
        /// cref="XmlUtility.CreateWriterSettings"/>.</remarks>

        public static string Serialize <T>(T obj)
        {
            var builder  = new StringBuilder();
            var settings = XmlUtility.CreateWriterSettings();

            using (var writer = XmlWriter.Create(builder, settings)) {
                var serializer = new NetDataContractSerializer();
                serializer.WriteObject(writer, obj);
            }

            return(builder.ToString());
        }
Exemplo n.º 23
0
        public static void WriteObject(string fileName)
        {
            Console.WriteLine("Creating a Person object and serializing it.");

            // Creating the serializer
            ComplexNumber             number = new ComplexNumberWithMagnitude(3, 4);
            FileStream                fs     = new FileStream(fileName, FileMode.Create);
            XmlDictionaryWriter       writer = XmlDictionaryWriter.CreateTextWriter(fs);
            NetDataContractSerializer ser    = new NetDataContractSerializer();

            ser.WriteObject(writer, number);
            writer.Close();
        }
Exemplo n.º 24
0
        //<snippet1>
        public static void WriteObject(string fileName)
        {
            Console.WriteLine(
                "Creating a Person object and serializing it.");
            Person                    p1     = new Person("Zighetti", "Barbara", 101);
            FileStream                fs     = new FileStream(fileName, FileMode.Create);
            XmlDictionaryWriter       writer = XmlDictionaryWriter.CreateTextWriter(fs);
            NetDataContractSerializer ser    =
                new NetDataContractSerializer();

            ser.WriteObject(writer, p1);
            writer.Close();
        }
Exemplo n.º 25
0
        //</snippet14>

        public void CannotSerialize()
        {
            //<snippet15>
            FileStream fs        = new FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite);
            XElement   myElement = new XElement("Parent", new XElement("child1", "form"),
                                                new XElement("child2", "base"),
                                                new XElement("child3", "formbase")
                                                );
            NetDataContractSerializer dcs = new NetDataContractSerializer();

            dcs.WriteObject(fs, myElement);
            //</snippet15>
        }
Exemplo n.º 26
0
        //Сохранение состояния библиотеки в файл
        public void Serialize(String FileName)
        {
            var serializer        = new NetDataContractSerializer();
            var xmlWriterSettings = new XmlWriterSettings {
                Indent = true
            };

            using (var xmlWriter =
                       XmlWriter.Create(FileName, xmlWriterSettings))
            {
                serializer.WriteObject(xmlWriter, this);
            }
        }
Exemplo n.º 27
0
 public static string SerializeWithNetDcs(object obj)
 {
     using (var ms = new MemoryStream())
     {
         using (var sr = new StreamReader(ms, Encoding.UTF8))
         {
             var serializer = new NetDataContractSerializer();
             serializer.WriteObject(ms, obj);
             ms.Position = 0;
             return(sr.ReadToEnd());
         }
     }
 }
Exemplo n.º 28
0
        public static void Serialize(LambdaExpression expression, Object paramValue)
        {
            // Serialize Expression
            var serializedExpression = new ExpressionSerializer(new TypeResolver(assemblies)).Serialize(expression);

            File.WriteAllText(expressionfile, serializedExpression.ToString());

            // Serialize Parameter
            using (fs = new FileStream(paramfile, FileMode.Create, FileAccess.ReadWrite))
            {
                paramSerializer.WriteObject(fs, paramValue);
            }
        }
 public static byte[] SerializeXmlBinary(object obj)
 {
     using (var ms = new MemoryStream())
     {
         using (var wtr = XmlDictionaryWriter.CreateBinaryWriter(ms))
         {
             var serializer = new NetDataContractSerializer();
             serializer.WriteObject(wtr, obj);
             ms.Flush();
         }
         return(ms.ToArray());
     }
 }
Exemplo n.º 30
0
        public void Update(T dto)
        {
            if (!scope.IsRegistered <IDtoPortalHandleUpdate <T> >())
            {
                throw new DtoPortalDalNotRegisteredException();
            }

            var dal = scope.Resolve <IDtoPortalHandleUpdate <T> >();

            // Update a serialized object
            // Simulate going to the application server
            NetDataContractSerializer serializer = new NetDataContractSerializer();

            // Client to server
            MemoryStream ms = new MemoryStream();

            serializer.WriteObject(ms, dto);

            ms.Seek(0, 0);

            var newDto = (T)serializer.ReadObject(ms);

            dal.Update(newDto);

            // Server to client
            ms = new MemoryStream();

            serializer.WriteObject(ms, newDto);

            ms.Seek(0, 0);

            // Context get's send to DtoBase.OnDeserialized
            // So that as each Dto is deserialized we send it
            // to the BO that created the corresponding BO
            serializer.Context = new StreamingContext(StreamingContextStates.CrossMachine, updateManager);

            var returnDto = (T)serializer.ReadObject(ms);
        }