WCF (Restful Web Services) + JSON + Silverlight 4 方法

 
WCF (Restful Web Services) + JSON + Silverlight 4 方法
 

   MainPage.xaml
 
   <Grid x:Name="LayoutRoot" Background="White" VerticalAlignment="Top">
      <sdk:Label HorizontalAlignment="Left" Name="lbl" VerticalAlignment="Top" Width="800" Height="600" FontSize="12" Margin="5,5,0,0" />
   </Grid>
 
   MainPage.xaml.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Net;
   using System.Windows.Controls;
   using System.Json;
 
   namespace SilverlightApplication
   {
      public partial class MainPage : UserControl
      {
 
         public MainPage()
         {
            InitializeComponent();
 
            WebClient client = new WebClient();
            client.DownloadStringAsync(new Uri("http://vmser001/Service.svc/stockjson/"), UriKind.Absolute);
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
         }
 
         void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
         {
            try
            {
               JsonArray stockset = (JsonArray)(JsonArray.Parse(e.Result));
 
               var LINQSet = (from item in stockset
                  select new Stock
                  {
                     StockID = item["StockID"].ToString().Replace("\"", ""),
                     StockName = item["StockName"].ToString().Replace("\"", "")
                  }).Take(20);
 
               List<Stock> stocklist = LINQSet.ToList() as List<Stock>;
 
               foreach (Stock item in stocklist)
               {
                  this.lbl.Content += item.StockID + " — " + item.StockName + "\n";
               }
            }
            catch (Exception ex)
            {
               this.lbl.Content = ex.Message;
            }
         }
 
         private class Stock{
            public string StockID {get; set;}
            public string StockName { get; set; }
         }
 
      }
   }
 
   clientaccesspolicy.xml (令 Silverlight 得到 Permission 連接 WCF Application – 放係 WCF Application 既 Root Folder 上)
 
   <?xml version="1.0" encoding="utf-8" ?>
   <access-policy>
      <cross-domain-access>
         <policy>
            <allow-from http-request-headers="*">
               <domain uri="*" />
            </allow-from>
            <grant-to>
               <resource path="/" include-subpaths="true" />
            </grant-to>
         </policy>
      </cross-domain-access>
   </access-policy>
 
   crossdomain.xml (令 Silverlight 得到 Permission 連接 WCF Application – 放係 WCF Application 既 Root Folder 上)
 
   <?xml version="1.0"?>
   <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
   <cross-domain-policy>
      <allow-http-request-headers-from domain="*" headers="*"/>
   </cross-domain-policy>