GVKun编程网logo

稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据

21

如果您对稳扎稳打Silverlight(19)-2.0通信之调用REST服务,处理JSON格式,XML格式,RSS/ATOM格式的数据感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了

如果您对稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据的详细内容,并且为您提供关于上接稳扎稳打Silverlight(17) - 2.0数据之详解DataGrid, 绑定数据到ListBox、上接稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据、上接稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据、上接稳扎稳打Silverlight(23) - 2.0通信之调用WCF的双向通信(Duplex Service)的有价值信息。

本文目录一览:

稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据

稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据

  [索引页]
[源码下载]

稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式,XML格式,RSS/ATOM格式的数据

作者: webabcd
介绍
Silverlight 2.0 调用REST服务,处理JSON格式,RSS/ATOM格式的数据
    通过 System.Net.WebClient 类调用 REST 服务
    通过 System.Json 命名控件下的类处理 JSON 数据
    通过 System.Xml.Linq 命名空间下的类(LINQ to XML)处理 XML 数据
    通过 System.ServiceModel.Syndication 命名空间下的类处理 RSS/ATOM 数据
在线DEMO
http://www.cnblogs.com/webabcd/archive/2008/10/09/1307486.html  
示例
1、调用 REST 服务,返回 JSON 数据
REST.cs(WCF创建的REST服务)

using  System;

using  System.Linq;

using  System.Runtime.Serialization;

using  System.ServiceModel;

using  System.ServiceModel.Activation;


using  System.ServiceModel.Web;

using  System.Collections.Generic;

using  System.Text;

using  System.IO;


/// <summary>

/// 提供 REST 服务的类

/// 注:Silverlight只支持 GET 和 POST

/// </summary>

[ServiceContract]

[AspNetCompatibilityRequirements(RequirementsMode 
=  AspNetCompatibilityRequirementsMode.Allowed)]

public   class  REST

{

    
/// <summary>

    
/// 用于演示返回 JSON(对象) 的 REST 服务

    
/// </summary>

    
/// <param name="name"></param>

    
/// <returns></returns>

    [OperationContract]

    [WebGet(UriTemplate 
= "User/{name}/json", ResponseFormat = Webmessageformat.Json)]

    
public User HelloJson(string name)

    
{

        
return new User { Name = name, DayOfBirth = new DateTime(1980214) };

    }


    
/// <summary>

    
/// 用于演示返回 JSON(集合) 的 REST 服务

    
/// </summary>

    
/// <returns></returns>

    [OperationContract]

    [WebGet(UriTemplate 
= "Users/json", ResponseFormat = Webmessageformat.Json)]

    
public List<User> HelloJson2()

    
{

        
return new List<User> 

        

            
new User(){ Name = "webabcd01"11) },

            
new User(){ Name = "webabcd02"2) },

            
new User(){ Name = "webabcd03"33) },

        }
;

    }

}


Json.xaml 

< UserControl  x:Class ="Silverlight20.Communication.Json"

    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  

    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml" >

    
< StackPanel  HorizontalAlignment ="Left"  Width ="600" >

    

        
< TextBox  x:Name ="txtMsgJson"  Margin ="5"   />

        
< TextBox  x:Name ="txtMsgJson2"  Margin ="5"   />  

        

    
</ StackPanel >

</ UserControl >


Json.xaml.cs

using  System;

using  System.Collections.Generic;

using  System.Linq;

using  System.Net;

using  System.Windows;

using  System.Windows.Controls;

using  System.Windows.Documents;

using  System.Windows.Input;

using  System.Windows.Media;

using  System.Windows.Media.Animation;

using  System.Windows.Shapes;


using  System.IO;


namespace  Silverlight20.Communication

{

    
public partial class Json : UserControl

    
{

        
public Json()

        
{

            InitializeComponent();


            
// 演示如何处理 JSON(对象)

            JsonDemo();


            
// 演示如何处理 JSON(集合)

            JsonDemo2();

        }


        
/// <summary>

        
/// 演示如何处理 JSON(对象)

        
/// </summary>

        void JsonDemo()

        
{

            
// REST 服务的 URL

            Uri uri = new Uri("http://localhost:3036/REST.svc/User/webabcd/json", UriKind.Absolute);


            
// 实例化 WebClient

            System.Net.WebClient client = new System.Net.WebClient();


            client.DownloadStringCompleted 
+= new DownloadStringCompletedEventHandler(json_DownloadStringCompleted);

            client.DownloadStringAsync(uri);


            txtMsgJson.Text 
= "读取 JSON(对象) 数据中。。。";

        }


        
void json_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

        
{

            
if (e.Error != null)

            
{

                
// 发生错误的话,则打印出来

                txtMsgJson.Text = e.Error.ToString();

                
return;

            }


            
// 将获得的字符串转换为 JSON(对象)

            var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result);

            var ms 
= new MemoryStream(buffer);

            var jsonObject 
= System.Json.JsonObject.Load(ms) as System.Json.JsonObject;


            txtMsgJson.Text 
= e.Result + "\r\n";

            
// 解析 JSON(对象)

            txtMsgJson.Text += string.Format("姓名: {0}, 生日: {1}",

                (
string)jsonObject["Name"],

                ((DateTime)jsonObject[
"DayOfBirth"]).ToString("yyyy-MM-dd"));


            
/* 

             * 总结:

             * JsonObject - 一个具有零或多个 key-value 对的无序集合。继承自抽象类 JsonValue

             *     JsonObject.Load(Stream) - 将指定的字符串流反序列化为 JSON 对象(CLR可用的类型)

             *     JsonObject[key] - JsonObject 索引器,获取 JsonObject 的指定key的value

             *     JsonObject.ContainsKey(key) - JsonObject 对象内是否具有指定的key

             
*/

        }


        
/// <summary>

        
/// 演示如何处理 JSON(集合)

        
/// </summary>

        void JsonDemo2()

        
{

            
// REST 服务的 URL

            Uri uri = new Uri("http://localhost:3036/REST.svc/Users/json", UriKind.Absolute);


            
// 实例化 WebClient

            System.Net.WebClient client = new System.Net.WebClient();


            client.DownloadStringCompleted 
+= new DownloadStringCompletedEventHandler(json2_DownloadStringCompleted);

            client.DownloadStringAsync(uri);


            txtMsgJson2.Text 
= "读取 JSON(集合) 数据中。。。";

        }


        
void json2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

        
{

            
if (e.Error != null)

            
{

                
// 发生错误的话,则打印出来

                txtMsgJson2.Text = e.Error.ToString();

                
return;

            }


            
// 将获得的字符串转换为 JSON(集合)

            var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result);

            var ms 
= new MemoryStream(buffer);

            var jsonArray 
= System.Json.JsonArray.Load(ms) as System.Json.JsonArray;


            txtMsgJson2.Text 
= e.Result + "\r\n";

            txtMsgJson2.Text 
+= string.Format("姓名: {0},

                (
string)jsonArray.First()["Name"],

                ((DateTime)jsonArray.Single(p 
=> p["Name"== "webabcd02")["DayOfBirth"]).ToString("yyyy-MM-dd"));


            
/* 

             * 总结:

             * JsonArray - 一个具有零或多个 JsonValue(抽象类,JsonObject和JsonArray都继承自此类) 对象的有序序列

             *     JsonArray.Load(Stream) - 将指定的字符串流反序列化为 JSON 对象(CLR可用的类型)

             *     JsonArray[index] - JsonArray 索引器,获取 JsonArray 的指定索引的 JsonValue

             *     JsonArray 支持 LINQ

             
*/

        }

    }

}

上接稳扎稳打Silverlight(17) - 2.0数据之详解DataGrid, 绑定数据到ListBox

上接稳扎稳打Silverlight(17) - 2.0数据之详解DataGrid, 绑定数据到ListBox


2、DataGrid02.xaml
<UserControl x:
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data">
        <StackPanel HorizontalAlignment="Left">

                <StackPanel Orientation="Vertical" Margin="5">
                
                        <CheckBox Content="是否只读" Margin="5"    
                                Checked="chkReadOnly_Changed" Unchecked="chkReadOnly_Changed" />

                        <CheckBox Content="冻结列" Margin="5"
                                Checked="chkFreezeColumn_Changed" Unchecked="chkFreezeColumn_Changed"/>

                        <CheckBox Content="行的选中模式,是否只能单选" Margin="5"
                                Checked="chkSelectionMode_Changed" Unchecked="chkSelectionMode_Changed" />

                        <CheckBox Content="是否允许拖动列" IsChecked="true" Margin="5"    
                                Checked="chkColReorder_Changed" Unchecked="chkColReorder_Changed"/>

                        <CheckBox Content="是否允许改变列的宽度" IsChecked="true" Margin="5"
                                Checked="chkColResize_Changed" Unchecked="chkColResize_Changed"/>
                                
                        <CheckBox Content="是否允许列的排序" IsChecked="true" Margin="5"
                                Checked="chkColSort_Changed" Unchecked="chkColSort_Changed"/>

                        <CheckBox Content="改变表格的垂直分隔线的 Brush" Margin="5"    
                                Checked="chkCustomGridLineVertical_Changed" Unchecked="chkCustomGridLineVertical_Changed"/>
                                
                        <CheckBox Content="改变表格的水平分隔线的 Brush" Margin="5"
                                Checked="chkCustomGridLineHorizontal_Changed" Unchecked="chkCustomGridLineHorizontal_Changed"/>

                        <ComboBox SelectionChanged="cboHeaders_SelectionChanged" Width="200" HorizontalAlignment="Left">
                                <ComboBoxItem Content="列头和行头均显示" Tag="All" />
                                <ComboBoxItem Content="只显示列头(默认值)" Tag="Column" IsSelected="True" />
                                <ComboBoxItem Content="只显示行头" Tag="Row" />
                                <ComboBoxItem Content="列头和行头均不显示" Tag="None" />
                        </ComboBox>

                </StackPanel>

                <!--
                GridLinesVisibility - 表格分隔线的显示方式 [System.Windows.Controls.DataGridGridLinesVisibility枚举]
                        DataGridGridLinesVisibility.None - 都不显示
                        DataGridGridLinesVisibility.Horizontal - 只显示水平分隔线
                        DataGridGridLinesVisibility.Vertical - 只显示垂直分隔线。默认值
                        DataGridGridLinesVisibility.All - 显示水平和垂直分隔线
                RowBackground - 奇数数据行背景
                AlternatingRowBackground - 偶数数据行背景
                -->
                <data:DataGrid x:Name="DataGrid1" Margin="5"
                        Width="400" Height="200"
                        AutoGenerateColumns="False"
                        GridLinesVisibility="All"
                        RowBackground="White"
                        AlternatingRowBackground="Yellow"
                        ItemsSource="{Binding}"
                >

                        <data:DataGrid.Columns>
                        
                                <!--
                                IsReadOnly - 该列的单元格是否只读
                                CanUserReorder - 该列是否可以拖动
                                CanUserResize - 该列是否可以改变列宽
                                CanUserSort - 该列是否可以排序
                                SortMemberPath - 该列的排序字段
                                -->
                                <data:DataGridTextColumn Header="姓名" Binding="{Binding Name}"    
                                        IsReadOnly="False"
                                        CanUserReorder="True"    
                                        CanUserResize="True"    
                                        CanUserSort="True"    
                                        SortMemberPath="Name"    
                                />
                                
                                <!--
                                Width - 列宽
                                        Auto - 根据列头内容的宽度和单元格内容的宽度自动设置列宽
                                        SizetoCells - 根据单元格内容的宽度设置列宽
                                        SizetoHeader - 根据列头内容的宽度设置列宽
                                        Pixel - 像素值
                                -->
                                <data:DataGridTextColumn Header="生日" Binding="{Binding DayOfBirth}" Width="100" />
                                <data:DataGridTextColumn Header="年龄" Binding="{Binding Age}" />
                                <data:DataGridCheckBoxColumn Header="性别" Binding="{Binding Male}" />
                                <data:DataGridTextColumn Header="姓名" Binding="{Binding Name}" />
                                <data:DataGridTextColumn Header="生日" Binding="{Binding DayOfBirth}" />
                                <data:DataGridTextColumn Header="年龄" Binding="{Binding Age}" />
                                <data:DataGridCheckBoxColumn Header="性别" Binding="{Binding Male}" />
                        </data:DataGrid.Columns>

                </data:DataGrid>

        </StackPanel>
</UserControl>
 
DataGrid02.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


namespace Silverlight20.Data

{

         public partial class DataGrid02 : UserControl

        {

                 public DataGrid02()

                {

                        InitializeComponent();


                        BindData();

                }


                 void BindData()

                {

                        var source = new Data.sourceData();


                         // 设置 DataGrid 的数据源

                        DataGrid1.DataContext = source.GetData();

                }


                 private void chkReadOnly_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         // IsReadOnly - 单元格是否只读。默认值 false

                        DataGrid1.IsReadOnly = ( bool)chk.IsChecked;

                }


                 private void chkFreezeColumn_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         // FrozenColumnCount - 表格所冻结的列的总数(从左边开始数)。默认值 0

                         if (chk.IsChecked == true)

                                DataGrid1.FrozenColumnCount = 1;

                         else if (chk.IsChecked == false)

                                DataGrid1.FrozenColumnCount = 0;

                }

                

                 private void chkSelectionMode_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         // SelectionMode - 行的选中模式 [System.Windows.Controls.DataGridSelectionMode枚举]

                         //         DataGridSelectionMode.Single - 只能单选

                         //         DataGridSelectionMode.Extended - 可以多选(通过Ctrl或Shift的配合)。默认值

                         if (chk.IsChecked == true)

                                DataGrid1.SelectionMode = DataGridSelectionMode.Single;

                         else if (chk.IsChecked == false)

                                DataGrid1.SelectionMode = DataGridSelectionMode.Extended;

                }


                 private void chkColReorder_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         // CanUserReorderColumns - 是否允许拖动列。默认值 true

                         if (DataGrid1 != null)

                                DataGrid1.CanUserReorderColumns = ( bool)chk.IsChecked;

                }


                 private void chkColResize_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         // CanUserResizeColumns - 是否允许改变列的宽度。默认值 true

                         if (DataGrid1 != null)

                                DataGrid1.CanUserResizeColumns = ( bool)chk.IsChecked;

                }


                 private void chkColSort_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         // CanUserSortColumns - 是否允许列的排序。默认值 true

                         if (DataGrid1 != null)

                                DataGrid1.CanUserSortColumns = ( bool)chk.IsChecked;

                }


                 private void chkCustomGridLineVertical_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         if (DataGrid1 != null)

                        {

                                 // VerticalGridLinesBrush - 改变表格的垂直分隔线的 Brush

                                 if (chk.IsChecked == true)

                                        DataGrid1.VerticalGridLinesBrush = new SolidColorBrush(Colors.Blue);

                                 else

                                        DataGrid1.VerticalGridLinesBrush = new SolidColorBrush(Color.FromArgb(255,223,227,230));

                        }

                }


                 private void chkCustomGridLineHorizontal_Changed( object sender,RoutedEventArgs e)

                {

                        CheckBox chk = sender as CheckBox;


                         if (DataGrid1 != null)

                        {

                                 // HorizontalGridLinesBrush - 改变表格的水平分隔线的 Brush

                                 if (chk.IsChecked == true)

                                        DataGrid1.HorizontalGridLinesBrush = new SolidColorBrush(Colors.Blue);

                                 else

                                        DataGrid1.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromArgb(255,230));

                        }

                }


                 private void cboHeaders_SelectionChanged( object sender,RoutedEventArgs e)

                {

                        ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem;


                         if (DataGrid1 != null)

                        {

                                 // HeadersVisibility - 表头(包括列头和行头)的显示方式 [System.Windows.Controls.DataGridHeadersVisibility枚举]

                                 //         DataGridHeadersVisibility.All - 列头和行头均显示

                                 //         DataGridHeadersVisibility.Column - 只显示列头。默认值

                                 //         DataGridHeadersVisibility.Row - 只显示行头

                                 //         DataGridHeadersVisibility.None - 列头和行头均不显示

                                 if (cbi.Tag.ToString() == "All")

                                        DataGrid1.HeadersVisibility = DataGridHeadersVisibility.All;

                                 else if (cbi.Tag.ToString() == "Column")

                                        DataGrid1.HeadersVisibility = DataGridHeadersVisibility.Column;

                                 else if (cbi.Tag.ToString() == "Row")

                                        DataGrid1.HeadersVisibility = DataGridHeadersVisibility.Row;

                                 else if (cbi.Tag.ToString() == "None")

                                        DataGrid1.HeadersVisibility = DataGridHeadersVisibility.None;

                        }

                }

        }

}
 
 
3、ListBox.xaml
<UserControl x:https://www.jb51.cc/tag/Box/" target="_blank">Box"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <StackPanel HorizontalAlignment="Left">

                <!--
                ListBox.ItemTemplate - ListBox 的选项模板
                        DataTemplate - 手工定义 ListBox 的选项数据
                -->
                <ListBox x:Name="ListBox1" Margin="5" Width="200" Height="100">
                        <ListBox.ItemTemplate>
                                <DataTemplate>
                                        <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{Binding Name}" Margin="5" />
                                                <TextBlock Text="{Binding Age}" Margin="5" />
                                        </StackPanel>
                                </DataTemplate>
                        </ListBox.ItemTemplate>
                </ListBox>
                
        </StackPanel>
</UserControl>
 
ListBox.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


namespace Silverlight20.Data

{

         public partial class ListBox : UserControl

        {

                 public ListBox()

                {

                        InitializeComponent();    

                        

                        BindData();

                }


                 void BindData()

                {

                        var source = new Data.sourceData();


                         // 设置 ListBox 的数据源

                        ListBox1.ItemsSource = source.GetData();

                }

        }

}
 
 
OK
[源码下载]

上接稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据

上接稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据

2、调用 REST 服务,返回 XML 数据
REST.cs(WCF创建的REST服务)

using System;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;


using System.ServiceModel.Web;

using System.Collections.Generic;

using System.Text;

using System.IO;


/// <summary>
/// 提供 REST 服务的类
/// 注:Silverlight只支持 GET 和 POST
/// </summary>

[ServiceContract]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class REST

{

         /// <summary>

         /// 用于演示返回 XML(对象) 的 REST 服务

         /// </summary>

         /// <param name="name"></param>

         /// <returns></returns>

        [OperationContract]

        [WebGet(UriTemplate = "User/{name}/xml",ResponseFormat = Webmessageformat.Xml)]

         public User HelloXml( string name)

        {

                 return new User { Name = name,DayOfBirth = new DateTime(1980,2,14) };

        }


         /// <summary>

         /// 用于演示返回 XML(集合) 的 REST 服务

         /// </summary>

         /// <returns></returns>

        [OperationContract]

        [WebGet(UriTemplate = "Users/xml",ResponseFormat = Webmessageformat.Xml)]

         public List<User> HelloXml2()

        {

                 return new List<User>    

                {    

                         new User(){ Name = "webabcd01",1,1) },

                         new User(){ Name = "webabcd02",2) },

                         new User(){ Name = "webabcd03",3,3) },

                };

        }

}
 
Xml.xaml
<UserControl x:
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <StackPanel HorizontalAlignment="Left" Width="600">

                <TextBox x:Name="txtMsgXml" Margin="5" />
                <TextBox x:Name="txtMsgXml2" Margin="5" />

        </StackPanel>
</UserControl>
 
Xml.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


using System.Xml.Linq;

using System.IO;


namespace Silverlight20.Communication

{

         public partial class Xml : UserControl

        {

                 public Xml()

                {

                        InitializeComponent();


                         // 演示如何处理 XML(对象)

                        XmlDemo();


                         // 演示如何处理 XML(集合)

                        XmlDemo2();

                }


                 /// <summary>

                 /// 演示如何处理 XML(对象)

                 /// </summary>

                 void XmlDemo()

                {

                         // REST 服务的 URL

                        Uri uri = new Uri( "http://localhost:3036/REST.svc/User/webabcd/xml",UriKind.Absolute);


                        // 实例化 WebClient

                        System.Net.WebClient client = new System.Net.WebClient();


                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml_DownloadStringCompleted);

                        client.DownloadStringAsync(uri);


                        txtMsgXml.Text = "读取 XML(对象) 数据中。。。";

                }


                void xml_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)

                {

                        if (e.Error != null)

                        {

                                // 发生错误的话,则打印出来

                                txtMsgXml.Text = e.Error.ToString();

                                return;

                        }


                        // 将获得的字符串转换为 XML(对象)

                        var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result);

                        var ms = new MemoryStream(buffer);


                        XElement xmlObject = XElement.Load(ms);


                        txtMsgXml.Text = e.Result + "\r\n";

                        XNamespace ns = "http://webabcd.cnblogs.com/";

                        txtMsgXml.Text += string.Format("姓名: {0},生日: {1}",

                                (string)xmlObject.Element(ns + "Name"),

                                ((DateTime)xmlObject.Element(ns + "DayOfBirth")).ToString("yyyy-MM-dd"));


                        /*    

                         * 总结:

                         * XElement - 表示一个 XML 元素

                         *         XElement.Element - XML 元素内的 XML 元素

                         *         XElement.Attribute - XML 元素内的 XML 属性

                         *         XElement.Load(Stream) - 使用指定流创建一个 XElement 对象

                         *         XElement.Parse(String) - 解析指定的 XML 字符串为一个 XElement 对象

                         * XAttribute - 表示一个 XML 属性

                         */

                }


                /// <summary>

                /// 演示如何处理 XML(集合)

                /// </summary>

                void XmlDemo2()

                {

                        // REST 服务的 URL

                        Uri uri = new Uri("http://localhost:3036/REST.svc/Users/xml",UriKind.Absolute);


                        // 实例化 WebClient

                        System.Net.WebClient client = new System.Net.WebClient();


                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xml2_DownloadStringCompleted);

                        client.DownloadStringAsync(uri);


                        txtMsgXml2.Text = "读取 XML(集合) 数据中。。。";

                }


                void xml2_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)

                {

                        if (e.Error != null)

                        {

                                // 发生错误的话,则打印出来

                                txtMsgXml2.Text = e.Error.ToString();

                                return;

                        }


                        // 将获得的字符串转换为 XML(集合)

                        XDocument xmlObject = XDocument.Parse(e.Result);


                        txtMsgXml2.Text = e.Result + "\r\n";

                        XNamespace ns = "http://webabcd.cnblogs.com/";

                        var obj = from p in xmlObject.Elements(ns + "ArrayOfUser").Elements(ns + "User")

                                            where p.Element(ns + "Name").Value == "webabcd02"

                                            select new { Name = (string)p.Element(ns + "Name"),DayOfBirth = (DateTime)p.Element(ns + "DayOfBirth") };

                        

                        txtMsgXml2.Text += string.Format("姓名: {0},

                                obj.First().Name,

                                obj.First().DayOfBirth.ToString("yyyy-MM-dd"));



                        /*    

                         * 总结:

                         * LINQ to XML 相当的方便

                         */

                }

        }

}
 
 
3、调用 REST 服务,返回 RSS/Atom 数据
Proxy.aspx.cs(返回指定的URL地址的内容的服务)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;


public partial class Proxy : System.Web.UI.Page

{

         protected void Page_Load( object sender,EventArgs e)

        {

                 // 获取某个 url 地址的 html 并在页面上输出


                 string url = Request.QueryString[ "url"];


                System.Net.WebClient client = new System.Net.WebClient();

                client.Encoding = System.Text.Encoding.UTF8;


                Response.Write(client.DownloadString(url));

                Response.End();

        }

}
 
RSSAtom.xaml
<UserControl x:https://www.jb51.cc/tag/RSS/" target="_blank">RSSAtom"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <StackPanel HorizontalAlignment="Left" >

                <TextBox x:Name="txtMsgRSS" Width="600" Margin="5" />

                <StackPanel Orientation="Horizontal">
                
                        <ListBox x:Name="list" Width="300" Margin="5" SelectionChanged="list_SelectionChanged">
                                <ListBox.ItemTemplate>
                                        <DataTemplate>
                                                <TextBlock Text="{Binding Title.Text}"></TextBlock>
                                        </DataTemplate>
                                </ListBox.ItemTemplate>
                        </ListBox>

                        <TextBlock x:Name="detail" Width="300" Margin="5" Text="{Binding Summary.Text}" textwrapping="Wrap" />
                        
                </StackPanel>
                
        </StackPanel>
</UserControl>
 
RSSAtom.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


using System.Xml;

using System.IO;

using System.ServiceModel.Syndication;


namespace Silverlight20.Communication

{

         public partial class RSSAtom : UserControl

        {

                 public RSSAtom()

                {

                        InitializeComponent();


                         // 演示如何处理 RSS/Atom

                        RSSDemo();

                }


                 /// <summary>

                 /// 演示如何处理 RSS/Atom

                 /// </summary>

                 void RSSDemo()

                {

                         // 让一个代理页面去请求相关的 RSS/Atom(如果用Silverlight直接去请求,则需要在目标域的根目录下配置策略文件)

                        Uri uri = new Uri( "http://localhost:3036/Proxy.aspx?url=http://webabcd.cnblogs.com/RSS",UriKind.Absolute);


                        // 实例化 WebClient

                        System.Net.WebClient client = new System.Net.WebClient();


                        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(RSS_DownloadStringCompleted);

                        client.DownloadStringAsync(uri);


                        txtMsgRSS.Text = "读取 RSS 数据中。。。";

                }


                void RSS_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)

                {

                        if (e.Error != null)

                        {

                                // 发生错误的话,则打印出来

                                txtMsgRSS.Text = e.Error.ToString();

                                return;

                        }


                        // 将获得的字符串转换为 XmlReader

                        var buffer = System.Text.Encoding.UTF8.GetBytes(e.Result);

                        var ms = new MemoryStream(buffer);

                        XmlReader reader = XmlReader.Create(ms);


                        // 从指定的 XmlReader 中加载,以生成 SyndicationFeed

                        SyndicationFeed Feed = SyndicationFeed.Load(reader);


                        // 设置 list 的数据源为 RSS/Atom 的项集合(SyndicationFeed.Items)

                        list.ItemsSource = Feed.Items;

                        txtMsgRSS.Text = e.Result + "\r\n";

                }


                private void list_SelectionChanged(object sender,SelectionChangedEventArgs e)

                {

                        // 设置 detail 的数据上下文为 RSS/Atom 的指定项(SyndicationItem)

                        detail.DataContext = list.SelectedItem as SyndicationItem;

                }

        }

}
 

OK
[源码下载]

上接稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据

上接稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据


2、以字符串的形式和流的形式上传数据
REST.cs(WCF创建的用于演示以字符串的形式和流的形式上传数据的REST服务)

using System;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;


using System.ServiceModel.Web;

using System.Collections.Generic;

using System.Text;

using System.IO;


/// <summary>
/// 提供 REST 服务的类
/// 注:Silverlight只支持 GET 和 POST
/// </summary>

[ServiceContract]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class REST

{

         /// <summary>

         /// 用于演示返回 JSON(对象) 的 REST 服务

         /// </summary>

         /// <param name="name"></param>

         /// <returns></returns>

        [OperationContract]

        [WebGet(UriTemplate = "User/{name}/json",ResponseFormat = Webmessageformat.Json)]

         public User HelloJson( string name)

        {

                 return new User { Name = name,DayOfBirth = new DateTime(1980,2,14) };

        }


         /// <summary>

         /// 用于演示返回 JSON(集合) 的 REST 服务

         /// </summary>

         /// <returns></returns>

        [OperationContract]

        [WebGet(UriTemplate = "Users/json",ResponseFormat = Webmessageformat.Json)]

         public List<User> HelloJson2()

        {

                 return new List<User>    

                {    

                         new User(){ Name = "webabcd01",1,1) },

                         new User(){ Name = "webabcd02",2) },

                         new User(){ Name = "webabcd03",3,3) },

                };

        }


         /// <summary>

         /// 用于演示返回 XML(对象) 的 REST 服务

         /// </summary>

         /// <param name="name"></param>

         /// <returns></returns>

        [OperationContract]

        [WebGet(UriTemplate = "User/{name}/xml",ResponseFormat = Webmessageformat.Xml)]

         public User HelloXml( string name)

        {

                 return new User { Name = name,14) };

        }


         /// <summary>

         /// 用于演示返回 XML(集合) 的 REST 服务

         /// </summary>

         /// <returns></returns>

        [OperationContract]

        [WebGet(UriTemplate = "Users/xml",ResponseFormat = Webmessageformat.Xml)]

         public List<User> HelloXml2()

        {

                 return new List<User>    

                {    

                         new User(){ Name = "webabcd01",

                };

        }


         /// <summary>

         /// 用于演示以字符串的形式上传数据的 REST 服务

         /// </summary>

         /// <param name="fileName">上传的文件名</param>

         /// <param name="stream">POST 过来的数据</param>

         /// <returns></returns>

        [OperationContract]

        [WebInvoke(UriTemplate = "UploadString/?fileName={fileName}",Method = "POST",ResponseFormat = Webmessageformat.Json)]

         public bool UploadString( string fileName,Stream stream)

        {

                 // 文件的服务端保存路径

                 string path = Path.Combine("C:\\",fileName);


                 try

                {

                         using (StreamReader sr = new StreamReader(stream))

                        {

                                 // 将 POST 过来的被 Base64 编码过字符串传换成 byte[]

                                 byte[] buffer = Convert.FromBase64String(sr.ReadToEnd());


                                 using (FileStream fs = new FileStream(path,FileMode.Create,FileAccess.Write,FileShare.None))

                                {

                                         // 将文件写入到服务端

                                        fs.Write(buffer,buffer.Length);

                                }

                        }


                         return true;

                }

                 catch

                {

                         return false;

                }

        }


         /// <summary>

         /// 用于演示以流的形式上传数据的 REST 服务

         /// </summary>

         /// <param name="fileName">上传的文件名</param>

         /// <param name="stream">POST 过来的数据(流的方式)</param>

         /// <returns></returns>

        [OperationContract]

        [WebInvoke(UriTemplate = "UploadStream/?fileName={fileName}",ResponseFormat = Webmessageformat.Json)]

         public bool UploadStream( string fileName,fileName);


                 try

                {

                         using (FileStream fs = new FileStream(path,FileShare.None))

                        {

                                 byte[] buffer = new byte[4096];

                                 int count = 0;


                                 // 每 POST 过来 4096 字节的数据,往服务端写一次

                                 while ((count = stream.Read(buffer,buffer.Length)) > 0)

                                {

                                        fs.Write(buffer,count);

                                }

                        }


                         return true;

                }

                 catch

                {

                         return false;

                }

        }

}
 
WebClientUpload.xaml
<UserControl x:
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <StackPanel HorizontalAlignment="Left" Orientation="Horizontal">            
            
                <StackPanel Margin="5" Width="200">
                        <TextBox x:Name="lblMsgString" Margin="5" />
                        <ProgressBar x:Name="progressBarString" Height="20" Margin="5" Minimum="0" Maximum="100" />
                        <Button x:Name="btnString" Content="上传文件(字符串的方式)" Margin="5" Click="btnString_Click" />
                </StackPanel>
                
                <StackPanel Margin="5" Width="200">
                        <TextBox x:Name="lblMsgStream" Margin="5" />
                        <ProgressBar x:Name="progressBarStream" Height="20" Margin="5" Minimum="0" Maximum="100" />
                        <Button x:Name="btnStream" Content="上传文件(流的方式)" Margin="5" Click="btnStream_Click" />
                </StackPanel>
                
        </StackPanel>
</UserControl>
 
WebClientUpload.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


using System.IO;

using System.Windows.Resources;

using System.ComponentModel;

using System.Windows.browser;


namespace Silverlight20.Communication

{

         public partial class WebClientUpload : UserControl

        {

                 // 用于演示以字符串的形式上传数据

                 string _urlString = "http://localhost:3036/REST.svc/UploadString/?fileName=";


                // 用于演示以流的形式上传数据

                string _urlStream = "http://localhost:3036/REST.svc/UploadStream/?fileName=";


                public WebClientUpload()

                {

                        InitializeComponent();

                }


                /// <summary>

                /// 演示字符串式上传

                /// </summary>

                /// <param name="sender"></param>

                /// <param name="e"></param>

                private void btnString_Click(object sender,RoutedEventArgs e)

                {

                        string data = "";


                        /*

                         * OpenFileDialog - 文件对话框

                         *         ShowDialog() - 显示文件对话框。在文件对话框中单击“确定”则返回true,反之则返回false

                         *         File - 所选文件的 FileInfo 对象

                         */


                        OpenFileDialog dialog = new OpenFileDialog();


                        if (dialog.ShowDialog() == true)

                        {

                                using (FileStream fs = dialog.File.OpenRead())

                                {

                                        byte[] buffer = new byte[fs.Length];

                                        fs.Read(buffer,buffer.Length);


                                        // 将指定的 byte[] 转换为字符串(使用Base64编码)

                                        data = Convert.ToBase64String(buffer);

                                }


                                /*

                                 * WebClient - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类

                                 *         UploadStringCompleted - 上传数据完毕后(包括取消操作及有错误发生时)所触发的事件

                                 *         UploadProgressChanged - 上传数据过程中所触发的事件。正在上传或上传完全部数据后会触发

                                 *         Headers - 与请求相关的的标头的 key/value 对集合

                                 *         UploadStringAsync(Uri address,string data) - 以字符串的形式上传数据到指定的 URI。所使用的 HTTP 方法默认为 POST

                                 *                 Uri address - 接收上传数据的 URI

                                 *                 string data - 需要上传的数据

                                 */


                                System.Net.WebClient clientUploadString = new System.Net.WebClient();


                                clientUploadString.UploadStringCompleted += new UploadStringCompletedEventHandler(clientUploadString_UploadStringCompleted);

                                clientUploadString.UploadProgressChanged += new UploadProgressChangedEventHandler(clientUploadString_UploadProgressChanged);


                                Uri uri = new Uri(_urlString + dialog.File.Name,UriKind.Absolute);

                                clientUploadString.Headers["Content-Type"] = "application/x-www-form-urlencoded";


                                clientUploadString.UploadStringAsync(uri,data);

                        }

                }


                void clientUploadString_UploadProgressChanged(object sender,UploadProgressChangedEventArgs e)

                {

                        /*

                         * UploadProgressChangedEventArgs.Progresspercentage - 上传完成的百分比

                         * UploadProgressChangedEventArgs.BytesSent - 当前发送的字节数

                         * UploadProgressChangedEventArgs.TotalBytesToSend - 总共需要发送的字节数

                         * UploadProgressChangedEventArgs.BytesReceived - 当前接收的字节数

                         * UploadProgressChangedEventArgs.TotalBytesToReceive - 总共需要接收的字节数

                         * UploadProgressChangedEventArgs.UserState - 用户标识

                         */


                        lblMsgString.Text = string.Format("上传完成的百分比:{0}\r\n当前发送的字节数:{1}\r\n总共需要发送的字节数:{2}\r\n当前接收的字节数:{3}\r\n总共需要接收的字节数:{4}\r\n",

                                e.Progresspercentage.ToString(),

                                e.BytesSent.ToString(),

                                e.TotalBytesToSend.ToString(),

                                e.BytesReceived.ToString(),

                                e.TotalBytesToReceive.ToString());


                        progressBarString.Value = (double)e.Progresspercentage;

                }


                void clientUploadString_UploadStringCompleted(object sender,UploadStringCompletedEventArgs e)

                {

                        /*

                         * UploadStringCompletedEventArgs.Error - 该异步操作期间是否发生了错误

                         * UploadStringCompletedEventArgs.Cancelled - 该异步操作是否已被取消

                         * UploadStringCompletedEventArgs.Result - 服务端返回的数据(字符串类型)

                         * UploadStringCompletedEventArgs.UserState - 用户标识

                         */


                        if (e.Error != null)

                        {

                                lblMsgString.Text += e.Error.ToString();

                                return;

                        }


                        if (e.Cancelled != true)

                        {

                                var jsonObject = System.Json.JsonObject.Parse(e.Result);

                                

                                lblMsgString.Text += string.Format("是否上传成功:{0}",

                                        (bool)jsonObject);

                        }

                }




                /// <summary>

                /// 演示流式上传

                /// </summary>

                /// <param name="sender"></param>

                /// <param name="e"></param>

                private void btnStream_Click(object sender,RoutedEventArgs e)

                {

                        FileStream fs = null;


                        OpenFileDialog dialog = new OpenFileDialog();


                        if (dialog.ShowDialog() == true)

                        {

                                fs = dialog.File.OpenRead();


                                /*

                                 * WebClient - 将数据发送到指定的 URI,或者从指定的 URI 接收数据的类

                                 *         OpenWriteCompleted - 在打开用于上传的流完成时(包括取消操作及有错误发生时)所触发的事件

                                 *         WriteStreamClosed - 在写入数据流的异步操作完成时(包括取消操作及有错误发生时)所触发的事件

                                 *         UploadProgressChanged - 上传数据过程中所触发的事件。如果调用 OpenWriteAsync() 则不会触发此事件

                                 *         Headers - 与请求相关的的标头的 key/value 对集合

                                 *         OpenWriteAsync(Uri address,string method,Object userToken) - 打开流以使用指定的方法向指定的 URI 写入数据

                                 *                 Uri address - 接收上传数据的 URI

                                 *                 string method - 所使用的 HTTP 方法(POST 或 GET)

                                 *                 Object userToken - 需要上传的数据流

                                 */


                                System.Net.WebClient clientUploadStream = new System.Net.WebClient();


                                clientUploadStream.OpenWriteCompleted += new OpenWriteCompletedEventHandler(clientUploadStream_OpenWriteCompleted);

                                clientUploadStream.UploadProgressChanged += new UploadProgressChangedEventHandler(clientUploadStream_UploadProgressChanged);

                                clientUploadStream.WriteStreamClosed += new WriteStreamClosedEventHandler(clientUploadStream_WriteStreamClosed);


                                Uri uri = new Uri(_urlStream + dialog.File.Name,UriKind.Absolute);

                                clientUploadStream.Headers["Content-Type"] = "multipart/form-data";


                                clientUploadStream.OpenWriteAsync(uri,"POST",fs);

                        }

                }


                void clientUploadStream_UploadProgressChanged(object sender,UploadProgressChangedEventArgs e)

                {

                        // 因为是调用 OpenWriteAsync(),所以不会触发 UploadProgressChanged 事件


                        lblMsgString.Text = string.Format("上传完成的百分比:{0}\r\n当前发送的字节数:{1}\r\n总共需要发送的字节数:{2}\r\n当前接收的字节数:{3}\r\n总共需要接收的字节数:{4}\r\n",

                                e.TotalBytesToReceive.ToString());


                        progressBarStream.Value = (double)e.Progresspercentage;

                }


                void clientUploadStream_OpenWriteCompleted(object sender,OpenWriteCompletedEventArgs e)

                {

                        System.Net.WebClient client = sender as System.Net.WebClient;


                        if (e.Error != null)

                        {

                                lblMsgStream.Text += e.Error.ToString();

                                return;

                        }


                        if (e.Cancelled != true)

                        {

                                // e.UserState - 需要上传的流(客户端流)

                                Stream clientStream = e.UserState as Stream;


                                // e.Result - 目标地址的流(服务端流)

                                Stream serverStream = e.Result;


                                byte[] buffer = new byte[4096];

                                int count = 0;


                                // clientStream.Read - 将需要上传的流读取到指定的字节数组中

                                while ((count = clientStream.Read(buffer,buffer.Length)) > 0)

                                {

                                        // serverStream.Write - 将指定的字节数组写入到目标地址的流

                                        serverStream.Write(buffer,count);

                                }


                                serverStream.Close();

                                clientStream.Close();

                        }

                }


                void clientUploadStream_WriteStreamClosed(object sender,WriteStreamClosedEventArgs e)

                {

                        if (e.Error != null)

                        {

                                lblMsgStream.Text += e.Error.ToString();

                                return;

                        }

                        else

                        {

                                lblMsgStream.Text += "上传完成";

                        }

                }

        }

}


/*

* 其他:

* 1、WebClient 对象一次只能启动一个请求。如果在一个请求完成(包括出错和取消)前,即IsBusy为true时,进行第二个请求,则第二个请求将会抛出 NotSupportedException 类型的异常

* 2、如果 WebClient 对象的 BaseAddress 属性不为空,则 BaseAddress 与 URI(相对地址) 组合在一起构成绝对 URI

* 3、WebClient 类的 AllowReadStreamBuffering 属性:是否对从 Internet 资源接收的数据做缓冲处理。默认值为true,将数据缓存在客户端内存中,以便随时被应用程序读取

*/
 
 
OK
[源码下载]

上接稳扎稳打Silverlight(23) - 2.0通信之调用WCF的双向通信(Duplex Service)

上接稳扎稳打Silverlight(23) - 2.0通信之调用WCF的双向通信(Duplex Service)


客户端:
DuplexService.xaml
<UserControl x:
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <StackPanel HorizontalAlignment="Left" Margin="5">
        
                <TextBox x:Name="txtStockCode" Text="请输入股票代码" Margin="5" />
                <Button x:Name="btnSubmit" Content="获取股票信息" Click="btnSubmit_Click" Margin="5" />
                <Button x:Name="btnStop" Content="停止获取" Click="btnStop_Click"    Margin="5" />
                <TextBlock x:Name="lblStockMessage" Margin="5" />
        
        </StackPanel>
</UserControl>
 
DuplexService.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;


using System.ServiceModel;

using System.ServiceModel.Channels;

using System.Threading;

using System.IO;


namespace Silverlight20.Communication

{

         public partial class DuplexService : UserControl

        {

                SynchronizationContext _syncContext;


                 // 是否接收服务端发送过来的消息

                 bool _status = true;


                 public DuplexService()

                {

                        InitializeComponent();

                }


                 private void btnSubmit_Click( object sender,RoutedEventArgs e)

                {

                        _status = true;


                         // UI 线程

                        _syncContext = SynchronizationContext.Current;


                        PollingDuplexHttpBinding binding = new PollingDuplexHttpBinding()

                        {

                                 // InactivityTimeout - 服务端与客户端在此超时时间内无任何消息交换的情况下,服务会关闭其会话

                                InactivityTimeout = TimeSpan.FromMinutes(1)

                        };


                         // 构造 IDuplexSessionChannel 的信道工厂

                        IChannelFactory<IDuplexSessionChannel> factory =

                                binding.BuildChannelFactory<IDuplexSessionChannel>( new BindingParameterCollection());


                         // 打开信道工厂

                        IAsyncResult factoryOpenResult =

                                factory.Beginopen( new AsyncCallback(OnopenCompleteFactory),factory);


                         if (factoryOpenResult.CompletedSynchronously)

                        {

                                 // 如果信道工厂被打开的这个 异步操作 已经被 同步完成 则执行下一步

                                CompleteOpenFactory(factoryOpenResult);

                        }

                }


                 private void btnStop_Click( object sender,RoutedEventArgs e)

                {

                        _status = false;

                }


                 void OnopenCompleteFactory(IAsyncResult result)

                {

                         // 该异步操作已被同步完成的话则不做任何操作,反之则执行下一步

                         if (result.CompletedSynchronously)

                                 return;

                         else

                                CompleteOpenFactory(result);

                }


                 void CompleteOpenFactory(IAsyncResult result)

                {

                        IChannelFactory<IDuplexSessionChannel> factory = result.AsyncState as IChannelFactory<IDuplexSessionChannel>;


                         // 完成异步操作,以打开信道工厂

                        factory.EndOpen(result);


                         // 在信道工厂上根据指定的地址创建信道

                        IDuplexSessionChannel channel =

                                factory.CreateChannel( new EndpointAddress( "http://localhost:3036/DuplexService.svc"));


                        // 打开信道

                        IAsyncResult channelOpenResult =

                                channel.Beginopen(new AsyncCallback(OnopenCompleteChannel),channel);


                        if (channelOpenResult.CompletedSynchronously)

                        {

                                // 如果信道被打开的这个 异步操作 已经被 同步完成 则执行下一步

                                CompleteOpenChannel(channelOpenResult);

                        }

                }


                void OnopenCompleteChannel(IAsyncResult result)

                {

                        // 该异步操作已被同步完成的话则不做任何操作,反之则执行下一步

                        if (result.CompletedSynchronously)

                                return;

                        else

                                CompleteOpenChannel(result);

                }


                void CompleteOpenChannel(IAsyncResult result)

                {

                        IDuplexSessionChannel channel = result.AsyncState as IDuplexSessionChannel;


                        // 完成异步操作,以打开信道

                        channel.EndOpen(result);


                        // 构造需要发送到服务端的 System.ServiceModel.Channels.Message (客户端终结点与服务端终结点之间的通信单元)

                        Message message = Message.CreateMessage(

                                channel.GetProperty<MessageVersion>(),// MessageVersion.soap11 (Duplex 服务仅支持 Soap11)

                                "Silverlight20/IDuplexService/SendStockCode",// Action 为请求的目的地(需要执行的某行为的路径)

                                txtStockCode.Text);


                        // 向目的地发送消息

                        IAsyncResult resultChannel =

                                channel.BeginSend(message,new AsyncCallback(OnSend),channel);


                        if (resultChannel.CompletedSynchronously)

                        {

                                // 如果向目的地发送消息的这个 异步操作 已经被 同步完成 则执行下一步

                                CompleteOnSend(resultChannel);

                        }


                        // 监听指定的信道,用于接收返回的消息

                        ReceiveLoop(channel);

                }


                void OnSend(IAsyncResult result)

                {

                        // 该异步操作已被同步完成的话则不做任何操作,反之则执行下一步

                        if (result.CompletedSynchronously)

                                return;

                        else

                                CompleteOnSend(result);

                }


                void CompleteOnSend(IAsyncResult result)

                {

                        try

                        {

                                IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState;


                                // 完成异步操作,以完成向目的地发送消息的操作

                                channel.EndSend(result);

                        }

                        catch (Exception ex)

                        {

                                _syncContext.Post(WriteText,ex.ToString() + Environment.NewLine);

                        }

                }


                void ReceiveLoop(IDuplexSessionChannel channel)

                {

                        // 监听指定的信道,用于接收返回的消息

                        IAsyncResult result =    

                                channel.BeginReceive(new AsyncCallback(OnReceiveComplete),channel);


                        if (result.CompletedSynchronously)

                        {

                                CompleteReceive(result);

                        }

                }


                void OnReceiveComplete(IAsyncResult result)

                {

                        if (result.CompletedSynchronously)

                                return;

                        else

                                CompleteReceive(result);

                }


                void CompleteReceive(IAsyncResult result)

                {

                        IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState;


                        try

                        {

                                // 完成异步操作,以接收到服务端发过来的消息

                                Message receivedMessage = channel.EndReceive(result);


                                if (receivedMessage == null)

                                {

                                        // 服务端会话已被关闭

                                        // 此时应该关闭客户端会话,或向服务端发送消息以启动一个新的会话

                                }

                                else

                                {

                                        // 将接收到的信息输出到界面上

                                        string text = receivedMessage.GetBody<string>();

                                        _syncContext.Post(WriteText,text + Environment.NewLine);


                                        if (!_status)

                                        {

                                                // 关闭信道

                                                IAsyncResult resultFactory =

                                                        channel.BeginClose(new AsyncCallback(OnCloseChannel),channel);


                                                if (resultFactory.CompletedSynchronously)

                                                {

                                                        CompleteCloseChannel(result);

                                                }


                                        }

                                        else

                                        {

                                                // 继续监听指定的信道,用于接收返回的消息

                                                ReceiveLoop(channel);

                                        }

                                }

                        }

                        catch (Exception ex)

                        {

                                // 出错则记日志

                                using (StreamWriter sw = new StreamWriter(@"C:\Silverlight_Duplex_Log.txt",true))

                                {

                                        sw.Write(ex.ToString());

                                        sw.WriteLine();

                                }

                        }

                }


                void OnCloseChannel(IAsyncResult result)

                {

                        if (result.CompletedSynchronously)

                                return;

                        else

                                CompleteCloseChannel(result);

                }


                void CompleteCloseChannel(IAsyncResult result)

                {

                        IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState;


                        // 完成异步操作,以关闭信道

                        channel.EndClose(result);

                }


                void WriteText(object text)

                {

                        // 将信息打到界面上

                        lblStockMessage.Text += (string)text;

                }

        }

}
 
 
OK
[源码下载]

今天的关于稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据的分享已经结束,谢谢您的关注,如果想了解更多关于上接稳扎稳打Silverlight(17) - 2.0数据之详解DataGrid, 绑定数据到ListBox、上接稳扎稳打Silverlight(19) - 2.0通信之调用REST服务,处理JSON格式, XML格式, RSS/ATOM格式的数据、上接稳扎稳打Silverlight(20) - 2.0通信之WebClient, 以字符串的形式上传/下载数据、上接稳扎稳打Silverlight(23) - 2.0通信之调用WCF的双向通信(Duplex Service)的相关知识,请在本站进行查询。

本文标签: