Exemplo n.º 1
0
        /// <summary>
        /// Writes the job (which implements ISerializable) to the provided
        /// file stream.
        /// </summary>
        /// <param name="job">ScheduledJob job to save</param>
        /// <param name="fs">FileStream</param>
        private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
        {
            XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();

            serializer.WriteObject(fs, job);
            fs.Flush();
        }
			public XElement ToElement(object val, Func<Type, XNamespace> getNamespace)
			{
				var serializer = new NetDataContractSerializer();
				using (var ms = new MemoryStream())
				{
					serializer.WriteObject(ms, val);
					ms.Seek(0, SeekOrigin.Begin);
					return XElement.Load(new XmlTextReader(ms));
				}
			}
 public static byte[] Serialize(object graph)
 {
     using (MemoryStream memStream = new MemoryStream())
     using (GZipStream zipStream = new GZipStream(memStream, CompressionMode.Compress))
     {
         using (XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(zipStream))
         {
             NetDataContractSerializer serializer = new NetDataContractSerializer();
             serializer.WriteObject(xmlDictionaryWriter, graph);
             xmlDictionaryWriter.Close();
         }
         zipStream.Close();
         return memStream.ToArray();
     }
 }
        private string Serialize(object value, Type type)
        {
            using (var m = new MemoryStream())
            {
                var w = XmlDictionaryWriter.CreateTextWriter(m, Encoding.Unicode);

                //var s = new DataContractSerializer(type, null, Int32.MaxValue, false, false, null, new PluginDataContractResolver());
                var s = new NetDataContractSerializer();

                s.WriteObject(w, value);
                w.Flush();
                w.Close();

                return System.Text.Encoding.Unicode.GetString(m.ToArray());
            }
        }
 private static Response GetSerializedVersion(object response)
 {
     try
     {
         using (var stream = new MemoryStream())
         {
             var serializer = new NetDataContractSerializer();
             serializer.WriteObject(stream, response);
             stream.Position = 0;
             return (Response)serializer.ReadObject(stream);
         }
     }
     catch (Exception ex)
     {
         throw new ColomboSerializationException(string.Format("{0} could not be serialized.", response), ex);
     }
 }
 private static void WriteCompilerOutput(string path, WorkflowCompilerResults results)
 {
     using (Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
     {
         XmlWriterSettings settings = new XmlWriterSettings {
             Indent = true
         };
         using (XmlWriter writer = XmlWriter.Create(stream, settings))
         {
             NetDataContractSerializer serializer = new NetDataContractSerializer();
             SurrogateSelector selector = new SurrogateSelector();
             selector.AddSurrogate(typeof(MemberAttributes), serializer.Context, new CompilerResultsSurrogate());
             serializer.SurrogateSelector = selector;
             serializer.WriteObject(writer, results);
         }
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Writes the job status information to the provided
        /// file stream.
        /// </summary>
        /// <param name="job">ScheduledJob job to save</param>
        /// <param name="fs">FileStream</param>
        private static void SaveStatusToFile(ScheduledJob job, FileStream fs)
        {
            StatusInfo statusInfo = new StatusInfo(
                job.InstanceId,
                job.Name,
                job.Location,
                job.Command,
                job.StatusMessage,
                job.JobStateInfo.State,
                job.HasMoreData,
                job.PSBeginTime,
                job.PSEndTime,
                job.Definition);

            XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();

            serializer.WriteObject(fs, statusInfo);
            fs.Flush();
        }
        public void Net_data_contract_serialization_will_not_change_the_type_of_a_collection()
        {
            using (var session = DataAccess.OpenSession())
            {
                var forum = session.Get<ForumModel>(1);

                //company.EmployeesList made public for the purpose of
                //this demo
                Assert.AreEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());

                var serializer = new NetDataContractSerializer();

                //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.AreEqual(typeof(NHibernate.Collection.Generic.PersistentGenericBag<TopicModel>), forum.Topics.GetType());
            }
        }
Exemplo n.º 9
0
        private bool TryNetDataContractSerializer(Type type)
        {
            using (var m = new MemoryStream())
            {
                var w = XmlTextWriter.Create(
                    m,
                    new XmlWriterSettings()
                    {
                        Indent = true,
                        Encoding = Encoding.Unicode,
                        NamespaceHandling = NamespaceHandling.OmitDuplicates,
                    });

                var s = new NetDataContractSerializer(
                    new StreamingContext(),
                    int.MaxValue,
                    false,
                    System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
                    null);

                var o = Activator.CreateInstance(type, true);

                s.WriteObject(w, o);
                w.Flush();
                w.Close();

                // Don't forget to skip byte order mark
                var buffer = m.ToArray();
                var prelen = Encoding.Unicode.GetPreamble().Length;
                var xml = System.Text.Encoding.Unicode.GetString(buffer, prelen, buffer.Length - prelen);
            }

            return true;
        }
Exemplo n.º 10
0
		private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
		{
			XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
			netDataContractSerializer.WriteObject(fs, job);
			fs.Flush();
		}
Exemplo n.º 11
0
        public static void SaveSchemas(string filename)
        {
            using ( FileStream fs = new FileStream(filename, FileMode.Create) )
             {
            XmlWriter xw = XmlWriter.Create(fs);
            xw.WriteStartDocument();

            xw.WriteStartElement("SchemaDefinitions");
            foreach ( var schema in schemas )
            {
               NetDataContractSerializer sr = new NetDataContractSerializer();
               sr.WriteObject(xw, schema.Value);
            }
            xw.WriteEndElement(); // SchemaDefinitions

            xw.WriteEndDocument();
            xw.Flush();
             }
        }
        byte[] GetBinarySerializedForm(object instance)
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();
            MemoryStream memStr = new MemoryStream();
            XmlDictionaryWriter dictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(memStr);

            serializer.WriteObject(dictionaryWriter, instance);
            dictionaryWriter.Flush();

            byte[] bytes = memStr.ToArray();

            dictionaryWriter.Close();
            memStr.Close();

            return bytes;
        }
Exemplo n.º 13
0
        public static string Serialize(object value)
        {
            if (value == null)
            {
                return String.Empty;
            }
            else
            {
                using (var m = new MemoryStream())
                {
                    var w = XmlTextWriter.Create(
                        m,
                        new XmlWriterSettings()
                        {
                            Indent = true,
                            Encoding = Encoding.Unicode,
                            NamespaceHandling = NamespaceHandling.OmitDuplicates,
                        });

                    var s = new NetDataContractSerializer();

                    s.WriteObject(w, value);
                    w.Flush();
                    w.Close();

                    // Don't forget to skip byte order mark
                    var buffer = m.ToArray();
                    var prelen = Encoding.Unicode.GetPreamble().Length;
                    return System.Text.Encoding.Unicode.GetString(buffer, prelen, buffer.Length - prelen);
                }
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Writes the job (which implements ISerializable) to the provided
 /// file stream.
 /// </summary>
 /// <param name="job">ScheduledJob job to save</param>
 /// <param name="fs">FileStream</param>
 private static void SaveResultsToFile(ScheduledJob job, FileStream fs)
 {
     XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
     serializer.WriteObject(fs, job);
     fs.Flush();
 }
Exemplo n.º 15
0
 /// <summary>
 /// Saves the machine to an output stream.
 /// </summary>
 /// <param name="output"></param>
 public void Save(Stream output)
 {
     NetDataContractSerializer serializer = new NetDataContractSerializer();
     serializer.WriteObject(output, this);
 }
Exemplo n.º 16
0
        /// <summary>
        /// Adds this scheduled job definition to the job definition store.
        /// </summary>
        private void AddToJobStore()
        {
            FileStream fs = null;
            try
            {
                fs = ScheduledJobStore.CreateFileForJobDefinition(Name);
                _definitionFilePath = ScheduledJobStore.GetJobDefinitionLocation();
                _definitionOutputPath = ScheduledJobStore.GetJobRunOutputDirectory(Name);

                XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
                serializer.WriteObject(fs, this);
                fs.Flush();
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            // If credentials are provided then update permissions.
            if (Credential != null)
            {
                UpdateFilePermissions(Credential.UserName);
            }
        }
Exemplo n.º 17
0
		private void UpdateJobStore()
		{
			FileStream fileForJobDefinition = null;
			try
			{
				fileForJobDefinition = ScheduledJobStore.GetFileForJobDefinition(this.Name, FileMode.Create, FileAccess.Write, FileShare.None);
				XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
				netDataContractSerializer.WriteObject(fileForJobDefinition, this);
				fileForJobDefinition.Flush();
			}
			finally
			{
				if (fileForJobDefinition != null)
				{
					fileForJobDefinition.Close();
				}
			}
			if (this.Credential != null)
			{
				this.UpdateFilePermissions(this.Credential.UserName);
			}
		}
Exemplo n.º 18
0
        /// <summary>
        /// Updates existing file with this definition information.
        /// </summary>
        private void UpdateJobStore()
        {
            FileStream fs = null;
            try
            {
                // Overwrite the existing file.
                fs = GetFileStream(
                    Name,
                    _definitionFilePath,
                    FileMode.Create,
                    FileAccess.Write,
                    FileShare.None);

                XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer();
                serializer.WriteObject(fs, this);
                fs.Flush();
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            // If credentials are provided then update permissions.
            if (Credential != null)
            {
                UpdateFilePermissions(Credential.UserName);
            }
        }
Exemplo n.º 19
0
 public static void SerializeUsingNetDataContract(object objectToSerialize, string filename)
 {
     using (FileStream fs = new FileStream(filename, FileMode.Create))
     {
         using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs))
         {
             NetDataContractSerializer ser = new NetDataContractSerializer();
             //List<Type> knownTypes = new List<Type>();
             //DataContractSerializer ser = new DataContractSerializer(typeof(List<ArchAngel.Providers.Database.Model.Database>), "root", "http://www/", knownTypes, 1000, false, true, null);
             ser.WriteObject(writer, objectToSerialize);
             writer.Close();
         }
     }
 }
Exemplo n.º 20
0
 static void SaveData()
 {
     lock (_saveDataLocker)
     {
         try
         {
             var ds = new NetDataContractSerializer();
             using (Stream s = File.Create(_dataFilePath))
             {
                 ds.WriteObject(s, _serverData);
             }
         }
         catch (DirectoryNotFoundException)
         {
             try
             {
                 Directory.CreateDirectory(Path.GetDirectoryName(_dataFilePath));
                 SaveData();
             }
             catch (Exception _e)
             {
                 Logger.LogError("invalid save path?", THIS, _e);
             }
         }
         catch (Exception _e)
         {
             Logger.LogError("there was a problem with save server data", THIS, _e);
         }
     }
 }
Exemplo n.º 21
0
        public static void WriteObject(string fileName)
        {
            Console.WriteLine("Creating a Person object and serializing it.");

            // Creating the serializer
            ComplexNumber number = new ComplexNumberWithMagnitude(3, 4);
            FileStream fs = new FileStream(fileName, FileMode.Create);
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
            NetDataContractSerializer ser = new NetDataContractSerializer();

            ser.WriteObject(writer, number);
            writer.Close();
        }
Exemplo n.º 22
0
		private void AddToJobStore()
		{
			FileStream fileStream = null;
			try
			{
				fileStream = ScheduledJobStore.CreateFileForJobDefinition(this.Name);
				this._definitionFilePath = ScheduledJobStore.GetJobDefinitionLocation();
				this._definitionOutputPath = ScheduledJobStore.GetJobRunOutputDirectory(this.Name);
				XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
				netDataContractSerializer.WriteObject(fileStream, this);
				fileStream.Flush();
			}
			finally
			{
				if (fileStream != null)
				{
					fileStream.Close();
				}
			}
			if (this.Credential != null)
			{
				this.UpdateFilePermissions(this.Credential.UserName);
			}
		}
Exemplo n.º 23
0
        public void ET_WCF_Serialization_List()
        {
            var model = new Book
            {
                ChapterList =
                {
                    new Chapter {
                        Id = 111,
                        Name = "Chapter1",
                    },
                    new Chapter {
                        Id = 222,
                        Name = "Chapter2",
                    },
                }
            };

            //序列化。
            var serializer = new NetDataContractSerializer();
            var stream = new MemoryStream();
            serializer.WriteObject(stream, model);

            //读取 xml
            byte[] bytes = stream.ToArray();
            string xml = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
            Assert.IsTrue(xml.Contains("<Book"));
            Assert.IsTrue(xml.Contains("<ChapterList"));
            Assert.IsTrue(xml.Contains("<Chapter"));
            Assert.IsTrue(xml.Contains("111"));
            Assert.IsTrue(xml.Contains("<Name"));
            Assert.IsTrue(xml.Contains("Chapter1"));

            //反序列化
            stream.Seek(0, SeekOrigin.Begin);
            var model2 = (Book)serializer.ReadObject(stream);

            Assert.IsTrue(model2.GetProperty(Book.ChapterListProperty) != null);
            Assert.IsTrue(model2.ChapterList.Count == 2);
            Assert.IsTrue(model2.ChapterList[0].Id == 111);
            Assert.IsTrue(model2.ChapterList[0].Name == "Chapter1");
        }
        string GetXmlSerializedForm(object instance)
        {
            NetDataContractSerializer serializer = new NetDataContractSerializer();
            MemoryStream memStr = new MemoryStream();

            serializer.WriteObject(memStr, instance);

            string xml = UnicodeEncoding.UTF8.GetString(memStr.ToArray());

            memStr.Close();

            return xml;
        }
 public void Serialize(System.IO.Stream stream, object instance)
 {
     NetDataContractSerializer serializer = new NetDataContractSerializer();
     serializer.WriteObject(stream, instance);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Сохранение данных в файл "data.xml" (сериализация).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();

            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                XmlTextWriter xmlw = new XmlTextWriter(saveFileDialog1.FileName, System.Text.Encoding.UTF8);
                xmlw.Formatting = Formatting.Indented;
                NetDataContractSerializer dcs = new NetDataContractSerializer();
                dcs.WriteObject(xmlw, polygons.List);
                xmlw.Close();
            }
        }
Exemplo n.º 27
0
		internal int SerializeAndSaveToFile(object source, string filePath)
		{
			int length;
			if (!this._version.EnableEncryption)
			{
				FileStream fileStream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
				GZipStream gZipStream = new GZipStream(fileStream, CompressionMode.Compress);
				bool flag = false;
				Exception exception = null;
				try
				{
					try
					{
						XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
						gZipStream.Write(PSWorkflowFileInstanceStore.EncryptFalse, 0, 1);
						netDataContractSerializer.WriteObject(gZipStream, source);
						length = (int)fileStream.Length;
						return length;
					}
					catch (SerializationException serializationException1)
					{
						SerializationException serializationException = serializationException1;
						flag = true;
						exception = serializationException;
					}
					catch (InvalidDataContractException invalidDataContractException1)
					{
						InvalidDataContractException invalidDataContractException = invalidDataContractException1;
						flag = true;
						exception = invalidDataContractException;
					}
					catch (Exception exception2)
					{
						Exception exception1 = exception2;
						this.Tracer.TraceException(exception1);
						throw;
					}
					if (flag)
					{
						this.ThrowErrorOrWriteWarning(exception);
					}
					return 0;
				}
				finally
				{
					gZipStream.Close();
					fileStream.Close();
					gZipStream.Dispose();
					fileStream.Dispose();
				}
				return length;
			}
			else
			{
				ArraySegment<byte> nums = this.Encrypt(this.SerializeObject(source));
				this.SaveToFile2(nums, filePath);
				return nums.Count;
			}
		}
Exemplo n.º 28
0
		internal ArraySegment<byte> SerializeObject(object source)
		{
			if (!this._version.EnableCompression)
			{
				ArraySegment<byte> nums = new ArraySegment<byte>(PSWorkflowFileInstanceStore.NullArray);
				try
				{
					XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
					using (MemoryStream memoryStream = new MemoryStream())
					{
						netDataContractSerializer.WriteObject(memoryStream, source);
						nums = new ArraySegment<byte>(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
					}
				}
				catch (SerializationException serializationException1)
				{
					SerializationException serializationException = serializationException1;
					this.ThrowErrorOrWriteWarning(serializationException);
				}
				catch (InvalidDataContractException invalidDataContractException1)
				{
					InvalidDataContractException invalidDataContractException = invalidDataContractException1;
					this.ThrowErrorOrWriteWarning(invalidDataContractException);
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					this.Tracer.TraceException(exception);
					throw;
				}
				return nums;
			}
			else
			{
				return this.SerializeObject2(source);
			}
		}
Exemplo n.º 29
0
		internal ArraySegment<byte> SerializeObject2(object source)
		{
			ArraySegment<byte> nums = new ArraySegment<byte>(PSWorkflowFileInstanceStore.NullArray);
			try
			{
				XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
				using (MemoryStream memoryStream = new MemoryStream())
				{
					netDataContractSerializer.WriteObject(memoryStream, source);
					byte[] numArray = new byte[(IntPtr)(memoryStream.Length + (long)1)];
					numArray[0] = 70;
					Buffer.BlockCopy(memoryStream.GetBuffer(), 0, numArray, 1, (int)memoryStream.Length);
					nums = new ArraySegment<byte>(numArray, 0, (int)numArray.Length);
					memoryStream.Close();
				}
			}
			catch (SerializationException serializationException1)
			{
				SerializationException serializationException = serializationException1;
				this.ThrowErrorOrWriteWarning(serializationException);
			}
			catch (InvalidDataContractException invalidDataContractException1)
			{
				InvalidDataContractException invalidDataContractException = invalidDataContractException1;
				this.ThrowErrorOrWriteWarning(invalidDataContractException);
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				this.Tracer.TraceException(exception);
				throw;
			}
			return nums;
		}
Exemplo n.º 30
0
		private static void SaveStatusToFile(ScheduledJob job, FileStream fs)
		{
			StatusInfo statusInfo = new StatusInfo(job.InstanceId, job.Name, job.Location, job.Command, job.StatusMessage, job.JobStateInfo.State, job.HasMoreData, job.PSBeginTime, job.PSEndTime, job.Definition);
			XmlObjectSerializer netDataContractSerializer = new NetDataContractSerializer();
			netDataContractSerializer.WriteObject(fs, statusInfo);
			fs.Flush();
		}
Exemplo n.º 31
0
        /// <summary>
        /// Serialize data.
        /// </summary>
        /// <param name="data">Data to serialize.</param>
        /// <param name="encoding">The encoding to use.</param>
        /// <returns>The serialized data.</returns>
        public string Serialize( object data, Encoding encoding = null )
        {
            if ( encoding == null )
             {
            encoding = DefaultEncoding;
             }

             if ( data == null )
             {
            data = new NullObject();
             }

             string result;
             using ( var outerMmemoryStream = new MemoryStream() )
             {
            using ( var xmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter( outerMmemoryStream, encoding ) )
            {
               var netDataContractSerializer = new NetDataContractSerializer();

               netDataContractSerializer.WriteObject( xmlDictionaryWriter, data );
            }

            using ( var innerMemoryStream = new MemoryStream( outerMmemoryStream.ToArray() ) )
            {
               var streamReader = new StreamReader( innerMemoryStream, encoding );
               result = streamReader.ReadToEnd();
            }
             }

             return result;
        }