C # Use Webservices to call WebServices for addition, deletion, modification, and query,

Source: Internet
Author: User

C # Use Webservices to call WebServices for addition, deletion, modification, and query,

The trainee tutor asked for a project to use Winform to call WebServices to implement the add, delete, modify, and query functions. Write down this blog as a summary of this project. If you have any suggestions, leave a message. Thank you for your correction.

1. First of all, when I received this project, I had no idea what WebServices were, so the first step was to figure out What WebServices was. Now there is a vague concept. For example, if www.weather.com.cn wants to query the daily weather conditions for users, it certainly cannot allow users to directly access its database. Therefore, www.weather.com.cn writes weather query methods into WebServices, allowing users to call these interfaces through WebServices to query the weather.

2. Next, because we publish a WebServices for others to call. Therefore, we need to configure the IIS server on the local machine. The procedure is as follows:

1 --> open the computer and find to uninstall or change the program

2 --> Find to enable or disable Windows.

3 --> point all the three items below (I don't know how to point them, I just clicked them all)

4 --> click "OK". At this time, the IIS configuration is complete.

5 --> now go to the service to find the IIS service. If you see this option, it should be noted that our IIS configuration is complete.

 

3. After IIS is configured, You can compile a Web program in.

1 --> Create an empty Web Application

2 --> at this time, we will see a ceshiWebServices project. Right-click to add a new project and select Web Service. The name is free.

3 --> now we can see a default Hello World method.

4 --> next we will release this Web service. The steps are as follows: (1) Right-click the project and click Publish. (2) follow the steps of the image.

 

 

 

 

 

 

 

 

At this point, our Web service should have been released.

5 --> next, let's go to the IIS server and have a look.

 

6 --> note that you need to enable directory browsing.

 

 

7 --> Find the right panel and Click Browse. If no problem exists, the following page appears. (Sometimes some inexplicable errors, such as 403,404,409 and so on, Baidu)

 

8 --> so far, WebServices has been released successfully.

 

4. Below we will use the Winform program to call this WebServices, because my goal is to call this WebServices to implement the add, delete, modify, and query function, so I will go directly to the code.

1 --> code implementation of the WebServices add, delete, modify, and query function (only 1 public class Infos: System. Web. Services. WebService

  2     {  3   4         [WebMethod]  5         public string HelloWorld()  6         {  7             return "Hello World";  8         }  9  10         [WebMethod] 11         public DataSet select(int userid,string username) 12         { 13             try 14             { 15                 DataSet ds = new DataSet(); 16                 string constr = "Data source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456"; 17                 using (SqlConnection con = new SqlConnection(constr)) 18                 { 19                     if (con.State == ConnectionState.Closed) 20                     { 21                         con.Open(); 22                     } 23                     string sql = "select * from TB_UserInfo where userid='" + userid + "' or username='" + username + "'"; 24                     SqlDataAdapter da = new SqlDataAdapter(sql, con); 25                     da.Fill(ds); 26                     con.Close(); 27                 } 28                 return ds; 29             } 30             catch (Exception ex) 31             { 32                 return new DataSet(); 33             } 34             35         } 36  47         [WebMethod] 48  49         public bool add(string UserID, string UserName, string UserSex, string UserAge, string UserPassword, string UserType) 50         {  51           string constr = "Data source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456"; 52           using (SqlConnection con = new SqlConnection(constr)) 53             { 54                string sql = "insert into TB_UserInfo values ('"+UserID+"','"+UserName+"','"+UserSex+"','"+UserAge+"','"+UserPassword+"','"+UserType+"')"; 55                 using (SqlCommand cmd = new SqlCommand(sql, con)) 56                 { 57                     try 58                     { 59                         con.Open(); 60                         cmd.ExecuteNonQuery(); 61                         con.Close(); 62                         return true; 63                     } 64                     catch (Exception ex) 65                     { 66                         return false; 67                     } 68                 } 69             } 70         } 71  72         [WebMethod] 73  74         public bool delete(string UserID,ref string errormessage) 75         { 76             string constr = "Data Source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456"; 77             using (SqlConnection con = new SqlConnection(constr)) 78             { 79                 string sql ="delete from TB_UserInfos where UserID='"+UserID+"'"; 80                 using (SqlCommand cmd = new SqlCommand(sql, con)) 81                 { 82                     try 83                     { 84                         con.Open(); 85                         cmd.ExecuteNonQuery(); 86                         con.Close(); 87                         return true; 88                     } 89                     catch (Exception ex)  90                     { 91                         errormessage=ex.Message.ToString(); 92                         return false; 93                     } 94                     95                 } 96             } 97         } 98  99         [WebMethod]100         public bool update(string UserID, string UserName, string UserSex, string UserAge, string UserPassword, string UserType, ref string errormessage)101         {102             string constr = "Data Source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456";103             using (SqlConnection con = new SqlConnection(constr))104             {105                 string sql = "update TB_UserInfo set UserName='"+UserName+"',UserSex='"+UserSex+"',UserAge='"+UserAge+"',UserPassword='"+UserPassword+"',UserType='"+UserType+"' where UserID='"+UserID+"'";106                 using (SqlCommand cmd = new SqlCommand(sql, con))107                 {108                     try109                     {110                         con.Open();111                         cmd.ExecuteNonQuery();112                         con.Close();113                         return true;114                     }115                     catch (Exception ex)116                     {117                         errormessage = ex.Message.ToString();118                         return false;119                     }120                 }     121                 122             }123         }124   }125     

2 --> because my WinForm is ready, perform the following operations on this basis.

The interface is as follows:

3 --> first, we need to reference the Web service address. We can find the address of the Web service just released, http: // localhost: 1666/Infos. asmx, because I did it directly on the basis of my previous work, the previous Web Service was created, and there was no written method in it, so I pasted my Web address.

Find the project where WinForm is located, right-click --> Add --> service reference

Enter the address of WebServices we released earlier. As I have added references, I will not try again here.

4 --> because we want to call WebServices, We need to instantiate it first.

The Code is as follows: (for reference only)

As I have just completed my work under the guidance of my teacher today, I am also confused about some code. So I will paste it here to help you continue to think and practice tomorrow.

Namespace WindowsFormsApplication14 {public partial class Form1: Form {private ServiceReference. infosSoapClient ws; // This saves the need to instantiate public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {// TODO: this line of code loads data into the table "dB_UserSystemDataSet.TB_UserInfo. You can move or delete it as needed. // This. tB_UserInfoTableAdapter.Fill (this. dB_UserSystemDataSet.TB_UserInfo); // LoadData (); ws = new ServiceReference. infosSoapClient (); // same as above} private void button#click (object sender, EventArgs e) {string UserID = txtUserID. text. trim (); string UserName = txtUserName. text. trim (); string UserSex = this. comboBox2.Text; string UserAge = txtUserAge. text; string UserPassword = txtUserPassword. text; str Ing UserType = this. comboBox3.Text; string errorinfo = ""; if (ws. add (txtUserID. text, txtUserName. text, this. comboBox2.Text, txtUserAge. text, txtUserPassword. text, this. comboBox3.Text, ref errorinfo) {MessageBox. show ("registered" + errorinfo);} else {MessageBox. show ("registration failed" + errorinfo) ;}} private void button2_Click (object sender, EventArgs e) {int UserAge = 0; try {int. parse (txtUserAge. text); User Age = Convert. toInt32 (txtUserAge. text);} catch (Exception) {MessageBox. show ("incorrect input", "Operation prompt", MessageBoxButtons. OKCancel, MessageBoxIcon. warning); return;} string errorinfo = ""; if (ws. update (txtUserID. text, txtUserName. text, this. comboBox2.Text, txtUserAge. text, txtUserPassword. text, this. comboBox3.Text, ref errorinfo) {MessageBox. show ("updated successfully");} else {MessageBox. show ("update failed") ;}} private void Button3_Click (object sender, EventArgs e) {DialogResult result = MessageBox. Show ("are you sure you want to delete it? "," Operation prompt ", MessageBoxButtons. OKCancel, MessageBoxIcon. warning); if (result = System. windows. forms. dialogResult. OK) {string errorinfo = ""; if (ws. delete (txtUserID. text, ref errorinfo) {MessageBox. show ("deleted successfully" + errorinfo);} else {MessageBox. show ("failed to delete" + errorinfo) ;}} private void button4_Click (object sender, EventArgs e) {DataSet ds = new DataSet (); if (comboBox1.SelectedIndex> = 0) {if (comboBox1.SelectedIndex = 0) {ds = ws. select (Convert. toInt32 (textBox1.Text), "");} else if (comboBox1.SelectedIndex = 1) {ds = ws. select (0, textBox1.Text);} dgv. dataSource = ds. tables [0];} // this. showResult ();}}}

Note the following:

When we update the statement in WebServices, we must go back to our WinForm project to update the service reference.

 

5 --> now we can call WebServices.

 

I wrote my blog for the first time and worked out the first project in my life in a strict sense. As a result, I am not excited, my thoughts are chaotic, and my articles are messy. Please forgive me and give me some valuable comments.

 

Add a little idle talk:

I feel that sometimes people are really cheap. When I was in college, I was lying in a dormitory every day and looking for something to do. Now, I want to really start to grow up, and somehow start to miss the boring time in the dormitory. I think this should be a fear, because all the things I encounter during my internship have never been touched by before, fear failure, and fear that I am not doing well. Like when I got this project, my first thought was not how to design it, but how to write code on my own. However, I want to find a video tutorial and the source code in one step. Later, I found that this is impossible. Even if I find the source code, it will not happen next time. Therefore, I should change my mind to a secondary school or a secondary school. If I encounter problems, I will find a solution. If I cannot solve the problem, I will ask my teacher or Baidu for advice. In this way, a project is created, and you can enjoy the problem solving process and have a sense of accomplishment.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.