Execute/Query against SQL Compact 4.0 in ASP.NET - asp.net

I'm writing a small little utility MVC app and I need to have the ability to execute ad-hoc queries against my one-table SQL Compact 4.0 .sdf file for management (Web Matrix isn't working right for development, and it won't be available on the PC this will ultimately be running on). Using Entity Framework code-first, everything is working fine, but to do an ad-hoc query, I figured I'd need to connect to it the way I would have in the pre-EF days (see below)
cn = new SqlConnection("Data Source=|DataDirectory|LocalScanData.sdf");
SqlCommand cmd = new SqlCommand(query, cn);
if (cn.State != ConnectionState.Open) cn.Open();
if (query.ToUpper().StartsWith("INSERT") || query.ToUpper().StartsWith("UPDATE") || query.ToUpper().StartsWith("DELETE"))
{
TempData["RowsAffected"] = cmd.ExecuteNonQuery();
return RedirectToAction("SQL");
}
else
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return RedirectToAction("SQL", dt);
}
But when I try that, I get A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server). So, the question, is how can I connect to a SQL CE 4.0 database the old fashioned way? I've also tried using System.Data.SqlServerCe but then I get errors that lead me to believe that only works for CE 3.5 databases.
Any help?

It happened to me, too. It is the way the sdf ddbb works, you can't execute a query against that. You have to create dataset, dataadapter and so on.

Related

Can you insert a new database connection in an existing database connection in OLEDB?

I am creating a program in which I am trying to have a new database connection in an existing database connection in OLEDB using ASP.net. Is that even possible?
"Connection within connection" is likely not what you have in mind. But there is no issue with having both OleDb and SQLServer connections operating together in one ASP.NET application, you can add these 2 or many more connections to one app.
Answer is yes. Please make sure you close the connections after using by using statement or close() explicitly. More here.
using (OleDbConnection connection1 = new OleDbConnection(connectionString1))
using (OleDbConnection connection2 = new OleDbConnection(connectionString2))
{
connection1.Open();
connection2.Open();
// Do something
}

Connecting MS SQL DataBase To GODADDY host

I am new to uploading websites online, I have uploaded my website to Godaddy host and run perfectly but i don't know how to connect my MS Sql Data base and how to configure my connection string ! can any one help me or give me a tutorial of how doing this starting from a normal MS sql Database with normal connection string(Local DB and Local connection string) until uploading it online ?
Connecting to a sql server database on go daddy works the same way as connecting to any other Sql Server db from a .Net perspective.
Log in to your go daddy account to get the connection string info. There's even code samples in there for how to configure your connection string.
Alos, here's a link about .net connection strings in general
http://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
One of the advantages of using MS SQL is that you can use the SqlClient native libraries, which are faster than ODBC, etc.
using System.Data;
using System.Data.SqlClient;
public class Demo {
public DataTable ConnectAndQuery() {
SqlConnection cn = new SqlConnection("Data Source=IP-GOES-HERE;Initial Catalog=YOUR-DATABASE-NAME-HERE;user id=DB-USER-HERE;password=DB-PASS-HERE;Connection Timeout=300");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM TableName", cn);
DataSet results = new DataSet();
da.Fill(results);
return results;
}
}
I usually store my connection strings in the web.config. There's actually a specific section you can store them in, if you'd like. Here's an example of that:
http://msdn.microsoft.com/en-us/library/dx0f3cf2(v=vs.85).aspx

asp.net MySql MySqlConnection - implement a connection pool or equivalent

It's my first time of using MySql on ASP.Net.
Unlike MSSql which I use quite often, I've noticed that using MySqlConnection to connect to the db takes ages (I mean a second or two),
MySql.Data.MySqlClient.MySqlConnection connection = new MySqlConnection(DBConnectionString);
Therefore I would like to know how can I implement a connection pool, or whatever recommended structure that could store one connection object (MySqlConnection) to be used across the application.
Is there a common practice for doing so or any other recommendations ?
Here's the code I'm using - maybe I'm doing something wrong here ?
MySql.Data.MySqlClient.MySqlConnection connection = new MySqlConnection(DBConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
if (connection.State != ConnectionState.Open)
{
try
{
connection.Open();
}
catch (MySqlException ex)
{
throw (ex);
}
}
MySqlCommand cmd = new MySqlCommand("SELECT this FROM that", connection);
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
cmd.Connection.Close();
According to the documentation it's on by default. Further, you're creating the instance with the connection string, so that's good, because it allows the connector to leverage the pool immediately. So, the fact that it's taking a second or two to create those connections is almost certainly unrelated to connection pooling and more related to the hardware you're providing MySQL in the environment you're working in.
The term hardware is really broad here because you could be dealing with everything from network to disk and memory related issues.
Do read the documentation - it does show you how to adjust the connection pooling - so that may help you. I make that statement because your question doesn't give us a lot of information surrounding exactly how you're using this server or these connections.

System.InvalidOperationException: Internal connection fatal error

Our staging web application on .Net 4.0 and SQL Server 2008 R2 was running smooth for more then 2 months.
All of a sudden, we started getting error in the application saying:
Error Message: System.InvalidOperationException: Internal connection fatal error.
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.HasMoreResults()
This comes whenever my data base query is returning more then ~700 rows.
Strangely, my production web site (with the same code base as the staging) runs well while connected to the staging data base.
I have tried connecting my staging web server to the production data base (similar copy of the staging data base) and i get the same error.
This error is interminent, some times the page loads, and sometimes I get the error.
If I reduce the number of rows to less then 700, the pages work fine.
The particular Stored Proc is getting called only once in my page.
I did the following:
Modified the code to use the command object in using block.
Closing the connection immediately after the usage is done.
Compared the staging and production IIS serve settings, and they looked similar.
Same MDAC is installed on both the web servers.
But nothing helps and I still get the error in the staging web server.
The query runs fine in SQL Server Management Studio and takes < 3 sec.
Can anyone please suggest any solution to this?
This is the code base where the Stored Proc is getting called:
string strSPName = SQLSchema.strSQLSchema + SPNames.<Some SP Name>;
using (conn)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = strSPName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.Add(SPParams.<Some Param>, SqlDbType.Int);
cmd.Parameters[0].Value = <value of Param>;
conn.Open();
dsSubmitter = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dsSubmitter);
if (dsSubmitter.Tables.Count != 0)
{
dsSubmitter.Tables[0].TableName = DALConstants.<Table Name>;
}
conn.Close();
}
The SP is quite simple with a select statement and with a INNER join between the master and detail table. The master table has ~400 rows and detail table > 10,000 rows. The SQL Query returns around 4000 rows.
Looks like issue with SqlAdapter, why don't you try installing .net framework again.
clean up solution and rebuild it.

SQL Connection Forcibly Closed

I'm having difficulty with an SQL query against Server 2008 from IIS7. I have a VB.NET class library which runs an update statement. The underlying code used to create the connection hasn't changed, but suddenly the query is failing in our testing and development environments. It does, however, still work against the same server/database using the slightly older code in our production environment.
I've tried setting the connection timeout in the web.config and I'm at a loss to explain the cause.
The basic structure of the query is:
Dim conn = New SqlConnection()
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass"
conn.Open()
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE ..."
cmd.Parameters.AddWithValue("#UName", user.name)
cmd.ExecuteNonQuery() 'fails with error
End Using
The error is:
A transport-level error has occurred when sending the request to the
server. (provider: TCP Provider, error: 0 - An existing connection was
forcibly closed by the remote host.)
I've tried restarting IIS and the SQL server and I'm totally out of ideas. I just need a fix
You need to open the connection before calling SqlCommand.ExecuteNonQuery(). You do this by calling SqlConnection.Open().
Dim conn = New SqlConnection()
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass"
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE ..."
cmd.Parameters.AddWithValue("#UName", user.name)
conn.Open()
cmd.ExecuteNonQuery() 'fails with error
conn.Close()
End Using
Also, ensure you database isn't in single user mode.
This helped another person who was stuck recently. You could examine the problem from the database server by setting up a SQL Server Profiler.
You can find lots of info about SQL Profiler by just googling around. Here's a site with a video that might help you get started. For starters, you would be able to see if the request is even reaching the database server.
This was a nightmare to track down. It turned out to be cause by a horrible quirk in VB.NET. Nullable datetimes seem to be coerced to DateTime.MinValue, which resulted in a DateTime.MinValue being inserted into an sql datetime. The fix was to check for either !property.HasValue && property.Value != DateTime.MinValue when setting the parameters for the command.
This is a network-level error. The database server is killing the connection for some reason. In order to troubleshoot this, I would open a connection using SSMS to the DEV and TEST servers and make sure that I can run simple queries w/o problems. It's unlikely that the issue is your library since you would be getting timeout or some other kind of errors.
as Lcarus, said, database server is killing the connection for unknown reason.
you can check the logs, to verfiy. Log path will be C:\Program Files\Microsoft SQL Server\<your instance>\MSSQL\LOG
from MSDN Blog MSDN Blog
this will occur when A connection is taken from the connection pool,
the application does not know that the physical connection is gone, an
attempt to use it is done under the assumption that the physical
connection is still there.

Resources