How to avoid distributed transaction? - c#

There is a C# program calling a stored proc which has insert linkedserver... from ..... The C# program using Entity framework (ctx.Database.ExecuteSqlCommand("....")).
I've tried
Change the property "Enable Promotion of Distributed Transaction" to false.
Add "Enlist=false" in the connection string of the C# program
Change the MSDTC of the SQL server to allow anonymous authentication...
But it still gets the following error.
A severe error occurred on the current command. The results, if any, should be discarded.
OLE DB provider "SQLNCLI11" for linked server "...." returned message "No transaction is active.".

Related

Can't initialize local SQL Server database with EFCore commandline tools

I've been trying to follow several different tutorials with EFCore and .net core and I've been totally blocked at the point where I try and create a local database.
I've used both the powershell tools and the commandline tools to try and create an initial migration (or do anything, really).
I consistently get the error:
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)
The database does not currently exist on the system, though local SQL Server appears to be up and running.
Here is the c# code for adding the context:
services.AddDbContextPool<TestDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestDb")
)
);
This is the connection string code:
"TestDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDb"
I get similar errors whether I run add-migration, dotnet ef migration add, or dotnet ef dbcontext info. (note: with the dotnet calls I am using the -s ..\{webproject}\{webproject}.csproj property
I've also messed with the connection string by adding various combinations of Trusted_Connection=True; MultipleActiveResultSets=True;, and Integrated Security=true.
I've gone into SSMS and ensured the Server authentication is SQL Server and Windows Authentication Mode and that Maximum Connections is set to 0 (unlimited). I've also gone to logins and tried adding the user to pretty much all the server roles.
So, yeah, I'm pretty confused. I've worked with EF for years, though this is my first experience with EFCore and I'm definitely more of a developer than a SQL Admin. This is also my first time trying to use the local db on this particular computer.
Edit: Looking at error.log in AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb I see this error:
2020-01-28 10:15:03.50 Logon Error: 18456, Severity: 14, State: 38.
2020-01-28 10:15:03.50 Logon Login failed for user 'LAPTOP-NC6HQ4TB\ripli'. Reason: Failed to open the explicitly specified database 'TestDb'. [CLIENT: <named pipe>]
Which is confusing. Of course I can't open the specified database. The entire point is I want to create a DB that doesn't yet exist.
Found the answer. Sorry to everyone who tried to help, as you wouldn't have had enough information to solve it.
In the DbContext I had tried to add some code to the constructor to try and populate some data to the database as part of a test. This caused several problems. If the Database hadn't yet been created it tried to connect to the DB before it had been created, which caused the problems I described.
Furthermore, if I had created the db manually it would try to access the DbSets (which had not yet been created), and then complain that the set name was invalid (which, at this point it was.
This all might have been fine if the DB had been created in advance, but since I was using the DbContext to construct the database, it understandably caused problems.
And all of this headache would have been avoided had I not violated SRP and not tried to (even temporarily) hijack a context constructor to hack in some test data.
The takeaway here? Don't pollute your constructors with unrelated hacks. Bleh.

U-SQL data source as SQL Server inside a UDF

I need to extract rows from a SQL table where some columns are encrypted using SQL Server's new 'Always Encrypted' feature. I see that I cannot use the 'AZURESQLDB' DataSource feature and there needs to be decryption done before reading the data in plain text. Are there plans to add this capability?. Meanwhile, I tried to write a user defined function that will do the same operation(connect, decrypt data and return object) in a registered assembly but when it runs, I get the following error:
Inner exception from user expression: 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)
I have checked the code and everything seems correct. The connection string is used by the SqlConnection object and works fine in all other applications. I am guessing that the connectivity to external data sources from within a UDF is blocked. Is there any way around this?
Are you using the DATA SOURCE in U-SQL for representing your SQL Server instance and you cannot get it to read encrypted data? If so, please file a feature request at http://aka.ms/adlfeedback.
You cannot call out to network resources directly from within U-SQL user code for the reasons explained here.
One way around this might be to create a stored procedure which does the hard work, the decryption then renders the data. Then use Azure Data Factory with a Stored Proc Task to access the decrypted data and move what you need to the Data Lake - not including the secure data. From there you could then access it using a U-SQL script. One idea? Let me know if you need me to work up more of an example.

Servicestack OrmLite - Execute as User/Impersonation

I am using Servicestack OrmLite as a data layer for my application (.NET C# 3.5/SQL Server).
One of the design requirements (It isn't greenfield, so it is mandatory) is to have commands executed as a particular user which has a schema attached on the SQL server side.
After creating the DbContext with OpenDbConnection() I send an Execute as User command to SQL server so that they are executing with the correct login, and they are switched over to the correct schema for that login.
The error I am getting back for selects against that connection later in the process is:
A severe error occurred on the current command. The results, if any, should be discarded.
Thoughts:
Connection pooling is losing the current user command sent to SQL server?
Is there a built in User/schema handler extension to OrmLite that I haven't seen?
RegisterConnection?
Thanks for your input.

Sql Server isn't closing a connection to linked Server after execution

I am using a linked server to update records in AS/400. It isn't closing the connections properly. On the AS/400 side there are still a number of connections idle. In the sql log it is showing:
EXCEPTION_ACCESS_VIOLATION writing address 0000000000000024 at 0x0000000077BDE4B4
It doesn't appear that it is every time we open a connection and update the file on the AS/400 side. We updated 222 records and there were still 210 connections open. I would expect there to be 222.
We are calling a stored procedure from a .NET app. In the stored procedure we are executing:
EXECUTE (#as400Query) at S100405D
Where the as400Query is a string with the update statement and S100405D is the linked server. The records are getting updated in the AS/400, so that isn't an issue. Just seems that when trying to close the connections, there is an error. Also I checked the settings on the linked server and the connection timeout = 0 (off). Not sure if setting a timeout will close them, or it won't matter because it is throwing an error anyways.
Any help would be greatly appreciated!
Brian
are you submiting any sort of code to close the connection on the AS side? SQL server will only close its connecion, any other connection opened on any other RDBMS won't be managed by SQL
As an IBM i programmer, I would not expect to see any errors during a stored procedure call. Rarely, the OS will throw an exception if there is a parameter mis-match. The most common is the caller (C#) using VARCHAR and the IBM side declaring it as CHAR.
Aside from that, have the IBM people make sure they are current on PTFs.
As a style matter, I would not expect to see:
open connection
CALL proc
close connection
for each row to be updated. Rather, I would expect
open connection
loop
CALL proc
end loop
close connection

Exception handling in windows Application of C# language from Sql Server 2005

I want List of all types exceptions which may be generated during remotely connection between C# application and sql server2005 like updating, inserting etc..
When connected to a Sql Server, whenever an exception is thrown, it will be a SqlException.
From documentation:
This class is created whenever the .NET Framework Data Provider for
SQL Server encounters an error generated from the server.
In the SQL Server instance, a list of all defined error codes is available in the sysmessages table.
SQLException is always thrown when the error originates from the server. The SQLException object will identify which of those errors occurred in its Number property.
Most exceptions that move up from the db layer to the application layer deal with the sqlexception class. In this case, these have to do with the following:
time out exceptions
incorrect credentials (security)
incorrect server name / ip address
SQL Server does not exist (etc)
To handle exceptions that are caused by inserts or updates involves exception handling within your actual procedure (sproc). You could also handle these by custom exceptions that you create.

Categories

Resources