티스토리 뷰

반응형

Portable Class Library에서 HttpClient를 사용하는 방법에 대해 간단하게 소개하려고 한다.

 

1. Portable Class Library Change Target Frameworks

* .Net Framework 4.5 (4.0도 가능할듯..)

* Silverlight 4 and higher

* Windows Phone 7.5 and higher

* .Net for Windows Store apps

 

2. 필요한 Nuget Package

 

* Base Class Library (BCL) Blog : 여기가 메인 이군요

http://blogs.msdn.com/b/bclteam/

 

* Microsoft HTTP Client Libraries

PCL에서 HttpClient를 사용하도록 해주는 패키지

 

* Async for .Net Framework 4, Silverlight 4 and 5, and Win...

PCL에서 Async, AWait를 사용하도록 해주는 패키지

이 라이브러리를 설치하면 Microsoft BCL Build Components, BCL Portablity Pack for .NET Framework 4, Silverlight 4...라는 라이브러리가 동시에 설치됨

http://blogs.msdn.com/b/bclteam/archive/2012/10/22/using-async-await-without-net-framework-4-5.aspx

 

* Json.NET

Json 데이터 처리를 위한 패키지

 

* WebUtility for Portable Class Library

WebUtility (HttpUtility) in Portable Class Library

PCL에서 HtmlDecode, HtmlEncode, UrlDecode, UrlEncode를 해주는 패키지

string decodedInput = WebUtility.HtmlDecode(encodedInput);
string encodedInput = WebUtility.HtmlEncode(Input);
string decodedUrl = WebUtility.UrlDecode(encodedUrl);
string encodedUrl = WebUtility.UrlEncode(url);

 

 

 

3. WebAPIBase.cs

 

    public abstract class WebAPIBase<T> : BindableBase
    {
        /// <summary>
        /// 베이스Uri
        /// </summary>
        private string baseUri;

        /// <summary>
        /// 서비스 Uri
        /// </summary>
        public string ServiceUri { get; set; }

        private ICollection<T> resultCollection;

        /// <summary>
        /// 결과 컬렉션
        /// </summary>
        public ICollection<T> ResultCollection
        {
            get { return resultCollection; }
            set
            {
                resultCollection = value;
                OnPropertyChanged("ResultCollection");
            }
        }

        /// <summary>
        /// 결과코드
        /// </summary>
        public string ResultCode { get; set; }

        /// <summary>
        /// 결과메시지
        /// </summary>
        public string ResultMsg { get; set; }

        /// <summary>
        /// 반환갯수
        /// </summary>
        public int NumOfRows { get; set; }

        private int pageNo;
        /// <summary>
        /// 페이지 번호
        /// </summary>
        public int PageNo
        {
            get { return pageNo; }
            set
            {
                pageNo = value;
                OnPropertyChanged("PageNo");
            }
        }

        private int totalCount;
        /// <summary>
        /// 전체 카운트
        /// </summary>
        public int TotalCount
        {
            get { return totalCount; }
            set
            {
                totalCount = value;
                OnPropertyChanged("TotalCount");
            }
        }

        /// <summary>
        /// 토탈 페이지 = totalCount / NumOfRows + 1
        /// </summary>
        public int TotalPage { get; set; }

        /// <summary>
        /// 생성자
        /// </summary>
        public WebAPIBase()
        {
            ResultCollection = new ObservableCollection<T>();
            baseUri = "http://localhost:2852";
            ServiceUri = "";
            NumOfRows = 30;
            PageNo = 1;

            this.PropertyChanged +=
                (s, e) =>
                {
                    switch (e.PropertyName)
                    {
                        case "TotalCount":
                            if (TotalCount > 0)
                            {
                                TotalPage = TotalCount / NumOfRows;
                                if ((TotalCount % NumOfRows) > 0)
                                    TotalPage++;
                            }
                            else
                            {
                                TotalPage = 0;
                            }
                            break;
                    }
                };
        }

        /// <summary>
        /// 조회
        /// </summary>
        protected async Task<string> GetData(string para)
        {
            string result = string.Empty;
            using (HttpClient hc = new HttpClient())
            {
                try
                {
                    var uri = string.Format("{0}{1}", baseUri, ServiceUri);
                    result = await hc.GetStringAsync(uri);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
            return result;
        }

        /// <summary>
        /// 조회
        /// </summary>
        public abstract Task<bool> Get(string para);

    }

 

4. TestWebAPI.cs

 

    public class TestWebAPI : WebAPIBase<PersonModel>
    {
        /// <summary>
        /// 인스턴스
        /// </summary>
        private readonly static TestWebAPI instance = new TestWebAPI();

        /// <summary>
        /// 인스턴스 프로퍼티
        /// </summary>
        public static TestWebAPI Instance
        {
            get
            {
                return instance;
            }
        }
       
        /// <summary>
        /// 생성자
        /// </summary>
        public TestWebAPI()
            : base()
        {
            ServiceUri = "/api/values";
        }

        /// <summary>
        /// WebAPI 호출
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public override async System.Threading.Tasks.Task<bool> Get(string para)
        {
            bool resultValue = false;

            var result = await GetData(para);
            if (!string.IsNullOrEmpty(result))
            {
                ResultCollection = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PersonModel>>(result);
                TotalCount = ResultCollection.Count;
                resultValue = true;
            }
            return resultValue;
        }

    }

 

5. MainViewModel.cs

 

    public class MainViewModel : BindableBase, IMainViewModel
    {
        public ObservableCollection<PersonModel> People { get; set; }

        public MainViewModel()
        {
            People = new ObservableCollection<PersonModel>();

            People.Add(new PersonModel { Id = 1, Name = "kaki104", Age = 11, Sex = true });
        }

        private async void GetPeople()
        {
            var result = await TestWebAPI.Instance.Get("");
            if (result == true)
            {
                foreach (var item in TestWebAPI.Instance.ResultCollection)
                {
                    People.Add(item);
                }
            }
        }

        private string _text;

        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                OnPropertyChanged("Text");
            }
        }

        private PersonModel person;

        public PersonModel Person
        {
            get { return person; }
            set
            {
                person = value;
                OnPropertyChanged("Person");
            }
        }

        private DelegateCommand getListCommand;
        public DelegateCommand GetListCommand
        {
            get
            {
                if (getListCommand == null)
                {
                    getListCommand = new DelegateCommand(
                        args =>
                        {
                            GetPeople();
                        });
                }
                return getListCommand;
            }
        }

        private DelegateCommand clearCommand;
        public DelegateCommand ClearCommand
        {
            get
            {
                if (clearCommand == null)
                {
                    clearCommand = new DelegateCommand(
                        args =>
                        {
                            People.Clear();
                        });
                }
                return clearCommand;
            }
        }
       

        private DelegateCommand personClickedCommand;
        public DelegateCommand PersonClickedCommand
        {
            get
            {
                if (personClickedCommand == null)
                {
                    personClickedCommand = new DelegateCommand(
                        args =>
                        {
                        });
                }
                return personClickedCommand;
            }
        }
    }

 

6. 결과

Silverlight 5와 Windows Phone 7.1에서 사용한 화면

 

현재 ViewModel까지 PCL에 올려놓고 WPF, Silverlight, Windows Phone, Windows 8 store app까지 함께 사용하는 방법에 대해 테스트 하는 중이라 전체 소스를 공개 하지는 않는다.

전에 facebook에서 HttpClient를 사용하지 못해서 안타까워하는 분이 있는 것 같아서 포스트 한다.

 

 

반응형
댓글