첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

[TestServer 프로젝트 실행 결과]

[TestClient 프로젝트 실행 결과]

TestSolution.zip
다운로드

[TestCommon 프로젝트]

▶ Product.cs

namespace TestCommon
{
    /// <summary>
    /// 제품
    /// </summary>
    public class Product
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public
 
        #region ID - ID
 
        /// <summary>
        /// ID
        /// </summary>
        public int ID { get; set; }
 
        #endregion
        #region 제품명 - Name
 
        /// <summary>
        /// 제품명
        /// </summary>
        public string Name { get; set; }
 
        #endregion
        #region 카테고리 - Category
 
        /// <summary>
        /// 카테고리
        /// </summary>
        public string Category { get; set; }
 
        #endregion
        #region 가격 - Price
 
        /// <summary>
        /// 가격
        /// </summary>
        public decimal Price { get; set; }
 
        #endregion
    }
}

 

728x90

 

[TestServer 프로젝트]

▶ ProductsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

using TestCommon;

namespace TestServer
{
    /// <summary>
    /// 제품들 컨트롤러
    /// </summary>
    public class ProductsController : ApiController
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 제품 리스트
        /// </summary>
        private static List<Product> _productList = new List<Product> 
        { 
            new Product { ID = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1      }, 
            new Product { ID = 2, Name = "Yo-yo"      , Category = "Toys"     , Price = 3.75M  }, 
            new Product { ID = 3, Name = "Hammer"     , Category = "Hardware" , Price = 16.99M } 
        };

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 제품 추가하기 - AddProduct(source)

        /// <summary>
        /// 제품 추가하기
        /// </summary>
        /// <param name="source">소스 제품</param>
        /// <returns>처리 결과</returns>
        [HttpPost]
        public IHttpActionResult AddProduct(Product source)
        {
            _productList.Add(source);

            return Ok("SUCCESS");
        }

        #endregion
        #region 제품 수정하기 - UpdateProduct(source)

        /// <summary>
        /// 제품 수정하기
        /// </summary>
        /// <param name="source">소스 제품</param>
        /// <returns>처리 결과</returns>
        [HttpPut]
        public IHttpActionResult UpdateProduct(Product source)
        {
            for(int i = 0; i < _productList.Count; i++)
            {
                Product product = _productList[i];

                if(product.ID == source.ID)
                {
                    _productList[i].Name     = source.Name;
                    _productList[i].Category = source.Category;
                    _productList[i].Price    = source.Price;

                    return Ok("SUCCESS");
                }
            }

            return Ok("NOUPDATE");
        }

        #endregion
        #region 제품 삭제하기 - DeleteProduct(id)

        /// <summary>
        /// 제품 삭제하기
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>처리 결과</returns>
        [HttpDelete]
        public IHttpActionResult DeleteProduct(int id)
        {
            for(int i = 0; i < _productList.Count; i++)
            {
                if(_productList[i].ID == id)
                {
                    _productList.RemoveAt(i);

                    return Ok("SUCCESS");
                }
            }

            return Ok("NODELETE");
        }

        #endregion

        #region 모든 제품 리스트 구하기 - GetAllProductList()

        /// <summary>
        /// 모든 제품 리스트 구하기
        /// </summary>
        /// <returns>모든 제품 리스트</returns>
        public List<Product> GetAllProductList()
        {
            return _productList;
        }

        #endregion
        #region 카테고리로 제품 리스트 구하기 - GetProductListByCategory(category)

        /// <summary>
        /// 카테고리로 제품 리스트 구하기
        /// </summary>
        /// <param name="category">카테고리</param>
        /// <returns>제품 리스트</returns>
        public List<Product> GetProductListByCategory(string category)
        {
            return _productList.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)).ToList();
        }

        #endregion
        #region 제품 구하기 - GetProduct(id)

        /// <summary>
        /// 제품 구하기
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>제품</returns>
        public IHttpActionResult GetProduct(int id)
        {
            Product product = _productList.FirstOrDefault(p => p.ID == id);

            if(product == null)
            {
                return NotFound();
            }

            return Ok(product);
        }

        #endregion
    }
}

 

300x250

 

▶ Program.cs

using System;
using System.Diagnostics;
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace TestServer
{
    /// <summary>
    /// 프로그램
    /// </summary>
    class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 프로그램 시작하기 - Main()

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        private static void Main()
        {
            string serverURL      = string.Format("http://127.0.0.1:{0}", 8080);
            string bindingAddress = string.Format("http://+:{0}/"       , 8080);

            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(serverURL);

            configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

            try
            {
                AddHTTPURLReservation(bindingAddress);

                using(HttpSelfHostServer server = new HttpSelfHostServer(configuration))
                {
                    server.OpenAsync().Wait();

                    Console.WriteLine("서버를 중단하기 위해서 아무 키나 눌러 주시기 바랍니다.");

                    Console.ReadKey(true);
                }
            }
            finally
            {
                DeleteHTTLURLReservation(bindingAddress);
            }
        }

        #endregion

        #region HTTP URL 예약 추가하기 - AddHTTPURLReservation(bindingAddress)

        /// <summary>
        /// HTTP URL 예약 추가하기
        /// </summary>
        /// <param name="bindingAddress">바인딩 주소</param>
        private static void AddHTTPURLReservation(string bindingAddress)
        {
            try
            {
                string argument = string.Format("http add urlacl url={0} user=everyone listen=yes", bindingAddress);

                ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", argument);

                processStartInfo.Verb            = "runas";
                processStartInfo.CreateNoWindow  = true;
                processStartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                processStartInfo.UseShellExecute = true;

                Process.Start(processStartInfo).WaitForExit();
            }
            catch
            {
            }
        }

        #endregion
        #region HTTP URL 예약 삭제하기 - DeleteHTTLURLReservation(bindingAddress)

        /// <summary>
        /// HTTP URL 예약 삭제하기
        /// </summary>
        /// <param name="bindingAddress">바인딩 주소</param>
        private static void DeleteHTTLURLReservation(string bindingAddress)
        {
            try
            {
                string argument = string.Format("http delete urlacl url={0}", bindingAddress);

                ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", argument);

                processStartInfo.Verb            = "runas";
                processStartInfo.CreateNoWindow  = true;
                processStartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                processStartInfo.UseShellExecute = true;

                Process.Start(processStartInfo).WaitForExit();
            }
            catch
            {
            }
        }

        #endregion
    }
}

 

[TestClient 프로젝트]

▶ Program.cs

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

using TestCommon;

namespace TestClient
{
    /// <summary>
    /// 프로그램
    /// </summary>
    class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region HTTP 클라이언트 구하기 - GetHTTPClient(baseAddress)

        /// <summary>
        /// HTTP 클라이언트 구하기
        /// </summary>
        /// <param name="baseAddress">기준 주소</param>
        /// <returns>HTTP 클라이언트</returns>
        private static HttpClient GetHTTPClient(string baseAddress)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(baseAddress);

            client.DefaultRequestHeaders.Accept.Clear();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return client;
        }

        #endregion

        #region 제품 추가하기 - AddProduct(client, product)

        /// <summary>
        /// 제품 추가하기
        /// </summary>
        /// <param name="client">클라이언트</param>
        /// <param name="product">제품</param>
        /// <returns>결과 코드 태스크</returns>
        private static async Task<string> AddProduct(HttpClient client, Product product)
        {
            string url = string.Format("api/products/");

            var response = await client.PostAsJsonAsync<Product>(url, product);

            if(response.IsSuccessStatusCode)
            {
                string resultCode = await response.Content.ReadAsAsync<string>();

                return resultCode;
            }

            return null;
        }

        #endregion
        #region 제품 수정하기 - UpdateProduct(client, product)

        /// <summary>
        /// 제품 수정하기
        /// </summary>
        /// <param name="client">클라이언트</param>
        /// <param name="product">제품</param>
        /// <returns>결과 코드 태스크</returns>
        private static async Task<string> UpdateProduct(HttpClient client, Product product)
        {
            string url = string.Format("api/products/");

            var response = await client.PutAsJsonAsync(url, product);

            if(response.IsSuccessStatusCode)
            {
                string resultCode = await response.Content.ReadAsAsync<string>();

                return resultCode;
            }

            return null;
        }

        #endregion
        #region 제품 삭제하기 - DeleteProduct(client, id)

        /// <summary>
        /// 제품 삭제하기
        /// </summary>
        /// <param name="client">클라이언트</param>
        /// <param name="id">ID</param>
        /// <returns>결과 코드</returns>
        private static async Task<string> DeleteProduct(HttpClient client, int id)
        {
            string url = string.Format("api/products/{0}", id);

            var response = await client.DeleteAsync(url);

            if(response.IsSuccessStatusCode)
            {
                string resultCode = await response.Content.ReadAsAsync<string>();

                return resultCode;
            }

            return null;
        }

        #endregion

        #region 모든 제품 리스트 구하기 - GetAllProductList(client)

        /// <summary>
        /// 모든 제품 리스트 구하기
        /// </summary>
        /// <param name="client">클라이언트</param>
        /// <returns>제품 리스트</returns>
        private static async Task<List<Product>> GetAllProductList(HttpClient client)
        {
            string url = string.Format("api/products/");

            HttpResponseMessage response = await client.GetAsync(url);

            if(response.IsSuccessStatusCode)
            {
                List<Product> productList = await response.Content.ReadAsAsync<List<Product>>();

                return productList;
            }

            return null;
        }

        #endregion
        #region 카테고리로 제품 리스트 구하기 - GetProductListByCategory(client, category)

        /// <summary>
        /// 카테고리로 제품 리스트 구하기
        /// </summary>
        /// <param name="client">클라이언트</param>
        /// <param name="category">카테고리</param>
        /// <returns>제품 리스트</returns>
        private static async Task<List<Product>> GetProductListByCategory(HttpClient client, string category)
        {
            string url = string.Format("api/products/?category={0}", category);

            HttpResponseMessage response = await client.GetAsync(url);

            if(response.IsSuccessStatusCode)
            {
                List<Product> productList = await response.Content.ReadAsAsync<List<Product>>();

                return productList;
            }

            return null;
        }

        #endregion
        #region ID로 제품 구하기 - GetProductByID(client, id)

        /// <summary>
        /// ID로 제품 구하기
        /// </summary>
        /// <param name="client">클라이언트</param>
        /// <param name="id">ID</param>
        /// <returns>제품 태스크</returns>
        private static async Task<Product> GetProductByID(HttpClient client, int id)
        {
            string url = string.Format("api/products/{0}", id);

            HttpResponseMessage response = await client.GetAsync(url);

            if(response.IsSuccessStatusCode)
            {
                Product product = await response.Content.ReadAsAsync<Product>();

                return product;
            }

            return null;
        }

        #endregion

        #region 프로그램 시작하기 - Main()

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        private static void Main()
        {
            List<Product> productList = null;

            Product product = null;

            using(HttpClient client = GetHTTPClient("http://localhost:8080/"))
            {
                Console.WriteLine("제품을 추가합니다.");
                Console.WriteLine("--------------------------------------------------");

                Product source = new Product();

                source.ID       = 4;
                source.Name     = "제품1";
                source.Price    = 10m;
                source.Category = "그룹1";

                AddProduct(client, source).GetAwaiter().GetResult();

                Console.WriteLine("");
                Console.WriteLine("제품을 수정합니다.");
                Console.WriteLine("--------------------------------------------------");

                source.Name     = "제품2";
                source.Category = "그룹2";

                UpdateProduct(client, source).GetAwaiter().GetResult();

                Console.WriteLine("");
                Console.WriteLine("모든 제품을 조회합니다.");
                Console.WriteLine("--------------------------------------------------");

                productList = GetAllProductList(client).GetAwaiter().GetResult();

                for(int i = 0; i < productList.Count; i++)
                {
                    product = productList[i];

                    Console.WriteLine("{0}, {1}, {2}, {3}", product.ID, product.Name, product.Category, product.Price);
                }

                Console.WriteLine("");
                Console.WriteLine("제품을 삭제합니다.");
                Console.WriteLine("--------------------------------------------------");

                DeleteProduct(client, source.ID).GetAwaiter().GetResult();

                Console.WriteLine("");
                Console.WriteLine("모든 제품을 조회합니다.");
                Console.WriteLine("--------------------------------------------------");

                productList = GetAllProductList(client).GetAwaiter().GetResult();

                for(int i = 0; i < productList.Count; i++)
                {
                    product = productList[i];

                    Console.WriteLine("{0}, {1}, {2}, {3}", product.ID, product.Name, product.Category, product.Price);
                }

                Console.WriteLine("");
                Console.WriteLine("특정 제품을 조회합니다.");
                Console.WriteLine("--------------------------------------------------");

                product = GetProductByID(client, 3).GetAwaiter().GetResult();

                Console.WriteLine("ID       : {0}", product.ID      );
                Console.WriteLine("제품명   : {0}", product.Name    );
                Console.WriteLine("가격     : {0}", product.Price   );
                Console.WriteLine("카테고리 : {0}", product.Category);

                Console.WriteLine("");
                Console.WriteLine("카테고리로 제품 리스트를 조회합니다.");
                Console.WriteLine("--------------------------------------------------");

                productList = GetProductListByCategory(client, "Hardware").GetAwaiter().GetResult();

                for(int i = 0; i < productList.Count; i++)
                {
                    product = productList[i];

                    Console.WriteLine("{0}, {1}, {2}, {3}", product.ID, product.Name, product.Category, product.Price);
                }

                Console.WriteLine("--------------------------------------------------");

                Console.WriteLine("아무 키나 눌러 주시기 바랍니다.");

                Console.ReadKey(true);
            }
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요