Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I made a web service that connects to a database hosted in SQL Server 2008 R2 on my local computer, and makes some operations on it.

This is the connection string in the web service:

C#
conn = new SqlConnection("Data Source=amir-pc\\SQLEXPRESS;User Id=sa;Password=1234; Initial Catalog=Election;Integrated Security=True");


It works well and successfully accesses the database and runs right.

Now I want to add this web service to IIS.

I successfully added it on Windows 7 to the IIS and can run it from the browser.

localhost/election_service/service.asmx

but when I tried to call a function that checks the connection, it failed, and I don't know why. This is the function:

C#
[WebMethod]
    public string Check_conn()
    {
        try
        {
            conn.Open();
            conn.Close();
            return "ok";
        }
        catch 
        {
            return "failed";
        }
    }

Is there any modification I must to do to be able to access the database?
Posted

1 solution

Amir

Have you instantiated the conn object with the above mentioned connection string?

Also do check if the connection is already open or not, since if the connection is already open the conn.open will throw InvalidOperationException exception resulting in your function returning false in catch statement. So ideally check this:

C#
public string Check_conn()
   {
       try
       {
           if(!conn.IsOpen)
           {
             conn.Open();
             conn.Close();
           }
           return "ok";
       }
       catch
       {
           return "failed";
       }
   }


Regards
Pawan
 
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