Windows应用程序从Web服务器获取数据

问题描述:

嗨朋友们,



我有一个需要从网络服务器检索一些信息的Windows应用程序。

并且,SQL Server不对公众开放。所以我创建了一个ASP.NET页面,它读取数据并将数据作为XML发回。我将在我的应用程序中使用它并处理它。

这是正确的方式吗?或者我应该使用任何其他技术?

这是我的ASPNet代码,它以XML格式发送数据...



Hi friends,

I have a windows application that needs to retrieve some information from the webserver.
And, the SQL Server is not open to the Public. So I created one ASP.NET page that reads the data and sends back the data as XML. I will use this in my application and process it.
Is this the right kind of way? or should I use any other technologies ??
This is my ASPNet Code that sends the data as XML...

protected void Page_Load(object sender, EventArgs e)
      {
          try
          {
              Response.ContentType = "text/plain";
              string u_id_str = (Request["userid"] != null ? Request["userid"] : ""), hdd_code = (Request["hdcode"] != null ? Request["hdcode"] : "");
              if (u_id_str != "")
              {
                    int u_id = -1;
                    if (Int32.TryParse(u_id_str, out u_id))
                    {
                        SqlConnection con = new SqlConnection("Data Source=SQLServerName;Initial Catalog=DB;User Id=Username;Password=Password");
                        SqlCommand com = new SqlCommand();
                        com.Connection = con;
                        con.Open();
                        com.CommandText = "SELECT UserID FROM vw_Users WHERE UserId = " + u_id;
                        SqlDataReader dread = com.ExecuteReader();
                        if (dread.Read())
                        {
                            if (!dread.IsClosed) dread.Close();
                            com.CommandText = "SELECT * FROM fconvwpurchased WHERE customerid = " + u_id + " AND expirydate > '" + DateTime.Today.ToString("dd/MMM/yyyy") + "'";
                            DataSet DsPurchased = new DataSet("LicenseList");
                            DataTable DtPurchased = new DataTable("fconvwpurchased");
                            DsPurchased.Tables.Add(DtPurchased);
                            SqlDataAdapter sdad = new SqlDataAdapter(com);
                            sdad.Fill(DtPurchased);
                            if (DtPurchased.Rows.Count > 0 )
                            {


                                foreach (DataRow drr in DtPurchased.Rows)
                                {
                                    com.CommandText = "SELECT COUNT(sl) FROM fcontblLicenses WHERE productcode = '" + drr["ProCode"].ToString() + "' AND customerid = " + u_id;
                                    if (com.ExecuteScalar() != null && com.ExecuteScalar() != DBNull.Value)
                                    {
                                        drr["qty"] = Convert.ToInt32(drr["qty"]) - Convert.ToInt32(com.ExecuteScalar());
                                        DtPurchased.AcceptChanges();
                                    }
                                }

                                StringWriter sw = new StringWriter();
                                DsPurchased.WriteXml(sw);
                                Response.Write(sw.ToString());

                            }
                            else
                            {
                                Response.Write("NO_DATA");
                            }

                        }
                        else
                            Response.Write("NO_USER");
                        if (!dread.IsClosed) dread.Close();
                        con.Close();

                    }
                    else
                        Response.Write("NO_USER");
              }
              else
                  Response.Write("NO_USER");

          }
          catch
          {
              Response.Write("ERROR");
          }
      }







和我的Windows应用程序,我正在使用这个...






and for my Windows Application, I am using this...

private string HttpRequestServer(string urltoconnect, string postData)
        {
            try
            {
                // Create a request using a URL that can receive a post. 
                WebRequest request = WebRequest.Create(urltoconnect);
                // Set the Method property of the request to POST.
                request.Method = "POST";
                // Create POST data and convert it to a byte array.

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                // Clean up the streams.
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;
            }
            catch
            {
                return "ERROR";
            }
        }

1-您可以使用 CookieContainer 传递证书里面。在Web服务上验证用户。如果用户通过身份验证,则从CookieContainer收集信息并返回结果集



注意:在WebMethods上启用会话。帮助:可以查看此内容链接 [ ^ ]



2-不要将直接(内联)quries 用于数据库,因为它们非常危险,如果用户在参数内部传递特殊字符,则无法处理。使用存储过程,如果不是使用参数化quries 来保存自己的问题和注射。
1- You may use CookieContainer to pass Credentials inside. Authenticate user at web-service. If user authenticated then collect information from CookieContainer and return result-set

Note: Enable Session on your WebMethods. For Help: may review this link[^]

2- Do not use direct (inline) quries to database as they are very risky and can't handle if user pass special chracters inside parameters. Either use stored procedures, if not than Use Parametrized quries to save yourself of issues and injections.


你可以使用webservice或wcf服务。



,只需在窗口应用程序代码中添加服务的webreference。
you can use webservice or wcf service.

and simply add the webreference the of the service in your window application code.