In Visual Studio, click the File
menu, then New
and select Project
. Then find ASP.NET Empty Web Application
within Web
. Give it a sensible name and then click OK
. In the Solution Explorer, right-click the new project under the solution, click Add
and select New Item
and find Web Service
within Web
. Name it Data.asmx
and click Add
. You should then see the code behind your new web service Data
class.
Now you can declare your own class to represent a database record, e.g. see class Record
below. Then create instances of Record
in your GetData()
method by calling the Get*Type*() methods on the SqlDataReader
. You'll need to look at the data types on your database columns and call the appropriate method e.g. GetString()
, GetInt32()
etc...
class Data : System.Web.Services.WebService
{
public class Record
{
public string AccountType { get; set; }
public string PartDescription { get; set; }
public int PartNumber { get; set; }
public string OrderRef { get; set; }
public DateTime TransactionDate { get; set; }
}
[WebMethod]
public static List<Record> GetData(string param)
{
SqlConnection con = new SqlConnection(@"ConnectionString");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT type,desc,num,ref,date FROM foo", con);
SqlDataReader dr = cmd.ExecuteReader();
List<Record> records = new List<Record>();
while (dr.Read())
{
records.Add(new Record() {
AccountType = dr.GetString(0),
PartDescription = dr.GetString(1),
PartNumber = dr.GetInt32(2),
OrderRef = dr.GetString(3),
TransactionDate = dr.GetDateTime(4)
});
}
dr.Close();
con.Close();
return records;
}
}
Hint: it's better to add parameters to the query via the cmd.Parameters
collection rather than using string concatenation.
Now you should be in a position to run or deploy your web service and get the URL of its WSDL. For an example of calling from InfoPath, there is a nice walk-through here.