.NET Framework クライアント アプリケーションの作成 (WCF Data Services クイック スタート)

これは、WCF Data Services クイック スタートの最後のタスクです。 このタスクでは、コンソール アプリケーションをソリューションに追加し、この新しいクライアント アプリケーションに Open Data Protocol (OData) フィードへの参照を追加します。次に、生成されたクライアント データ サービス クラスおよびクライアント ライブラリを使用して、クライアント アプリケーションから OData フィードにアクセスします。

Dd728278.note(ja-jp,VS.100).gif注 :
データ フィードへのアクセスには .NET Framework ベースのクライアント アプリケーションは必要ありません。データ サービスは、OData フィードを使用する任意のアプリケーション コンポーネントからアクセスできます。詳細については、「クライアント アプリケーションでのデータ サービスの使用 (WCF Data Services)」を参照してください。

Visual Studio を使用してクライアント アプリケーションを作成するには

  1. ソリューション エクスプローラーでソリューションを右クリックし、[追加][新しいプロジェクト] の順にクリックします。

  2. [プロジェクトの種類][Windows] をクリックして、[テンプレート] ペインで [WPF アプリケーション] を選択します。

  3. プロジェクト名として「NorthwindClient」を入力し、[OK] をクリックします。

  4. ファイル Window1.xaml を開き、XAML コードを次のコードに置き換えます。

        <Window x:Class="MainWindow"
        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>
    

データ サービス参照をプロジェクトに追加するには

  1. NorthwindClient プロジェクトを右クリックして、[サービス参照の追加][探索] の順にクリックします。

    最初のタスクで作成した Northwind データ サービスが表示されます。

  2. [名前空間] テキスト ボックスに「Northwind」と入力し、[OK] をクリックします。

    プロジェクトに新しいコード ファイルが追加されます。このコード ファイルには、データ サービス リソースにアクセスし、オブジェクトとしてデータ サービス リソースと対話するデータ クラスが含まれています。 データ クラスは、名前空間 NorthwindClient.Northwind で作成されます。

WPF アプリケーションのデータ サービスにアクセスするには

  1. NorthwindClient の下のソリューション エクスプローラーでプロジェクトを右クリックして、[参照の追加] をクリックします。

  2. [参照の追加] ダイアログ ボックスで、[.NET] タブをクリックし、System.Data.Services.Client.dll アセンブリを選択して、[OK] をクリックします。 NorthwindClient の下のソリューション エクスプローラーで、Window1.xaml ファイルのコード ページを開き、次の using ステートメント (Visual Basic の場合は Imports) を追加します。

    Imports System.Data.Services.Client
    Imports NorthwindClient.Northwind
    
    using System.Data.Services.Client;
    using NorthwindClient.Northwind;
    
  3. 次のコードを挿入します。このコードは、データ サービスを照会し、DataServiceCollection に対する結果を Window1 クラスにバインドします。

    Dd728278.note(ja-jp,VS.100).gif注 :
    ホスト名 localhost:12345 を Northwind データ サービスのインスタンスをホストするサーバーとポートで置き換えます。

    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("https://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
    
    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("https://localhost:12345/Northwind.svc");
    
    private void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            // Instantiate the DataServiceContext.
            context = new NorthwindEntities(svcUri);
    
            // 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());
        }
    }
    
  4. 次のコードを挿入します。このコードは、変更内容を Window1 クラスに保存します。

    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
    
    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();
    }
    

NorthwindClient アプリケーションをビルドして実行するには

  1. ソリューション エクスプローラーで NorthwindClient プロジェクトを右クリックして [スタートアップ プロジェクトに設定] を選択します。.

  2. F5 キーを押してアプリケーションを起動します。

    ソリューションがビルドされ、クライアント アプリケーションが起動します。 データがサービスから要求され、コンソールに表示されます。

  3. データ グリッドの Quantity 列の値を編集し、[保存] をクリックします。

    変更内容はデータ サービスに保存されます。

    Dd728278.note(ja-jp,VS.100).gif注 :
    このバージョンの NorthwindClient アプリケーションでは、エンティティの追加と削除はサポートされません。

次の手順

ここでは、サンプル Northwind の OData フィードにアクセスするクライアント アプリケーションを作成しました。 WCF Data Services クイック スタートも完了しました。 .NET Framework アプリケーションから OData フィードへのアクセスの詳細については、「WCF Data Services クライアント ライブラリ」を参照してください。

参照

概念

WCF Data Services を使用した作業の開始
WCF Data Services リソース