The transaction manager has disabled its support for remote/network transactions - asp.net

I'm using SQL Server and ASP.NET. I have the following function:
Using js = daoFactory.CreateJoinScope()
Using tran = New Transactions.TransactionScope()
'...
tran.Complete()
End Using
End Using
However, the following exception is thrown:
The transaction manager has disabled its support for remote/network transactions.
Description of JoinScope:
Public Class JoinScope
Implements IJoinScope
Implements IDisposable
'...
End Class
I have worked this way in another application with the same environment without a problem, but here I have this problem. What could I do to fix the issue?

Make sure that the "Distributed Transaction Coordinator" Service is
running on both database and client.
Also make sure you check "Network DTC Access", "Allow Remote Client",
"Allow Inbound/Outbound" and "Enable TIP".
To enable Network DTC Access for MS DTC transactions
Open the Component Services snap-in.
To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.
Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.
On the Action menu, click Properties.
Click the Security tab and make the following changes:
In Security Settings, select the Network DTC Access check box.
In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.

I had a store procedure that call another store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error.
This article helped me and I used this script:
EXEC sp_serveroption #server = 'LinkedServer IP or Name',#optname = 'remote proc transaction promotion', #optvalue = 'false' ;
for more detail look at this:
Linked server : The partner transaction manager has disabled its support for remote/network transactions

In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:
Example:
void someFunction()
{
using (var db = new DBContext(GetConnectionString()))
{
using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
}
}
}
void someOtherFunction()
{
using (var db = new DBContext(GetConnectionString()))
{
db.Whatever // <- Exception.
}
}

I was getting this issue intermittently, I had followed the instructions here and very similar ones elsewhere. All was configured correctly.
This page: http://sysadminwebsite.wordpress.com/2012/05/29/9/ helped me find the problem.
Basically I had duplicate CID's for the MSDTC across both servers. HKEY_CLASSES_ROOT\CID
See: http://msdn.microsoft.com/en-us/library/aa561924.aspx section Ensure that MSDTC is assigned a unique CID value
I am working with virtual servers and our server team likes to use the same image for every server. It's a simple fix and we didn't need a restart. But the DTC service did need setting to Automatic startup and did need to be started after the re-install.

Comment from answer: "make sure you use the same open connection for all the database calls inside the transaction. – Magnus"
Our users are stored in a separate db from the data I was working with in the transactions. Opening the db connection to get the user was causing this error for me. Moving the other db connection and user lookup outside of the transaction scope fixed the error.

I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.
The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction
The partner transaction manager has disabled its support for remote/network transactions*
Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.
EF model generated method based attempt:
db.SomeStoredProcedure();
ExecuteSqlCommand based attempt:
db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");
With:
var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";
connection.Open();
var result = cmd.ExecuteNonQuery();
That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.
I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.
The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.

I was having this issue with a linked server in SSMS while trying to create a stored procedure.
On the linked server, I changed the server option "Enable Promotion on Distributed Transaction" to False.
Screenshot of Server Options

If you could not find Local DTC in the component services try to run this PowerShell script first:
$DTCSettings = #(
"NetworkDtcAccess", # Network DTC Access
"NetworkDtcAccessClients", # Allow Remote Clients ( Client and Administration)
"NetworkDtcAccessAdmin", # Allow Remote Administration ( Client and Administration)
"NetworkDtcAccessTransactions", # (Transaction Manager Communication )
"NetworkDtcAccessInbound", # Allow Inbound (Transaction Manager Communication )
"NetworkDtcAccessOutbound" , # Allow Outbound (Transaction Manager Communication )
"XaTransactions", # Enable XA Transactions
"LuTransactions" # Enable SNA LU 6.2 Transactions
)
foreach($setting in $DTCSettings)
{
Set-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security -Name $setting -Value 1
}
Restart-Service msdtc
And it appears!
Source: The partner transaction manager has disabled its support for remote/network transactions

In case others have the same issue:
I had a similar error happening. turned out I was wrapping several SQL statements in a transactions, where one of them executed on a linked server (Merge statement in an EXEC(...) AT Server statement). I resolved the issue by opening a separate connection to the linked server, encapsulating that statement in a try...catch then abort the transaction on the original connection in case the catch is tripped.

I had the same error message. For me changing pooling=False to ;pooling=true;Max Pool Size=200 in the connection string fixed the problem.

Related

Specifying default schema WebSpehere 8.5 Server

I am working on a migration project where we are migrating one application from Weblogic to Websphere 8.5 server.
In Weblogic server, we can specify default schema while creating datasource but I don't see same option in WebSpehere 8.5 server.
Is there any custom property through which we can set it , I tried currentSchema=MySchema but it did not work.
This answer requires significantly more work, but I'm including it because it's the designed solution to customize pretty much anything about a connection, including the schema. WebSphere Application Sever allows you to provide/extend a DataStoreHelper.
Knowledge Center document on providing a custom DataStoreHelper
In this case, you can extend com.ibm.websphere.rsadapter.Oracle11gDataStoreHelper.
JavaDoc for Oracle11gDataStoreHelper
The following methods will be of interest:
doConnectionSetup, which performs one-time initialization on a connection when it is first created
doConnectionCleanup, which resets connection state before returning it to the connection pool.
When you override doConnectionSetup, you are supplied with the newly created connection, upon which you can do,
super.doConnectionSetup(connection);
Statement stmt = connection.createStatement();
try {
stmt.execute(sqlToUpdateSchema);
} finally {
stmt.close();
}
doConnectionCleanup lets you account for the possibility that application code that is using the connection might switch the schema to something else. doConnectionCleanup gives you the opportunity to reset it. Again, you are supplied with a connection, upon which you can do,
super.doConnectionCleanup(connection);
Statement stmt = connection.createStatement();
try {
stmt.execute(sqlToUpdateSchema);
} finally {
stmt.close();
}
Note that in both cases, invoking the corresponding super class method is important to ensure you don't wipe out the database-specific initialization/cleanup code that WebSphere Application Server has built in based on the database.
As far as I know Weblogic only allows setting a default schema by setting the 'Init SQLto a SQL string which sets the current schema in the database, such asSQL ALTER SESSION SET CURRENT_SCHEMA=MySchema`. So, this answer is assuming the only way to set the current schema of a data source is via SQL.
In WebSphere, the closest thing to WebLogic's Init SQL is the preTestSQLString property on WebSphere.
The idea of the preTestSQLString property is that WebSphere will execute a very simple SQL statement to verify that you can connect to your database properly when the server is starting. Typically values for this property are really basic things like select 1 from dual', but since you can put in whatever SQL you want, you could setpreTestSQLStringtoSQL ALTER SESSION SET CURRENT_SCHEMA=MySchema`.
Steps from the WebSphere documentation (link):
In the administrative console, click Resources > JDBC providers.
Select a provider and click Data Sources under Additional properties.
Select a data source and click WebSphere Application Server data source properties under Additional properties.
Select the PreTest Connections check box.
Type a value for the PreTest Connection Retry Interval, which is measured in seconds. This property determines the frequency with which a new connection request is made after a pretest operation fails.
Type a valid SQL statement for the PreTest SQL String. Use a reliable SQL command, with minimal performance impact; this statement is processed each time a connection is obtained from the free pool.
For example, "select 1 from dual" in oracle or "SQL select 1" in SQL Server.
Universal Connection Pool (UCP) is a Java connection pool and the whitepaper "UCP with Webshere" shows how to set up UCP as a datasource.
for JDBC datasource, the steps are similar but, you can choose the default JDBC driver option.
Check out the paper for reference.

Azure SQL Database sometimes unreachable from Azure Websites

I have a asp.net application deployed to Azure websites connecting to Azure SQL Database. This has been working fine for the last year, but last weekend I have started getting errors connecting to the database giving the following stacktrace.
[Win32Exception (0x80004005): Access is denied]
[SqlException (0x80131904): 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)]
This error comes and goes staying a few hours and then goes away for a few hours. The database is always accessible from my machine.
A few things that I have tried are:
Adding a "allow all" firewall rule (0.0.0.0-255.255.255.255) has no effect
Changing the connection string to use the database owner as credential has no effect.
what does have effect is to change the azure hosting level to something else. This resolves the issue temporarily and the website can access the database for a few hours more.
What could have have happened for this error to start showing up? The application hasn't been changed since August.
EDIT:
Azure support found that there was socket and port exhaustion on the instance. What the root cause for that is, is still unkown.
Craig is correct in that you need to implement SQLAzure Transient Fault Handling. You can find instructions here: https://msdn.microsoft.com/en-us/library/hh680899(v=pandp.50).aspx
From the article
You can instantiate a PolicyRetry object and wrap the calls that you
make to SQL Azure using the ExecuteAction method using the methods
show in the previous topics. However, the block also includes direct
support for working with SQL Azure through the ReliableSqlConnection
class.
The following code snippet shows an example of how to open a reliable
connection to SQL Azure.
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.AzureStorage;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure;
...
// Get an instance of the RetryManager class.
var retryManager = EnterpriseLibraryContainer.Current.GetInstance<RetryManager>();
// Create a retry policy that uses a default retry strategy from the
// configuration.
var retryPolicy = retryManager.GetDefaultSqlConnectionRetryPolicy();
using (ReliableSqlConnection conn =
new ReliableSqlConnection(connString, retryPolicy))
{
// Attempt to open a connection using the retry policy specified
// when the constructor is invoked.
conn.Open();
// ... execute SQL queries against this connection ...
}
The following code snippet shows an example of how to execute a SQL command with retries.
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.AzureStorage;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.SqlAzure;
using System.Data;
...
using (ReliableSqlConnection conn = new ReliableSqlConnection(connString, retryPolicy))
{
conn.Open();
IDbCommand selectCommand = conn.CreateCommand();
selectCommand.CommandText =
"UPDATE Application SET [DateUpdated] = getdate()";
// Execute the above query using a retry-aware ExecuteCommand method which
// will automatically retry if the query has failed (or connection was
// dropped).
int recordsAffected = conn.ExecuteCommand(selectCommand, retryPolicy);
}
The answer from Azure support indicated that the connection issues I was experiencing was due to port/socket exhaustion. This was probably caused by another website on the same hosting plan.
Some answers to why the symptoms were removed by changing hosting service level:
Changing the hosting plan helped for a while since this moved the virtual machine and closed all sockets.
Changing the hosting plan from level B to level S helped since azure limits the number of sockets on level B.

dynamics AX batch job through ODBC

I have problems with an ODBC connection used in a batch job: when executed, I have the following error message :
"The ODBC operation failed.Unable to connect to database
Invalid connection String attribute Trusted_Connection
Unabe to create object 'OdbcConnection' "
I try to connect to an Access database, I use the following code:
LoginProperty loginProperty;
OdbcConnection odbcConnection;
;
loginProperty = new LoginProperty();
loginProperty.setDSN("MyDSN");
loginProperty.setDatabase("MyDatabase");
odbcConnection = new OdbcConnection(loginProperty);
when debugging, it crashes on odbcConnection = new OdbcConnection(loginProperty). I tested the same code in a job in local client execution, there was no problem and it worked fine(without defining login password in code or DSN). My DSN seems to be OK on AOS, I'm using AX 2009 without SP1, I saw some examples where there was login/password defined in loginProperty object , the setUserName() and setPassword() methods are not available in my AX version loginProperty object. My class is executed on server-side (as any batch job).
Is there some particular setup to do to connect to ODBC datasource through batch job?
any ideas or suggestions?
thanks for your help
Edit:AOS is running on Windows server 2003 32 bits, ODBC tested on it, works fine but doesn't work in AX through batch job
Most likely you will need a 32-bit DSN connection for your AX. I would create both versions on the AOS server.
Look here for details.
It may be caused due to permisions. "trusted connection" refers to the fact that you connect to the database through the user logged to the current session. When you run a Job from the AX client, this is executed with the user that runs the current AX client (the one logged to the active session); When code is executed from server in a batch job, code is executed through the user that runs the AOS windows service.
Has this user permissions to read/write/access the access file and directory?
If you are on a 64 bit machine use C:\Windows\SysWOW64\odbca32.exe to create the datasource.
Check under which ID the AOS runs, log on with that ID and make sure you can 'see' the data source.
Also make sure that the AOS account has access to the directory/files (if using file-based odbc)

SQL Server service broker reporting as off when I have written a query to turn it on

I have made a small ASP.NET website. It uses sqlcachedependency
The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported. Please enable the Service Broker for this database if you wish to use notifications.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported. Please enable the Service Broker for this database if you wish to use notifications.
Source Error:
Line 12: System.Data.SqlClient.SqlDependency.Start(connString);
This is the erroneous line in my global.asax.
However, in sql server (2005), I enabled service broker like so (I connect and run the SQL Server service when I debug my site):
ALTER DATABASE mynewdatabase SET ENABLE_BROKER with rollback immediate
And this was successful.
What am I missing? I am trying to use sql caching dependency and have followed all procedures.
Thanks
I faced the same problem on one of our servers. this solved the issue (replace DBNAME with database name)
ALTER DATABASE DBNAME SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE DBNAME SET ENABLE_BROKER;
Finally, check whether you get 1 for is_broker_enabled flag:
SELECT is_broker_enabled FROM sys.databases WHERE name = 'DBNAME'
Do you use a normal SQL instance, including Express, or are you using User Instances? ie. your connection string uses "AttachDbFilename" option? On user instances because the MDF is attached each time the instance is created, the Service Broker gets disabled each time because attach and restore operations always disable the broker in the database.
Ditch the "with rollback immediate" and try running the statement again.
Does it hang? If so kill any other sessions that are in the database and are blocking the session trying to alter the database.
Here's the script I mentioned in my comment.
use master
go
declare #parent int
declare #cmd varchar(100)
set #parent = 53
while exists (select * from sys.sysprocesses where spid = #parent and blocked <> 0)
begin
select #cmd = 'kill ' + cast(blocked as varchar(10))
from sys.sysprocesses
where spid = #parent
print #cmd
exec (#cmd)
end
You can change it by
Data Base - > Properties -> Options -> Service Broker

How can I create a database on my server from the web?

I have an admin account for my website where I add new clients. When a new client is added, they get an account and their own database.
The problem is I can't create new databases on my server from my admin account. When running it locally, I can add a database locally. But, when I try adding to the server running my website off the server, I get
CREATE DATABASE permission denied in database 'master'.
I've been able to add the database (locally) a few ways. This is one of the simpler working versions:
tmpConn.ConnectionString = "Data Source=.\\SQLEXPRESS; DATABASE = master;Integrated Security=True;";
sqlCreateDBQuery = " CREATE DATABASE " + dbname;
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
try
{
tmpConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{}
I suspect that whatever account you're using to connect to Sql Server doesn't have permissions to CREATE DATABASE. You're probably using Integrated Security, which would use Network Service/ASP.NET to connect to MSSQL. You need to create a new connection string that uses Sql Authentication with sa (or another sysadmin) credentials.
Oh - and this would work locally because you're running it under Visual Studio's WebDev.exe which is run with your local user account - which is probably set up as a sysadmin in MSSQL.
You should contact your service provider. (Or the maintainer of the server).
You need create database and create database user permissions. Your service provider should be able to facilitate this.
Something else no one has suggested is what kind of validation you are doing on the dbname value. Are you sure there are no spaces in it? That it's not a reserved word? That it doesn't contain malicious code? At very least you should encase it in brackets:
sqlCreateDBQuery = String.Format(" CREATE DATABASE [{0}]", dbname);
I really hope you aren't allowing the user to type this name directly into a textbox somewhere. Even if you use property security on the initial input and this is pulled back from a common "clients" db of some kind, you might be setting yourself up for a 2nd order Sql Injection vulnerability.
After you've addressed that, we can look at the error message here. In this case, the problem is that your web user does not have appropriate CREATE permissions. You need to correct that and it should allow you to proceed. You probably want to reserve a special account for this that you switch to just at this time, so your application doesn't normally run in a context that would allow this kind of action.
Check the permissions for MySQL: Does your admin account have different settings for a local connection versus any host?

Resources