本文整理汇总了C#中System.Runtime.Serialization.DataContractSerializer.WriteObject方法的典型用法代码示例。如果您正苦于以下问题:C# DataContractSerializer.WriteObject方法的具体用法?C# DataContractSerializer.WriteObject怎么用?C# DataContractSerializer.WriteObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Runtime.Serialization.DataContractSerializer
的用法示例。
在下文中一共展示了DataContractSerializer.WriteObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例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: Main
static void Main()
{
Record record1 = new Record(1, 2, "+", 3);
Console.WriteLine("Original record: {0}", record1.ToString());
MemoryStream stream1 = new MemoryStream();
//Serialize the Record object to a memory stream using DataContractSerializer.
System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(Record));
serializer.WriteObject(stream1, record1);
stream1.Position = 0;
//Deserialize the Record object back into a new record object
Record record2 = (Record)serializer.ReadObject(stream1);
Console.WriteLine("Deserialized record: {0}", record2.ToString());
MemoryStream stream2 = new MemoryStream();
XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2);
serializer.WriteObject(binaryDictionaryWriter, record1);
binaryDictionaryWriter.Flush();
//report the length of the streams
Console.WriteLine("Text Stream is {0} bytes long", stream1.Length);
Console.WriteLine("Binary Stream is {0} bytes long", stream2.Length);
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}
示例4: SerializerGeneration
public void SerializerGeneration()
{
var tester = new FirstCallTester(Console.Out);
tester.Start();
var msg = new Messages();
tester.Stop();
tester.Start();
CreateProto();
tester.Stop();
tester.Start();
CreateProto();
tester.Stop();
tester.Report();
var reportwatch = new Reportwatch();
reportwatch.Start("Protobuf");
var proto = ProtoBuf.Meta.TypeModel.Create();
proto.Add(typeof(UserInfo), true);
proto.CompileInPlace();
reportwatch.Stop("Protobuf");
reportwatch.Start("Protobuf serialize");
proto.Serialize(new MemoryStream(), CreateObj());
reportwatch.Stop("Protobuf serialize");
reportwatch.Start("Protobuf serialize 2");
proto.Serialize(new MemoryStream(), CreateObj());
reportwatch.Stop("Protobuf serialize 2");
reportwatch.Start("DataContractSerializer ctor");
DataContractSerializer xml = new DataContractSerializer(typeof(UserInfo));
reportwatch.Stop("DataContractSerializer ctor");
reportwatch.Start("DataContractSerializer serialize");
xml.WriteObject(new MemoryStream(), CreateObj());
reportwatch.Stop("DataContractSerializer serialize");
reportwatch.Start("DataContractSerializer serialize 2");
xml.WriteObject(new MemoryStream(), CreateObj());
reportwatch.Stop("DataContractSerializer serialize 2");
reportwatch.Report("Protobuf");
reportwatch.Report("Protobuf serialize");
reportwatch.Report("Protobuf serialize 2");
reportwatch.Report("DataContractSerializer ctor");
reportwatch.Report("DataContractSerializer serialize");
reportwatch.Report("DataContractSerializer serialize 2");
Assert.IsTrue(reportwatch.GetTime(new Regex("(Protobuf)")) <= reportwatch.GetTime(new Regex("(DataContractSerializer)")));
}
示例5: assure_object_graph_is_Serialized_correctly
public void assure_object_graph_is_Serialized_correctly()
{
DataContractSerializer serializer = new DataContractSerializer(typeof(IEnumerable<Changeset>), null, int.MaxValue, false, false, null);
ChangesetServer server = new ChangesetServer() { Name = "Test name", Url = "http://www.smeedee.org" };
Changeset changeset = new Changeset() { Server = server, Comment = "SmeeDee", Revision = 1001, Author = new Author("tuxbear")};
Changeset changeset2 = new Changeset() { Server = server, Comment = "SmeeDee2", Revision = 1002, Author = new Author("tuxbear")};
server.Changesets.Add(changeset);
server.Changesets.Add(changeset2);
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, new [] {changeset, changeset2});
stream.Position = 0;
object deSerialized = serializer.ReadObject(stream);
var changesets = deSerialized as IEnumerable<Changeset>;
var firstDeserialized = changesets.ElementAt(0);
firstDeserialized.Revision.ShouldBe(1001);
var secondDeserialized = changesets.ElementAt(1);
secondDeserialized.Revision.ShouldBe(1002);
}
示例6: 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);
}
}
示例7: 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);
}
}
示例8: Data_contract_serialization_will_change_the_type_of_a_collection
public void Data_contract_serialization_will_change_the_type_of_a_collection()
{
using (var session = DataAccess.OpenSession())
{
var forum = session.Get<ForumModel>(1);
Assert.AreEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());
var knownTypes = new List<Type>
{
typeof (TopicModel),
typeof (NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>),
typeof (NHibernate.Impl.CollectionFilterImpl)
};
var serializer = new DataContractSerializer(typeof(ForumModel), knownTypes);
//serialize company to a memory stream
Stream stream = new MemoryStream();
serializer.WriteObject(stream, forum);
Console.WriteLine();
//deserialize the memory stream back to a company
stream.Position = 0;
forum = (ForumModel)serializer.ReadObject(stream);
Assert.AreNotEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());
Assert.AreEqual(typeof(TopicModel[]), forum.Topics.GetType());
}
}
示例9: dangnhapButton_Click
private async void dangnhapButton_Click(object sender, RoutedEventArgs e)
{
//kiem tra xem co nguoidung khong
NguoiDung nguoidung = connection.Query<NguoiDung>("SELECT * FROM NGUOIDUNG WHERE tenDangNhap=?", tendangnhapTextBox.Text).FirstOrDefault();
if (nguoidung != null && nguoidung.TenDangNhap == tendangnhapTextBox.Text && nguoidung.MatKhau == matkhauPasswordBox.Password)
{
using (IsolatedStorageFileStream fileStream = ISOFile.OpenFile("CurrentUser", FileMode.Create))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(NguoiDung));
serializer.WriteObject(fileStream, nguoidung);
}
// chuyen den TrangChu
Frame.Navigate(typeof(Shell), nguoidung);
Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1);
}
else
{
MessageDialog msDialog = new MessageDialog("Tên đăng nhập hoặc Mật khẩu không đúng!");
await msDialog.ShowAsync();
}
}
示例10: Bug205_ExposingIEnumerable
// http://bugzilla.xamarin.com/show_bug.cgi?id=205
// https://bugzilla.novell.com/show_bug.cgi?id=688414
public void Bug205_ExposingIEnumerable ()
{
var ds = new DataContractSerializer (typeof (IEnumerable<int>));
using (var xw = XmlWriter.Create (System.IO.Stream.Null))
ds.WriteObject (xw, new int [] { 1, 2, 3 });
// the above should not throw System.Runtime.Serialization.SerializationException
}
示例11: SaveConfig
internal void SaveConfig(string fileName)
{
var ser = new DataContractSerializer(typeof(DalConfig));
var settings = new XmlWriterSettings { Indent = true, Encoding=Encoding.Unicode };
using (var writer = XmlWriter.Create(fileName, settings))
{
ser.WriteObject(writer, Config);
}
// by now the connection string is already in the collection
AddConnectionStringToProject(Config.ApplicationConnectionString, _connectionStrings[Config.ApplicationConnectionString]);
ProjectItem dalProjectItem = _package.GetEnvDTE().Solution.FindProjectItem(fileName);
var dalProjectItemChildren = dalProjectItem.ProjectItems;
foreach (ProjectItem item in dalProjectItemChildren)
{
// there is only one child item with this extension
if (item.Name.ToUpper().EndsWith(".tt".ToUpper()))
{
var pi = item.Object as VSProjectItem;
var prop = item.Properties.OfType<Property>().FirstOrDefault(p => p.Name == "CustomTool");
if (prop != null && pi != null)
pi.RunCustomTool();
}
}
}
示例12: SerializeIntervalDie50T100UsingDataContracts
public void SerializeIntervalDie50T100UsingDataContracts()
{
dieSerializer = new DataContractSerializer(typeof(Die));
serializedR50t100 = new MemoryStream();
dieSerializer.WriteObject(serializedR50t100, r50t100);
serializedR50t100.Position = 0;
}
示例13: SerializeDiceChainUsingDataContracts
public void SerializeDiceChainUsingDataContracts()
{
diceChainSerializer = new DataContractSerializer(typeof(DiceChain));
serializedD2d20mr3t6p40 = new MemoryStream();
diceChainSerializer.WriteObject(serializedD2d20mr3t6p40, d2d20mr3t6p40);
serializedD2d20mr3t6p40.Position = 0;
}
示例14: TestSerializeDateTimeOffsetNullable
public void TestSerializeDateTimeOffsetNullable ()
{
// Create the writer object.
StringBuilder stringBuilder = new StringBuilder ();
DateTimeOffset? dto = new DateTimeOffset (2012, 05, 04, 02, 34, 00, new TimeSpan (-2, 0, 0));;
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 xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/System\"><DateTime>2012-05-04T04:34:00Z</DateTime><OffsetMinutes>-120</OffsetMinutes></DateTimeOffset>";
Assert.AreEqual (expectedXml, actualXml, "#1 Nullable 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 Nullable DateTimeOffset deserialization error");
}
}
示例15: 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 = "";
}