I m testing how to retrieve data from SQL Server in Web Service. I m using SQL Server 2008 R2, asp.net web service application project template in VS 2010.
Let’s say I have a table that has 4 columns and w/o any constaints(for the sake of conversation).
- FirstName
- LastName
- University
I want to be able to get all the values of my SQL table if a user inputs value for FirstName. Later I would change FirstName to NTID or some meaningful column.Right now my web service just returns single value let’s say LastName if a user types in FirstName.
Being a new to web services, I m trying to learn as much as I can and would greatly appreciate your time and effort in helping me out. TIA.
Where/how do I make changes at my code below
Here’s is my Data helper class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace EmployeeRecs
{
public class DataHelper
{
//create new method to get Employee record based on First Name
public static string GetEmployee(string firstName)
{
string LastName = "";
//Create Connection
SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");
//Sql Command
SqlCommand cmd = new SqlCommand("Select LastName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);
//Open Connection
con.Open();
//To Read From SQL Server
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
LastName = dr["LastName"].ToString();
}
//Close Connection
dr.Close();
con.Close();
return LastName;
}
}
}
And here’s my asmx.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace EmployeeRecs
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
//Create new web method to get Employee last name
[WebMethod]
public string GetEmployee(string firstName)
{
return DataHelper.GetEmployee(firstName);
}
}
}
Besides the SQL injection, a few things:
Create a DataContract and create a model for the data you want to return
Fill that model with your SQL Query results and return it from your service
Expose it:
Full Code from OP for posterity:
This might be useful to other folks struggling with the same situation. So I m posting my code for the solution:
Create a new WCF PRoject in VS 2010, I used .net version 3.5 and selected WCF Service Library under WCF template.
Here’s my code under IService1.cs
And here’s my code under Service1.cs