sp_execute_policy Error in SQL, How To Create SQL Facets Policies - sql

I am trying to create a policy in sql that would constrain sproc to a naming convention.
As when someone creates a new sproc they would be forced to prefix the sproc with sp_
Like - sp_MySprocName.
But I am getting the error below when i try to create a new sproc with the correct naming convention.
When I right click on Policy and choose my policy I click on the Evaluate option and everything runs just fine, unlike when I actually create a new sproc I get this error.
Msg 6522, Level 16, State 1, Procedure sp_execute_policy, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "sp_execute_policy":
System.TypeInitializationException: The type initializer for 'Microsoft.SqlServer.Management.Dmf.PolicyEvaluationHelper' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.Diagnostics.STrace, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException:
at Microsoft.SqlServer.Management.Dmf.PolicyEvaluationHelper..cctor()
System.TypeInitializationException:
at Microsoft.SqlServer.Management.Dmf.PolicyEvaluationHelper.EvaluateAutomatedPolicy(String policy, SqlXml eventData, Int64& historyId)
at Microsoft.SqlServer.Management.Dmf.PolicyEvaluationWrapper.EvaluateAutomatedPolicy(String policy, SqlXml eventData, Int64& historyId)
What do I need to do to get ride of this error?
I have updated the stored procedures to prefix of proc_. Now they're proc_MyProcedure.
I am still getting the same error.
Any suggestions?

Basically the problem was that microsoft.sqlserver.diadnostics.strace.dll was not installed in the GAC. Furthermore, this file was not on my server, and not on the installation DVDs, so I couldn't install it. I found it on my PC at home, but there was a trick to getting to my work server.
I believe that I've fixed the problem by copying
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\Microsoft.SqlServer.Diagnostics.STrace to C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSSHell\Common7\IDE

Related

F# SqlDataProvider, "The type initializer for 'Main' threw an exception.'

I have been attempting to use the SqlProvider type provider on several different databases where I work. In Visual Studio, intellisense for these different DBs (of types MS Access, SQL Server, and an ODBC connection) all work as shown below:
I've even tried it on the Northwind example database:
It does not matter the connection I actually choose, they seem to all result in 2 exceptions when the code is actually run:
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'Main' threw an exception.
Source=SqlProviderTest2
StackTrace:
at Main.main(String[] _arg1) in C:\Users\***\source\repos\SqlProviderTest2\Program.fs:line 29
Inner Exception 1:
TypeInitializationException: The type initializer for '<StartupCode$SqlProviderTest2>.$Main' threw an exception.
Inner Exception 2:
FileLoadException: Could not load file or assembly 'System.Data.OleDb, Version=4.0.1.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
How is it possible that the intellisense can detect the DB but not work when the program is actually run? Is there a common fix for this?
(Using Visual Studio 2019 Professional, if that makes a difference.)

Why is my Deployment script causing me errors?

I am working on a project in visual studio 2012. Recently, I added a database project to the solution. The database already existed before I added it to the solution and everything worked fine.
Now, however, when I try to run the application I get errors. The errors are being caused by a computer-generated file called [database name].sql. At the top of the tile, it reads:
/*
Deployment script for [the database name here]
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
This file gets re-created every time the application runs. The errors that occur appear to be syntax errors. I cannot fix them because any changes I make to the file are irrelevant because a new file gets generated with each run and the errors re-appear.
I tried looking into this more online but had trouble. This is all rather new to me.
Here are some of the errors being created:
GO
:setvar DatabaseName "(the database name is here)"
which gives me three errors that read:
Error 88 SQL80001: Incorrect syntax near ':'.
Error 89 SQL80001: 'DatabaseName' is not a recognized option.
Error 90 SQL80001: Incorrect syntax near '"(the database name is here in the code)"'.
Also, there is a line of code that reads:
CREATE USER [(the domain)\(the username)] FOR LOGIN [(the domain)\(the username)];
GO
which gives the following error:
Error 119 SQL72014: .Net SqlClient Data Provider: Msg 15401, Level 16, State 1, Line 1 Windows NT user or group '(the domain)\(the username)' not found. Check the name again.
From the errors you have posted it looks like there are two issues:
Windows NT user or group '(the domain)\(the username)' not found. - The user being used to access the database doesn't exist. As it's a Windows user I'm guessing that it uses the current user's credentials.
Make sure that your instance of SQL can accept Windows logins and that you (and anyone else building the software) has the necessary access rights.
'DatabaseName' is not a recognized option. - This is more than likely also caused by the first issue, but double check that the database exists.
The error message caught me out recently as it did not relate to the cause of my problem at all. It turns out my SQL script was incorrectly written (for my case - I forgot to add IDENTITY (1,1) to my PK column) to begin with.
Moral of the story for me was to test out the SQL data file in SSMS first.

MQQueueManager Constructor throwing FileNotFoundException

I have the following vb.net code:
Imports IBM.WMQ
[...]
MQEnvironment.Hostname = hostName
MQEnvironment.Port = portNumber
MQEnvironment.Channel = channelName
queueManager = New MQQueueManager(queueManagerName) ' error here
which is throwing the following error:
System.IO.FileNotFoundException occurred
FileName=C:\Users\User\Documents\Visual Studio 2012\Projects\[...]\bin\Debug\mqclient.ini
HResult=-2147024894
Message=Could not find file 'C:\Users\User\Documents\Visual Studio 2012\Projects\[...]\bin\Debug\mqclient.ini'.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
I am not using any ini files in the construction of my queue manager, so does anyone have any idea what's going on - why is it even looking for one, and why in the same directory as the program? I have installed the MQ client, and afaik I have all the environmental variables, etc. set up properly.
Thanks for any help you can give
Is that an unhandled or a first chance exception? Internally, the MQ .net layer will try to read a MQClient.ini but should function quite happily without it. It reads the file for compatibility with the C client, and can handle some of the MQClient.ini stanzas. I would not have expected an absence of such a file to cause problems, but it will try to open it internally. Was that the full callstack, as I'd have expected some MQ libraries on the stack otherwise.

Firebird Error: "operating system directive CreateFile failed"

Did any one see this error ??
I'm using Firebird 2.1 and database create statement is getting failed on v.first stored procedure execution.
Error Message:
[869] : There was a problem creating a DBProvider with the following parameters: StoredProcedureName:sel_NextObjectID
2. operating system directive CreateFile failed
3. operating system directive CreateFile failed
Stack Trace
2.at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
at FirebirdSql.Data.FirebirdClient.FbConnectionPool.Create()
at FirebirdSql.Data.FirebirdClient.FbConnectionPool.CheckOut()
at FirebirdSql.Data.FirebirdClient.FbConnection.Open()
at FirebirdDBProvider.NewProvider_Internal(String commandText, String connectionString, CommandType commandType)
3 at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect()
at FirebirdSql.Data.FirebirdClient.FbConnectionPool.Create()
at FirebirdSql.Data.FirebirdClient.FbConnectionPool.CheckOut()
at FirebirdSql.Data.FirebirdClient.FbConnection.Open()
at FirebirdDBProvider.NewProvider_Internal(String commandText, String connectionString, CommandType commandType)
You can get this error when you are attempting to connect to a database which does not yet exist.
It is not entirely clear from your post what you mean with 'database create statement is getting failed on v.first stored procedure execution', but I assume you are attempting to create a database and then execute DDL.
To connect to a database, you first need to create it. To create a database you need to use createDatabase first.
Well, deleting all temp file fixed this thing. Found the same issue on firebird too.
1) Make sure your application (on which you're facing this issue) is not running.
2) One Run dialog (Window + R) and type in “%temp%” and click “ok”
3) In the opened folder delete all the files (which can be deleted).
4) Start the application.
Just had same issue, the reason was no free space available on the system drive.

Sql 2005 CLR Integration - Is Dynamic Assembly Loading supported?

I have a static class which loads a .NET assembly dynamically (using Assembly.LoadFile method)
I get the following error message:
Msg 6522, Level 16, State 2, Line 3
A .NET Framework error occurred during execution of user-defined routine or aggregate "MySQLCLRUDFFunction":
System.TypeInitializationException: The type initializer for 'MyClassName' threw an exception. ---> System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
.
When I try assign CAS security using this declaration
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
I instead get this exception
Msg 6522, Level 16, State 2, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "MySQLCLRUDFFunction":
System.TypeInitializationException: The type initializer for 'MyClassName' threw an exception. ---> System.Security.SecurityException: Request failed.
Note: I have given my SQL Server service account "Full Access" to my dynamic assemly file on disk. I copied my dyamic assembly using syntax:
create Assembly TestAssembly
From 'C:\MyTestAssembly.dll';
--Alter Assembly to copy dynamic assembly file
Alter Assembly TestAssembly add file from 'C:\mydynamicassembly.dll';
After turning TRUSTWORTHY ON and setting PERMISSION_SET = UNSAFE I now get this exception
Msg 6522, Level 16, State 2, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "MySQLCLRUDFFunction":
System.TypeInitializationException: The type initializer for 'MyClassName' threw an exception. ---> System.IO.FileLoadException: LoadFrom(), LoadFile(), Load(byte[]) and LoadModule() have been disabled by the host.
As the error message states, dynamic assembly loading is completely disallowed by SQL Server - even under unsafe. The only way for Assembly.Load calls to succeed is if the assembly is already loaded in the database via CREATE ASSEMBLY or in the GAC and on the list of supported ("blessed") assemblies. There is another post on this on the sqlclr blog.
I know this is a very old question now, but I have recently found a way to achieve what you want. When you try and using Assembly.Load(...) in a SQL CLR hosted assembly, it will explicitly fail, this is by design, even with PERMISSION_SET = UNSAFE. This is to ensure the stability of the database server.
The technique to loading your dynamic assemblies, is to register them first and then resolve the type using Type.GetType(...) passing in the fully qualified type name (including assembly version information.
Here are the steps:
1.Compile the type, and finalise on disk (i.e. do not create in-memory assemblies). The CompilerResults type will have a CompiledAssembly property and PathToCompiledAssembly property. Use the latter as accessing the CompiledAssembly property will attempt to use Assembly.Load.
2.Using the path, I call a stored procedure from my code (using new SqlConnection("Context Connection = true")) which I pass in the name of the assembly (which I have predetermined) and the compiled assembly path:
CREATE PROCEDURE re.CreateAssembly
#name VARCHAR(100),
#path VARCHAR(1000)
AS
BEGIN
DECLARE #sql NVARCHAR(2000)
SET #sql = N'CREATE ASSEMBLY [' + #name + '] AUTHORIZATION [DatabaseUser] FROM ''' + #path + ''' WITH PERMISSION_SET + SAFE';
EXEC sp_executesql #sql;
END
GO
3.Using your predetermined name, you can use Type.GetType(...), e.g.:
string typeName = "MyCompiledAssembly.MyClass, MyCompiledAssembly, Version=0.0.0.0, Culture=Neutral, PublicKeyToken=null, ProcessorArchitecture=MSIL";
Type type = Type.GetType(typeName);
When the SQLCLR attempts to resolve the type, it should find it, because in step 2 you've already registered the assembly with Sql Server.
I'm guessing you've got the PERMISSION_SET set to SAFE when you did CREATE ASSEMBLY (this will be the default if you didn't specify it). You'll need to change it to EXTERNAL_ACCESS or UNSAFE if you want to do this.
http://msdn.microsoft.com/en-us/library/ms189524.aspx
I was one the developers # Microsoft who worked on SQL-CLR integration, so I may be able to help.
To achieve what you want you need to do two things:
Mark data base as TRUSTWORTHY
Mark assembly as UNSAFE (database must be trustworthy)
The account under which SQL Server runs must have permissions to access the file on the the file system. Often times the file is on a network share but SQL Server is run under local account that has no permission to access network, so this is often a problem. SQL Express in itse default installation does not have rights to C:.
Note that doing all those things has several negative side-effects:
serious security implications - you are effectively ceding control over the instance to the code in unsafe assembly as it can now use raw pointers to access/change anything in the engine.
Stability - you're also ceding stability guarantees for the same reasons.
Portability and disaster recovery - if you database has to move elsewhere for load-balancing or is restored from backup after machine failure you will not have the mydynamicassembly.dll on the new machine.
If at all possible, consider redesigning your app so that all needed assemblies are pre-loaded into the database itself.
[EDIT: if none of the above helps it best to ask on MSDN forums].