Dear members and administrators,
Hello everyone, a pleasant day.
I've been studying C# for quite sometime and now I am doing a very simple Web application and a Web Service in which this Web Service will handle all database commands such as open, close, add a record, delete, and edit. So far, I am still stuck in opening a database.
This is the code of my Web Service, the file name is
Service.asmx:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
private const string connectionString ="Server=MARK\\SQLEXPRESS2005;Database=SampleDatabase;Trusted_Connection=True;";
string sqlQuery;
DataSet dataSet;
bool isConnectionFailed;
SqlConnection sqlConnection;
public Service () {
}
[WebMethod]
public void connectToDatabase(){
sqlConnection = new SqlConnection(connectionString);
try {
sqlConnection.Open();
isConnectionFailed = false;
}
catch (Exception exception) {
isConnectionFailed = true;
}
finally { }
}
[WebMethod]
public string getConnectionMessage() {
string message="";
if (isConnectionFailed)
message = "Error while connecting to Microsoft SQL Server.";
else
message = "Connection SUCCESSFUL!!!";
return message;
}
}
I tested it and it works fine.
Then I created a new Solution/Project, a Web Application in C#. Afterwards, I added my WebService as a Web Reference to this Web Project(or Solution). This is the code of
Default.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace WebProject
{
public partial class _Default : System.Web.UI.Page
{
WebServiceDatabase.Service service = new WebProject.WebServiceDatabase.Service();
protected void Page_Load(object sender, EventArgs e)
{
service.connectToDatabase();
lblConnectionMessage.Text = service.getConnectionMessage();
}
}
}
I tested it and it works fine. The web browser(IE) displays the string:
Connection SUCCESSFUL!!!
BUT, when I tried to disconnect/stop the service of my SQL Server and try to run again the
Default.aspx, I am still recieving the same message (i.e.
Connection SUCCESSFUL!!!). Is not that I should be receiving
Error while connecting to Microsoft SQL Server because my SQL Server has stopped?
Can anyone help me how would I change my webservice code?
Thank you and more power.
Warm regards,
Mark