C#WebService实战篇

以下仅是本人学习用,欢迎大家指正。

目的:构建对外接口,验证成功后方能返回数据

WebService对外接口不是全部对外公开,用户密码凭以下信息来来验证身份。

                调用ID                                   用户名                            密码                               数据库                  说明                                      
1001   test 123321 A 查询订单数据
1002 admin   111111 C 查询对账单
         

先根据ID,用户,密码来验证身份,如果身份通过,则自动匹配数据库A,然后返回相应的数据集,如果没通过,则返回异常代码或空结果。

 

 

 [WebMethod]
        public byte[] GET_CUSTOMER_TEST(string companyid, string userid, string userpwd)
        {
            string database = GetDatabase(companyid, userid, userpwd);
            if (database.Length>0)
            {
                try
                {
                    using (DataSet ds = SqlDataAdapter(server, database, "你的存储过程", CommandType.StoredProcedure, null))
                    {
                        if (ds != null)
                            return GetDataSetSurrogateZipBytes(ds);
                        else return null;
                    }
                }
                catch
                {
                    return null;
                }
            }
           else return null;
        }

因为是根据前台输入的ID号,来指定库名,所以:

 private string GetDatabase(string companyid, string userid, string userpwd)
        {
            try
            {
                SqlParameter[] sp = new SqlParameter[] { new SqlParameter("@companyid", companyid) ,
             new SqlParameter("@userid", userid) ,
             new SqlParameter("@userpwd", userpwd)        };
                using (DataSet ds = SqlDataAdapter("(local)", "study", "select dbs from users where @companyid=companyid and @userid=userid and @userpwd=userpwd", CommandType.Text, sp))
                {
                    if ((ds != null) && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {

                        return ValidDBS = ds.Tables[0].Rows[0]["DBS"].ToString();
                    }
                    else
                    {
                        return "";
                    }

                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
   

 

 

 

 private byte[] GetDataSetSurrogateZipBytes(DataSet ds)
        {
            DataSetSurrogate dss = new DataSetSurrogate(ds);
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, dss);
            byte[] buffer = ms.ToArray();
            byte[] Zipbuffer = Compress(buffer);
            return Zipbuffer;
        }
        //压缩压缩后的字节数组
        private byte[] Compress(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Stream zipStream = new GZipStream(ms, CompressionMode.Compress, true))
                {
                    zipStream.Write(data, 0, data.Length);
                    zipStream.Close();
                    ms.Position = 0;
                    byte[] buffer = new byte[ms.Length];
                    ms.Read(buffer, 0, int.Parse(ms.Length.ToString()));
                    return buffer;
                }
            }
        }

 

 private SqlConnection GetCon(string server, string database)
        {
            try
            {
                uid = "sa";
                pwd = "XXXX";
                return new SqlConnection("server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd + ";Pooling=true;Min Pool Size=0;Max Pool Size=300");

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

   private DataSet SqlDataAdapter(string server, string database, string Query, CommandType cmdtype, SqlParameter[] sp)
        {
            using (SqlConnection Conn = this.GetCon(server, database))
            {
                using (SqlCommand command = new SqlCommand(Query, Conn))
                {
                    command.CommandType = cmdtype;
                    if (sp != null && sp.Length > 0)
                    {
                        command.Parameters.AddRange(sp);
                    }
                    using (SqlDataAdapter adp = new SqlDataAdapter())
                    {
                        using (DataSet dataset = new DataSet())
                        {
                            try
                            {
                                adp.SelectCommand = command;
                                Conn.Open();
                                adp.Fill(dataset);
                                Conn.Close();
                                return dataset;
                            }
                            catch
                            {
                                Conn.Close();
                                dataset.Dispose();
                                adp.Dispose();
                                command.Dispose();
                                return null;
                            }
                            finally
                            {
                                Conn.Close();
                                dataset.Dispose();
                                adp.Dispose();
                                command.Dispose();
                            }
                        }
                    }
                }
            }
        }


这样服务器端就架设好了,前台代码如下:

  private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string companyid = this.textBox1.Text.Trim();
                string userid = this.textBox2.Text.Trim();
                string userpwd = this.textBox3.Text.Trim();
                 
                gridControl1.DataSource = new Class1().GetDsTest(companyid, userid, userpwd).Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

 

 

 public DataSet GetDsTest(string companyid, string userid, string userpwd)
        {
            try
            {
                byte[] zipbytes = WS.QSP_GET_CUSTOMER_TEST(companyid, userid, userpwd);
                if (zipbytes != null)
                    return ConvertToDataSet(zipbytes);
                else return NullDs();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 MYNWS.SviceInterface WS = new 我的WS.MYNWS.SviceInterface();
         public static byte[] Decompress(byte[] data)
         {
             try
             {
                 using (MemoryStream ms = new MemoryStream(data))
                 {
                     Stream zipStream = null;
                     zipStream = new GZipStream(ms, CompressionMode.Decompress);
                     byte[] dc_data = null;
                     dc_data = ExtractBytesFromStream(zipStream, data.Length);
                     return dc_data;
                 }
                 ///返回解压后的二进制数组
             }
             catch
             {
                 return null;
             }
         }

        public static byte[] ExtractBytesFromStream(Stream zipStream, int dataBlock)
        {
            try
            {
                byte[] data = null;
                int totalBytesRead = 0;
                while (true)
                {
                    Array.Resize(ref data, totalBytesRead + dataBlock + 1);
                    int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    totalBytesRead += bytesRead;
                }
                Array.Resize(ref data, totalBytesRead);
                return data;
            }
            catch
            {
                return null;
            }
        }
        public static DataSet ConvertToDataSet(byte[] ZipByte)
        {          
            try
            {               
                if (ZipByte != null)
                {
                    byte[] buffer = Decompress(ZipByte);
                    BinaryFormatter bf = new BinaryFormatter();
                    DataSetSurrogate dss= bf.Deserialize(new MemoryStream(buffer)) as DataSetSurrogate;
                    using (DataSet ds = dss.ConvertToDataSet())
                    {
                        return ds;
                    }
                }
                else { return null; }
            }
            catch (Exception ex) { throw ex; }
        }

        private DataSet NullDs()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn cl = dt.Columns.Add("id", typeof(string));
            DataRow dr = dt.NewRow();
            dr["id"] = "没有找到";
            dt.Rows.Add(dr);
            ds.Tables.Add(dt);
            return ds;
        }

 

 这里有几个问题:一是,每次都要去验证,去获取DBS,重复劳动了

其次,如果验证失败,如何返回错误编号,友好提示给前台,是验证失败了,不至于因为点不出数据来,CS端就不停的点不停的点,浪费资源。

网上还有其它的方法,还没有去实战,下一篇准备亲测一下(天下文章一大抄,害人不浅,所以我还是慢一点,实打实一点吧,笨人有笨人的办法)

posted @ 2013-08-05 11:25  永远的菜鸟@me  阅读(1420)  评论(0编辑  收藏  举报