ASP.Net webservice with SQL Server database connectivity - asp.net

I'm a complete beginner in ASP.Net webservices can anyone point me to a good tutorial by which I may implement a web service with SQL Server database connectivity?
Thanks in advance

1. Create the Project in Visual Studio
go to Visual Studio>New Project(select .Net Framework 3.5) >ASP.net Web Service Application
This will create a web service with a HelloWorld example like
public string HelloWorld()
{
return "Hello World";
}
2. Create a Database and Obtain the connection string
3. Define WebMethod
To create a new method that can be accessed by clients over the network,create functions under [WebMethod] tag.
4.Common structure for using database connection
add using statements like
using System.Data;
using System.Data.SqlClient;
Create an SqlConnection like
SqlConnection con = new SqlConnection(#"<your connection string>");
create your SqlCommand like
SqlCommand cmd = new SqlCommand(#"<Your SQL Query>", con);
open the Connection by calling
con.Open();
Execute the query in a try-catch block like:
try
{
int i=cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
con.Close();
return "Failed";
}
Remember ExecuteNonQuery() does not return a cursor it only returns the number of rows affected,
for select operations where it requires a datareader,use an SqlDataReader like
SqlDataReader dr = cmd.ExecuteReader();
and use the reader like
using (dr)
{
while (dr.Read())
{
result = dr[0].ToString();
}
dr.Close();
con.Close();
}

Here is a video that will walk you through how to retrieve data from MS SQL Server in ASP.NET web service.

Related

c# asp.net waiting for state in db to change

I am building a web application where a job submitted by user is handled by a background service and the communication between web app and background service is done on database. So when a search starts, web application inserts a record into db and waits till the status field of the record changes. As I understand, if I implement this on the request thread, I am blocking one of the pool threads unnecessarily, but cannot get my head around to do this asynchronously. What is the best practice in this case?
SQLDependency is very useful, but on the server side it provided only half the solution. I overcame the other half by using SignalR to signal the client that the query is over. In the end it was quite an efficient and elegant solution. Thanks for the info!
public class KYHub : Hub
{
void OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= OnChange;
if (e.Info != SqlNotificationInfo.Error && e.Info != SqlNotificationInfo.Delete)
{
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["cnnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SearchResult result= SearchResult.Parse(conn, Caller.TaskID);
conn.Close();
Caller.endsearch(result);
}
}
public void Search(SearchParam search)
{
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["cnnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
search.ClientID = Caller.id;
int QueryID = search.Save(conn);
Caller.TaskID = QueryID;
SqlCommand cmd = new SqlCommand(String.Format("SELECT Completed FROM dbo.Tasks WHERE TaskID={0}", QueryID), conn);
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += OnChange;
cmd.ExecuteReader();
conn.Close();
}
}
If you are using SQL Server as your DB then you can use a ADO.NET feature called SQLDependency,
What this dose when setup correctly is, when ever there is a change in table (which you will configure) a C# event will be raised.
Here is a article that expains it
Note: You will have to setup your SQL server to enable this.
http://www.codeproject.com/Articles/12335/Using-SqlDependency-for-data-change-events
And this one expains how to refresh page after data in table has changed
http://msdn.microsoft.com/en-us/library/e3w8402y%28v=vs.80%29.aspx

Database Queries don't run but neither are the SQL Exceptions Thrown

I am running C# .NET code where I need to test certain values that have been entered in a web page form and then passed to the server. The server then uses those values
in a query string to return a value. I encase these query instructions within a try-catch block in order to trace any Sql exceptions.
The problem is this:
Once the application has started, the connection string is set, and the query is run, I don't get a stack trace from the catch block's SQL Exception but instead
I just get a blank/empty value within the method that ran the query. The method will return a Boolean variable to indicate if there was any value read from the query and if so it returns true however it always returns false which should not happen because I have checked the query string that it builds by pasting it into MS SQL 2008's Query Console and running it. The results from running the pasted SQL instruction test does produce non-null data from the query. Thank much for your help.
I'm running VS2003 with IIS 6.0 and using MS SQL 2008 Enterprise Studio
Here is the code segment for the web.config and C# code. Thanks much for your help.:
<system.web>
<!-- DYNAMIC DEBUG COMPILATION
Set compilation debug="true" to enable ASPX debugging. Otherwise, setting this value to
false will improve runtime performance of this application.
Set compilation debug="true" to insert debugging symbols (.pdb information)
into the compiled page. Because this creates a larger file that executes
more slowly, you should set this value to true only when debugging and to
false at all other times. For more information, refer to the documentation about
debugging ASP.NET files.
-->
<compilation defaultLanguage="c#" debug="true" />
====================
//This method takes one string and returns either country name or Canadian state as a string, according to query.
private string candStateCountryCheck(string strQuery)
{
string strStateCountry = "";
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
try
{
string strConnection = ConfigurationSettings.AppSettings["OLEDBConnectionString"];
con = new SqlConnection(strConnection);
con.Open();
cmd = new SqlCommand(strQuery, con);
sdr = cmd.ExecuteReader();
if(sdr.Read())
{
strStateCountry = sdr.GetString(0);
}
}
catch (Exception exc)
{
ErrorLabel.Text = "ERROR:" + exc.Message;
}
finally
{
if (sdr != null)
sdr.Close();
if (cmd != null)
cmd.Dispose();
if (con != null)
con.Close();
}
return strStateCountry;
}
This should work, but I think your should use ExecuteScaler for single result queries. I also encourage you to use parameterized queries:
while (sdr.Read())
{
strStateCountry = sdr.GetString(0);
}
ExucuteScaler example:
try
{
string strConnection = ConfigurationSettings.AppSettings["OLEDBConnectionString"];
using(SqlConnection con = new SqlConnection(strConnection))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(strQuery, con))
{
strStateCountry = (String)cmd.ExecuteScalar();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I'll try to avoid anything here that won't work with VS2003, but it's gonna be hard... VS2003 is getting pretty old now, and you know that the express edition of VS2010 is available for free, right?
Also, this is a re-write of your code to show a better example of how it should look, if it were using a fictional database. You did not share any of your database structure, any example data, or what a query might look like, so that's the best we can do for now:
private string candStateCountryCheck(string toTest)
{
string sql = "SELECT countryStateName FROM SomeTable WHERE ItemKey LIKE #Query + '%';";
try
{
string strConnection = ConfigurationSettings.AppSettings["OLEDBConnectionString"];
con = new SqlConnection(strConnection);
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#Query", SqlDbType.VarChar, 50).Value = toTest;
con.Open();
return cmd.ExecuteScalar().ToString();
}
catch (Exception exc)
{
ErrorLabel.Text = "ERROR:" + exc.Message;
}
finally
{
cmd.Dispose();
con.Dispose();
}
}
You NEVER want to write methods that expect fully-formed sql code as arguments.

Connecting an ASP.NET MVC application to MySQL

How can I point my ASP.NET MVC application to a MySQL database?
Once you download the MySQL ADO.NET Connector it's a simple matter of referencing the assembly in your project and writing the queries, the same way you would do in any other application, nothing specific MVC:
using (var connection = new MySqlConnection(ConnectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT name FROM foo;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("name"));
// TODO: do something with the name ...
}
}
}

SQLiteException: Unable to open the database file

I'm new to windows mobile programming and I'm trying to create a Windows Mobile 6 application using sqlite. Write now I have built a dummy test application where I try to read the contents of a an sqlite table.
The problem is that I keep receiving SQLiteException: Unable to open the database file.
My code is below:
using (var cn = new SQLiteConnection(#"Data Source=C:myfirsttest.s3db;"))
{
try
{
//Connect to SQLite database
cn.Open();
//Create the SQL Command
var cmd = new SQLiteCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM MyTable";
//Retrieve the records using SQLiteDataReader
var dr = cmd.ExecuteReader();
while (dr.Read())
{
//display records
var id = dr["ID"].ToString();
}
}
catch(Exception ex)
{
//display any exeptions
var except = ex.Message;
}
finally
{
cn.Close();
}
}
Can anyone help me please with that? Or suggest a tutorial where I can find how to setup sqlite in a windows mobile 6 project?
Windows CE (the base OS for WinMo) does not have drives nor does it have a concept of a working folder. This means that all paths must be fully qualified. You probably want something like:
new SQLiteConnection(#"Data Source=\myfirsttest.s3db;")
or
new SQLiteConnection(#"Data Source=\[my app path]\myfirsttest.s3db;")

asp.net connection open and close

Let say i have one asp.net application that is having some page that uses the connection continuesly.....
i have open the connection in class file in construscter ......
and i m accessing it using the object of the class....when ever database operation are required...
in start the application is running fine....but after some operation with database in datagrid(ex. sorting,paging,other).... it's gets slow...and again start working after some time....
do you guys have any solution or any suggession for that.....
i have used the connection in following way....
public class student_operation
{
public SqlConnection cn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public SqlDataAdapter ad = new SqlDataAdapter();
public DataSet rs = new DataSet();
public DataSet rs1 = new DataSet();
public student_operation()
{
//
// TODO: Add constructor logic here
//
try
{
cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
cn.Open();
}
catch (Exception)
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
cn.Open();
}
}
}
}
Make sure you are opening AND closing your connection. Don't worry about "pooling" the connection. .Net will handle that for you automatically. Just open the connection, do your work and close the connection (even if that's done in the static part).
I don't see where you are closing your connection. I would implement IDisposable and clean everything up there. Then you can access your class in a using statement.

Resources