locked
How to use Return response with TASK in my web api and repository classes RRS feed

  • Question

  • User264732274 posted

    here i like to discuss my code

    see web api code

        [RoutePrefix("api/customer")]
        public class CustomerController : ApiController
        {
            static readonly ICustomerRepository repository = new CustomerRepository();
    
            [HttpGet, Route("GetAll")]
            public IEnumerable<Customer> GetAllCustomers()
            {
                return repository.GetAll();
            }
    
            [HttpGet, Route("GetByID/{customerID}")]
            public Customer GetCustomer(string customerID)
            {
                Customer customer = repository.Get(customerID);
                if (customer == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return customer;
            }
    
            [HttpGet, Route("GetByCountryName/{country}")]
            public IEnumerable<Customer> GetCustomersByCountry(string country)
            {
                return repository.GetAll().Where(
                    c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
            }
    
            public HttpResponseMessage PostCustomer(Customer customer)
            {
                customer = repository.Add(customer);
                var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
    
                string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
                response.Headers.Location = new Uri(uri);
                return response;
            }
    
            public void PutProduct(string customerID, Customer customer)
            {
                customer.CustomerID = customerID;
                if (!repository.Update(customer))
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
            }
    
            public void DeleteProduct(string customerID)
            {
                Customer customer = repository.Get(customerID);
                if (customer == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                repository.Remove(customerID);
            }
        }

    ICustomerRepository repository code

        public interface ICustomerRepository
        {
            IEnumerable<Customer> GetAll();
            Customer Get(string customerID);
            Customer Add(Customer item);
            bool Remove(string customerID);
            bool Update(Customer item);
        }

    ICustomerRepository code

        public class CustomerRepository : ICustomerRepository
        {
            private string ConnectionString = ""; // @"Server=192.168.6.2\BBAKOLKATA;Database=Northwind;User Id=sa;Password=tintin11#;";
            //NorthWindConnectionString
            public CustomerRepository()
            {
                ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
            }
    
            public IEnumerable<Customer> GetAll()
            {
                List<Customer> customers = new List<Customer>();
                string query = string.Format("SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax] FROM [Customers]");
    
                using (SqlConnection con =
                        new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
    
                        while (reader.Read())
                        {
                            Customer customer = new Customer();
                            customer.CustomerID = reader.GetString(0);
                            customer.CompanyName = reader.GetString(1);
                            customer.ContactName = reader.GetString(2);
                            customer.ContactTitle = reader.GetString(3);
                            customer.Address = reader.GetString(4);
                            customer.City = reader.GetString(5);
    
                            if (reader.GetValue(6) != null)
                            {
                                customer.Region = reader.GetValue(6).ToString();
                            }
                            else
                            {
                                customer.Region = string.Empty;    
                            }
    
                            if (reader.GetValue(7) != null)
                            {
                                customer.PostalCode = reader.GetValue(7).ToString();
                            }
                            else
                            {
                                customer.PostalCode = string.Empty;
                            }
    
                            customer.Country = reader.GetString(8);
                            customer.Phone = reader.GetString(9);
    
                            if(reader.GetValue(10) != null)
                            {
                                customer.Fax = reader.GetValue(10).ToString() ;   
                            }
                            else
                            {
                                customer.Fax = string.Empty;   
                            }
                            
                            customers.Add(customer);
                        }
                        con.Close(); 
                    }
                }
                return customers.ToArray();
            }
    
            public Customer Get(string customerID)
            {
                Customer customer = new Customer();
                string query = string.Format(" SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax] FROM [Customers] " +
                    "  WHERE CustomerID LIKE '%"+ customerID + "%'");
    
                using (SqlConnection con =
                        new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        
                        while (reader.Read())
                        {
                            customer.CustomerID = reader.GetString(0);
                            customer.CompanyName = reader.GetString(1);
                            customer.ContactName = reader.GetString(2);
                            customer.ContactTitle = reader.GetString(3);
                            customer.Address = reader.GetString(4);
                            customer.City = reader.GetString(5);
    
                            if (reader.GetValue(6) != null)
                            {
                                customer.Region = reader.GetValue(6).ToString();
                            }
                            else
                            {
                                customer.Region = string.Empty;
                            }
    
                            if (reader.GetValue(7) != null)
                            {
                                customer.PostalCode = reader.GetValue(7).ToString();
                            }
                            else
                            {
                                customer.PostalCode = string.Empty;
                            }
    
                            customer.Country = reader.GetString(8);
                            customer.Phone = reader.GetString(9);
    
                            if (reader.GetValue(10) != null)
                            {
                                customer.Fax = reader.GetValue(10).ToString();
                            }
                            else
                            {
                                customer.Fax = string.Empty;
                            }
                            
                        }
                        con.Close(); 
                    }
                }
                return customer;
            }
    
            public Customer Add(Customer item)
            {            
                string query = string.Format("INSERT INTO [Customers] " +
                            " ( [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country] " +
                            " ,[Phone], [Fax] ) VALUES " +
                           " ( '{0}', '{1}', '{2}', '{3}', '{4}',  '{5}', '{6}', '{7}', '{8}',  '{9}', '{10}' )", item.CustomerID, item.CompanyName, item.ContactName,
                           item.ContactTitle, item.Address, item.City, item.Region, item.PostalCode,  item.Country, item.Phone, item.Fax);
    
                using (SqlConnection con =
                        new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
    
                return item;
            }
    
            public bool Remove(string customerID)
            {
                string query = string.Format("DELETE FROM [Customers] WHERE CustomerID LIKE '{0}", customerID); 
    
                using (SqlConnection con =
                        new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
    
                return true;
            }
    
            public bool Update(Customer item)
            {
                string query = string.Format("UPDATE [Customers] " +
                        " SET [CustomerID] = '{0}'," +
                        " [CompanyName] = '{1}', " +
                        " [ContactName] = '{2}', " +
                        " [ContactTitle] = '{3}', " +
                        " [Address] = '{4}', " +
                        " [City] = '{5}', " +
                        " [Region] = '{6}', " +
                        " [PostalCode] = '{7}', " +
                        " [Country] = '{8}', " +
                        " [Phone] = '{9}', " +
                        " [Fax] = '{10}' " +
                        " WHERE CustomerID LIKE '{11}'", item.CustomerID, item.CompanyName, item.ContactName, item.ContactTitle, item.Address, item.City, item.Region,
                         item.PostalCode, item.Country, item.Phone, item.Fax, item.CustomerID);                    
                
                using (SqlConnection con =
                        new SqlConnection(ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
    
                return true;
            }
        }

    customer class code

        public class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactTitle { get; set; }
    
            public string Address { get; set; }
    
            public string Region { get; set; }
    
            public string PostalCode { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
            public string Phone { get; set; }
            public string Fax { get; set; }
        }

    now please give another set of code using my code where task will be used and return. i like to use task in my all web api action and also in repository too. i want to make my web api fully asynchronous.

    looking for modified code with task usage.

    another thing when we use task in web api then do we need to take any special care to write http client class just to call asynchronous web api action ?

    thanks

    Tuesday, August 23, 2016 1:32 PM

Answers

  • User36583972 posted

    Hi sudip_inn,

    You can use asynchronous in your Web API. You can refer the following example.

    WebAPI:

           [AllowAnonymous]
            [HttpGet]
            public async Task<string> testasync()
            {
                return await Task.Run(() => TestASS());
            }
    
            private string TestASS()
            {
                return "test app";
            }
    

    Client:

       using (var client = new System.Net.Http.HttpClient())
                {
                    // HTTP POST
                    var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var response = client.GetAsync("/api/Values").Result;
                    string s = await response.Content.ReadAsStringAsync();
                    Response.Write(s);
                }

    Asynchronous Programming in Web API /ASP.NET MVC:

    http://www.codeproject.com/Tips/805923/Asynchronous-programming-in-Web-API-ASP-NET-MVC

    please give another set of code using my code where task will be used and return. i like to use task in my all web api action and also in repository too. i want to make my web api fully asynchronous

    Please refer the solutions provide above and modify by yourself.

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 24, 2016 4:22 AM