コード例 #1
0
        public Project Open(FileInfo path)
        {
            Project    project = null;
            FileStream reader  = null;

            try
            {
                reader = new FileStream(path.FullName, FileMode.Open, FileAccess.Read);

                var serializer = new DataContractSerializer(typeof(Project));

                project = serializer.ReadObject(reader) as Project;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }

            return(project);
        }
コード例 #2
0
        /// <summary>
        /// Creates the configuration object from the configuration section.
        /// </summary>
        /// <param name="parent">The parent object.</param>
        /// <param name="configContext">The configuration context object.</param>
        /// <param name="section">The section as XML node.</param>
        /// <returns>The created section handler object.</returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            if (section == null)
            {
                throw new ArgumentNullException("section");
            }

            XmlNode element = section.FirstChild;

            while (element != null && !typeof(XmlElement).IsInstanceOfType(element))
            {
                element = element.NextSibling;
            }

            XmlNodeReader reader = new XmlNodeReader(element);

            try {
                DataContractSerializer serializer    = new DataContractSerializer(typeof(ConfigurationLocation));
                ConfigurationLocation  configuration = serializer.ReadObject(reader) as ConfigurationLocation;
                return(configuration);
            } finally {
                reader.Close();
            }
        }
コード例 #3
0
        /// <summary>
        /// Reads the transport report.
        /// </summary>
        /// <param name="transportReportFileName">Name of the transport report file.</param>
        /// <returns>The Transport Report</returns>
        public TransportReport ReadTransportReport(string transportReportFileName)
        {
            if (File.Exists(transportReportFileName))
            {
                try
                {
                    XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas();
                    XRQ.MaxStringContentLength = int.MaxValue;

                    using (FileStream fs = new FileStream(transportReportFileName, FileMode.Open))
                        using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ))
                        {
                            DataContractSerializer ser = new DataContractSerializer(typeof(TransportReport));
                            TransportReport        tr  = (TransportReport)ser.ReadObject(reader, true);
                            return(tr);
                        }
                }
                catch (SerializationException)
                {
                    throw;
                }
            }
            return(null);
        }
コード例 #4
0
        public void ModelBaseCollection_SerializationTest1()
        {
            var people = new SimplePersonCollection();

            people.FirstName = "Tom";
            people.LastName  = "Jones";

            people.Add(new SimplePerson());
            people.Add(new SimplePerson());
            people.Add(new SimplePerson());

            var stream     = new MemoryStream();
            var serializer = new DataContractSerializer(typeof(SimplePersonCollection));

            serializer.WriteObject(stream, people);
            stream.Position = 0;
            var newPeople = (SimplePersonCollection)serializer.ReadObject(stream);

            //Property serialization isn't supported by the data contract serializer
            //Assert.AreEqual(people.FirstName, newPeople.FirstName);
            //Assert.AreEqual(people.LastName, newPeople.LastName);
            //Assert.AreEqual(people.FullName, newPeople.FullName);
            Assert.AreEqual(people.Count, newPeople.Count);
        }
コード例 #5
0
        //反序列化XML文件
        public static async Task <T> ReadAsync <T>(string filename)
        {
            //获取实体类类型实例化一个对象
            T sessionState_ = default(T);
            IStorageFolder applicationFolder = await GetDataFolder();

            StorageFile file = await applicationFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

            if (file == null)
            {
                return(sessionState_);
            }
            try
            {
                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    sessionState_ = (T)serializer.ReadObject(inStream.AsStreamForRead());
                }
            }
            catch (Exception)
            { }
            return(sessionState_);
        }
コード例 #6
0
        public void TradeXml()
        {
            var obj = TradeGenerator.NewSwap();

            var serializer = new DataContractSerializer(obj.GetType());
            var settings   = new XmlWriterSettings();

            settings.Encoding = new System.Text.UTF8Encoding(false);

            var sw = new StringWriter();

            using (var xw = XmlWriter.Create(sw))
            {
                serializer.WriteObject(xw, obj);
            }

            Console.WriteLine(sw.ToString());

            var rw    = XmlReader.Create(new StringReader(sw.ToString()));
            var trade = (Trade)serializer.ReadObject(rw);

            Assert.AreEqual(obj.Legs[0].Cashflows[0].PaymentDate, trade.Legs[0].Cashflows[0].PaymentDate);
            Assert.AreEqual(obj.Legs[1].Cashflows[1].StartDate, trade.Legs[1].Cashflows[1].StartDate);
        }
コード例 #7
0
        /// <summary>
        /// Desirializes the given type.
        /// </summary>
        /// <param name="serializedObject">The serialized object. A <see cref="T:System.Byte[]"/> Object.</param>
        /// <returns>A <see cref="T:T"/> Object.</returns>
        //[System.Diagnostics.DebuggerStepThrough]
        public static T DataContractBinaryDeSerialize <T>(byte[] serializedObject)
        {
            #region Access Log
#if TRACE
            {
                Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
            }
#endif
            #endregion Access Log
            try
            {
                MemoryStream ms = new MemoryStream(serializedObject);
                ms.Write(serializedObject, 0, serializedObject.Length);
                ms.Seek(0, 0);
                DataContractSerializer ser = new DataContractSerializer(typeof(T));
                Object obj = ser.ReadObject(ms);
                ms.Close();
                return((T)obj);
            }
            catch (Exception ex)
            {
                MemoryStream ms = new MemoryStream();
                ms.Write(serializedObject, 0, serializedObject.Length);
                ms.Seek(0, 0);
                BinaryFormatter b   = new BinaryFormatter();
                Object          obj = b.Deserialize(ms);
                ms.Close();
                CacheException cex = (CacheException)obj;
                if (cex != null)
                {
                    // TODO: Shared Cache Exception
                    Handler.LogHandler.Error(cex.StackTrace, ex);
                }
                return((T)obj);
            }
        }
コード例 #8
0
        /// <summary>
        /// Reads the UA endpoint information associated the CLSID
        /// </summary>
        /// <param name="clsid">The CLSID used to activate the COM server.</param>
        /// <returns>The endpoint.</returns>
        private static ConfiguredEndpoint LoadConfiguredEndpointFromFile(Guid clsid)
        {
            try {
                string relativePath = Utils.Format("{0}\\{1}.xml", ComPseudoServersDirectory, clsid);
                string absolutePath = Utils.GetAbsoluteFilePath(relativePath, false, false, false);

                // oops - nothing found.
                if (absolutePath == null)
                {
                    return(null);
                }

                // open the file.
                FileStream istrm = File.Open(absolutePath, FileMode.Open, FileAccess.Read);

                using (XmlTextReader reader = new XmlTextReader(istrm)) {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(ConfiguredEndpoint));
                    return((ConfiguredEndpoint)serializer.ReadObject(reader, false));
                }
            } catch (Exception e) {
                Utils.Trace(e, "Unexpected error loading endpoint configuration for COM Proxy with CLSID={0}.", clsid);
                return(null);
            }
        }
コード例 #9
0
        /// <summary>
        /// Загрузка информации об записях из файла
        /// </summary>
        public List <NotebookItem> LoadNotebookItems()
        {
            try
            {
                if (!File.Exists(notebookItemsFilePath))
                {
                    return(new List <NotebookItem>());
                }

                DataContractSerializer dcs = new DataContractSerializer(typeof(List <NotebookItem>));
                using (FileStream fs = new FileStream(notebookItemsFilePath, FileMode.Open))
                {
                    using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()))
                    {
                        return((List <NotebookItem>)dcs.ReadObject(reader));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Не удалось считать данные из файла: {e.Message}");
                return(new List <NotebookItem>());
            }
        }
コード例 #10
0
 public static string LoadDataContractFromXml(out T obj, string FilePath)
 {
     try
     {
         // Serialization
         var s = new DataContractSerializer(typeof(T));
         using (var w = File.OpenRead(FilePath))
         {
             obj = (T)s.ReadObject(w);
         }
     }
     catch (Exception ex)
     {
         obj = default(T);
         var msg = ex.Message;
         if (ex.InnerException != null)
         {
             msg += " [" + ex.InnerException.Message + "]";
         }
         return(msg);
         //return ex.ToString();
     }
     return(null);
 }
コード例 #11
0
        public void XmlSerialization()
        {
            var    serializer = new DataContractSerializer(typeof(Rule));
            string text;

            using (var writer = new StringWriter())
            {
                Rule rule = Rule.Create("Customer.LastName", mreOperator.Equal, "Doe")
                            & (Rule.Create("Customer.FirstName", mreOperator.Equal, "John")
                               | Rule.Create("Customer.FirstName", mreOperator.Equal, "Jane"));

                using (var xw = XmlWriter.Create(writer))
                    serializer.WriteObject(xw, rule);
                text = writer.ToString();
            }

            Rule newRule; // add breakpoint here, to view XML in text.

            using (var reader = new StringReader(text))
                using (var xr = XmlReader.Create(reader))
                {
                    newRule = (Rule)serializer.ReadObject(xr);
                }

            var order = ExampleUsage.GetOrder();

            MRE  engine   = new MRE();
            var  fakeName = engine.CompileRule <Order>(newRule);
            bool passes   = fakeName(order);

            Assert.IsTrue(passes);

            order.Customer.FirstName = "Philip";
            passes = fakeName(order);
            Assert.IsFalse(passes);
        }
コード例 #12
0
        private IDocumentContract DeserializeDocument(MemoryStream stream, DocumentContractType documentContractType)
        {
            DataContractSerializer serializer = null;

            switch (documentContractType)
            {
            case DocumentContractType.Metafile:
                serializer = new DataContractSerializer(typeof(MetafileDocumentContract));
                break;

            case DocumentContractType.Pdf:
                serializer = new DataContractSerializer(typeof(PdfDocumentContract));
                break;

            case DocumentContractType.Zebra:
                serializer = new DataContractSerializer(typeof(ZebraDocumentContract));
                break;

            default:
                throw new ArgumentException("Unsupported value", nameof(documentContractType));
            }

            return((IDocumentContract)serializer.ReadObject(stream));
        }
コード例 #13
0
        public void DerivedDerivedSerializationEvents_DataContractSerializer()
        {
            string xml =
                @"<DerivedDerivedSerializationEventOrderTestObject xmlns=""http://schemas.datacontract.org/2004/07/Newtonsoft.Json.Tests.Serialization"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""/>";

            DataContractSerializer ss = new DataContractSerializer(
                typeof(DerivedDerivedSerializationEventOrderTestObject)
                );

            DerivedDerivedSerializationEventOrderTestObject c =
                (DerivedDerivedSerializationEventOrderTestObject)ss.ReadObject(
                    new MemoryStream(Encoding.UTF8.GetBytes(xml))
                    );

            MemoryStream ms = new MemoryStream();

            ss.WriteObject(ms, c);

            IList <string> e = c.GetEvents();

            StringAssert.AreEqual(
                @"OnDeserializing
OnDeserializing_Derived
OnDeserializing_Derived_Derived
OnDeserialized
OnDeserialized_Derived
OnDeserialized_Derived_Derived
OnSerializing
OnSerializing_Derived
OnSerializing_Derived_Derived
OnSerialized
OnSerialized_Derived
OnSerialized_Derived_Derived",
                string.Join(Environment.NewLine, e.ToArray())
                );
        }
コード例 #14
0
        static async private Task <T> RestoreAsync <T>(string filename)

        {
            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);

            if (sessionFile == null)
            {
                return(default(T));
            }
            IInputStream sessionInputStream = await sessionFile.OpenReadAsync();

            //Using DataContractSerializer , look at the cat-class
            var sessionSerializer = new DataContractSerializer(typeof(T),
                                                               new DataContractSerializerSettings
            {
            });
            var data = (T)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead());

            //Using XmlSerializer , look at the Dog-class
            //var serializer = new XmlSerializer(typeof(List<object>), new Type[] { typeof(T) });
            //_data = (List<object>)serializer.Deserialize(sessionInputStream.AsStreamForRead());
            sessionInputStream.Dispose();
            return(data);
        }
コード例 #15
0
ファイル: Vector4DTest.cs プロジェクト: terrynoya/DigitalRune
        public void SerializationXml2()
        {
            Vector4D v1 = new Vector4D(0.1, -0.2, 2, 40);
            Vector4D v2;

            string fileName = "SerializationVector4D_DataContractSerializer.xml";

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            var serializer = new DataContractSerializer(typeof(Vector4D));

            using (var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write))
                using (var writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
                    serializer.WriteObject(writer, v1);

            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                    v2 = (Vector4D)serializer.ReadObject(reader);

            Assert.AreEqual(v1, v2);
        }
コード例 #16
0
        public void SerializationXml2()
        {
            Matrix22D m1 = new Matrix22D(12, 23, 45, 67);
            Matrix22D m2;

            string fileName = "SerializationMatrix22D_DataContractSerializer.xml";

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            var serializer = new DataContractSerializer(typeof(Matrix22D));

            using (var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write))
                using (var writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
                    serializer.WriteObject(writer, m1);

            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                    m2 = (Matrix22D)serializer.ReadObject(reader);

            Assert.AreEqual(m1, m2);
        }
コード例 #17
0
        private static State LoadState(string path)
        {
            State state = new State();

            try {
                using (var fs = new FileStream(Settings.persistenSavePath, FileMode.Open, FileAccess.Read)) {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(State));
                    state = (State)serializer.ReadObject(fs);
                }
                foreach (var e in state.futureEvents)
                {
                    if (e.Value.processed == null)
                    {
                        e.Value.processed = new ManualResetEvent(false);
                    }
                }
                Logger.log(7, Category.StateEngine, Severity.Info, string.Format("State {0} loaded", path));
                return(state);
            }
            catch (Exception e) {
                Logger.log(8, Category.StateEngine, Severity.Error, "Failed to load state: " + e.Message);
                return(new State());
            }
        }
コード例 #18
0
ファイル: IO.cs プロジェクト: p-org/TraceViewer
        /// <summary>
        /// Returns the specified trace.
        /// </summary>
        /// <returns>MachineActionTrace</returns>
        internal static BugTrace LoadTrace()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Sets filter for file extension and default file extension.
            openFileDialog.DefaultExt = ".pstrace";
            openFileDialog.Filter     = "P# Trace Files|*.pstrace";

            // Displays OpenFileDialog by calling the ShowDialog method.
            bool?result = openFileDialog.ShowDialog();

            BugTrace trace = null;

            if (result == true)
            {
                string fileName = openFileDialog.FileName;
                if (fileName != null)
                {
                    using (Stream stream = File.Open(fileName, FileMode.Open))
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(BugTrace));
                        try
                        {
                            trace = (BugTrace)serializer.ReadObject(stream);
                        }
                        catch
                        {
                            MessageBox.Show($"Bug trace '{fileName}' is not readable." +
                                            "Please make sure you selected a '.pstrace' file.");
                        }
                    }
                }
            }

            return(trace);
        }
コード例 #19
0
        private async void ReadEmployees(object o, RoutedEventArgs e)
        {
            try
            {
                // find a file
                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                Stream        stream        = await storageFolder.OpenStreamForReadAsync("employees.dat");

                // is it empty
                if (stream == null)
                {
                    employees = new List <Employee>();
                }

                // read data
                DataContractSerializer serializer = new DataContractSerializer(typeof(List <Employee>));
                employees = (List <Employee>)serializer.ReadObject(stream);
                ShowEmployees();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Following exception has happend (reading): " + ex.ToString());
            }
        }
コード例 #20
0
        private static FileGenerationConfiguration GetFromPath(string filePath)
        {
            FileGenerationConfiguration result = null;

            if (File.Exists(filePath))
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(FileGenerationConfiguration));

                using (Mutex mutex = new Mutex(false, FileOperations.GetMutexName(filePath)))
                {
                    try
                    {
                        mutex.WaitOne();

                        using (var sr = File.OpenRead(filePath))
                        {
                            result = ser.ReadObject(sr) as FileGenerationConfiguration;
                        }
                    }
                    catch (Exception ex)
                    {
                        DTEHelper.WriteExceptionToOutput(null, ex);

                        FileOperations.CreateBackUpFile(filePath, ex);

                        result = null;
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }

            return(result);
        }
コード例 #21
0
        /// <summary>
        /// The load cached image info.
        /// </summary>
        public static void LoadCachedImageInfo()
        {
            var storageFile = IsolatedStorageFile.GetUserStoreForApplication();

            if (!storageFile.FileExists(imageCacheFile))
            {
                imageCacheDictionary = new Dictionary <string, ImageCacheItem>();
                return;
            }

            bool success = false;

            using (var fileStream = storageFile.OpenFile(imageCacheFile, FileMode.Open))
            {
                var serializer = new DataContractSerializer(typeof(Dictionary <string, ImageCacheItem>));

                try
                {
                    imageCacheDictionary = (Dictionary <string, ImageCacheItem>)serializer.ReadObject(fileStream);
                    success = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to read image cache file. " + ex);
                }
            }

            if (success)
            {
                return;
            }

            /* An error occured, so delete the existing cached item. */
            storageFile.DeleteFile(imageCacheFile);
            imageCacheDictionary = new Dictionary <string, ImageCacheItem>();
        }
コード例 #22
0
 static void Main()
 {
     try
     {
         Console.WriteLine("Testing serialization");
         DataContractSerializer formatter = new DataContractSerializer(typeof(Junk));
         MemoryStream           stream    = new MemoryStream();
         Junk junk = new Junk();
         junk.Name  = "Junk";
         junk.Value = 15;
         formatter.WriteObject(stream, junk);
         Console.WriteLine("Wrote object to stream");
         stream.Seek(0, SeekOrigin.Begin);
         Junk savedJunk = formatter.ReadObject(stream) as Junk;
         Console.WriteLine("Deserialized name = {0}", savedJunk.Name);
         Console.WriteLine("Deserialized value = {0}", savedJunk.Value);
         Console.WriteLine("Testing complete");
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         Console.WriteLine(ex.StackTrace);
     }
 }
コード例 #23
0
ファイル: XmlSerializer.cs プロジェクト: jiangsq123/YAFNET
        private static object Deserialize(string xml, Type type, XmlDictionaryReaderQuotas quotas)
        {
            try
            {
#if WINDOWS_PHONE
                using (var reader = XmlDictionaryReader.Create(xml))
                {
                    var serializer = new DataContractSerializer(type);
                    return(serializer.ReadObject(reader));
                }
#else
                var bytes = Encoding.UTF8.GetBytes(xml);
                using (var reader = XmlDictionaryReader.CreateTextReader(bytes, quotas))
                {
                    var serializer = new DataContractSerializer(type);
                    return(serializer.ReadObject(reader));
                }
#endif
            }
            catch (Exception ex)
            {
                throw new SerializationException("DeserializeDataContract: Error converting type: " + ex.Message, ex);
            }
        }
コード例 #24
0
ファイル: DeepCopyHelper.cs プロジェクト: ziichuan/KelpNet
        public static CopyType DeepCopy <CopyType>(CopyType target)
        {
            CopyType result;

            using (MemoryStream mem = new MemoryStream())
            {
                DataContractSerializer bf = new DataContractSerializer(typeof(Function <T>), new DataContractSerializerSettings {
                    KnownTypes = ModelIO <T> .KnownTypes, PreserveObjectReferences = true
                });

                try
                {
                    bf.WriteObject(mem, target);
                    mem.Position = 0;
                    result       = (CopyType)bf.ReadObject(mem);
                }
                finally
                {
                    mem.Close();
                }
            }

            return(result);
        }
コード例 #25
0
        private async Task RestoreAsync()
        {
            _settings = new Dictionary <String, Object>();

            try
            {
                // Get the input stream for the SessionState file
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(_fileName);

                using (IInputStream inStream = await file.OpenSequentialReadAsync())
                {
                    // Deserialize the Session State
                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes);
                    _settings = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead());
                }
            }
            catch (FileNotFoundException)
            {
                // If there is no modern settings file, this is probably their first application run
                // and we may need to migrate their old settings.
                if (_fileName == CriticalSettingsManager.Current._fileName)
                {
                    // We just wrote directly into the settings object, so we need to manually
                    // queue a save operation. That can happen later though, it does not need
                    // to be synchronous.
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(async() =>
                    {
                        await Save();
                    });
                }
            }
            catch
            {
                // Do nothing, just start again with empty settings object.
            }
        }
コード例 #26
0
        public static async System.Threading.Tasks.Task <List <ShowInfo> > LoadData(string filename)
        {
            try
            {
                if (ApplicationData.Current.LocalFolder.TryGetItemAsync(filename) != null)
                {
                    StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);

                    using (IInputStream inStream = await file.OpenSequentialReadAsync())
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(string));
                        var json = (string)serializer.ReadObject(inStream.AsStreamForRead());
                        var data = JsonConvert.DeserializeObject <List <ShowInfo> >(json);
                        return(data);
                    }
                }
                else
                {
                    return(new List <ShowInfo>());
                }

                //var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
                //using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
                //{
                //    string text = dataReader.ReadString(buffer.Length);
                //}
            }
            catch (FileNotFoundException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #27
0
        public void DataContractSerializerDuplicateNameEnumTest()
        {
            MemoryStream ms = new MemoryStream();
            var          s  = new DataContractSerializer(typeof(DuplicateEnumNameTestClass));

            ExceptionAssert.Throws <InvalidDataContractException>(() =>
            {
                s.WriteObject(ms, new DuplicateEnumNameTestClass
                {
                    Value  = DuplicateNameEnum.foo_bar,
                    Value2 = DuplicateNameEnum2.foo_bar_NOT_USED
                });

                string xml = @"<DuplicateEnumNameTestClass xmlns=""http://schemas.datacontract.org/2004/07/Newtonsoft.Json.Tests.Converters"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
    <Value>foo_bar</Value>
    <Value2>foo_bar</Value2>
</DuplicateEnumNameTestClass>";

                var o = (DuplicateEnumNameTestClass)s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

                Assert.AreEqual(DuplicateNameEnum.foo_bar, o.Value);
                Assert.AreEqual(DuplicateNameEnum2.FooBar, o.Value2);
            }, "Type 'Newtonsoft.Json.Tests.Converters.DuplicateNameEnum' contains two members 'foo_bar' 'and 'FooBar' with the same name 'foo_bar'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using EnumMemberAttribute attribute.");
        }
コード例 #28
0
        public void SerializationXml2()
        {
            QuaternionD q1 = new QuaternionD(0.1, -0.2, 6, 40);
            QuaternionD q2;

            string fileName = "SerializationQuaternionD_DataContractSerializer.xml";

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            var serializer = new DataContractSerializer(typeof(QuaternionD));

            using (var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write))
                using (var writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
                    serializer.WriteObject(writer, q1);

            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
                    q2 = (QuaternionD)serializer.ReadObject(reader);

            Assert.AreEqual(q1, q2);
        }
コード例 #29
0
        internal static void Load()
        {
            if (!File.Exists(keyfile))
            {
                return;
            }

            try
            {
                DataContractSerializer reader =
                    new DataContractSerializer(typeof(AuthKeys),
                                               new Type[] { typeof(AuthKey) });

                using (var fs = new FileStream(keyfile, FileMode.Open))
                    using (var sr = new CryptoStream(fs, Rij.algorithm.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        Keys = (AuthKeys)reader.ReadObject(sr);
                    }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
コード例 #30
0
ファイル: Bug36100.cs プロジェクト: Profit0004/mono
		public void SerializerDynamicInvoke ()
		{
			var a = new DingusSyncData ();
			a.Aircraft = new AircraftDTO[] { new AircraftDTO () { } };
			a.AircraftTypes = new AircraftTypeDTO[] { new AircraftTypeDTO () };
			a.Airlines= new AirlineDTO[] { new AirlineDTO () };
			a.Airports= new AirportDTO[] { new AirportDTO() };
			a.Approaches= new ApproachDTO[] { new ApproachDTO() };
			a.ApproachesLegs= new ApproachesLegDTO[] { new ApproachesLegDTO() };
			a.Binaries= new BinaryCatalogDTO[] { new BinaryCatalogDTO() };
			a.Crews= new CrewDTO[] { new CrewDTO() };
			a.Days= new DayDTO[] { new DayDTO() };
			a.EmploymentEvents= new EmploymentEventDTO[] { new EmploymentEventDTO() };
			a.Events= new EventDTO[] { new EventDTO() };
			a.FlightDataInspection = new DataInspection ();
			a.GlobalSettings= new GlobalSettingDTO[] { new GlobalSettingDTO() };
			a.Hotels= new HotelDTO[] { new HotelDTO() };
			a.Legs= new LegDTO[] { new LegDTO() };
			a.Notes= new NoteDTO[] { new NoteDTO() };
			a.PayperiodEvents= new PayperiodEventDTO[] { new PayperiodEventDTO() };
			a.PayrollCategories= new PayrollCategoryDTO[] { new PayrollCategoryDTO() };
			a.Payrolls= new PayrollDTO[] { new PayrollDTO() };
			a.Performances= new PerformanceDTO[] { new PerformanceDTO() };
			a.Positions= new PositionDTO[] { new PositionDTO() };
			a.ReglatoryOperationTypes= new ReglatoryOperationTypeDTO[] { new ReglatoryOperationTypeDTO() };
			a.Trips= new TripDTO[] { new TripDTO() };
			a.UserSettings= new UserSettingDTO[] { new UserSettingDTO() };

			Console.WriteLine ("Size is: {0}", global::System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)));
			using (var ms = new MemoryStream ()) {
				DataContractSerializer serializer = new DataContractSerializer (typeof(DingusSyncData));
				serializer.WriteObject (ms, a);
				ms.Position = 0;
				var b = serializer.ReadObject (ms);
			}
		}
コード例 #31
0
        static void Main(string[] args)
        {
            var input = new TestDto {
                Name = " with leading whitespace"
            };

            byte[] data;
            {
                var seralizer = new DataContractSerializer(typeof(TestDto));
                using (var mem = new MemoryStream())
                {
                    seralizer.WriteObject(mem, input);
                    data = mem.ToArray();
                }
            }
            {
                var seralizer = new DataContractSerializer(typeof(TestDto));
                using (var mem = new MemoryStream(data))
                {
                    var output = (TestDto)seralizer.ReadObject(mem);
                    Console.WriteLine(">{0}<", output.Name);
                }
            }
        }
コード例 #32
0
ファイル: MainViewModel.cs プロジェクト: ogazitt/zaplify
        public About GetAboutData()
        {
            // trace getting data
            TraceHelper.AddMessage("Get About Data");

            // get a stream to the about XML file
            Stream stream = AppResourcesHelper.GetResourceStream("About.xml");

            // deserialize the file
            DataContractSerializer dc = new DataContractSerializer(typeof(About));
            return (About) dc.ReadObject(stream);
        }
コード例 #33
0
        /// <summary>
        ///     Restores previously saved <see cref="SessionState" />.  Any <see cref="Frame" /> instances
        ///     registered with <see cref="RegisterFrame" /> will also restore their prior navigation
        ///     state, which in turn gives their active <see cref="Page" /> an opportunity restore its
        ///     state.
        /// </summary>
        /// <param name="sessionBaseKey">
        ///     An optional key that identifies the type of session.
        ///     This can be used to distinguish between multiple application launch scenarios.
        /// </param>
        /// <returns>
        ///     An asynchronous task that reflects when session state has been read.  The
        ///     content of <see cref="SessionState" /> should not be relied upon until this task
        ///     completes.
        /// </returns>
        public static async Task RestoreAsync(string sessionBaseKey = null)
        {
            _sessionState = new Dictionary<string, object>();

            try
            {
                // Get the input stream for the SessionState file
                var file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
                using (var inStream = await file.OpenSequentialReadAsync())
                {
                    // Deserialize the Session State
                    var serializer = new DataContractSerializer(typeof (Dictionary<string, object>), _knownTypes);
                    _sessionState = (Dictionary<string, object>) serializer.ReadObject(inStream.AsStreamForRead());
                }

                // Restore any registered frames to their saved state
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame) &&
                        (string) frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey)
                    {
                        frame.ClearValue(FrameSessionStateProperty);
                        RestoreFrameNavigationState(frame);
                    }
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
コード例 #34
0
ファイル: SerializeTest.cs プロジェクト: chrishaly/RpcLite
        private static void Test2()
        {
            #if NETCORE

            //ProtoBufTest.Test();
            {
                object exobj = null;
                try
                {
                    var b = 3;
                    b = 0;
                    var c = 2 / b;
                }
                catch (Exception exs)
                {
                    exobj = exs;
                }
                //var ex = new Exception("test ex");
                var ex = exobj;
                //var ex = new ServiceTest.Contract.Product
                //{
                //	Id = 223,
                //	Name = "abc book",
                //	Category = "Book",
                //	ListDate = DateTime.Now,
                //	Price = 34,
                //	Tags = new List<string>
                //	{
                //		"book",
                //		"tech",
                //		"new"
                //	}
                //};

                {
                    try
                    {
                        var setting = new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                            ContractResolver = new SerializeContractResolver()
                        };
                        var json = JsonConvert.SerializeObject(ex, setting);
                        Console.WriteLine(json);
                        var dex = JsonConvert.DeserializeObject(json, ex.GetType(), setting);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                var dcs = new DataContractSerializer(ex.GetType());
                var ms = new MemoryStream();
                dcs.WriteObject(ms, ex);

                ms.Position = 0;
                var dex3 = dcs.ReadObject(ms);
                var xml = Encoding.UTF8.GetString(ms.ToArray());

                var jss = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ex.GetType());
                var jsms = new MemoryStream();
                jss.WriteObject(jsms, ex);

                ms.Position = 0;
                var dexjs = dcs.ReadObject(ms);
                var jsss = Encoding.UTF8.GetString(ms.ToArray());

                var product = new ServiceTest.Contract.Product
                {
                    Id = 223,
                    Name = "abc book",
                    Category = "Book",
                    ListDate = DateTime.Now,
                    Price = 34,
                    Tags = new List<string>
                    {
                        "book",
                        "tech",
                        "new"
                    }
                };
                var xmlSeriaizer = new System.Xml.Serialization.XmlSerializer(product.GetType());
                var stringWriter = new StringWriter();
                //var xmlWriter = new XmlWriter();
                xmlSeriaizer.Serialize(stringWriter, (object)product);
            }
            #endif
        }
コード例 #35
-1
        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
        {
            string xmlContent = jsonReader.ReadElementContentAsString();

            DataContractSerializer dataContractSerializer = new DataContractSerializer(TraditionalDataContract.UnderlyingType,
                GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences

            MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent));
            object xmlValue;
            XmlDictionaryReaderQuotas quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas;
            if (quotas == null)
            {
                xmlValue = dataContractSerializer.ReadObject(memoryStream);
            }
            else
            {
                xmlValue = dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(memoryStream, quotas));
            }
            if (context != null)
            {
                context.AddNewObject(xmlValue);
            }
            return xmlValue;
        }