Click here to Skip to main content
15,888,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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...

C#
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");
          }
      }



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

C#
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";
            }
        }
Posted
Comments
Herman<T>.Instance 11-Feb-14 7:06am    
I should place if (!dread.IsClosed) dread.Close();
con.Close();
in a Finally block
Yesudasan Moses 11-Feb-14 7:08am    
Thats out of scope naa ?
This is working fine,,, but I am concerned if this is the right technology to use...

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.
 
Share this answer
 
v3
you can use webservice or wcf service.

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900