Overview
The release of Silverlight 2 Beta 1 brings us a lot of surprises from Runtime and Tools, such as supporting the framework languages Visual Basic, Visual C #, IronRuby, Ironpython, A series of new features such as JSON, Web Service, WCF, and Sockets support. The article "one-step learning Silverlight 2 series" takes you to Silverlight 2 development quickly from the following aspects: Silverlight 2 basic knowledge, data and communication, custom controls, animation, and graphic images.
This article briefly introduces how to communicate with WCF in Silverlight 2.
Simple Example
In this example, a list of the latest essays is obtained through WCF and displayed in Silverlight. The final result is as follows.
First define a data contract:
[DataContract]public class Post{ public Post(int id,string title,string author) { this.Id = id; this.Title = title; this.Author = author; } [DataMember] public int Id { get; set; } [DataMember] public string Title { get; set; } [DataMember] public string Author { get; set; }}
Add a WCF Service file in a Web project named Blog. svc.
Define a service contract:
[ServiceContract]public interface IBlog{ [OperationContract] Post[] GetPosts();}
The implementation service can be read from the database or other data sources. For demonstration convenience, we initialize a set directly:
Public class Blog: IBlog {public Post [] GetPosts () {List <Post> posts = new List <Post> () {new Post (1, "One-Step Silverlight 2 series (13): WebRequest for data and communication", "TerryLee"), new Post (2, "one-step Silverlight 2 series (12 ): webClient for data and communication "," TerryLee "), new Post (3," one-step learning Silverlight 2 series (11): Data Binding "," TerryLee "), new Post (4, "one-step learning Silverlight 2 series (10): using user controls", "TerryLee"), new Post (5, "One-step learning Silverlight 2 series (9): using the control template", "TerryLee"), new Post (6, "one-step learning Silverlight 2 series (8 ): use a style to encapsulate the control's perception "," TerryLee ")}; return posts. toArray ();}}
Modify the service configuration in Web. config. Use basicHttpBinding to bind and enable httpGetEnabled to view the service in the browser:
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="TerryLee.SilverlightDemo27Web.BlogBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="TerryLee.SilverlightDemo27Web.BlogBehavior" name="TerryLee.SilverlightDemo27Web.Blog"> <endpoint address="" binding="basicHttpBinding" contract="TerryLee.SilverlightDemo27Web.IBlog"> </endpoint> </service> </services></system.serviceModel>
Set the port number of the Web application to fixed port 52424. Enter http: // localhost: 52424/Blog. svc in the browser to check whether the service is normal:
Now, the server is ready for implementation. The following section shows the compiling interface:
<Grid Background = "# 46461F"> <Grid. rowDefinitions> <RowDefinition Height = "40"> </RowDefinition> <RowDefinition Height = "*"> </RowDefinition> </Grid. rowDefinitions> <Grid. columnDefinitions> <ColumnDefinition> </Grid. columnDefinitions> <Border Grid. row = "0" Grid. column = "0" CornerRadius = "15" Width = "240" Height = "36" Background = "Orange" Margin = "20 0 0 0" HorizontalAlignment = "Left"> <textBlock Text = "latest essay" Foreground = "White" HorizontalAlignment = "Left" verticalignment = "Center" Margin = "20 0 0 0"> </TextBlock> </Border> <listBox x: name = "Posts" Grid. row = "1" Margin = "40 10 10 10"> <ListBox. itemTemplate> <DataTemplate> <StackPanel Orientation = "Horizontal"> <TextBlock Text = "{Binding Id}" Height = "40" Foreground = "Red"> </TextBlock> <TextBlock text = "{Binding Title}" Height = "40"> </TextBlock> <TextBlock Text = "{Binding Author}" Height = "40" Foreground = "Orange"> </TextBlock> </StackPanel> </DataTemplate> </ListBox. itemTemplate> </ListBox> </Grid>
Add a service reference to the Silverlight project, enter the address http: // localhost: 52424/Blog. svc, and enter the namespace BlogService.
After adding the client, you can view the generated client object in the Object Browser:
Of course, you can also manually write the client code. Please refer to the relevant content of WCF and I will not go into details here. The following code calls the service and obtains data. The asynchronous mode is still used here. Because BasicHttpBinding is adopted in the configuration of the WCF Service, BasicHttpBinding is also used on the client. We need to register the GetPostsCompleted event processing method for callback after completion, and call the GetPostsAsync () method to obtain data. The complete code is as follows:
public partial class Page : UserControl{ public Page() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { Binding binding = new BasicHttpBinding(); EndpointAddress endPoint = new EndpointAddress( "http://localhost:52424/Blog.svc"); BlogClient client = new BlogClient(binding, endPoint); client.GetPostsCompleted += new EventHandler<GetPostsCompletedEventArgs>(client_GetPostsCompleted); client.GetPostsAsync(); } void client_GetPostsCompleted(object sender, GetPostsCompletedEventArgs e) { if (e.Error == null) { Posts.ItemsSource = e.Result; } }}
So far, a complete example of calling WCF in Silverlight 2 is complete. The effect after running is as follows:
Conclusion
This article briefly demonstrates how to communicate with WCF in Silverlight 2. You can download the sample code from here.
Next article: Step by Step Silverlight 2 series (15): ASMX for data and communication