How to build basic web service with ASP.NET in C# – step 1

Each web service begins as a stateless class with one or more methods that the remote clients call to invoke your code.

C# in Depth, 3rd EditionManaged Windows VPS Hosting

BookService is designed to allow remote clients to retrieve information about books provided by the store. The class provides GetBooks() method that returns a DataSet with the full set of books information. It also provides a GetBooksCount() method, which simply return the number of books in the database. In this case you need some basic ADO.NET code to provide these methods.

 

public class BooksService

{

private string connectionString;

public BooksService ()

{

string connectionString =

WebConfigurationManager.ConnectionStrings[“BookStore”].ConnectionString;

}

public int GetBooksCount()

{

SqlConnection con = new SqlConnection(connectionString);

string sql = “SELECT COUNT(*) FROM Books”;

SqlCommand cmd = new SqlCommand(sql, con);

// Open the connection and get the value.

con.Open();

int numBooks = -1;

try

{

numBooks = (int)cmd.ExecuteScalar();

}

finally

{

con.Close();

}

return numBooks;

}

public DataSet GetBooks()

{

// Create the command and the connection.

string sql = “SELECT ISBN, AuthorLName, AuthorFName, Title, ” +

“Pages, PriceĀ  FROM Books”;

SqlConnection con = new SqlConnection(connectionString);

SqlDataAdapter da = new SqlDataAdapter(sql, con);

DataSet ds = new DataSet();

// Fill the DataSet.

da.Fill(ds, “Books”);

return ds;

}

}

You can use GetBooks() and GetBooksCount() in any web page in the same project, because both methods are public.