当前位置: 首页>>代码示例>>C#>>正文


C# Serialization.DataContractSerializer类代码示例

本文整理汇总了C#中System.Runtime.Serialization.DataContractSerializer的典型用法代码示例。如果您正苦于以下问题:C# DataContractSerializer类的具体用法?C# DataContractSerializer怎么用?C# DataContractSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DataContractSerializer类属于System.Runtime.Serialization命名空间,在下文中一共展示了DataContractSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Translate

        public string Translate(string text, string from, string to)
        {
            using (var client = new HttpClient())
            {
                var url = string.Format(
                        _translatorApiUrlFormat,
                        HttpUtility.UrlEncode(text),
                        HttpUtility.UrlEncode(from),
                        HttpUtility.UrlEncode(to));

                using (var message = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());

                    using (var result = client.SendAsync(message).Result)
                    {
                        if (!result.IsSuccessStatusCode)
                        {
                            throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
                        }

                        using (var responseStream = result.Content.ReadAsStreamAsync().Result)
                        {
                            var serializer = new DataContractSerializer(typeof(string));

                            return serializer.ReadObject(responseStream) as string;
                        }
                    }
                }
            }
        }
开发者ID:rhysgodfrey,项目名称:Trosi,代码行数:31,代码来源:Translator.cs

示例2: SaveAsync

        /// <summary>
        /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
        /// registered with <see cref="RegisterFrame"/> will also preserve their current
        /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
        /// to save its state.
        /// </summary>
        /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // Save the navigation state for all registered frames
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Serialize the session state synchronously to avoid asynchronous access to shared
                // state
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Get an output stream for the SessionState file and write the state asynchronously
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
开发者ID:TREEDWELLER,项目名称:qtree-samples,代码行数:40,代码来源:SuspensionManager.cs

示例3: PingAdversary

        public void PingAdversary(ProximityDevice device, NotifyNfcReady notify)
        {
            if (subscribeId != -1)
            {
                proximityDevice.StopSubscribingForMessage(subscribeId);
                subscribeId = -1;
            }

            if (publishId != -1)
            {
                proximityDevice.StopPublishingMessage(publishId);
                publishId = -1;
            }

            if (state == NfcManager.ProtoState.Busy)
            {
                return;
            }

            state = NfcManager.ProtoState.NotReady;
            notifyReady = notify;
            initialMessage.devicetime = random.NextDouble();
            MemoryStream stream = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(initialMessage.GetType());
            serializer.WriteObject(stream, initialMessage);
            stream.Position = 0;
            var dataWriter = new DataWriter();
            dataWriter.WriteBytes(stream.GetBuffer());
            proximityDevice = device;
            publishId = proximityDevice.PublishBinaryMessage("Windows.CarTrumps", dataWriter.DetachBuffer());
            subscribeId = proximityDevice.SubscribeForMessage("Windows.CarTrumps", OnMessageReceived);
        }
开发者ID:morefun0302,项目名称:car-trumps,代码行数:32,代码来源:NfcInitiationMessage.cs

示例4: deserializeInvoice_Click

        private void deserializeInvoice_Click(object sender, EventArgs e)
        {
            var serializer = new DataContractSerializer(typeof(Invoice));

            var reader = XmlReader.Create(new StringReader(objectData.Text));

            try
            {
                var invoice = (Invoice)serializer.ReadObject(reader);
                var msg = "== Invoice Customer:\nName: " + invoice.Customer.FirstName + " " + invoice.Customer.LastName + "\nBirth Date: " + invoice.Customer.BirthDate;

                msg += "\n\n== Products";

                for (int index = 0; index < invoice.Products.Count; index++)
                {
                    msg += "\n== == Product " + index;
                    msg += "\n== Name: " + invoice.Products[index].Name;
                    msg += "\n== Price: " + invoice.Products[index].Price;
                }

                MessageBox.Show(msg);
            }
            catch (Exception)
            {
                MessageBox.Show("Object couldn't be deserialized.\nCheck you input data.");
            }
        }
开发者ID:sergio-garcia,项目名称:flexserializer,代码行数:27,代码来源:Form1.cs

示例5: SaveAsync

        /// <summary>
        /// 現在の <see cref="SessionState"/> を保存します。
        /// <see cref="RegisterFrame"/> で登録された <see cref="Frame"/> インスタンスは、現在のナビゲーション スタックも保存します。
        /// これは、アクティブな <see cref="Page"/> に状態を保存する機会を
        /// 順番に提供します。
        /// </summary>
        /// <returns>セッション状態が保存されたときに反映される非同期タスクです。</returns>
        public static async Task SaveAsync()
        {
            try
            {
            // 登録されているすべてのフレームのナビゲーション状態を保存します
            foreach (var weakFrameReference in _registeredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }

            // セッション状態を同期的にシリアル化して、共有状態への非同期アクセスを
            // 状態
            MemoryStream sessionData = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, _sessionState);
            
                // SessionState ファイルの出力ストリームを取得し、状態を非同期的に書き込みます
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
开发者ID:runceel,项目名称:metroapps,代码行数:41,代码来源:SuspensionManager.cs

示例6: TestSerializeNullDateTimeOffsetNullable

		public void TestSerializeNullDateTimeOffsetNullable ()
		{
			 // Create the writer object.
			StringBuilder stringBuilder = new StringBuilder ();

			DateTimeOffset? dto = null;

			DataContractSerializer ser = new DataContractSerializer (typeof (DateTimeOffset?));

			using (var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StringWriter (stringBuilder))))
			{
				ser.WriteObject (xw, dto);
			}

			string actualXml   = stringBuilder.ToString ();
			string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DateTimeOffset i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/System\" />";
			
			Assert.AreEqual (expectedXml, actualXml, "#1 Null DateTimeOffset? serialization error");

			using (var xr = XmlDictionaryReader.CreateDictionaryReader (XmlReader.Create (new StringReader (actualXml))))
			{
				DateTimeOffset? actualDto = (DateTimeOffset?)ser.ReadObject (xr, true);

				Assert.AreEqual (dto, actualDto, "#2 Null DateTimeOffset? deserialization error");
				Assert.IsNull (actualDto, "#3 Null DateTimeOffset? deserialization error");
			}
		}
开发者ID:nlhepler,项目名称:mono,代码行数:27,代码来源:Bug3258Test.cs

示例7: Deserialize

        /// <summary>
        ///     Deserialize the given data to an output description
        /// </summary>
        public IOutputDescription Deserialize(string data)
        {
            IOutputDescription outputDescription = null;

            if (!string.IsNullOrWhiteSpace(data))
            {
                data = data.Replace("<![CDATA[", "");
                data = data.Replace("]]>", "");

                var dataContractSerializer = new DataContractSerializer(typeof (IOutputDescription), _knownTypes);

                using (var stringReader = new StringReader(StripKnownLegacyTags(data)))
                {
                    using (var xmlTextReader = new XmlTextReader(stringReader))
                    {
                        try
                        {
                            outputDescription = dataContractSerializer.ReadObject(xmlTextReader) as IOutputDescription;
                        }
                        catch (Exception ex)
                        {
                            Dev2Logger.Log.Error(ex);
                            // we want to return null                    
                        }
                    }
                }
            }

            return outputDescription;
        }
开发者ID:NatashaSchutte,项目名称:Warewolf-ESB,代码行数:33,代码来源:OutputDescriptionSerializationService.cs

示例8: receiveByID

        public object receiveByID(string MessageID, string InputQueue)
        {
            // Open existing queue
            using (MessageQueue queue = new MessageQueue(InputQueue))
            {
                //Peek to find message with the MessageID in the label
                while (true)
                {
                    Message[] peekedmessage = queue.GetAllMessages();
                    foreach (Message m in peekedmessage)
                    {
                        if (m.Label.StartsWith(MessageID))
                        {
                            using (Message message = queue.ReceiveById(m.Id))
                            {
                                RequestGuid = MessageID;
                                // Gets object type from the message label
                                Type objType = Type.GetType(message.Label.Split('|')[1], true, true);

                                // Derializes object from the stream
                                DataContractSerializer serializer = new DataContractSerializer(objType);
                                return serializer.ReadObject(message.BodyStream);
                            }
                        }
                    }
                    System.Threading.Thread.Sleep(10);
                }
            }
        }
开发者ID:NickABoen,项目名称:CIS526_TeamProjects,代码行数:29,代码来源:ObjectMessageQueue.cs

示例9: SaveKittenToStorage

        public async void SaveKittenToStorage()
        {
            // Get the current values of the object we want to save
            KittenObject ko = new KittenObject();
            ko.KittenName = _currentKittenName;
            ko.KittenAge = _currentKittenAge;
            ko.KittenImage = _currentKittenImg.OriginalString;

            // Add that object to our ObservableCollection
            if (KittenItems == null)
                KittenItems = new ObservableCollection<KittenObject>();
            KittenItems.Add(ko);

            // Create or the file we want to save
            StorageFile kittenFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("Kittens4Ever.kitten", CreationCollisionOption.ReplaceExisting);
            // Get the file stream
            var writeStream = await kittenFile.OpenStreamForWriteAsync();

            // Serialize our data to this file stream
            DataContractSerializer kittenSerial = new DataContractSerializer(typeof(ObservableCollection<KittenObject>));
            kittenSerial.WriteObject(writeStream, KittenItems);
            await writeStream.FlushAsync();
            writeStream.Close();

            // Reset the bound properties
            CurrentKittenAge = "0";
            CurrentKittenImg = new Uri("http://placekitten.com/205/205");
            CurrentKittenName = "";
        }
开发者ID:WindowsPhone-8-TrainingKit,项目名称:PRESENTATION-Fundamentals,代码行数:29,代码来源:MainViewModel.cs

示例10: SaveAsync

        /// <summary>
        /// Enregistre le <see cref="SessionState"/> actuel. Toutes les instances de <see cref="Frame"/>
        /// inscrites avec <see cref="RegisterFrame"/> conservent également leur
        /// pile de navigation actuelle, ce qui permet à leur <see cref="Page"/> active
        /// d'enregistrer son état.
        /// </summary>
        /// <returns>Tâche asynchrone qui reflète quand l'état de session a été enregistré.</returns>
        public static async Task SaveAsync()
        {
            try
            {
                // Enregistre l'état de navigation pour tous les frames inscrits
                foreach (var weakFrameReference in _registeredFrames)
                {
                    Frame frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Sérialise l'état de session de manière synchrone pour éviter un accès asynchrone à un
                // état
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Obtient un flux de sortie pour le fichier SessionState file et écrit l'état de manière asynchrone
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    await sessionData.CopyToAsync(fileStream);
                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SuspensionManagerException(e);
            }
        }
开发者ID:CasaTeam,项目名称:MetroExplorer,代码行数:41,代码来源:SuspensionManager.cs

示例11: LoadMemberList

        //Methods
        public MemberList LoadMemberList()
        {
            try
            {
                MemberList loaded = null;

                if (System.IO.File.Exists(this.fullFilePath))
                {
                    using (FileStream readFileStream = new FileStream(this.fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        DataContractSerializer deserializer = new DataContractSerializer(typeof(MemberList));
                        loaded = (MemberList)deserializer.ReadObject(readFileStream);
                    }

                    if (loaded != null)
                    {
                        //setup subscriptions
                        loaded.SetupSubscriptions();
                    }

                    return loaded;
                }
            }
            catch { }

            return null;
        }
开发者ID:of222au,项目名称:1DV607-Objektorienterad-analys-och-design-med-UML,代码行数:28,代码来源:Storage.cs

示例12: SaveAsync

        public async Task SaveAsync()
        {
            try
            {
                SaveFrameNavigationState(_frame);

                // Serialize the session state synchronously to avoid asynchronous access to shared state
                MemoryStream sessionData = new MemoryStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, Dictionary<string, object>>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Get an output stream for the SessionState file and write the state asynchronously
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Constants.SessionStateFileName, CreationCollisionOption.ReplaceExisting);
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    var provider = new DataProtectionProvider("LOCAL=user");

                    // Encrypt the session data and write it to disk.
                    await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);
                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SessionStateServiceException(e);
            }
        }
开发者ID:ryanhorath,项目名称:Rybird.Framework,代码行数:28,代码来源:SessionStateService.cs

示例13: Load

        public CompetitionClassModel Load()
        {
            using (XmlReader reader = XmlReader.Create(path, new XmlReaderSettings { CloseInput = true }))
            {
                var serializer = new DataContractSerializer(typeof (CompetitionClassModelXml));

                try
                {
                    var xmlObject = (CompetitionClassModelXml) serializer.ReadObject(reader);
                    return CompetitionClassModelXml.FromXmlObject(xmlObject);
                }
                catch (Exception ex)
                {
                    Log.Error("Failed to load model from XML file.", ex);
                    string message = $"Failed to load run configuration from file:\n\n{path}\n\n" +
                        $"Error message: {ex.Message}\n\nClick Ok to discard this file and use default settings.\n" +
                        "Click Cancel to close this application without making changes.";
                    DialogResult response = MessageBox.Show(message, "Error - Dog Agility Competition Management System",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
                    if (response == DialogResult.OK)
                    {
                        return new CompetitionClassModel();
                    }

                    Environment.Exit(0);
                    throw;
                }
            }
        }
开发者ID:bkoelman,项目名称:DogAgilityCompetitionManagement,代码行数:29,代码来源:ModelSerializer.cs

示例14: SaveAsync

        /// <summary>
        /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
        /// registered with <see cref="RegisterFrame"/> will also preserve their current
        /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
        /// to save its state.
        /// </summary>
        /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
        public static async Task SaveAsync()
        {
            // Save the navigation state for all registered frames
            foreach (var weakFrameReference in RegisteredFrames)
            {
                Frame frame;
                if (weakFrameReference.TryGetTarget(out frame))
                {
                    SaveFrameNavigationState(frame);
                }
            }

            var sessionData = new MemoryStream();
            var serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
            serializer.WriteObject(sessionData, sessionState);

            // Get an output stream for the SessionState file and write the state asynchronously
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(SessionStateFilename, CreationCollisionOption.ReplaceExisting);
            using (var fileStream = await file.OpenStreamForWriteAsync())
            {
                sessionData.Seek(0, SeekOrigin.Begin);
                await sessionData.CopyToAsync(fileStream);
                await fileStream.FlushAsync();
            }
        }
开发者ID:shiftkey,项目名称:better-win8-templates,代码行数:32,代码来源:SuspensionManager.cs

示例15: GetBenutzer

 private List<Benutzer> GetBenutzer()
 {
     HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri + "benutzer/");
     webrequest.Method = "GET";
     HttpWebResponse webresponse = null;
     try
     {
         webresponse = (HttpWebResponse)webrequest.GetResponse();
         HttpStatusCode rc = webresponse.StatusCode;
         DataContractSerializer serl = new DataContractSerializer(typeof(List<Benutzer>));
         return (List<Benutzer>)serl.ReadObject(webresponse.GetResponseStream());
     }
     catch (WebException we)
     {
         if (we.Response != null)
         {
             webresponse = (HttpWebResponse)we.Response;
             MessageBox.Show(webresponse.StatusDescription + "!", "Fehler");
         }
         else
         {
             MessageBox.Show("Server nicht erreichbar!", "Fehler");
         }
         return new List<Benutzer>();
     }
     finally
     {
         if (webresponse != null)
             webresponse.Close();
     }
 }
开发者ID:Golgoin,项目名称:ProjektarbeitVokabeltrainer,代码行数:31,代码来源:Start.xaml.cs


注:本文中的System.Runtime.Serialization.DataContractSerializer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。