Avoiding distributed transtactions on connection to multiple DBs on the same SQL server, .net Core - .net-core

We are migrating a project from .NET Framework to .NET Core, the project is working with multiple data bases that are on the same SQL server. In the past we used a transaction scope for any transaction that we wanted to roll back in case of an error.
When the transaction is involving multiple DBs the transaction is being promoted to a distributed transactions which is not supported in .NET Core.
Question is, if all DBs are actually on the same server, if I will use a 'cross-database queries' like is suggested at the very last part of this Answer will I be insured against such a scenario?
Does 'cross-database queries' simply means running raw-SQL commands like:
using(TransactionScope scope = new TransactionScope())
{
var connection = new SqlConnection(connectionString);
connection.Open();
var SqlComm1 = new SqlCommand("Insert into TableA...", connection);
SqlComm1 .ExecuteNonQuery();
var SqlComm2 = new SqlCommand("Insert into [DB2].[dbo].[TableB]...";
SqlComm2 .ExecuteNonQuery();
.
.
}
if not, can I get a code example of what it actually is?
lastly, while using 'cross-database queries' can I take advantage of anything from my actual DBContexts? like connections, dbSets or anything and if so, how?

Related

SignalR + SQLNotifications in .NetCore

Hi I have a webApi and I want to notify when a record changes in the DB. I'm trying to use SQLNotification but this code generates error
sqlcommand does not contain definition for Notification
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
}
Is posible to use SQLNotifications in NetCore 2.0?
I may be mistaken but I don't believe it is available currently based on:
Microsoft's announcement stating:
Simplified Scale-Out Model
Unfortunately, when it comes to scaling out applications there is no “one size fits all” model – each application is different and has different requirements that need to be considered when scaling out the application. We have worked to improve, and simplify, the scale-out model and are providing a Redis based scale-out component in this Alpha. Support for other providers is being evaluated for the final release, for example service bus.
As well as this open issue and specifically David Fowler's comment:
It's just a very very bad way to do real time notifications as that's not what sql was meant for.

oracle ExecuteNonQuery freezes on ASP.Net

I am trying to run a non query using a Oracle connection in ASP C# with CLR 4.5. Here is my code:
string connectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString1"].ConnectionString;
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "update SALES_ADVENTUREWORKS2012.SALESORDERDETAIL set UNITPRICEDISCOUNT=0 where ROWGUID='4A399178-C0A0-447E-9973-6AB903B4AECD'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = QUERY_TIMEOUT;
int row_affected = cmd.ExecuteNonQuery();
HttpContext.Current.Response.Write("Rows affected:" + row_affected + "<br/>");
conn.Close();
when I run the query in oracle development tool, it works fine.
when I use the asp code above, it freezes when performing the query. It freezes forever even though I used a 5 second timeout.
I've tried using the managed and unmanaged oracle libraries; both behave the same.
Note that using the fill or scalar query work perfectly fine so there is nothing wrong with my connection string. Also the fact that oracle development can perform this update query proves that this is not a permission problem.
Any ideas?
Most likely your query is waiting to get access to the record. You probably have modified that row in "oracle development tool" and have not committed or rolled back that transaction.
Just commit/rollback in your tool or close open session.
You can check for open transactions in v$transaction view.
More on automatic locks in Oracle:
http://docs.oracle.com/cd/E11882_01/server.112/e41084/ap_locks001.htm
Are you certain you are using the 4.5 library? The 3.5 documentation states that the CommandTimeout property has no effect.
The 4.5 documentation suggests it should work, but the Remarks section doesn't mention the change, which warrants suspicion.
Otherwise, the code you posted doesn't seem to show where you actually set the value of QUERY_TIMEOUT to 5 seconds. If QUERY_TIMEOUT has a value of zero, then any other provider (SQLCommand, for example) would wait indefinitely. As vav suggested, locks from other sources could cause an indefinite wait.

How to access SQL Server from my WCF web service?

VS Express 2012, SQL Server Express 2012, Win 8.1
Hello,
I have a (very) simple WCF hosted as a web service on IIS. I also have a SQL Server instance (with 1 table) installed on the same machine.
I need a step-by-step guide on how to connect to SQL from the WCF (VB) and retrieve a single record from the table (ie: "SELECT LAST NAME FROM MYTABLE WHERE PK = 1;"). That's it. I don't need a 1,200 page manual -- which is all Google keeps throwing at me.
Anyone know of a quick, clean resource?
Thanks,
Jason
The main classes that are involved are SqlConnection and SqlCommand. The documentation of the classes contains some samples on how to use them. To get you started, here is a small sample:
Dim connStr = "Data Source=SQLServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=SSPI"
Using conn As New SqlConnection(connStr)
conn.Open()
Using cmd = conn.CreateCommand()
cmd.CommandText = "SELECT LAST_NAME FROM MYTABLE WHERE PK = #pk"
cmd.Parameters.AddWithValue("#pk", 1)
Dim result = cmd.ExecuteScalar()
If Typeof result Is DbNull Then
' Handle null value
Else
' Otherwise
End If
End Using
End Using
This sample assumes that you want to retrieve a single cell as in your statement. If you want to retrieve tabular data, have a look a the SqlDataReader or SqlDataAdapter class.
Please note that - especially in server applications - it is important to dispose of the created instances properly.
There is no difference on using ADO.NET in a WCF service or in a normal application from the point of view of the classes required.
The first thing needed is a connection string that allows your SqlConnection object to find the host and the database that you want to use. Here examples on connection strings
Then you usually need a SqlCommand that encapsulates the SQL text and parameters needed to retrieve the data (Here you setup your SELECT statement and conditions)
Finally you need a SqlDataReader that get the result of the command execution and allows you to loop over the results.
Here a sample that could get you started.
Keep in mind that this is just a minimal todo-list and there are numerous other ways to work with data. Basic objects like SqlDataAdapter, Dataset, DataTable present different ways to load data from a database and use that data. Then on top of these there are technologies like Linq To Sql and Object Relational Mapper tools that abstract the data access and offer high level functionality on top of data.
That's probably the reason you get so much informations on data access technologies

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.

ASP.NET MVC 2 - user defined database connection

I am looking to port my very basic DBMS software from classic ASP to ASP.net - however the user would need to input the connection details in order to connect to their specific DBMS server.
Is this at all possible with ASP.NET MVC (very similar to DSN-less connections in ASP).
Cheers,
Joel
The question should really be "is this possible with .NET", ASP.NET MVC is not a database technology, and DSN-less connections aren't ASP technology either. In .NET, it is the ADO.NET framework that allows you to access database resources, and it can be used from any .NET code, be it desktop, web and mobile too.
There are some specialised libraries for certain platforms, .NET includes native support for Sql Server, you can get the MySql Connector for .NET, etc.
All of these providers are built around the ADO.NET provider model, you can either use them explicitly, or you can use the provider-agnostic method. Here are two examples, the first being Sql Server:
string connectionString = "Server=....";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT [Name] FROM [People]"))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Do something here.
}
}
}
In the above example, I'm using the specific Sql Server ADO.NET types to create a connection to a database and execute an arbitrary query against it.
If you are intended to support multiple database platforms, it's probably best to design your code such that it can utilise the ADO.NET Factory classes which are specialised factories geared to the creation of platform specific types. In the example below, I've used the Factory classes to access a MySql Server database:
string connectionString = "Server=....";
DbProviderFactory factory = DbProviderFactories.GetFactory("MySql.Data");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.CommandText = "SELECT `Name` FROM Page";
connection.Open();
using (DbDataReader reader = command.ExecuteReader())
{
// Do something here.
}
}
}
Not the perfect example, but enough to get you going, but it's important to remember that DSN-less connections are not tied to ASP or ASP.NET.
Hope that helps.

Resources