Dapper & TransactionScope? - transactionscope

I just started playing around with Dapper. So far i love it. Does dapper not work with TransactionScope? I noticed that even if i never call TransactionScope.Complete then my changes are still committed to the database. If TransactionScope isn't supported now is there any plans in the future to support it? If not then you have to use traditional transaction management (System.Transactions.Transaction)?
Update: I just talked to Sam over Twitter. It should work. I'll update it tomorrow morning (at work) with the details to see if anyone can figure out why my changes were still being committed to the db even when i never called complete.

It was totally my fault and not fully understanding transactionscope. A connection is not automatically enlisted in transactionscope unless you open the connection within the transactionscope:
Automatic Enlistment
using (var scope = new TransactionScope())
{
con.Open();
//update/delete/insert commands here
...
scope.Complete();
}
Manual Enlistment
con.Open();
using (var scope = new TransactionScope())
{
con.EnlistTransaction(Transaction.Current);
//update/delte/insert statements here
...
scope.Complete();
}
Details can be found here: Details

Related

CosmosDB fails to Deserialize Object after moving to new Assembly

I am using CosmosDB to store my BotState and ConversationState. Now that my codebase has grown, we have started to refactor, and we moved some objects into a common library and such.
After doing so, making the call
userData = await _botAccessors.BotStateAccessor.GetAsync(turnContext, () => new UserData(), cancellationToken);
fails with the following exception
Error resolving type specified in JSON '...'. Path '['BotAccessors.BotState'].ConversationContext.PreviousResponses.$values[0].channelData.$type'.
I have looked in the Document of the CosmosDB and I see the problem.
I have tried to set the TypeNameHandling and TypeNameAssemblyFormatHandling as such
var requestOptions = new RequestOptions
{
JsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }
};
when creating the CosmosDbStorageOptions, but this does not allow me to resolve the issue.
Not sure what to try next.
This is a bug in the v2 of Azure Cosmos DocumentDB Client and has been for awhile. Reviewing that issue, it doesn't appear that they plan to fix it in v2 and have instead opted to fix it in v3. Unfortunately:
Bot Framework doesn't plan to update CosmosDbStorage to v3 since CosmosDbPartitionedStorage was released in its place.
Currently, CosmosDbPartitionedStorage is not compatible with non-partitioned databases. A migration plan and backwards-compatibility is currently being discussed but may not be released soon.
So, your only option right now is to basically clone CosmosDbStorage, calling it something like NiteLordsCosmosDbStorage, and performing JSON serialization in the ReadAsync() or WriteAsync() methods, as necessary.

Avoiding distributed transtactions on connection to multiple DBs on the same SQL server, .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?

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.

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.

How to write unit case for remote database connection in asp web application

I am new to unit testing for web applications
I have a function which creates a connection to a remote mysql database and perform some operations on it .
I want to have a test case which tests the connection is closed or not after the operations on database.
for example
fun1()
{
ODBCConnection con = new ODBCConnection(connString);
con.open();
}
in the above function, the connection is not closed?
how do i check this? can any one help?
In .Net, it's generally best to open your connections immediately before you use them. So rather than building (and testing) a function that connects to the database, you build and test a function that returns the correct connectionstring. You also have a reference database for your testing environment, and so you build your data access methods and create their own connection and test them against your reference database, that the right results come back.
Okay, based on your comment I can help you. Since you will be opening and closing the connection in the same function (as you should), you can do this:
public void fun1()
{
using (ODBCConnection con = new ODBCConnection(connString))
{
con.open();
//use the connection here
}
//connection is closed here because of the using block, even if an exception is thrown
}
There is no need to check if the connection closes in the code above. It will be closed in a timely manner by the using block, and that's guaranteed as much as anything can be in software. Just make sure you use that pattern everywhere you use connections.
In unit testing, the "units" to be tested are methods/functions. You test that the function performs as you expect it to, and nothing more. If you want to test specifically if a connection is closed, than the way to do it is to write a function to close the connection, and test that.

Resources