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); }
/// <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); } }
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(); }
public string Parse <XmlDto>(XmlDto from, bool indentXml) { try { if (Equals(@from, default(XmlDto))) { return(null); } using (var ms = MemoryStreamFactory.GetStream()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType()); #if !(SL5 || __IOS__ || XBOX || ANDROID || PCL) var xw = new XmlTextWriter(ms, Encoding); if (indentXml) { xw.Formatting = Formatting.Indented; } serializer.WriteObject(xw, from); xw.Flush(); #else serializer.WriteObject(ms, from); #endif ms.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(ms); return(reader.ReadToEnd()); } } catch (Exception ex) { throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex); } }
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)"))); }
public string Parse <XmlDto>(XmlDto xmlDto, bool indentXml) { try { if (Equals(xmlDto, default(XmlDto))) { return(null); } using (var ms = MemoryStreamFactory.GetStream()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(xmlDto.GetType()); var xw = new XmlTextWriter(ms, Encoding); if (indentXml) { xw.Formatting = Formatting.Indented; } serializer.WriteObject(xw, xmlDto); xw.Flush(); ms.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(ms); return(reader.ReadToEnd()); } } catch (Exception ex) { throw new SerializationException($"Error serializing object of type {xmlDto.GetType().FullName}", ex); } }
/// <summary> /// /// </summary> /// <param name="userId"></param> /// <param name="userDetails"></param> public static bool UpdatetUserProfile(int userId, UserDetailsTDO userDetails, out string errorMsg) { try { // hash user password userDetails.Password = (string.IsNullOrEmpty(userDetails.Password)) ? null : ValueHashUtil.CreateHash(userDetails.Password); // get XML based on UserDetailsTDO object XDocument xDoc = new XDocument(); using (var writer = xDoc.CreateWriter()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(userDetails.GetType()); serializer.WriteObject(writer, userDetails); } // update user details int errorCode; new ProjectDB(ConfigurationHelper.GPD_Connection).UpdateUserProfile(userId, xDoc, out errorCode, out errorMsg); return(errorCode == 0); } catch (Exception exc) { log.Error("Unable to Update User Profile. ERROR: " + exc.ToString()); errorMsg = "Unable to Update User Profile"; return(false); } }
static void Main(string[] args) { var path = "data.xml"; InitializeFile(path); Person p = new Person { Id = 1, Name = "John Doe" }; using (Stream stream = new FileStream(path, FileMode.Open)) { DataContractSerializer ser = new DataContractSerializer(typeof(Person)); ser.WriteObject(stream, p); Console.WriteLine("Serialized ..."); } using (Stream stream = new FileStream(path, FileMode.Open)) { DataContractSerializer ser = new DataContractSerializer(typeof(Person)); Person result = (Person)ser.ReadObject(stream); Console.WriteLine("Deserialize ..."); } Console.Write("Press a key to exit ... "); Console.ReadKey(); }
/// <summary> /// Den aktuellen <see cref="SessionState"/> speichern. Alle <see cref="Frame"/>-Instanzen, /// die bei <see cref="RegisterFrame"/> registriert wurden, behalten ebenfalls ihren aktuellen /// Navigationsstapel bei, wodurch deren aktive <see cref="Page"/> eine Gelegenheit /// zum Speichern des zugehörigen Zustands erhält. /// </summary> /// <returns>Eine asynchrone Aufgabe, die das Speichern des Sitzungszustands wiedergibt.</returns> public static async Task SaveAsync() { try { // Navigationszustand für alle registrierten Rahmen speichern foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Sitzungszustand synchron serialisieren, um einen asynchronen Zugriff auf den freigegebenen // Zustand MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Einen Ausgabedatenstrom für die SessionState-Datei abrufen und den Zustand asynchron schreiben 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); } }
/// <summary> /// Salvare l'oggetto <see cref="SessionState"/> corrente. Tutte le istanze di <see cref="Frame"/> /// registrate con <see cref="RegisterFrame"/> conserveranno lo /// stack di navigazione corrente, che a sua volta fornisce all'oggetto <see cref="Page"/> attivo la possibilità /// di salvare lo stato. /// </summary> /// <returns>Attività asincrona che riflette il momento in cui è stato salvato lo stato sessione.</returns> public static async Task SaveAsync() { try { // Salvare lo stato di navigazione per tutti i frame registrati foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Serializzare lo stato sessione in modo sincrono per evitare l'accesso asincrono allo stato // condiviso MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Richiamare un flusso di output per il file SessionState e scrivere lo stato in modo asincrono 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); } }
private void serializeToFile(string filePath, List <Type> knownTypes) { FileStream writer = null; try { //knownTypes.Add(typeof(TestListenerCollection)); System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(NewTestProperties), knownTypes); // Create a FileStream to write with. writer = new FileStream(filePath, FileMode.Create); // Write object out. serializer.WriteObject(writer, _testProperties); writer.Close(); } catch { throw; } finally { if (writer != null) { // Close file. writer.Close(); } } }
private static void WriteToDisk(XmlElement FLM, string fileName) { try { String DataDirectory = ConfigurationManager.AppSettings.Get("DataDirectory"); string fileNamePath = DataDirectory + "\\" + fileName + ".xml"; DataContractSerializer ser = new DataContractSerializer(typeof(XmlElement)); FileStream fs = new FileStream(fileNamePath, FileMode.Create); ser.WriteObject(fs, FLM); fs.Close(); } catch (Exception e) { try { EventLog.WriteEntry(System.Environment.UserName, "Write File Failed:" + e.Message, EventLogEntryType.Error); } catch (Exception eEventLog) { Exception eEventLogThrow = new Exception("Cannot write to event log: Check service permissions and EventSource exists", eEventLog); throw eEventLogThrow; } Exception eWriteError = new Exception("Cannot write to FLM to file", e); throw eWriteError; } }
public async Task SaveAsync(TValue value) { var kts = _knownTypes; await await Task.Factory.StartNew( async() => { var ms = new MemoryStream(); var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(TValue), kts); Value = value; ser.WriteObject(ms, value); ms.Position = 0; using (var strm = await _streamOpener(StreamOpenType.Write)) { await ms.CopyToAsync(strm); await strm.FlushAsync(); } }, CancellationToken.None, TaskCreationOptions.None, #if NET45 _sch.ExclusiveScheduler #else _sch #endif ); }
/// <summary> /// Guardar el <see cref="SessionState"/> actual. Toda instancia de <see cref="Frame"/> /// registrada en <see cref="RegisterFrame"/> también conservará la /// pila de navegación actual que, a su vez, ofrece a la <see cref="Page"/> activa la oportunidad /// de guardar su estado. /// </summary> /// <returns>Tarea asincrónica que refleja cuándo se ha guardado el estado de la sesión.</returns> public static async Task SaveAsync() { try { // Guardar el estado de navegación para todos los marcos registrados foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Serializar el estado de la sesión de forma sincrónica para impedir el acceso asincrónico al estado // compartido MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Obtener un flujo de salida para el archivo SessionState y escribir el estado de forma asincrónica 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); } }
public void SerializeIntervalDie50T100UsingDataContracts() { dieSerializer = new DataContractSerializer(typeof(Die)); serializedR50t100 = new MemoryStream(); dieSerializer.WriteObject(serializedR50t100, r50t100); serializedR50t100.Position = 0; }
public void SerializeDiceChainUsingDataContracts() { diceChainSerializer = new DataContractSerializer(typeof(DiceChain)); serializedD2d20mr3t6p40 = new MemoryStream(); diceChainSerializer.WriteObject(serializedD2d20mr3t6p40, d2d20mr3t6p40); serializedD2d20mr3t6p40.Position = 0; }
/// <summary> /// Salvar o <see cref="SessionState"/> atual. Quaisquer instâncias de <see cref="Frame"/> ///registradas com <see cref="RegisterFrame"/> também preservarão sua sua pilha de navegação atual /// que, por sua vez, dá à sua <see cref="Page"/> ativa uma oportunidade /// para salvar seu estado. /// </summary> /// <returns>Uma tarefa assíncrona que reflete quando o estado da sessão foi salvo.</returns> public static async Task SaveAsync() { try { // Salve o estado de navegação para todos os quadros registrados foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // Serialize o estado da sessão de forma síncrona para evitar acesso assíncrono a // estado MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // Obter um fluxo de saída para o arquivo SessionState e gravar o estado de forma assíncrona 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); } }
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(); } } }
public string Parse <XmlDto>(XmlDto from, bool indentXml) { try { if (Equals(@from, default(XmlDto))) { return(null); } using (var ms = MemoryStreamFactory.GetStream()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType()); var xw = new XmlTextWriter(ms, JsConfig.UTF8Encoding); if (indentXml) { xw.Formatting = Formatting.Indented; } serializer.WriteObject(xw, from); xw.Flush(); return(ms.ReadToEnd()); } } catch (Exception ex) { throw new SerializationException($"Error serializing object of type {@from.GetType().FullName}", ex); } }
private static void serializeToFile(TestProfile TestProfile, string filePath) { FileStream writer = null; try { System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(TestProfile)); // Create a FileStream to write with. writer = new FileStream(filePath, FileMode.Create); // Write object out. serializer.WriteObject(writer, TestProfile); writer.Close(); } catch { throw; } finally { if (writer != null) { // Close file. writer.Close(); } } }
/// <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); } }
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()); } }
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(); } }
// 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 }
/// <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); } }
/// <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(); } }
/// <summary> /// 儲存目前的 <see cref="SessionState"/>。任何 <see cref="Frame"/> 執行個體 /// 若在 <see cref="RegisterFrame"/> 中註冊,也會保留其目前 /// 導覽堆疊,從而使它們的使用中 <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); } }
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 = ""; }
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"); } }
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"); } }
/// <summary> /// Save the current SessionState for the provided navigationServices. All NavigationServices /// will also preserve their current navigation stack, which in turn gives their active /// <see cref="Page"/> an opportunity to save its state. /// </summary> /// <param name="navigationServices">The Navigation Services to save state for.</param> /// <returns>An asynchronous task that reflects when session state has been saved.</returns> public async Task SaveAsync(IEnumerable<NavigationService> navigationServices) { try { // Save the navigation state for all registered frames foreach (NavigationService service in navigationServices) { this.SessionState[service.Name] = service.SaveState(); } // Serialize the session state synchronously to avoid asynchronous access to shared state MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(this.SessionState.GetType(), this.KnownTypes); serializer.WriteObject(sessionData, this.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); } }
static void Main(string[] args) { List<Employee> list = new List<Employee>(6); Employee Employee1 = new Employee(1, "John"); Employee Employee2 = new Employee(2, "Jane"); list.Add(Employee1); list.Add(Employee2); list.Add(Employee1); FileStream writer = new FileStream("sample.xml", FileMode.Create); DataContractSerializer ser = new DataContractSerializer( type: typeof(List<Employee>), rootName: "root", rootNamespace: "rootns", knownTypes: null, maxItemsInObjectGraph: int.MaxValue, ignoreExtensionDataObject: false, preserveObjectReferences: true, // false is default value dataContractSurrogate: null); ser.WriteObject(writer, list); writer.Close(); }
/// <summary> /// Override this method to manually serialize child objects /// contained within the current object. /// </summary> /// <param name="info">Object containing serialized values.</param> /// <param name="formatter">Reference to the current MobileFormatter.</param> protected virtual void OnGetChildren(SerializationInfo info, MobileFormatter formatter) { bool mobileChildren = typeof(IMobileObject).IsAssignableFrom(typeof(T)); if (mobileChildren) { List <int> references = new List <int>(); foreach (IMobileObject child in this) { SerializationInfo childInfo = formatter.SerializeObject(child); references.Add(childInfo.ReferenceId); } if (references.Count > 0) { info.AddValue("$list", references); } } else { using (MemoryStream stream = new MemoryStream()) { serialization.DataContractSerializer serializer = new serialization.DataContractSerializer(GetType()); serializer.WriteObject(stream, this); stream.Flush(); info.AddValue("$list", stream.ToArray()); } } }
public void SaveConfig(string path, CheckConfiguration config) { var writer = new DataContractSerializer(typeof(CheckConfiguration)); var file = File.Open(path, FileMode.Create); writer.WriteObject(file, config); file.Close(); }
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); } }
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); }
public string Parse <XmlDto>(XmlDto from, bool indentXml) { try { using (var ms = new MemoryStream()) { using (var xw = new XmlTextWriter(ms, Encoding.UTF8)) { if (indentXml) { xw.Formatting = Formatting.Indented; } var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType()); serializer.WriteObject(xw, from); xw.Flush(); ms.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(ms)) { return(reader.ReadToEnd()); } } } } catch (Exception ex) { throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex); } }
internal static bool isSerializable(object value, out string message, List <Type> knownTypes = null) { bool serializable = false; try { System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(value.GetType(), knownTypes); // Create a memory stream and write to it. MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, value); // Just to verify memoryStream.Flush(); memoryStream.Position = 0; StreamReader reader = new StreamReader(memoryStream); message = reader.ReadToEnd(); serializable = true; } catch (Exception e) { message = e.Message; } return(serializable); }
/// <summary> /// 保存当前 <see cref="SessionState"/>。 任何 <see cref="Frame"/> 实例 /// (已向 <see cref="RegisterFrame"/> 注册)都还将保留其当前的 /// 导航堆栈,从而使其活动 <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); } } catch (Exception e) { throw new SuspensionManagerException(e); } }
/// <summary> /// Сохранение текущего <see cref="SessionState"/>. Любые экземпляры <see cref="Frame"/>, /// зарегистрированные с помощью <see cref="RegisterFrame"/>, также сохранят свой текущий /// стек навигации, который, в свою очередь, предоставляет их активной <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); } } catch (Exception e) { throw new SuspensionManagerException(e); } }
public void Save(string fontCollectionFile) { System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(FontCollection), new Type[] { typeof(Font) }); var stream = System.IO.File.OpenWrite(fontCollectionFile); serializer.WriteObject(stream, this); stream.Dispose(); }
public void SerializeToStream(object obj, Stream stream) { using (var xw = new XmlTextWriter(stream, Encoding.UTF8)) { var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType()); serializer.WriteObject(xw, obj); } }
static public void FileSave(string file_path, File_Finds file) { var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(File_Finds)); using (var fs = new FileStream(file_path, FileMode.Create)) { serializer.WriteObject(fs, file); } }
public static void Save(Stream File, LevelUtility.LevelBluePrint data) { if (File != null) { DataContractSerializer Serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(LevelUtility.LevelBluePrint)); Serializer.WriteObject(File, data); File.Close(); } }
public void CompressToStream<XmlDto>(XmlDto from, Stream stream) { using (var deflateStream = new DeflateStream(stream, CompressionMode.Compress)) using (var xw = new XmlTextWriter(deflateStream, Encoding)) { var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType()); serializer.WriteObject(xw, from); xw.Flush(); } }
//public static IQueryable<T> GetDataPaging<T>(this IEnumerable<T> entity, int RowsCount, int PageIndex, int PageSize) //{ // int startrow = PageSize * PageIndex; // int lastrow = startrow + PageSize; // return entity.Skip(startrow).Take(lastrow).AsQueryable<T>(); //} //public static DataTable GetDataPaging<T>(this T entity, int PageIndex, int PageSize)where T:class //{ // int startrow = PageSize * PageIndex; // int lastrow = startrow + PageSize; // int rowcount=db.GetTable<T>().Count(); // DataTable dt = new DataTable(); // dt = db.GetTable <T>().CustomClone(); // for (int i = 0; i <= rowcount; i++) // { // if (i >= startrow && i <= lastrow) // { // dt.Merge(db.GetTable<T>().Skip(startrow).Take(lastrow).ConvertToDataTable()); // i = lastrow; // } // else // { // DataRow dr = dt.NewRow(); // dt.Rows.Add(dr); // } // } // return dt; //} //public static int GetDataPagingCount<T>(this IEnumerable<T> entity) //{ // return entity.Count(); //} // Convert type (var)any datasource to DataTable //public static DataTable ConvertToDataTable<T>(this IEnumerable<T> varlist) //{ // DataTable dtReturn = new DataTable(); // // column names // PropertyInfo[] oProps = null; // if (varlist == null) return dtReturn; // foreach (T rec in varlist) // { // // Use reflection to get property names, to create table, Only first time, others will follow // if (oProps == null) // { // oProps = ((Type)rec.GetType()).GetProperties(); // foreach (PropertyInfo pi in oProps) // { // Type colType = pi.PropertyType; // if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()== typeof(Nullable<>))) // { // colType = colType.GetGenericArguments()[0]; // } // dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); // } // } // DataRow dr = dtReturn.NewRow(); // foreach (PropertyInfo pi in oProps) // { // dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null); // } // dtReturn.Rows.Add(dr); // } // return dtReturn; //} #endregion public static T CloneBySerializer <T>(this T source) where T : class { var obj = new System.Runtime.Serialization.DataContractSerializer(typeof(T)); using (var stream = new System.IO.MemoryStream()) { obj.WriteObject(stream, source); stream.Seek(0, System.IO.SeekOrigin.Begin); return((T)obj.ReadObject(stream)); } }
/// <summary> /// 『DataMemberAttribute Class』 /// 使用 [DataContract()] 标记class /// 使用 [DataMember(Name = "ID")] / [DataMember] 标记成员 /// 并且不要求成员访问修饰符为public /// </summary> public static void SerializeContractData <T>(T serializeClass, string filePath) { if (serializeClass != null) { FileStream fs = new FileStream(filePath, FileMode.Create); System.Xml.XmlDictionaryWriter writer = System.Xml.XmlDictionaryWriter.CreateTextWriter(fs); System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(typeof(T)); ser.WriteObject(writer, serializeClass); writer.Close(); fs.Close(); } }
public void SerializeToStream(object obj, Stream stream) { #if !SILVERLIGHT && !MONOTOUCH && !XBOX using (var xw = new XmlTextWriter(stream, Encoding)) { var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType()); serializer.WriteObject(xw, obj); } #else var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType()); serializer.WriteObject(stream, obj); #endif }
public void SerializeToStream(object obj, Stream stream) { #if !(SL5 || __IOS__ || XBOX || ANDROID || PCL) using (var xw = new XmlTextWriter(stream, Encoding)) { var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType()); serializer.WriteObject(xw, obj); } #else var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType()); serializer.WriteObject(stream, obj); #endif }
public string Parse<XmlDto>(XmlDto from, bool indentXml) { try { if (Equals(@from, default(XmlDto))) return null; using (var ms = new MemoryStream()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType()); #if !SILVERLIGHT && !MONOTOUCH && !XBOX using (var xw = new XmlTextWriter(ms, Encoding)) { if (indentXml) { xw.Formatting = Formatting.Indented; } serializer.WriteObject(xw, from); xw.Flush(); #else serializer.WriteObject(ms, from); #endif ms.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(ms)) { return reader.ReadToEnd(); } #if !SILVERLIGHT && !MONOTOUCH && !XBOX } #endif } } catch (Exception ex) { throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex); } }
public static string Serialize <T>(T data) { System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T), settings); string serializedData = null; using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); serializedData = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } return(serializedData); }
static ReceiptResponse signXml(ReceiptRequest request, string url, Guid cashboxid = default(Guid), string accesstoken = "00000000") { if (!url.EndsWith("/")) { url += "/"; } //var reqdata = UseCase17Request(1, 5, 5, cashboxid.ToString()); var ms = new System.IO.MemoryStream(); var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(fiskaltrust.ifPOS.v0.ReceiptRequest)); serializer.WriteObject(ms, request); //Console.WriteLine("{0:G} Sign request {1}", DateTime.Now, Encoding.UTF8.GetString(ms.ToArray())); var webreq = (HttpWebRequest)HttpWebRequest.Create(url + "xml/sign"); webreq.Method = "POST"; webreq.ContentType = "application/xml;charset=utf-8"; webreq.Headers.Add("cashboxid", cashboxid.ToString()); webreq.Headers.Add("accesstoken", accesstoken); webreq.ContentLength = ms.Length; using (var reqStream = webreq.GetRequestStream()) { reqStream.Write(ms.ToArray(), 0, (int)ms.Length); } var webresp = (HttpWebResponse)webreq.GetResponse(); if (webresp.StatusCode == HttpStatusCode.OK) { serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(fiskaltrust.ifPOS.v0.ReceiptResponse)); ms = new System.IO.MemoryStream(); webresp.GetResponseStream().CopyTo(ms); //Console.WriteLine("{0:G} Sign response {1}", DateTime.Now, Encoding.UTF8.GetString(ms.ToArray())); ms.Position = 0; fiskaltrust.ifPOS.v0.ReceiptResponse resp = (fiskaltrust.ifPOS.v0.ReceiptResponse)serializer.ReadObject(ms); return(resp); } else { //Console.WriteLine("{0:G} {1} {2}", DateTime.Now, webresp.StatusCode, webresp.StatusDescription); return(null); } }
public static void SerializeToWriter <T>(T value, TextWriter writer) { try { using (var xw = new XmlTextWriter(writer)) { var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T)); serializer.WriteObject(xw, value); } } catch (Exception ex) { throw new SerializationException(string.Format("Error serializing object of type {0}", typeof(T).FullName), ex); } }
public void NotificationObjectShouldBeDataContractSerializable() { var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(TestNotificationObject)); var stream = new System.IO.MemoryStream(); var testObject = new TestNotificationObject(); serializer.WriteObject(stream, testObject); stream.Seek(0, System.IO.SeekOrigin.Begin); var reconstitutedObject = serializer.ReadObject(stream) as TestNotificationObject; Assert.IsNotNull(reconstitutedObject); }
public string Serialize(object serializableObject) { using (var memoryStream = new MemoryStream()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(serializableObject.GetType(), _settings); serializer.WriteObject(memoryStream, serializableObject); memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream)) { var result = streamReader.ReadToEnd(); return(result); } } }
public string ConvertToHTML(DisplFormat format) { var dSer = new System.Runtime.Serialization.DataContractSerializer(this.GetType()); System.IO.MemoryStream ms = new System.IO.MemoryStream(); var xTrf = new System.Xml.Xsl.XslCompiledTransform(); var xTrfArg = new System.Xml.Xsl.XsltArgumentList(); var xSet = new System.Xml.Xsl.XsltSettings(true, true); var mstr = new System.Xml.XmlTextWriter(new System.IO.MemoryStream(), System.Text.Encoding.UTF8); var doc = new System.Xml.XmlDocument(); string xsltName = ""; switch (format) { case DisplFormat.single_item: xsltName = "~/xslt/ViewTransforms/RQI2SingleItemView.xslt"; break; case DisplFormat.short_title: xsltName = "~/xslt/ViewTransforms/RQI2ShortTitleView.xslt"; break; default: xsltName = "~/xslt/ViewTransforms/RQI2SingleItemView.xslt"; break; } dSer.WriteObject(ms, this); //TESTDATEI(EZEUGEN) //XmlDocument Doc = new XmlDocument(); //ms.Seek(0, System.IO.SeekOrigin.Begin); //Doc.Load(ms); //Doc.Save("C:/MVCTest.xml"); //ENDE TESTDATEI System.IO.TextReader tr = new System.IO.StringReader(System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position)); xTrf.Load(HttpContext.Current.Server.MapPath(xsltName), xSet, new XmlUrlResolver()); xTrfArg.AddParam("ApplPath", "", "http://" + HttpContext.Current.Request.ServerVariables.Get("HTTP_HOST") + (HttpContext.Current.Request.ApplicationPath.Equals("/") ? "" : HttpContext.Current.Request.ApplicationPath) + "/"); xTrfArg.AddParam("MyDocsPath", "", "http://" + HttpContext.Current.Request.ServerVariables.Get("HTTP_HOST") + (HttpContext.Current.Request.ApplicationPath.Equals("/") ? "" : HttpContext.Current.Request.ApplicationPath) + "/"); xTrfArg.AddExtensionObject("urn:TransformHelper", new TransformHelper.TransformUtils()); xTrf.Transform(new System.Xml.XPath.XPathDocument(tr), xTrfArg, mstr); mstr.BaseStream.Flush(); mstr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); doc.Load(mstr.BaseStream); //TESTDATEI EZEUGEN //doc.Save("C:/MVCTest.xml"); //mstr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); //var rd = new System.Xml.XmlTextReader(mstr.BaseStream); return(doc.OuterXml); }
public string Parse <XmlDto>(XmlDto from, bool indentXml) { try { using (var ms = new MemoryStream()) { var dcs = new System.Runtime.Serialization.DataContractSerializer(from.GetType()); dcs.WriteObject(ms, from); return(Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position)); } } catch (Exception ex) { throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex); } }
public static string Serialize <T>(T objectToSerialize, params Type[] otherTypes) { using (var memStm = new MemoryStream()) { var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T), otherTypes ?? Type.EmptyTypes); serializer.WriteObject(memStm, objectToSerialize); memStm.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memStm)) { string result = streamReader.ReadToEnd(); return(result); } } }
internal static string Serialize(Query запрос) { var sb = new StringBuilder(); var settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var ser = new System.Runtime.Serialization.DataContractSerializer(запрос.GetType()); using (var xml = XmlWriter.Create(sb, settings)) { ser.WriteObject(xml, запрос); xml.Flush(); return(sb.ToString()); } }