Condividi tramite


Creating the .NET Framework Client Application (WCF Data Services Quickstart)

Important

WCF Data Services has been deprecated and will no longer be available for download from the Microsoft Download Center. WCF Data Services supported earlier versions of the Microsoft OData (V1-V3) protocol only and has not been under active development. OData V1-V3 has been superseded by OData V4, which is an industry standard published by OASIS and ratified by ISO. OData V4 is supported through the OData V4 compliant core libraries available at Microsoft.OData.Core. Support documentation is available at OData.Net, and the OData V4 service libraries are available at Microsoft.AspNetCore.OData.

RESTier is the successor to WCF Data Services. RESTier helps you bootstrap a standardized, queryable, HTTP-based REST interface in minutes. Like WCF Data Services before it, Restier provides simple and straightforward ways to shape queries and intercept submissions before and after they hit the database. And like Web API + OData, you still have the flexibility to add your own custom queries and actions with techniques you're already familiar with.

This is the final task of the WCF Data Services quickstart. In this task, you will add a console application to the solution, add a reference to the Open Data Protocol (OData) feed into this new client application, and access the OData feed from the client application by using the generated client data service classes and client libraries.

Note

A .NET Framework-based client application is not required to access a data feed. The data service can be accessed by any application component that consumes an OData feed. For more information, see Using a Data Service in a Client Application.

To create the client application by using Visual Studio

  1. In Solution Explorer, right-click the solution, click Add, and then click New Project.

  2. In the left pane, select Installed > [Visual C# or Visual Basic] > Windows Desktop, and then select the WPF App template.

  3. Enter NorthwindClient for the project name, and then click OK.

  4. Open the file MainWindow.xaml and replace the XAML code with the following code:

        <Window x:Class="Window1"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="Northwind Orders" Height="335" Width="425" 
            Name="OrdersWindow" Loaded="Window1_Loaded">
        <Grid Name="orderItemsGrid">
            <ComboBox DisplayMemberPath="OrderID" ItemsSource="{Binding}"
                      IsSynchronizedWithCurrentItem="true" 
                      Height="23" Margin="92,12,198,0" Name="comboBoxOrder" VerticalAlignment="Top"/>
            <DataGrid ItemsSource="{Binding Path=Order_Details}"  
                      CanUserAddRows="False" CanUserDeleteRows="False"  
                      Name="orderItemsDataGrid" Margin="34,46,34,50"
                      AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn  Header="Product" Binding="{Binding ProductID, Mode=OneWay}" />
                    <DataGridTextColumn  Header="Quantity" Binding="{Binding Quantity, Mode=TwoWay}" />
                    <DataGridTextColumn  Header="Price" Binding="{Binding UnitPrice, Mode=TwoWay}" />
                    <DataGridTextColumn  Header="Discount" Binding="{Binding Discount, Mode=TwoWay}" />                
                </DataGrid.Columns>     
            </DataGrid>
            <Label Height="28" Margin="34,12,0,0" Name="orderLabel" VerticalAlignment="Top" 
                   HorizontalAlignment="Left" Width="65">Order:</Label>
            <StackPanel Name="Buttons" Orientation="Horizontal" HorizontalAlignment="Right" 
                        Height="40" Margin="0,257,22,0">
                <Button Height="23" HorizontalAlignment="Right" Margin="0,0,12,12" 
                    Name="buttonSave" VerticalAlignment="Bottom" Width="75" 
                        Click="buttonSaveChanges_Click">Save Changes
                </Button>
                <Button Height="23" Margin="0,0,12,12" 
                    Name="buttonClose" VerticalAlignment="Bottom" Width="75" 
                        Click="buttonClose_Click">Close</Button>
            </StackPanel>
        </Grid>
    </Window>
    

To add a data service reference to the project

  1. In Solution Explorer, right-click the NorthwindClient project, click Add > Service Reference, and then click Discover.

    This displays the Northwind data service that you created in the first task.

  2. In the Namespace text box, type Northwind, and then click OK.

    This adds a new code file to the project, which contains the data classes that are used to access and interact with data service resources as objects. The data classes are created in the namespace NorthwindClient.Northwind.

To access data service data in the WPF application

  1. In Solution Explorer under NorthwindClient, right-click the project and click Add Reference.

  2. In the Add Reference dialog box, click the .NET tab, select the System.Data.Services.Client.dll assembly, and then click OK.

  3. In Solution Explorer under NorthwindClient, open the code page for the MainWindow.xaml file, and add the following using statement (Imports in Visual Basic).

    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
    Imports System.Data.Services.Client
    Imports NorthwindClient.Northwind
    
    
  4. Insert the following code that queries that data service and binds the result to a DataServiceCollection<T> into the MainWindow class:

    Note

    You must replace the host name localhost:12345 with the server and port that is hosting your instance of the Northwind data service.

    private NorthwindEntities context;
    private string customerId = "ALFKI";
    
    // Replace the host server and port number with the values
    // for the test server hosting your Northwind data service instance.
    private Uri svcUri = new Uri("http://localhost:12345/Northwind.svc");
    
    private void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            // Instantiate the DataServiceContext.
            context = new NorthwindEntities(svcUri);
    
            context.IgnoreMissingProperties = true;
    
            // Define a LINQ query that returns Orders and
            // Order_Details for a specific customer.
            var ordersQuery = from o in context.Orders.Expand("Order_Details")
                              where o.Customer.CustomerID == customerId
                              select o;
    
            // Create an DataServiceCollection<T> based on
            // execution of the LINQ query for Orders.
            DataServiceCollection<Order> customerOrders = new
                DataServiceCollection<Order>(ordersQuery);
    
            // Make the DataServiceCollection<T> the binding source for the Grid.
            this.orderItemsGrid.DataContext = customerOrders;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    
    Private context As NorthwindEntities
    Private customerId As String = "ALFKI"
    
    ' Replace the host server and port number with the values 
    ' for the test server hosting your Northwind data service instance.
    Private svcUri As Uri = New Uri("http://localhost:12345/Northwind.svc")
    
    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            ' Instantiate the DataServiceContext.
            context = New NorthwindEntities(svcUri)
    
            ' Define a LINQ query that returns Orders and 
            ' Order_Details for a specific customer.
            Dim ordersQuery = From o In context.Orders.Expand("Order_Details") _
                              Where o.Customer.CustomerID = customerId _
                              Select o
    
            ' Create an DataServiceCollection(Of T) based on
            ' execution of the LINQ query for Orders.
            Dim customerOrders As DataServiceCollection(Of Order) = New _
                DataServiceCollection(Of Order)(ordersQuery)
    
            ' Make the DataServiceCollection<T> the binding source for the Grid.
            Me.orderItemsGrid.DataContext = customerOrders
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub
    
  5. Insert the following code that saves changes into the MainWindow class:

    private void buttonSaveChanges_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // Save changes made to objects tracked by the context.
            context.SaveChanges();
        }
        catch (DataServiceRequestException ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
    private void buttonClose_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
    
    Private Sub buttonSaveChanges_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            ' Save changes made to objects tracked by the context.
            context.SaveChanges()
        Catch ex As DataServiceRequestException
            MessageBox.Show(ex.ToString())
        End Try
    End Sub
    Private Sub buttonClose_Click(ByVal sender As Object, ByVal a As RoutedEventArgs)
        Me.Close()
    End Sub
    

To build and run the NorthwindClient application

  1. In Solution Explorer, right-click the NorthwindClient project and select Set as startup project.

  2. Press F5 to start the application.

    This builds the solution and starts the client application. Data is requested from the service and displayed in the console.

  3. Edit a value in the Quantity column of the data grid, and then click Save.

    Changes are saved to the data service.

    Note

    This version of the NorthwindClient application does not support adding and deleting of entities.

Next Steps

You have successfully created the client application that accesses the sample Northwind OData feed. You've also completed the WCF Data Services quickstart!

For more information about accessing an OData feed from a .NET Framework application, see WCF Data Services Client Library.

See also