German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Database Access with Web Service using Visual Studio

Written by omerkamal on Jul 20, 2007
Create a web service for accessing the online Database using Visual Studio 2005/ Visual Web Developer Express version

Explanation:

Download Project: DatabaseService.zip

So there could be one of two situations for you to create a new web service. Follow the one match your situation. Either you are creating it as independent new project or you are creating it in an existing Project.

 

(a) Create a web service in as a new Project

 
 
  1. Create a new Project using Visual Studio or Visual Web Developer and Name it “DatabaseWebservice”

Create a new web service project

 

Create new Web Serice Project

 
  1. If you dock the Solution Explorer you will be able to see two files. i.e. “Service.asmx” in the Root Directory and “Service.cs” in the “App_code” Directory.
 

Solution Explorer

 
 
  1. The code which the environment spit out will look like this:
 
using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{

    public Service () {

 

        //Uncomment the following line if using designed components

        //InitializeComponent();

    }
 
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
   
}
 
 

 
 

(b) Create a web service in an existing Project

 
 
  1. Create the web service in an existing Project and name it “DatabaseWebservice”

Create a Web Service in an existing Project

Add new Item Dialoge
  
  
  1. You will have “DatabaseWebservice.asmx” in the root Directory and “DatabaseWebservice.cs” in the “App_code
  2. The code which the environment spit out would look like this:
 

using System;

using System.Web;

using System.Collections;

using System.Web.Services;

using System.Web.Services.Protocols;

 
 
///
/// Summary description for DatabaseWebservice
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class DatabaseWebservice : System.Web.Services.WebService {

 

    public DatabaseWebservice () {

 

        //Uncomment the following line if using designed components

        //InitializeComponent();

    }
 
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
   
}
 
 

(c) Add a web method to the Service

 

So you noticed that the only difference is how the Environment will name your service.

 
Now add a new method to the above code.
 
[WebMethod]
    public DataSet GetLatestCsharp()
    {

        using (SqlConnection connection = new SqlConnection(

ConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString))
        {

            string Query = @"SELECT TOP 5 * FROM [Articles]

            WHERE ([Branch] = @Branch) ORDER BY [DateAdded] DESC";

            SqlCommand command = new SqlCommand(Query, connection);

            command.CommandType = CommandType.Text;
            command.Parameters.Add(

            "@Branch", SqlDbType.NVarChar).Value = "CS";           

 
connection.Open();

            SqlDataReader reader = command.ExecuteReader();

 

            DataTable myTable = new DataTable("myTable");

            myTable.Columns.Add("Article Title", typeof(string));

            myTable.Columns.Add("Authour", typeof(string));           

            myTable.Columns.Add("Link", typeof(string));
 

            while (reader.Read())

            {
                myTable.Rows.Add(

                new object[] reader["Title"].ToString(),

                reader["AuthourName"].ToString(),

               "dotnet-friends.com/"+

                reader["Link"].ToString()});
            }
            myTable.AcceptChanges();

DataSet ds = new DataSet();

            ds.Tables.Add(myTable);
            ds.AcceptChanges();

            return ds;

        }

    }

 

You see that we are using ConfigurationManager and SQL Data Objects. So don’t forget to include the related following references to your service header:

 
using System.Configuration;
using System.Data;

using System.Data.SqlClient;

 
Now the Complete code will look like this:
 
using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

 

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService

{

    public Service () {

 

        //Uncomment the following line if using designed components

        //InitializeComponent();

    }
 
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
 
    ///
    /// Get Latest 5 Articles/Tutorial in C-Sharp catagory
    ///
    ///

    [WebMethod(Description = "Get latest Five Articles and Tutorials of C#, It returns Untyped Dataset")]

    public DataSet GetLatestCsharp()
    {
        using (SqlConnection connection = new SqlConnection(

ConfigurationManager.ConnectionStrings["MyConnStr "].ConnectionString))

        {

            string Query = @"SELECT TOP 5 * FROM [Articles] WHERE

([Branch] = @Branch) ORDER BY [DateAdded] DESC";

 

            SqlCommand command = new SqlCommand(Query, connection);

            command.CommandType = CommandType.Text;
            command.Parameters.Add(
"@Branch", SqlDbType.NVarChar).Value = "CS";
 
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

 

            DataTable myTable = new DataTable("myTable");

            myTable.Columns.Add("Title", typeof(string));
           myTable.Columns.Add("Authour", typeof(string));
            myTable.Columns.Add("Link", typeof(string));
 

            while (reader.Read())

            {
                myTable.Rows.Add(

new object[] reader["Title"].ToString(),

reader["AuthourName"].ToString(),
"https://dotnet-friends.com/"+ reader["Link"].ToString()});
            }
 
            myTable.AcceptChanges();
 

            DataSet ds = new DataSet();

            ds.Tables.Add(myTable);
            ds.AcceptChanges();

            return ds;

        }
    }
   
}
 

So how are you going to access the service now? For this purpose You have to create a web service client.

 

In the following Tutorial you will get to know that how can we create a Webservice Client:

>> Creating a Web Service Client in .NET 3.0 using C#

 

Download the code:      Download Project: DatabaseService.zip

Visitors/Readers Comments
(for questions please use The Forum)



Praveen
Excellent article and easy to understand!

19/11/2007 19:57:24 UTC

Victor
Why you didn't close connection object before returning DataSet????

08/01/2008 12:56:12 UTC

jomet
Thanks for this great article!

08/01/2008 22:28:15 UTC

Qureshi
Excellent and easy to understand

08/01/2008 23:33:24 UTC

Zubair

>Very good article my friend :)

08/01/2008 23:35:12 UTC

Max
so cool

09/01/2008 02:35:18 UTC

Robert
its very good article i designed a website http://www.beijingticketing.com its olympic tickets website user can buy olympic tickets form beijingticketing very easily

09/01/2008 04:12:17 UTC

maya

sweet and simple...............

09/01/2008 05:03:24 UTC

amar
very nice......... and easy to Understand

10/01/2008 22:29:58 UTC

sugumar
It is very easy to understand and explained in a simple English

22/01/2008 04:50:16 UTC

deep
its good but i want it in vb.net .plz provide it

06/02/2008 09:14:22 UTC

Eshwar

Its excellent and easy to grasp.

how to provide only the connection string information in a webservice and access the connection string from the webservice to my application. Can u plz help me on this.

12/02/2008 04:42:17 UTC

kalilraguman

what about folder settings

 

20/02/2008 23:42:42 UTC

Vishal
Really Good Article...Easy to understand

26/04/2008 16:29:00 UTC

Jeová Almeida
How do you publish the web service on a web site, for using on a real enviroment?

20/05/2008 12:56:13 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)