SQL CLR function and OleDb permissions - sql-server-2005

I have a .NET 3.5 C# library that uses OleDb to pull data from an Excel file and return it in a DataRowCollection which is used by a CLR Table-Valued Function in SQL Server 2005.
I deployed the ASSEMBLY in SQL Server as sa and used PERMISSION_SET = EXTERNAL_ACCESS. The sa login has EXTERNAL ACCESS ASSEMBLY and the database has TRUSTWORTHY on.
The assembly is signed and I used the following caspol.exe command which indicated that it was successful:
-m -ag All_Code -url "C:\Testing\sqlFunction.dll" FullTrust -n "sqlFunction"
The SQL Server instance, my library and the Excel document are all on the same machine.
The SQL Server service is running as Local System (but while trying to get this to work I also tried running it as the AD user that I was logged in as which is also a local administrator).
I created a command line application to test run the library and everything runs fine and data is returned as expected.
But when I run the function from SSMS, I get this error in the result pane:
A .NET Framework error occurred during execution of user-defined routine or aggregate "GetExcelFile":
System.Security.SecurityException: Request for the permission of type 'System.Data.OleDb.OleDbPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException:
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.PermissionSet.Demand()
at System.Data.Common.DbConnectionOptions.DemandPermission()
at System.Data.OleDb.OleDbConnection.PermissionDemand()
at System.Data.OleDb.OleDbConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at System.Data.Common.DbDataAdapter.QuietOpen(IDbConnection connection, ConnectionState& originalState)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at GetExcelFunction.GetFile()
at GetExcelFunction.InitMethod(String logname)
I've deployed this on my personal dev machine (XP PRO) and our dev sandbox (Server 2003) and got the same error.
Most code access security issues revolve around the assembly running from a network share - but that's not the case here.
Any ideas? I'm tapped out.

Solved it!
PERMISSION_SET = EXTERNAL_ACCESS was not enough. I had to go all the way down to PERMISSION_SET = UNSAFE and then it started working. I can't believe I didn't try that before.

I am sorry that I am not providing a solution to the exact problem here.
But, you can use OPENROWSET function to work with Excel files from SQL Server.
CLR is not necessary, unless there is something that I don't know of.

I am looking the code using reflector. And I am purely speculating looking at the code.
Try initializing System.Data.OleDb.OleDbPermission class & use it's Add method to include the excel connection string to have permission (either before connection opens or query execution).
I hope that helps.

Related

Oracle.ManagedDataAccess.Core (3.21.41), Oracle Wallet with Proxy User has error ORA-01017: invalid username/password; logon denied

I have .net 5/6 application and due to compliance requirements, I am requested to use oracle wallet with proxy user (No password in connection string). To make it simple:
New connection string is: Data Source=myproxy; User Id=/;
I have put following files in current working directory i.e. bin/debug/net5.0:
tnsnames.ora
sample file data:
myproxy=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhostip)(PORT=myport))(CONNECT_DATA= (SERVICE_NAME =myservname)(SERVER=DEDICATED)))
sqlnet.ora
sample file data
SQLNET.WALLET_OVERRIDE = TRUE
SSL_CLIENT_AUTHENTICATION = FALSE
SSL_VERSION = 0
WALLET_LOCATION =(SOURCE =(METHOD = FILE)(METHOD_DATA =(DIRECTORY=mydirectories\wallets)))
I have .net framework application that works perfectly fine with above files and wallets. But I cannot seem to get it to work with .Net Core application. I have even used OracleConfiguration.OnsWalletLocation but no luck at all.
Here is the sample error:
Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01017: invalid username/password; logon denied
at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, OracleConnection connRefForCriteria, String affinityInstanceName, Boolean bForceMatch)
at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword, OracleConnection connRefForCriteria)
at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
You should use Oracle 19 DB driver for .NET Core instead of using Oracle.ManagedDataAccess.Client. The Oracle.ManagedDataAccess.Client is specific for .NET Framework.
The Oracle 19 DB driver for .NET Core is available as nuget called Oracle.ManagedDataAccess.Core and the nuget link is at: https://www.nuget.org/packages/Oracle.ManagedDataAccess.Core/
Use Oracle.ManagedDataAccess.Core version 3.21.4 or later to have support for .NET 5.0, and this nuget is recommended to use for Oracle 12c or later (such as Oracle 19).
See the dependencies:
I was able to run oracle wallet with .net5 application. For me, there was nothing wrong at the application level but oracle wallet. Oracle wallet with proxy user does not work for me but I was able to run oracle wallet with a schema user and password.
Apart from wallet creation, everything else is the same as in above question.
Here are the wallet creation commands to give you an idea of what works and what doesn't.
Wallet that works:
Create wallet
mkstore -wrl . -create
Create Credentials
mkstore -wrl . -createCredential myproxy mySchemaUserName mySchemaUserPassword
Wallet that does not work:
Create wallet
mkstore -wrl . -create
Create Credentials
mkstore -wrl . -createCredential myproxy myProxyUserName[mySchemaUserName] myProxyUserPassword
Make sure to have Oracle.ManagedDataAccess.Core nuget in your solution, tnsnames.ora and sqlnet.ora files in your bin/debug or bin/debug/net5.0 folder.
Data inside tnsnames.ora and sqlnet.ora files should be as in above question.

SqlException - The network path was not found

I'm running my code and getting this error. But what does it mean?
The network path was not found 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.ComponentModel.Win32Exception: The network path was not found
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): The network path was not found]
[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 is probably related to your database connection string or something like that.
I just solved this exception right now. What was happening is that I was using a connection string intended to be used when debugging in a different machine (the server).
I commented the wrong connection string in Web.config and uncommented the right one. Now I'm back in business... this is something I forget to look at after sometime not working in a given solution. ;)
You will also get this exact error if attempting to access your remote/prod db from localhost and you've forgotten that this particular hosting company requires VPN logon in order to access the db (do i feel silly).
There may be some reasons like:
Wrong SQL connection string.
SQL Server in services is not running.
Distributed Transaction Coordinator service is not running.
First try to connect from SQL Server Management Studio to your Remote database. If it connects it means problem is at the code side or at Visual Studio side if you are using the one.
Check the connectionstring, if the problem persists, check these two services:
Distributed Transaction Coordinator service
SQL Server services.
Go in services.msc and search and start these two services.
The above answer works for the Exception:
[Win32Exception (0x80004005): The network path was not found]
Possibly also check the sessionState tag in Web.config
Believe it or not, some projects I've worked on will set a connection string here as well.
Setting this config to:
<sessionState mode="InProc" />
Fixed this issue in my case after checking all other connection strings were correct.
Same problem with me. I solved this by adding # before connection string (C# has a thing called 'String Literals') like so:
SqlConnection sconnection = new SqlConnection(#"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");
sconnection.Open();
As others pointed out this could be more to do with the connectionstring config
Make sure,
user id and password are correct
Data Source is pointing to correct one , for example if you are using SQL express it will be .\SQLEXPRESS
Database is pointing to correct name of database
Hope that helps.
check your Connection String Properly.
Check that the connection is open.
String CS=ConfigurationManager.COnnectionStrings["DBCS"].connectionString;
if(!IsPostBack)
{enter code here
SqlConnection con = new SqlConnection(CS);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblCountry", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//Bind data
}
I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.
In my case I was connected to wrong WiFi.
At The Beginning, I faced the same error but with a different scenario.
I was having two connection strings, one for ado.net, and the other was for the EntityFramework, Both connections where correct. The problem specifically was within the edmx file of the EF, where I changed the ProviderManifestToken="2012" to ProviderManifestToken="2008" therefore, the application worked fine after that.
In my case, I had generated DbContext from an existing database. I had my connection string set in appSettings.json file; however, when I generated the class files by scaffolding the DbContext class it had incorrect connection string.
So make sure your connection string is proper in appSettings.json file as well as in DbContext file. This will solve your issue.
On my end, the problem was an unsuccessful connection to the VPN (while working from home). And yeah, the connectionString was using a context from remote server. Which resulted in the following error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The network path was not found</ExceptionMessage>
<ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
<StackTrace/>
</Error>
If you are using any db , please check connection string also
When I copied my solution from my pc to another one I had to change the connection string in web.config file.
Even if you have the same database name, you should do it for the server name as well.

DNN website: [SQL] Access Is Denied for Non-DNN-Framework Data Access

In a DNN page containing ANYTHING that accesses custom data (i.e., site-specific tables), we always get the following error:
Access Is Denied
[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)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6749670 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
Current config:
IIS pool set up as a local service
SQL runs as a localsystem service
All of the users have the proper DB ownership
DB can be accessed OK for the main DNN install (i.e. users can log in and all DNN-related database infrastructure can be read and displayed from the database), but for the custom modules that read the Connection string from the web.config, it throws the error above.
We've tried to:
Change to poolidentity and give the permission to that particular user/service, and we are experiencing the same problem.
I'm not sure if IIS Application Pools or SQL users are the issue. The error seems to be about the SQL instance which may or may not be set up correctly. However, if it's an SQL instance issue, as per the error message, we are not sure why database access for DNN functions (login, tabs, modules, etc.) are allowed but other connections (via LINQ data context for site-specific schema, or via where we hard-code the connection string) are denied.

Entity framework work locally but not on azure

I have a web project which works perfectly locally.
But when I change the connection string in my published web site on Azure to connect to my database on SQL Azure it will start giving this error.
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
at MyClass.OnModelCreating(DbModelBuilder modelBuilder) in c:\a\src\MyProject\Model.Context.cs:line 25
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
My Config has:
<connectionStrings>
<add name="MyDBEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[Removed].database.windows.net,1433;Database=MyDB;User ID=[Removed];Password=[Removed];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
<add name="MyDB" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[Removed].database.windows.net,1433;Database=MyDB;User ID=[Removed];Password=[Removed];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"" providerName="System.Data.EntityClient" />
</connectionStrings>
I tested using my unit test locally with that connection string and it works from my local machine connecting to SQL Azure database.
Any help appreciated.
I was having this exact problem today; it's my first time deploying to Azure. I've been pulling my hair out, except I don't have any left. I finally figured it out, and it's probably the same issue original poster here is having.
Just like the original poster, I tested in these configurations:
ran WCF Web App from Visual Studio against local DB -- success
deployed WCF Web App from Visual Studio to local IIS, ran against local DB -- success
ran WCF Web App from Visual Studio against Azure SQL DB -- success
deployed WCF App to Azure via Visual Studio, running against Azure SQL DB -- FAILURE!!
After reading another post (Code First vs. Database First) I got a hint. That post says that if "connection string has the metadata, EF thinks it is Model First or Database First" but if it's a "plain connection string, EF thinks it is Code First." I browsed the deployed Azure Web Site's web.config and confirmed that the connection string had the proper references to the Model-First metadata. So what was the problem???
I figured that perhaps the Azure Website wasn't reading the web.config's connection string. Thinking back to how I'd created the Azure Web Site, I remembered that I'd given the Azure SQL DB an alias with the exact same name as my connection string's 'label' in the web.config!! To clarify:
in the Azure admin console I went to the Website settings and reviewed the "connection string" settings "baked in" to my Azure web site as a side-effect of creating-website-with-DB -- connection string 'handle' was "SsnCustInfoModelContainer" -- I'd mistakenly given the connection the same 'handle'/'alias' as my web.config 'handle' for the connection string, thinking this would help. Instead, when EF looks for the connection string, it was finding this 'aliased' handle, which was a "plain" SQL connection string containing no metadata. This 'alias' masked the real connection string specified in the web.config.
So I destroyed my Azure SQL DB and my Azure Web Site. Then I recreated the Azure Web Site, but this time I asked for the connection string 'alias' of "SsnCustInfoModelContainer_Proto" for the connection to the associated Azure SQL Server. After initializing the Azure SQL DB from my local SQL Server Management Studio, I deployed the WCF web app again to the Azure Web Site (I had to download a new deployment profile, of course, to do this), I tried the app again. This time it worked -- the 'alias' "SsnCustInfoModelContainer_Proto" did not conflict with and was not found by EF. EF instead went on to find the true connection string, with all the proper metadata, in the web.config. Problem solved.

Cannot connect to SQL Server Database

I cannot connect to SQL Server Database.
I am trying to setup Membership with roles on my website using the MSDN Tutorial. It used to work only locally on my machine, however after following advice given on different forums, and on stackoverflow, the situation worsened, and now I can't even connect to the SQL Server Database.
When I run the aspnet.regsql.exe utility, I get the following error message:
"Setup failed.
Exception:
Unable to connect to SQL Server database.
----------------------------------------
Details of failure
----------------------------------------
System.Web.HttpException: Unable to connect to SQL Server database. ---> System.Data.SqlClient.SqlException: 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)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
--- End of inner exception stack trace ---
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
at System.Web.Management.SqlServices.Install(String database, SqlFeatures features, String connectionString)
at System.Web.Management.ConfirmPanel.Execute()"
Also, I am unable to use the ASP.NET Website Adimistration Tool. When I click on the Security tab I receive the following error:
"There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.
The following message may help in diagnosing the problem: Unable to connect to SQL Server database."
So, I click on the 'Choose Data Store' button as instructed, which allows me to select a a Provider. The provider is named 'AspNetSqlProvider', it has a Test link beside it. I click on Test and receive the following error message:
"Could not establish a connection to the database.
If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider."
The only other option on this page is to click "Back".
Can somebody please help me sort this out? It's been over a week now and I've searched high and low for answers and have been given so many links to posts that have been of no help. I'd appreciate any help at all.
I have tried running the Configuration Surface Tool and enabling pipes, local/remote connections, though this has made no difference at all.
I have even gone so far as to completely uninstall Visual Web Developer and SQL Server 2005 and 2008 and delete all traces left behind of these applications, and then re-downloaded them all and re-installed them all again.
No luck so far.
Please help
Thanks
Bael
Edit:
I have since tried disabling my firewall changing the port, with no luck.
SOLUTION:
Yes, this may be a little drastic. And I think that this solution should only be a last resort when all else fails.
I managed to fix whatever was wrong by uninstalling SQL Server 2005 and 2008. And then Registering for, downloading SQL Server Express Edition 2008 (with Management Tools) and installing them.
After installation was complete, I closed Visual Web Developer, opened it again, and clicked on the Security tab after opening ASP.NET Website Administration Tool and everything has just "worked" since...
Can you connect using sqlcmd locally?
Can you connect using sqlcmd from a remote machine?
Are you using a SQL username/password, or trusted Windows authentication? If the latter, run CommandPrompt/Powershell as a different user and see if you can connect.
My guess is that you haven't added logins to SQL, and that you're running aspnet.regsql.exe without escalated privileges. If it runs successfully from a Command Prompt that was Run As Administrator, then this is a useful sign.
There are a number of potential issues, but the escalated privileges is something I see often these days. It's better to create a dedicated account, give that an appropriate amount of access to the SQL instance, and then run Command Prompt as that account (shift-right-click to get the old 'Run as' option).