luni, 25 august 2014

DataContractAttribute C# example

DataContractAttribute specifies that the type defines or implements a data contract and is serializable by a serializer.
EnumMemberAttribute specifies that the field is an enumeration member and should be serialized.

Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.Serialization; 

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        [DataContract]
        public enum Country
        {
            [EnumMember(Value = "USA")]
            USA,
            [EnumMember(Value = "DE")]
            Germany,
            [EnumMember(Value = "FR")]
            France,
            NotASerializableEnumeration
        }

        [DataContract (Name = "Customer")]
        public class Customer : IExtensibleDataObject
        {
            public Customer(string name,  Country cnt)
            {
                Name = name;
                Contry = cnt;
            }
            private ExtensionDataObject extensioDataValue;
            public ExtensionDataObject ExtensionData
            {
                get { return extensioDataValue; }
                set { extensioDataValue = value; }
            }
            [DataMember]
            internal string Name;
            [DataMember]
            internal Country Contry;
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Customer p = new Customer("Microsoft"Country.USA );
            FileStream fs = new FileStream(@"C:\1.xml"FileMode.Create);
            try
            {
                DataContractSerializer ser = newDataContractSerializer(typeof(Customer));
                ser.WriteObject(fs, p);
            }
            catch (SerializationException exc)
            {
                 MessageBox.Show(exc.Message.ToString());    
            }
            finally
            {
                fs.Close();
            }
        }
     }
}

Niciun comentariu:

Trimiteți un comentariu