티스토리 뷰

반응형

마지막으로 각 클라이언트에서 DataService를 사용하는 방법에 대해 정리하도록 하자.

 

이전 포스트

OData Endpoint with ASP.NET Web API Part2 - Web

OData Endpoint with ASP.NET Web API Part1 - DAL

 

1. 기본 참고 포스트

Create a C# Client for the OData Endpoint

http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/getting-started-with-odata-in-web-api/create-an-odata-client

 

2. WCF Data Services Tool Install

OData Endpoint DataService를 사용하기 위해서는 별도의 Tool을 설치해야한다.

WCF Data Services 5.6.0 RTM Tools Installer

http://www.microsoft.com/en-us/download/details.aspx?id=39373

설명에는 모든 플랫폼에서 사용가능하다고 나와있다. 이전 버전에서는 몇개의 인스톨을 추가로 해줘야 가능했는데..하나로 통합이 되지 않았을까 추측해 본다.

만약, Windows 8 store app에서 Service References에 추가가 되지 않는다면 Windows 8용 tool을 찾아서 설치해주어야 한다.

* 하나로 통합이 되어 있는 것 확인

대신 PCLSample.W8 프로젝트의 packages.config 파일을 열어서 아래 두 부분을 삭제 한다. Nuget package에서는 아래 내용을 찾을 수 없다.

  <package id="Microsoft.Data.OData.WindowsStore" version="5.0.0" targetFramework="win" />
  <package id="Microsoft.Data.Services.Client.WindowsStore" version="5.0.0" targetFramework="win" />

 

3. 프로젝트 실행

Ctrl + F5를 눌러서 Web프로젝트를 실행한다. 서비스가 올라가야 Service Reference를 추가할 수 있다.

 

 

Web 프로젝트가 실행되면 실버라이트 페이지가 자동으로 오픈된다. 주소창에 아래와 같이 입력해 본다.

http://localhost:2852/odata/ : odata를 이용해서 접근할 수 있는 곳이 People이라는 것을 알 수 있다.

odata를 저장하겠냐고 물어보고, 이 데이터를 저장 후 메모장으로 열어 보면 아래와 같은 내용이 표시된다.

 

<?xml version="1.0" encoding="utf-8"?>
<service xml:base="http://localhost:2852/odata/" xmlns="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom">
  <workspace>
    <atom:title type="text">Default</atom:title>
    <collection href="People">
      <atom:title type="text">People</atom:title>
    </collection>
  </workspace>
</service>

 

 

http://localhost:2852/odata/$metadata : 전체 스키마 구조를 알 수 있다.

 

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
  <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <Schema Namespace="PCLSample.PCL.Models" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
      <EntityType Name="PersonModel">
        <Key>
          <PropertyRef Name="Id" />
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false" />
        <Property Name="Age" Type="Edm.Int32" Nullable="false" />
        <Property Name="Name" Type="Edm.String" />
        <Property Name="Sex" Type="Edm.Boolean" Nullable="false" />
      </EntityType>
    </Schema>
    <Schema Namespace="Default" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
      <EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
        <EntitySet Name="People" EntityType="PCLSample.PCL.Models.PersonModel" />
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>

 

4. PCLSample.SL5

Solution Explorer에서

PCLSample.SL5 프로젝트를 선택 -> 마우스 오른쪽 클릭 -> Add Service References

 

 

Address에 위와 같이 입력하고 Go를 누르면 Services 목록이 표시되며, 이 서비스를 PCLSampleService라는 이름을 프로젝트에 추가한다. 이 과정은 각 프로젝트마다 동일하다.

 

5. MainPage.xaml.cs

원래는 뷰 모델에서 처리해야하는데 현재 버전에서는 cs에서 작업하고 있다.

방금 추가한 서비스를 이용해서 데이터를 조회하고, 결과를 debug창에 출력한다.

 

    public partial class MainPage : UserControl
    {
        public IMainViewModel ViewModel
        {
            get { return DataContext as IMainViewModel; }
            set { DataContext = value; }
        }

        public MainPage()
        {
            InitializeComponent();

            ViewModel = App.GetInstance<IMainViewModel>();

            this.Loaded += MainPage_Loaded;
            this.Unloaded += MainPage_Unloaded;
        }

        void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= MainPage_Loaded;
            this.Unloaded -= MainPage_Unloaded;
        }

 

        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var result = await GetPeopleAsync();
            if (result == null) return;
            foreach (var item in result)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Silverlight5 Id:{0} Name:{1} Age:{2} Sex:{3}", item.Id, item.Name, item.Age, item.Sex));
            }
        }

 

        private async Task<IList<PersonModel>> GetPeopleAsync()
        {
            IList<PersonModel> returnValue = null;

            var container = new PCLSampleService.Container(new Uri("http://localhost:2852/odata/"));
            var dsq = container.People;
            TaskFactory<IList<PersonModel>> tf = new TaskFactory<IList<PersonModel>>();
            await TaskEx.Delay(2000);        //서비스가 실행되기 전에 호출하면 오류가 발생해서 지연 시킴
            returnValue = await tf.FromAsync(dsq.BeginExecute(null, null), iar =>
            {
                var result = dsq.EndExecute(iar);
                if (result != null)
                {
                    return result.ToList();
                }
                else
                {
                    return null;
                }
            });
            return returnValue;
        }

    }

 

6. Output

 

Silverlight5 Id:1 Name:kaki104 Age:20 Sex:True
Silverlight5 Id:2 Name:kaki105 Age:21 Sex:False
Silverlight5 Id:3 Name:kaki106 Age:22 Sex:True
Silverlight5 Id:4 Name:kaki107 Age:23 Sex:False
Silverlight5 Id:5 Name:kaki108 Age:24 Sex:True

 

7. Database

 

 

database에 Seed로 입력한 값이 들어가 있는 것을 알 수 있다.

 

8. 마무리

위와 같은 동일한 과정으로 Service References를 추가하고 사용하는 것을 Windows 8 store app, WPF에서도 동일하게 작업 했다.

자세한 사항은 아래 소스를 참고 하기 바란다.

 

9. 소스

SkyDrive link

http://sdrv.ms/18gTb1U

 

nuget package가 빠진 소스이며, 솔루션에서 마우스 오른쪽 클릭해서

Manage NuGet Packages for Solution..을 선택 하신 후 Restore를 선택하면 자동 인스톨 됨

nuget package가 포함된 소스가 필요하다면 리플로 신청 요망(메일주소와 함께)

 

반응형
댓글