Web服务小试牛刀
写文章喽~
楔子:
为么我会误打误撞的学了一下午WebService呢,因为我要交一个公选课作业。而这个公选课啊,本身本屌是没选上的。选了一个别的,后来,那个任课老师(我们专业的),希望我们选他的课。就开始跑教务处给我们调,本来说是调不过来了,但是就在这个公选课结课前三天,也就是昨天,我才知道。。奶奶的,我有了这门课,而且是和之前的那个课共存的,一个学期一个学生原则上是只能选一门课的。但是这样一开我发现自己要交两门公选作业,而这个的作业就是从2012“齐鲁软件设计大赛”选一个。思来想去,就选了这个最速成的WebService,为么说他是最速成的呢,因为其他的比如J2ME啊 android开发啊WP7的搭建环境太麻烦。。。。
正文:
还得交这个的报告,干脆先写博客抒发一下了
正正文:
这里所做的呢,就是自己写一个web service 然后在自己的网页和winform中调用。我没有发布,只是用的本机的虚拟路径,然后在同一个解决方案里引用的。
是以股票价格为例的,也就是你发布一个Web服务吧(股价),别人在自己的网页里可以引用,在自己的windowsForm里也可以。
话不多说,上教程啊
第一步:
建立一个空的解决方案
然后想这个空的解决方案添加一个asp.net Web服务,注意,这个地方要选.net framework2.0.不选2.0的话容易遇到兼容性问题,所以建议选择2.0 。

然后,现在添加数据库 我把它叫做bankDB.mdf

然后打开试图里的“服务器资源管理器”,在里面加一个表“Stock”,编写表如下:


添加了之后呢,在里面的App _Code加两个文件夹,这两个文件夹是至关重要的,因为他两分别代表了三层架构思想中的业务逻辑层和数据层
图如下
 Business文件夹下的StockSystem.cs是业务逻辑层。DataAccess文件夹下的Stock.cs是数据层
Business文件夹下的StockSystem.cs是业务逻辑层。DataAccess文件夹下的Stock.cs是数据层
他俩的源码如下
Stock:
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Data; 5 using System.Data.SqlClient; 6 /// <summary> 7 ///Stock 的摘要说明 8 /// </summary> 9 public class Stock 10 { 11 private SqlConnection conn; 12 private SqlConnection GetConnection() 13 { 14 if (conn == null || conn.State == ConnectionState.Closed) 15 conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\bankDB.mdf;Integrated Security=True;User Instance=True"); 16 return conn; 17 } 18 public DataSet Select(string selectSql) 19 { 20 DataSet ds = new DataSet(); 21 SqlDataAdapter adapter = new SqlDataAdapter(selectSql, this.GetConnection()); 22 adapter.Fill(ds, "Stock"); 23 return ds; 24 } 25 public bool Insert( 26 string name, float startPrice, float endPrice, float kcd, double sum, DateTime date 27 ) 28 { 29 string sql = string.Format("insert into Stock values ('{0}','{1}','{2}','{3}','{4}','{5}')", name, startPrice, endPrice, kcd, sum, date); 30 SqlCommand cmd = new SqlCommand(sql, this.GetConnection()); 31 try 32 { 33 cmd.Connection.Open(); 34 cmd.ExecuteNonQuery(); 35 36 } 37 catch (SqlException e) 38 { 39 Console.WriteLine(e.Message); 40 return false; 41 } 42 finally 43 { 44 cmd.Connection.Close(); 45 } 46 return true; 47 } 48 }
StockSystem:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | usingSystem;usingSystem.Collections.Generic;usingSystem.Web;usingSystem.Data;usingSystem.Data.SqlClient;/// <summary>///StockSystem 的摘要说明/// </summary>publicclassStockSystem{    Stock stock = newStock();    publicDataSet GetOneStockByName(stringname)    {        stringselectSql = string.Empty;        if(name.ToUpper() == "ALL") selectSql = "select * from Stock";        else            selectSql =string.Format ("select * from Stock where Name='{0}'",name) ;        returnstock.Select(selectSql);    }    publicboolInsertStock(        stringname, floatstartPrice, floatendPrice, floatkcd, doublesum, DateTime date        )    {        if(startPrice > 0 && endPrice > 0 && kcd > 0)            returnstock.Insert(name, startPrice, endPrice, kcd, sum, date);        else            returnfalse;    }} | 
然后添加一个新的名叫“StockService”的Web服务,通过添加新项的方式建立(在web项目上右键“添加新项”选择web服务),然后删掉原先默认生成的“Service.asmx”。在新建的StockService.cs添加如下代码
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | usingSystem;usingSystem.Collections.Generic;usingSystem.Web;usingSystem.Web.Services;usingSystem.Data;usingSystem.Data.SqlClient;/// <summary>///StockService 的摘要说明/// </summary>[WebService(Namespace = "MyStock")]publicclassStockService : System.Web.Services.WebService {    StockSystem stockManager = newStockSystem();    [WebMethod(Description = "按名字查询股票")]    publicDataSet GetstockByName(stringname)    {        returnstockManager.GetOneStockByName(name);    }    [WebMethod(Description = "插入一只股票")]    publicboolInsertStock(        stringname, floatstartPrice, floatendPrice, floatkcd, doublesum, DateTime date        )    {        returnstockManager.InsertStock(name, startPrice, endPrice, kcd, sum, date);    }    } | 
现在三层架构完成两层了。。。
但是这个Web服务还没发布出去,发布到网络上的IIS服务器现在本人还不会,只是发在本机上的虚拟目录里。
首先 打开 控制面板 管理工具 Internet信息服务
单击 网站 默认网站 右击默认网站 选择 添加虚拟目录 选择刚刚建立WebService的文件夹,就是第一张图里面的那个位置的目录
添加的时候会让你起一个别名,我在这里叫“StockService13”
添加之后是如下效果:

然后再右击StockService13,选择转为应用程序,这里很简单,进去取个名字就行了,建议跟之前的那个“别名”一致.
完成然后退出
下面是界面层
向解决方案添加一个Windows项目和一个ASP.NET网站项目,以显示咱们写的这个Web服务,可以被windows程序调用,也可以被网页调用。
前面讲到这个。。。数据层和业务逻辑层都构架好了,只剩下表面层的。下面说说表面层的事情:
右键 解决方案,添加新项,
“哎?我怎么没有这个解决方案呢,上来 就是那一个项目,别急,你没有让它显示出来。找到 工具 选项 项目和解决方案 勾选右边的 ‘总是显示解决方案’ ”
然后就可以了
右键 解决方案,添加新项,
选择 windows窗体,注意,这里也要选“.net 2.0”,这是为了避免出现兼容性问题。而且也是为了一会找web服务好找,如果用的是3.5的话,默认web服务是在兼容里面,不是很好找,也不是很兼容
接着再以同样的方法,添加一个ASP.NET网站项目。
添加完了之后,在你的解决方案管理器里面,就是这个样的了

现在引用刚刚我们发布在本机的服务
右键 web 这个项目 选择 添加web引用

然后选择”此方案中的Web服务”或者:“本地计算机上的web服务”都可以,因为笔者咋发布服务时遇到了如下错误,只能是选择‘此解决方案中的Web服务’了
就是这个错误

所以无奈只能选择了 此解决方案的那一个 ,然后在添加引用那里给它取个名
然后下面的工作就比较好做了
在你的Web里添加一个GridView一个textBox一个button 为button添加代码如下
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | usingSystem;usingSystem.Collections.Generic;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Data;usingSystem.Data.SqlClient;publicpartialclass_Default : System.Web.UI.Page {    protectedvoidPage_Load(objectsender, EventArgs e)    {    }    protectedvoidButton1_Click(objectsender, EventArgs e)    {        localhost13.StockService stockSev = newlocalhost13.StockService();        DataSet ds = stockSev.GetstockByName(TextBox1.Text.Trim());        this.GridView1.DataSource = ds.Tables[0].DefaultView;        this.GridView1.DataBind();    }} | 
注意 还要改一个地方 打开 web.config
改这个地方
<compilation debug="true">,原先是“false”,改成true。
然后编译一下。。。效果如下

在WinForm里面的工作肯定是轻车熟路 托一个datagridview拖一个 textBox 拖一个button 为button添加如下代码
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespaceWinForm{    publicpartialclassForm1 : Form    {        publicForm1()        {            InitializeComponent();        }        privatevoidbutton1_Click(objectsender, EventArgs e)        {            localhost13.StockService stockservice = newlocalhost13.StockService();            DataSet ds = stockservice.GetstockByName(textBox1.Text);            this.dataGridView1.DataSource = ds.Tables[0].DefaultView;        }    }} | 
运行一下效果如下

至此,这个简单的WebService就做完了 我们只添加了winform 的引用和web的引用,事实上,为手机的开发应该也是可以引用的,这也是未来的趋势。。。在这里先只演示前两项了。
 
                    
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号