Hiển thị các bài đăng có nhãn web service. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn web service. Hiển thị tất cả bài đăng

31 thg 3, 2012

Phương thức lấy CSDL SQL SERVER thông qua Web Service



//Phương thức lấy tên thành phố theo mã thành phố được truyền vào.
        public static Model.City GetCityIdOfNameCity(string cityId)
        {


         
            try
            {


                conn = new SqlConnection(cs);
                string sql = "SELECT cityName FROM city WHERE cityId = '" + cityId + "' ";
                SqlCommand cmd = new SqlCommand(sql, conn);
                conn.Open();
                reader = cmd.ExecuteReader();
                reader.Read();


                Model.City city = new Model.City();


            //    city.CityID = reader["cityId"].ToString();
                city.CityName = reader["cityName"].ToString();
            //    city.CityDescript = reader["cityDescription"].ToString();
                return city;
            }
            catch (Exception exp)
            {
                //Adding logging
                HttpContext.Current.Trace.Warn("Error", "Error in GetCityIdOfNameCity", exp);
            }
            finally
            {
                if (reader != null) reader.Close();
                if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;
        }



        //Phương thức lấy tất cả tên thành phố trong bảng "city"
        // Kết quả trả về là 1 List
        public static List<string> GetAllCity()
        {


            try
            {
                conn = new SqlConnection(cs);
                string sql = "SELECT cityName FROM city";
                SqlCommand command = new SqlCommand(sql, conn);
                conn.Open();
                reader = command.ExecuteReader();
                 List<string> _allCity = new List<string>();
                while (reader.Read())
                {
                    _allCity.Add(reader.GetString(0));
                }
                return _allCity;


            }
            catch (Exception)
            {
                HttpContext.Current.Trace.Warn("Error", "Error at GetAllCity !!!!");
            }
            finally
            {
                if (reader != null) reader.Close();
                if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;
        }


        //Phương thức lấy tất cả tên ngân hàng trong bảng "bank"
        // Kết quả trả về là 1 List

        public static List<string> GetAllBank()
        {


            try
            {
                conn = new SqlConnection(cs);
                string sql = "SELECT bankName FROM bank";
                SqlCommand command = new SqlCommand(sql, conn);
                conn.Open();
                reader = command.ExecuteReader();
                List<string> _allBank = new List<string>();
                while (reader.Read())
                {
                    _allBank.Add(reader.GetString(0));
                }
                return _allBank;


            }
            catch (Exception)
            {
                HttpContext.Current.Trace.Warn("Error", "Error at GetAllBank !!!!");
            }
            finally
            {
                if (reader != null) reader.Close();
                if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;




        }



        //Lấy các quận theo tên mã thành phố truyền vào
        public static List<string> GetDistrictOfCity(string cityId){

            try
            {
             
             
                conn = new SqlConnection(cs);
                string sql = "SELECT distrctName FROM district WHERE cityId = '" + cityId + "' ";
                SqlCommand command = new SqlCommand(sql, conn);
                conn.Open();
                reader = command.ExecuteReader();
                List<string> _allDist = new List<string>();
                while (reader.Read())
                {
                    _allDist.Add(reader.GetString(0));
                }
                return _allDist;
            }
            catch (Exception)
            {
                HttpContext.Current.Trace.Warn("Error", "Error at GetDistrict !!!!");
            }
            finally
            {
                if (reader != null) reader.Close();
                if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;


      }

     
        //Lấy các cây atm theo ngân hàng và quận trong thành phố
        public static List<string> getAtms(string bankId, string districtId)
        {
            try
            {




                conn = new SqlConnection(cs);
                string sql = "SELECT atmName FROM atm WHERE districtId = '" + districtId + "' AND  bankId = '" + bankId + "'";
                SqlCommand command = new SqlCommand(sql, conn);
                conn.Open();
                reader = command.ExecuteReader();
                List<string> _allAtms = new List<string>();
                while (reader.Read())
                {
                    _allAtms.Add(reader.GetString(0));
                }
                return _allAtms;
            }
            catch (Exception)
            {
                HttpContext.Current.Trace.Warn("Error", "Error at GetDistrict !!!!");
            }
            finally
            {
                if (reader != null) reader.Close();
                if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;


        }


database download tại đây : http://code.google.com/p/and-project-lbd/downloads/detail?name=data.rar&can=2&q=#makechanges

30 thg 3, 2012

Web Service kết nối đến CSDL SQL Server.

Hôm nay tôi sẽ trình này cách dùng Web service để kết nối đến CSDL. nhằm giúp các ứng dụng client có thể dễ dàng dùng CSDL cần thiết đang cần dùng.
cây thư mục của Project mà chúng ta sẽ thực hiện :



Ý tưởng : Ta có Database DBAtm.mdf có chứa 1 table với tên là city và các thuộc tính như cityId, cityName, cityDescription. Mục đính của chúng ta là sẽ viết 1 web service có thể gọi tìm kiếm theo cityId.

Đầu tiên các bạn tạo ra 1 class City.cs với nội dung sau :
Các phương thức set/get của các thuộc tính trong lớp này nhằm hiện thực các cột trong bảng city.





Sau đó các bạn vào Web.config thêm vào  thẻ <connectionString/> 1 thẻ <add/> với nội dung như sau :

<connectionStrings>
    <add name ="connStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ATMsService\ATMsService\data\DBAtm.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
  </connectionStrings>

Chú ý đến đoạn bôi dấu đỏ : đó chính là đường dẫn tuyệt đối đến thư mục data chứ CSDL của bạn.

Tiếp theo bạn tao 1 lớp DAL có mục đính nhằm kết nối đến CSDL và truy vấn nó.
Phương thức truy vấn của tôi như sau :


public static Model.City GetCity(string cityId)
        {
            SqlDataReader reader = null;
            SqlConnection conn = null;
            string cs = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            try
            {

                conn = new SqlConnection(cs);
                string sql = "SELECT cityId, cityName, cityDescription FROM city WHERE cityId = '" + cityId + "' ";
                SqlCommand cmd = new SqlCommand(sql, conn);
                conn.Open();
                reader = cmd.ExecuteReader();
                reader.Read();

                Model.City city = new Model.City();
                city.CityID = reader["cityId"].ToString();
                city.CityName = reader["cityName"].ToString();
                city.CityDescript = reader["cityDescription"].ToString();
                return city;
            }
            catch (Exception exp)
            {
                //Adding logging
                HttpContext.Current.Trace.Warn("Error", "Error in GetCity", exp);
            }
            finally
            {
                if (reader != null) reader.Close();
                if (conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;
        }




Bạn chỉ cần quan tâm đến những dòng đã được bôi đỏ.

Sau đó bạn tạo tiếp 1 class với tên BAL.cs với mục đính gọi lại phương thức GetCity của class DAL
như sau :

namespace Biz
{
    public class BAL
    {
        public static Model.City GetCity(string cityId)
        {
            Model.City city = DATA.DAL.GetCity(cityId);
            city.CityName = city.CityName + "ACME";
            return city;
        }
    }
}



Cuối cùng trong class ATMsService bạn gọi lại phương thức GetCity của lớp BAL với 1 câu lệnh duy nhất như sau.

[WebMethod]
        public Model.City GetCity(string cityId)
        {
            return Biz.BAL.GetCity(cityId);
        }

kết quả nhận được khi chúng ta chạy web service này như sau :
Trong table city của tôi có 1 bộ : [hcm,Thành phố HCM, Tỉnh thành Hồ Chí Minh, Việt Nam].
Tôi sẽ tìm kiếm bộ này theo tên : hcm.
kết quả như sau :


Bonus : phương thức lấy tất cả tên thành phố trong table city như sau :


   public static List<string> GetAllCity()
        {
            SqlDataReader reader = null;
            SqlConnection conn = null;
            string cs = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
            try
            {
                 conn = new SqlConnection(cs);
                 string sql = "SELECT cityName FROM city" ;
                 SqlCommand command = new SqlCommand(sql,conn);
                 conn.Open();
                 reader = command.ExecuteReader();
                 List<string> _allCity = new List<string>();
                while (reader.Read())
           {
                _allCity.Add(reader.GetString(0));
               }
                return _allCity;
 
            }
            catch (Exception)
            {
                HttpContext.Current.Trace.Warn("Error", "Error at GetAllCity !!!!");
            }finally{
                if(reader != null) reader.Close();
                if(conn != null && conn.State != ConnectionState.Closed) conn.Close();
            }
            return null;
        }
    }




Như vậy chúng ta đã có thể dùng web service truy xuất đến csdl sql server trên nền tàng .Net.
Bài sau mình sẽ dùng KSoap2 trên android để truy xuất CSDL từ Webservice này.

Download project tại đây : http://code.google.com/p/and-sungha-blog/downloads/detail?name=ATMsService.rar&can=2&q=#makechanges




Bản beta đầu tiên

Sau 6 tháng cả team cặm cụi làm việc điên cuồng, bản alpha cũng được giới thiệu ra toàn bộ công ty và được testing nội bộ công ty mà thôi. ...