Windows 8 Store Apps(60)-通信:ネットワーク情報の取得、シーケンス化、逆シーケンス化

52681 ワード

原文:
Windows 8 Store Apps(60)-通信:ネットワーク情報の取得、シーケンス化、逆シーケンス化
[ソースのダウンロード]
Windows 8 Store Apps(60)-通信:ネットワーク情報の取得、シーケンス化、逆シーケンス化
著者:webabcd Windows 8 Store Appsの通信を再想像
  • ネットワーク情報
  • を取得する.
  • シーケンス化-json
  • シーケンス化-xml
  • シーケンス化-rss atom
  • 例1、ネットワークに関する情報を取得する方法を示す.xaml.cs
    /*
    
     *              
    
     */
    
    
    
    using System;
    
    using System.Collections.Generic;
    
    using Windows.Networking.Connectivity;
    
    using Windows.UI.Xaml.Controls;
    
    using Windows.UI.Xaml.Navigation;
    
    using System.Linq;
    
    
    
    namespace XamlDemo.Communication
    
    {
    
        public sealed partial class NetworkInfo : Page
    
        {
    
            public NetworkInfo()
    
            {
    
                this.InitializeComponent();
    
            }
    
    
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
    
            {
    
                /*
    
                 * NetworkInformation -           
    
                 */
    
    
    
                //        Internet     ConnectionProfile   
    
                ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile();
    
    
    
                if (connectionProfile == null)
    
                    return;
    
    
    
                //         
    
                lblMsg.Text = "ProfileName: " + connectionProfile.ProfileName;
    
                lblMsg.Text += Environment.NewLine;
    
    
    
                //           (Windows.Networking.Connectivity.NetworkConnectivityLevel   )
    
                //     None -    
    
                //     LocalAccess -          
    
                //     ConstrainedInternetAccess -     internet   
    
                //     InternetAccess -     internet   
    
                lblMsg.Text += "NetworkConnectivityLevel: " + connectionProfile.GetNetworkConnectivityLevel();
    
                lblMsg.Text += Environment.NewLine;
    
    
    
                //                
    
                NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
    
    
    
                NetworkAdapter networkAdapter = connectionProfile.NetworkAdapter;
    
                if (networkAdapter != null)
    
                {
    
                    lblMsg.Text += "NetworkAdapterId: " + networkAdapter.NetworkAdapterId; //       ID
    
                    lblMsg.Text += Environment.NewLine;
    
                    lblMsg.Text += "InboundMaxBitsPerSecond: " + networkAdapter.InboundMaxBitsPerSecond; //           (  :bit/s)
    
                    lblMsg.Text += Environment.NewLine;
    
                    lblMsg.Text += "OutboundMaxBitsPerSecond: " + networkAdapter.OutboundMaxBitsPerSecond; //           (  :bit/s)
    
                    lblMsg.Text += Environment.NewLine;
    
                    lblMsg.Text += "NetworkTypes: " + networkAdapter.NetworkItem.GetNetworkTypes(); //     
    
                    lblMsg.Text += Environment.NewLine;
    
                }
    
    
    
                lblMsg.Text += Environment.NewLine;
    
    
    
                //         
    
                IReadOnlyList<ConnectionProfile> connectionProfiles = NetworkInformation.GetConnectionProfiles();
    
                foreach (ConnectionProfile cp in connectionProfiles)
    
                {
    
                    lblMsg.Text += "ProfileName: " + cp.ProfileName;
    
                    lblMsg.Text += Environment.NewLine;
    
    
    
                    //                       
    
                    DataUsage dataUsage = cp.GetLocalUsage(DateTime.Now.AddHours(-1), DateTime.Now);
    
    
    
                    lblMsg.Text += "BytesSent: " + dataUsage.BytesSent; //        
    
                    lblMsg.Text += Environment.NewLine;
    
                    lblMsg.Text += "BytesReceived: " + dataUsage.BytesReceived; //        
    
                    lblMsg.Text += Environment.NewLine;
    
                }
    
    
    
    
    
                //            
    
                ConnectionCost connectionCost = connectionProfile.GetConnectionCost();
    
                DataPlanStatus dataPlanStatus = connectionProfile.GetDataPlanStatus();
    
                NetworkSecuritySettings networkSecuritySettings = connectionProfile.NetworkSecuritySettings;
    
                IReadOnlyList<LanIdentifier> lanIdentifiers = NetworkInformation.GetLanIdentifiers();
    
            }
    
    
    
            void NetworkInformation_NetworkStatusChanged(object sender)
    
            {
    
    
    
            }
    
        }
    
    }

    シーケンス化と逆シーケンス化を実証するためのエンティティクラスCommunication/Serializer/Product.cs
    /*
    
     *                 
    
     * 
    
     *    DataContractJsonSerializer   DataContractSerializer           ,    DataContract, DataMember, KnownType
    
     *          DataContract, DataMember     
    
     */
    
    
    
    using System;
    
    using System.Collections.Generic;
    
    using System.Runtime.Serialization;
    
    
    
    namespace XamlDemo.Communication.Serializer
    
    {
    
        [DataContract(Name="product")]
    
        public class Product
    
        {
    
            [DataMember(Name = "productId", IsRequired = true, Order = 1)]
    
            public int ProductId { get; set; }
    
    
    
            [DataMember(Name = "name", IsRequired = true, Order = 2)]
    
            public string Name { get; set; }
    
    
    
            public decimal Price { get; set; }
    
    
    
            [DataMember(Name = "createTime", IsRequired = true, Order = 3)]
    
            public DateTime CreateTime { get; set; }
    
    
    
            public static List<Product> GetProducts()
    
            {
    
                List<Product> products = new List<Product>();
    
                for (int i = 0; i < 5; i++)
    
                {
    
                    products.Add(new Product
    
                    {
    
                        ProductId = i,
    
                        Name = "name: " + i.ToString().PadLeft(4, '0'),
    
                        Price = i * 100,
    
                        CreateTime = DateTime.Now.AddDays(-i)
    
                    });
    
                }
    
    
    
                return products;
    
            }
    
        }
    
    }

    2.jsonのシーケンス化と逆シーケンス化、およびjson文字列Communication/Serializer/Jsonの解析方法を示す.xaml.cs
    /*
    
     *    json          ,       json    
    
     * 
    
     * 1、   DataContractJsonSerializer   json          
    
     * 2、   JsonObject   JsonArray    json    
    
     */
    
    
    
    using System;
    
    using System.Collections.Generic;
    
    using System.IO;
    
    using System.Runtime.Serialization;
    
    using System.Runtime.Serialization.Json;
    
    using System.Text;
    
    using Windows.Data.Json;
    
    using Windows.UI.Xaml.Controls;
    
    using Windows.UI.Xaml.Navigation;
    
    
    
    namespace XamlDemo.Communication.Serializer
    
    {
    
        public sealed partial class Json : Page
    
        {
    
            private string _jsonString = "";
    
    
    
            public Json()
    
            {
    
                this.InitializeComponent();
    
            }
    
    
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
    
            {
    
                SerializeJson();
    
                DeserializeJson();
    
                ParseJson();
    
            }
    
    
    
            private void SerializeJson()
    
            {
    
                //        json    
    
                List<Product> products = Product.GetProducts();
    
    
    
                //      json  ,            
    
                DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
    
                settings.DateTimeFormat = new DateTimeFormat("yyyy-MM-dd HH:mm:ss");
    
    
    
                //     DataContractJsonSerializer   ,   json          
    
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Product>), settings);
    
    
    
                using (MemoryStream ms = new MemoryStream())
    
                {
    
                    // DataContractJsonSerializer.WriteObject() -    
    
                    serializer.WriteObject(ms, products);
    
    
    
                    var bytes = ms.ToArray();
    
                    _jsonString = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    
    
    
                    lblMsg.Text = _jsonString;
    
                }
    
            }
    
    
    
            private void DeserializeJson()
    
            {
    
                //
    
                DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
    
                settings.DateTimeFormat = new DateTimeFormat("yyyy-MM-dd HH:mm:ss");
    
    
    
                //     DataContractJsonSerializer   ,   json          
    
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Product>), settings);
    
    
    
                using (MemoryStream ms = new MemoryStream())
    
                {
    
                    var bytes = Encoding.UTF8.GetBytes(_jsonString);
    
                    ms.Write(bytes, 0, bytes.Length);
    
                    ms.Position = 0; //             
    
    
    
                    // DataContractJsonSerializer.ReadObject() -     
    
                    var result = serializer.ReadObject(ms) as List<Product>;
    
    
    
                    lblMsg.Text += Environment.NewLine;
    
                    lblMsg.Text += "First Product Name: " + result[0].Name;
    
                }
    
            }
    
    
    
    
    
            private void ParseJson()
    
            {
    
                // JsonArray - json   。     JsonArray.Parse()   json        JsonArray
    
                // JsonObject - json   。     JsonObject.Parse()   json        JsonObject
    
    
    
                JsonArray ja = JsonArray.Parse(_jsonString);
    
                JsonObject joFirst = ja[0].GetObject();
    
                string firstProductName = joFirst["name"].GetString();
    
    
    
                lblMsg.Text += Environment.NewLine;
    
                lblMsg.Text += "First Product Name: " + firstProductName;
    
            }
    
        }
    
    }

    3、xmlのシーケンス化と逆シーケンス化を実証し、xml文字列Communication/Serializer/MyXmlWriterをどのように解析するか.cs
    /*
    
     *     XmlWriter,          xmlns
    
     */
    
    
    
    using System.Xml;
    
    
    
    namespace XamlDemo.Communication.Serializer
    
    {
    
        public class MyXmlWriter : XmlWriter
    
        {
    
            private XmlWriter _writer;
    
            private bool _ignoreEndAttrCall = false;
    
    
    
            public MyXmlWriter(XmlWriter writer)
    
            {
    
                _writer = writer;
    
            }
    
            
    
            /*      */
    
            public override void WriteStartElement(string prefix, string localName, string ns)
    
            {
    
                if ((ns != null) && ns.StartsWith("http://schemas.datacontract.org"))
    
                {
    
                    ns = null;
    
                }
    
                _writer.WriteStartElement(prefix, localName, ns);
    
            }
    
    
    
            public override void WriteStartAttribute(string prefix, string localName, string ns)
    
            {
    
                if ((ns == null) || (ns == "http://www.w3.org/2001/XMLSchema-instance"))
    
                {
    
                    _ignoreEndAttrCall = true;
    
                    return;
    
                }
    
                _writer.WriteStartAttribute(prefix, localName, ns);
    
            }
    
    
    
            public override void WriteEndAttribute()
    
            {
    
                if (_ignoreEndAttrCall)
    
                {
    
                    _ignoreEndAttrCall = false;
    
                    return;
    
                }
    
                _writer.WriteEndAttribute();
    
            }
    
    
    
            public override void WriteString(string text)
    
            {
    
                if (_ignoreEndAttrCall)
    
                {
    
                    return;
    
                }
    
                _writer.WriteString(text);
    
            }
    
            /*      */
    
    
    
    
    
    
    
            #region          XmlWriter      
    
            public override void Flush()
    
            {
    
                _writer.Flush();
    
            }
    
    
    
            public override string LookupPrefix(string ns)
    
            {
    
                return _writer.LookupPrefix(ns);
    
            }
    
    
    
            public override void WriteBase64(byte[] buffer, int index, int count)
    
            {
    
                _writer.WriteBase64(buffer, index, count);
    
            }
    
    
    
            public override void WriteCData(string text)
    
            {
    
                _writer.WriteCData(text);
    
            }
    
    
    
            public override void WriteCharEntity(char ch)
    
            {
    
                _writer.WriteCharEntity(ch);
    
            }
    
    
    
            public override void WriteChars(char[] buffer, int index, int count)
    
            {
    
                _writer.WriteChars(buffer, index, count);
    
            }
    
    
    
            public override void WriteComment(string text)
    
            {
    
                _writer.WriteComment(text);
    
            }
    
    
    
            public override void WriteDocType(string name, string pubid, string sysid, string subset)
    
            {
    
                _writer.WriteDocType(name, pubid, sysid, subset);
    
            }
    
    
    
            public override void WriteEndDocument()
    
            {
    
                _writer.WriteEndDocument();
    
            }
    
    
    
            public override void WriteEndElement()
    
            {
    
                _writer.WriteEndElement();
    
            }
    
    
    
            public override void WriteEntityRef(string name)
    
            {
    
                _writer.WriteEntityRef(name);
    
            }
    
    
    
            public override void WriteFullEndElement()
    
            {
    
                _writer.WriteFullEndElement();
    
            }
    
    
    
            public override void WriteProcessingInstruction(string name, string text)
    
            {
    
                _writer.WriteProcessingInstruction(name, text);
    
            }
    
    
    
            public override void WriteRaw(string data)
    
            {
    
                _writer.WriteRaw(data);
    
            }
    
    
    
            public override void WriteRaw(char[] buffer, int index, int count)
    
            {
    
                _writer.WriteRaw(buffer, index, count);
    
            }
    
    
    
            public override void WriteStartDocument(bool standalone)
    
            {
    
                _writer.WriteStartDocument(standalone);
    
            }
    
    
    
            public override void WriteStartDocument()
    
            {
    
                _writer.WriteStartDocument();
    
            }
    
    
    
            public override WriteState WriteState
    
            {
    
                get { return _writer.WriteState; }
    
            }
    
    
    
            public override void WriteSurrogateCharEntity(char lowChar, char highChar)
    
            {
    
                _writer.WriteSurrogateCharEntity(lowChar, highChar);
    
            }
    
    
    
            public override void WriteWhitespace(string ws)
    
            {
    
                _writer.WriteWhitespace(ws);
    
            }
    
            #endregion
    
        }
    
    }

    Communication/Serializer/Xml.xaml.cs
    /*
    
     *    xml          ,       xml    
    
     * 
    
     * 1、   DataContractSerializer   xml          
    
     * 2、   XLinq(linq to xml)   xml    ,    xml   crud   
    
     * 
    
     *    xlinq   :http://www.cnblogs.com/webabcd/archive/2007/10/26/938122.html
    
     */
    
    
    
    using System;
    
    using System.Collections.Generic;
    
    using System.IO;
    
    using System.Linq;
    
    using System.Runtime.Serialization;
    
    using System.Text;
    
    using System.Xml;
    
    using System.Xml.Linq;
    
    using Windows.UI.Xaml.Controls;
    
    using Windows.UI.Xaml.Navigation;
    
    
    
    namespace XamlDemo.Communication.Serializer
    
    {
    
        public sealed partial class Xml : Page
    
        {
    
            private string _xmlStringWithoutXmlns = "";
    
            private string _xmlStringWithXmlns = "";
    
    
    
            public Xml()
    
            {
    
                this.InitializeComponent();
    
            }
    
    
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
    
            {
    
                SerializeXml();
    
                DeserializeXml();
    
                ParseXml();
    
            }
    
    
    
            private void SerializeXml()
    
            {
    
                //        xml    
    
                List<Product> products = Product.GetProducts();
    
    
    
                //     DataContractSerializer   ,   xml          ,          
    
                DataContractSerializer serializer = new DataContractSerializer(typeof(List<Product>), "root", "");
    
    
    
                //    ,        xmlns
    
                using (MemoryStream ms = new MemoryStream())
    
                {
    
                    // XmlWriterSettings -      XmlWriter
    
                    XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", NewLineChars = "
    ", Encoding = Encoding.UTF8 }; settings.OmitXmlDeclaration = true; // xml // XmlWriter( :MyXmlWriter.cs) , xml XmlWriter xmlWriter = MyXmlWriter.Create(ms, settings); MyXmlWriter myXmlWriter = new MyXmlWriter(xmlWriter); // DataContractSerializer.WriteObject() - serializer.WriteObject(myXmlWriter, products); xmlWriter.Flush(); xmlWriter.Dispose(); var bytes = ms.ToArray(); _xmlStringWithoutXmlns = Encoding.UTF8.GetString(bytes, 0, bytes.Length); /* * XmlWriter preamble * utf-8 xml , preamble 3 :EF(239), BB(187), BF(191) * preamble * WriteObject(MemoryStream, obj), preamble, XmlWriter xmlns */ // utf-8 preamble _xmlStringWithoutXmlns = TrimPreamble(_xmlStringWithoutXmlns, Encoding.UTF8); } lblMsg.Text = _xmlStringWithoutXmlns; // , preamble, xmlns using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, products); var bytes = ms.ToArray(); _xmlStringWithXmlns = Encoding.UTF8.GetString(bytes, 0, bytes.Length); } } private void DeserializeXml() { // DataContractSerializer , xml , DataContractSerializer serializer = new DataContractSerializer(typeof(List<Product>), "root", ""); using (MemoryStream ms = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(_xmlStringWithXmlns); ms.Write(bytes, 0, bytes.Length); ms.Seek(0, SeekOrigin.Begin); // // DataContractSerializer.ReadObject() - var result = serializer.ReadObject(ms) as List<Product>; lblMsg.Text += Environment.NewLine; lblMsg.Text += "First Product Name: " + result[0].Name; } } /// <summary> /// xlinq xml /// xml preamble, /// xlinq xml crud , :http://www.cnblogs.com/webabcd/archive/2007/10/26/938122.html /// </summary> private void ParseXml() { XDocument document = XDocument.Parse(_xmlStringWithoutXmlns); var products = from p in document.Root.Elements("product") select new Product { ProductId = int.Parse(p.Element("productId").Value), Name = p.Element("name").Value }; lblMsg.Text += Environment.NewLine; lblMsg.Text += "First Product Name: " + products.First().Name; } /// <summary> /// preamble /// </summary> public string TrimPreamble(string value, Encoding encoding) { if (string.IsNullOrEmpty(value)) return value; var bytes = encoding.GetPreamble(); string preamble = encoding.GetString(bytes, 0, bytes.Length); if (value.StartsWith(preamble)) value = value.Remove(0, preamble.Length); return value; } } }

    4、rss/atomの解析Communication/Serializer/RssAtomを実証する.xaml.cs
    /*
    
     *    rss/atom    
    
     * 
    
     *  :
    
     * 1、AtomPub:    HTTP   (post, get, put, delete)    crud web resources    ,     Atom Publishing Protocol
    
     * 2、Windows.Web.AtomPub.AtomPubClient -      AtomPub      
    
     */
    
    
    
    using System;
    
    using Windows.UI.Xaml;
    
    using Windows.UI.Xaml.Controls;
    
    using Windows.Web.Syndication;
    
    
    
    namespace XamlDemo.Communication.Serializer
    
    {
    
        public sealed partial class RssAtom : Page
    
        {
    
            public RssAtom()
    
            {
    
                this.InitializeComponent();
    
    
    
                this.Loaded += Rss_Loaded;
    
            }
    
    
    
            async void Rss_Loaded(object sender, RoutedEventArgs e)
    
            {
    
                Uri rssUri = new Uri("http://feed.cnblogs.com/blog/u/18098/rss");
    
    
    
                // SyndicationClient -      rss/atom   
    
                SyndicationClient client = new SyndicationClient();
    
    
    
                //       ,          Pragma: no-cache
    
                client.BypassCacheOnRetrieve = true; 
    
                //    http  
    
                client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
    
    
    
                lblMsg.Text = "downloading feed: " + rssUri.ToString();
    
                lblMsg.Text += Environment.NewLine;
    
    
    
                try
    
                {
    
                    //     
    
                    SyndicationFeed feed = await client.RetrieveFeedAsync(rssUri);
    
    
    
                    ISyndicationText title = feed.Title;
    
                    
    
                    lblMsg.Text += "feed title: " + title.Text;
    
                    lblMsg.Text += Environment.NewLine;
    
    
    
                    lblMsg.Text += "items count: " + feed.Items.Count;
    
                    lblMsg.Text += Environment.NewLine;
    
    
    
                    foreach (SyndicationItem item in feed.Items)
    
                    {
    
                        lblMsg.Text += "item title: " + item.Title.Text;
    
                        lblMsg.Text += Environment.NewLine;
    
                    }
    
                }
    
                catch (Exception ex)
    
                {
    
                    lblMsg.Text += Environment.NewLine;
    
    
    
                    //   errCode     SyndicationErrorStatus   
    
                    SyndicationErrorStatus status = SyndicationError.GetStatus(ex.HResult);
    
                    lblMsg.Text += status.ToString();
    
                    lblMsg.Text += Environment.NewLine;
    
    
    
                    lblMsg.Text += ex.ToString();
    
                }
    
            }
    
        }
    
    }

    OK [ソースのダウンロード]