本文整理汇总了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;
}
}
}
}
}
示例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);
}
}
示例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);
}
示例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.");
}
}
示例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);
}
}
示例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");
}
}
示例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;
}
示例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);
}
}
}
示例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 = "";
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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;
}
}
}
示例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();
}
}
示例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();
}
}