A net framework error occurred during execution of user defined routine or aggregate

I have a database will all CLR functions, I deploy it to a master database and then the rest of the servers get a backup and restore copy of it. For some reason some functionality works in some servers and not in other ones. I am aware the CLR routines requires external access and that is ok here. The assemblies below had to be manually deployed to make the original database work since I could not figure out how to have them deployed from VS2010 project.

I have a database will all CLR functions, I deploy it to a master database and then the rest of the servers get a backup and restore copy of it. For some reason some functionality works in some servers and not in other ones. I am aware the CLR routines
requires external access and that is ok here. The assemblies below had to be manually deployed to make the original database work since I could not figure out how to have them deployed from VS2010 project.

Can somebody guide me on how to make the same CLR database function the same accross multiple servers (most of them are Windows 2008 64 bit, couple test machines are Windows 7 64 bit and we have few Windows 7 32 bit)

Thanks in advance.

IF NOT EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N’System.DirectoryServices’ and is_user_defined = 1)

CREATE ASSEMBLY [System.DirectoryServices] FROM ‘C:WindowsMicrosoft.NETFrameworkv2.0.50727System.DirectoryServices.dll’

WITH PERMISSION_SET = UNSAFE

IF NOT EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N’System.Management’ and is_user_defined = 1)

CREATE ASSEMBLY [System.Management] FROM ‘C:WindowsMicrosoft.NETFrameworkv2.0.50727System.Management.dll’

WITH PERMISSION_SET = UNSAFE

IF NOT EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N’Microsoft.Data.Schema.ScriptDom’ and is_user_defined = 1)

CREATE ASSEMBLY [Microsoft.Data.Schema.ScriptDom] FROM ‘C:WindowsMicrosoft.NETFrameworkv2.0.50727Microsoft.Data.Schema.ScriptDom.dll’

WITH PERMISSION_SET = UNSAFE

IF NOT EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N’Microsoft.Data.Schema.ScriptDom.Sql’ and is_user_defined = 1)

CREATE ASSEMBLY [Microsoft.Data.Schema.ScriptDom.Sql] FROM ‘C:WindowsMicrosoft.NETFrameworkv2.0.50727Microsoft.Data.Schema.ScriptDom.Sql.dll’

WITH PERMISSION_SET = UNSAFE

Msg 6522, Level 16, State 2, Line 1

A .NET Framework error occurred during execution of user-defined routine or aggregate «GetVolumeInfo_CLR»: 

System.IO.FileLoadException: Could not load file or assembly ‘System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. Assembly in host store has a different signature than assembly in GAC. (Exception
from HRESULT: 0x80131050) See Microsoft Knowledge Base article 949080 for more information.

System.IO.FileLoadException: 

   at UtilClr.FileSystemFunctions.GetVolumeInfo()

.


Gokhan Varol

SQL Server 2017 Developer on Windows SQL Server 2017 Enterprise on Windows SQL Server 2017 Enterprise Core on Windows SQL Server 2017 Standard on Windows SQL Server 2016 Enterprise Core SQL Server 2016 Standard SQL Server 2016 Developer SQL Server 2016 Enterprise More…Less

Symptoms

Consider the following scenario:

  • You have a SQL CLR function in SQL Server 2016 and 2017.

  • The CLR function invokes Transact-SQL statements through impersonation calls, such as by calling the EXECUTE AS statement.

In this scenario, the execution fails, and you receive the following error message:

Msg 6522, Level 16, State 1, Procedure PrcedureName, Line 0 [Batch Start Line LineNumber]

A .NET Framework error occurred during execution of user-defined routine or aggregate «ProcedureName«:

System.Data.SqlClient.SqlException: The server principal «LoginName» is not able to access the database «DatabaseName» under the current security context.

Resolution

This fix is included in Cumulative Update 1 for SQL Server 2017.

Service pack information for SQL Server 2016

This issue is fixed in the following service pack for SQL Server:

       Service Pack 2 for SQL Server 2016

About SQL Server 2017 builds

Each new build for SQL Server 2017 contains all the hotfixes and security fixes that were in the previous build. We recommend that you install the latest build for SQL Server 2017.

Service packs are cumulative. Each new service pack contains all the fixes that are in previous service packs, together with any new fixes. Our recommendation is to apply the latest service pack and the latest cumulative update for that service pack. You do not have to install a previous service pack before you install the latest service pack. Use Table 1 in the following article for finding more information about the latest service pack and latest cumulative update.

How to determine the version, edition and update level of SQL Server and its components

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

References

Learn about the terminology Microsoft uses to describe software updates.

Need more help?

Asked
7 years, 2 months ago

Viewed
17k times

I am trying to deploy a SSDT 2012 SSIS project using Deploy option. But I am getting below error:

TITLE: SQL Server Integration Services

A .NET Framework error occurred during execution of user-defined routine or aggregate «deploy_project_internal»:
System.ComponentModel.Win32Exception: A required privilege is not held by the client
System.ComponentModel.Win32Exception:
at Microsoft.SqlServer.IntegrationServices.Server.ISServerProcess.StartProcess(Boolean bSuspendThread)
at Microsoft.SqlServer.IntegrationServices.Server.ServerApi.DeployProjectInternal(SqlInt64 deployId, SqlInt64 versionId, SqlInt64 projectId, SqlString projectName)
. (Microsoft SQL Server, Error: 6522)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=11.00.5058&EvtSrc=MSSQLServer&EvtID=6522&LinkId=20476

Any idea why this error? below is the screen shot of the error.

enter image description here

billinkc's user avatar

billinkc

58.1k9 gold badges102 silver badges158 bronze badges

asked Dec 9, 2015 at 22:42

user5661489's user avatar

Went through most of the other solutions but using the repair option worked.

The problem could have been due to the installation of Visual Studio and SSDT after SQL was installed.

Would be nice if MS provided better support for their products rather than leaving to the community to fix the problem.

answered Jul 24, 2019 at 0:39

Graeme's user avatar

2

answered Feb 7, 2019 at 11:41

SinisterPenguin's user avatar

If you faced this error when you want to connect Data Quality Services (from Data Quality Client or from SSIS DQS Cleansing component);

You can fix it in following way;

Why this happens:

When .NET Framework updates installs on Data Quality Server machine

example:

For me it happened when I installed SSDT – BI projects for Visual Studio 2012 which released yesterday!

Solution:

You need to upgrade data quality services dlls with these steps:

1- Open Command Prompt 

2- go to DQS installed folder with this:

cd C:Program FilesMicrosoft SQL ServerMSSQL11.MSSQLSERVERMSSQLBinn

3- Run this command:

DQSInstaller.exe -upgradedlls

after finishing upgradedlls you will be able to connect to DQS successfully.

here you can read MSDN article about it:

http://msdn.microsoft.com/library/hh479773.aspx

Reza Rad

Trainer, Consultant, Mentor

Reza Rad is a Microsoft Regional Director, an Author, Trainer, Speaker and Consultant. He has a BSc in Computer engineering; he has more than 20 years’ experience in data analysis, BI, databases, programming, and development mostly on Microsoft technologies. He is a Microsoft Data Platform MVP for nine continuous years (from 2011 till now) for his dedication in Microsoft BI. Reza is an active blogger and co-founder of RADACAD. Reza is also co-founder and co-organizer of Difinity conference in New Zealand.
His articles on different aspects of technologies, especially on MS BI, can be found on his blog: https://radacad.com/blog.
He wrote some books on MS SQL BI and also is writing some others, He was also an active member on online technical forums such as MSDN and Experts-Exchange, and was a moderator of MSDN SQL Server forums, and is an MCP, MCSE, and MCITP of BI. He is the leader of the New Zealand Business Intelligence users group. He is also the author of very popular book Power BI from Rookie to Rock Star, which is free with more than 1700 pages of content and the Power BI Pro Architecture published by Apress.
He is an International Speaker in Microsoft Ignite, Microsoft Business Applications Summit, Data Insight Summit, PASS Summit, SQL Saturday and SQL user groups. And He is a Microsoft Certified Trainer.
Reza’s passion is to help you find the best data solution, he is Data enthusiast.

If you are working with CLR in SQLServer you might run into

A .NET Framework error occurred during execution of user-defined routine or aggregate "MyCLRMethod":   System.InvalidOperationException: The context connection is already in use.

I cannot say this is the solution every time but it worked for me.  Look down to the top of the stack (furthest down in the text) and you get some more clues.

Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "MyCLRMethod":
System.InvalidOperationException: The context connection is already in use.
System.InvalidOperationException:
 at System.Data.SqlClient.SqlInternalConnectionSmi.Activate()
 at System.Data.SqlClient.SqlConnectionFactory.GetContextConnection(SqlConnectionString options, Object providerInfo, DbConnection owningConnection)
 at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
 at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
 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 Elvis.DatabaseCLR.UserDefinedFunctions.GetNextSampleID(DateTime readDate, Int32 meterID, Boolean useNextMeter)
 at Elvis.DatabaseCLR.UserDefinedFunctions.ConsumptionForNewMeter(Int32 sampleID, DateTime readDate, Int32 meterID, Decimal meterCoefficient, Int32 previousMeterConsumption, DateTime presentationDateOfSample)
 at Elvis.DatabaseCLR.UserDefinedFunctions.MyCLRMethod(Int32 sampleID, DateTime presentationDate, DateTime readDate, Int32 meterID, Decimal meterCoefficient, Boolean newMeter)

.

The MyCLRMethod calls two more methods until Open is called.  Playing around I found that I couldn’t open a connection if one already was open.  It sounds right since one of the deals with CLR in SQLServer is that we already have a connection.  The resolution is to tidy up the code so we only open the connection once, or open/closes it over and over again.

Tricks I used:
– When you get the error in your applicaiton copy the SQL string to your query editor and run it from there.
– Press F5 in Visual studio and have Visual studio deploy the CLR for you.  But use the query tool to run the query.  The error message is the same.
– Debug-through-printf, or “throw exception” in this case.  Drop in a throw-exception to find out exactly which Open call is failing.  The F5-and-wait and then run query takes a while.  If you have a logging possibility it is handy now.

Tags: clr in sqlserver, connectio, debugging, dotnet

This entry was posted on Thursday, September 2nd, 2010 at 21:27 and is filed under Code and Development.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Добрый день!
Есть сборка (это ее часть)

C#
1
2
3
4
5
6
7
8
9
10
 [Microsoft.SqlServer.Server.SqlFunction]
    public static string fn_fk1_getdata(string xml, string url)
    {
 
        ...
 
        StreamWriter sw = File.AppendText(@"C:FK1fk.log");
        sw.WriteLine(str1);
        sw.Close();
        ...

Она построена и опубликована. Создана сборка в SQL Server Management Studio 2008
При вызове сборки из процедуры возникает ошибка
A .NET Framework error occurred during execution of user-defined routine or aggregate «fn_fk1_getdata»: System.Security.SecurityException: Request for the permission of type ‘System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Cult

И еще нюанс: во всех сборках на сервере набор разрешений «неограниченный» , а у моей — «безопасный» и изменить не получается. Ошибка «Unsafe assembly permission was denied on object ‘server’, database ‘master'»

Подскажите, пожалуйста, что делать в такой ситуации???
Спасибо!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

This is one of the most common problems we get asked, and it’s also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null — which means that there is no instance of a class in the variable.
It’s a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn’t a pen there, you can’t sign your name on a piece of paper — and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can’t do anything that you would normally do once you retrieved your pen. Why is it empty? That’s the question — it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can’t tell, because we weren’t there, and even more importantly, we can’t even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow — and we can’t see your code, much less run it and find out what contains null when it shouldn’t.
But you can — and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can’t do that — we don’t have your code, we don’t know how to use it if we did have it, we don’t have your data. So try it — and see how much information you can find out!

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Assignees

@MladjoA

Comments

@IanKemp

docs.microsoft.com

Input:

select geometry::STLineFromText('LINESTRING ZM (1 2 0 0,3 4 0 0)', 0)

Result:

Msg 6522, Level 16, State 1, Line 8
A .NET Framework error occurred during execution of user-defined routine or aggregate "geometry": 
System.FormatException: 24142: Expected "(" at position 11. The input has "Z".
System.FormatException: 
   at Microsoft.SqlServer.Types.WellKnownTextReader.RecognizeToken(Char token)
   at Microsoft.SqlServer.Types.WellKnownTextReader.ParseLineStringText()
   at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)
   at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)
   at Microsoft.SqlServer.Types.SqlGeometry.GeometryFromText(OpenGisType type, SqlChars text, Int32 srid)

Occurs on both SQL Azure and SQL 2016 LocalDB.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

  • ID: ffb8630f-fe2c-f388-f2a7-1aca2a1a6a65
  • Version Independent ID: 1d4dda34-e068-0735-d405-70a7ac88ee34
  • Content: STLineFromText (geometry Data Type) — SQL Server
  • Content Source: docs/t-sql/spatial-geometry/stlinefromtext-geometry-data-type.md
  • Product: sql
  • Technology: t-sql
  • GitHub Login: @MladjoA
  • Microsoft Alias: mlandzic

@msebolt

@IanKemp Thank you for the question.

Does this work if you remove the ZM?

select geometry::STLineFromText('LINESTRING (1 2 0 0,3 4 0 0)', 0)

@airbreather

@IanKemp SQL Server seems to read WKT with Z/M/ZM data differently than the OGC WKT standard. See NetTopologySuite/NetTopologySuite#324 for when I first discovered this.

If the WKT is coming from NetTopologySuite, then you can useWKTWriter.ForMicrosoftSqlServer() (as of NTS 2.0.0) to get an instance of WKTWriter that writes out WKT in the format that SQL Server expects.

@IanKemp



Copy link


Contributor

Author

@IanKemp SQL Server seems to read WKT with Z/M/ZM data differently than the OGC WKT standard. See NetTopologySuite/NetTopologySuite#324 for when I first discovered this.

If the WKT is coming from NetTopologySuite, then you can useWKTWriter.ForMicrosoftSqlServer() (as of NTS 2.0.0) to get an instance of WKTWriter that writes out WKT in the format that SQL Server expects.

Sadly I am stuck on Core 2.2 / NTS 1.15 as our company has some pressing deadlines coming up and they don’t want to risk anything by migrating to 3.0 / NTS 2.0 until after said deadlines have been met.

Since MSSQL doesn’t fully implement OGC 06-103r4, a note should be added to the docs of the geometry::ST*FromText methods to give examples of the WKT geometries that aren’t supported.

@msebolt

Assigning this to the author for review.

@msebolt
msebolt

added

doc-enhancement

If the feedback is about suggested additions/improvements to the article, but there is no evidence

and removed

support-request

A support-style question where the customer needs help solving a problem

labels

Oct 4, 2019

@MladjoA

@IanKemp , thanks for bringing up this issue.
geometry::STLineFromText article is being updated with the remarks and examples for three-dimension and measured geometry WKT format as we speak. The rest of the related articles will be updated in the following days.

@vishnu4

If the WKT is coming from NetTopologySuite, then you can useWKTWriter.ForMicrosoftSqlServer() (as of NTS 2.0.0) to get an instance of WKTWriter that writes out WKT in the format that SQL Server expects.

What about if you’re not using WKTWriter directly, but just using .AsText() ? can we have an overload, or is there another method i can/should be using here?

@MladjoA

@vishnu4 , are you referring to an alternative NetTopologySuite functionality, or your question was related to SQL Server Spatial. If latter, can you please elaborate your scenario?

@vishnu4

@vishnu4

So it looks like i was able to get around my issue by replacing any occurance i had of
.AsText()
to
.ToWKT()

where ‘ToWKT’ is just an extension method i made below. keeping my sql/not sql options open with the second parameter too.:

public static string ToWKT(this NetTopologySuite.Geometries.Geometry geom, bool forSQL = true)
        {
            if (geom != null && geom.IsValid)
            {
                WKTWriter w;
                if (forSQL)
                {
                    w = WKTWriter.ForMicrosoftSqlServer();
                }
                else
                {
                    w = new WKTWriter();
                }
                return w.Write(geom);
            }
            return string.Empty;
        }

@cawrites

@IanKemp thank you for contacting Microsoft. It appears your original question has been answered. Please don’t hesitate to contact Microsoft again with your content-related questions.

@cawrites

Last week at customer side we faced the issue that project deployment of a SQL 2012 SSIS Project was not possible any more. On Wednesday we deployed the Project with Project-Deployment-Modell and all went fine. Doing the same thing on Friday with the new build the deployment failed. The following error message appeared:

Error 6522, A required privilege is not held by the client

Error 6522, A required privilege is not held by the client

Msg 6522, Level 16, State 1, Procedure deploy_project_internal, Line 0 A .NET Framework error occurred during execution of user-defined routine or aggregate „deploy_project_internal“: System.ComponentModel.Win32Exception: A required privilege is not held by the client System.ComponentModel.Win32Exception: at Microsoft.SqlServer.IntegrationServices.Server.ISServerProcess.StartProcess(Boolean bSuspendThread) at Microsoft.SqlServer.IntegrationServices.Server.ServerApi.DeployProjectInternal(SqlInt64 deployId, SqlInt64 versionId, SqlInt64 projectId, SqlString projectName) At first I thought it’s a Visual Studio 2010 / Data Tools issue. So I tried to deploy the project using the stored procedure „catalog.deploy_project“ but it failed with the same issue. On another server the deployment worked. So the project itself was still fine. While searching the web for error code and the error message I found hints pointing in the direction of CLR- or DCom-Permissions. Others reported that the error reappeared after a reboot. I checked the SQL-Server and Windows errorlog. The server was rebooted in the meantime and admins told the some group policies might have been applied to the server. So I tried the solutions presented in the web but none really worked, neihter giving the SQL-Server-Engine-Account and the SSIS-Service-Account the full permission in DCom-configuration nor adding the Service-Accounts to the local administrator group. Using Local-System-Account was no option as it was set to use Active-Directory-Service-Accounts. Another search in the internet brought up the hint to do a SQL-Server-Repair-Installation. But it was also said that this „fix“ only works to the next reboot. So this couldn’t be the correct answer. But then it came to my mind: „If a Repair-Installation helps and we know it has something to do with permissions and Group-Policies, let’s check which permissions are granted during the (Repair-)Installation.“ Microsoft says the following permissions are required:

SQL Server Service Permissions granted by SQL Server Setup
SQL Server Database Engine: (All rights are granted to the per-service SID. Default instance: NT SERVICEMSSQLSERVER. Named instance: NT SERVICEMSSQL$InstanceName.) Log on as a service (SeServiceLogonRight) Replace a process-level token (SeAssignPrimaryTokenPrivilege) Bypass traverse checking (SeChangeNotifyPrivilege) Adjust memory quotas for a process (SeIncreaseQuotaPrivilege)Permission to start SQL WriterPermission to read the Event Log servicePermission to read the Remote Procedure Call service
SQL Server Agent:(All rights are granted to the per-service SID. Default instance: NT ServiceSQLSERVERAGENT. Named instance: NT ServiceSQLAGENT$InstanceName.) Log on as a service (SeServiceLogonRight) Replace a process-level token (SeAssignPrimaryTokenPrivilege) Bypass traverse checking (SeChangeNotifyPrivilege) Adjust memory quotas for a process (SeIncreaseQuotaPrivilege)
SSIS:(All rights are granted to the per-service SID. Default instance and named instance: NT SERVICEMsDtsServer110. Integration Services does not have a separate process for a named instance.) Log on as a service (SeServiceLogonRight)Permission to write to application event log. Bypass traverse checking (SeChangeNotifyPrivilege) Impersonate a client after authentication (SeImpersonatePrivilege)

Information from: Microsoft By checking the granted permissions I saw that the one „Replace a process-level token (SeAssignPrimaryTokenPrivilege)“ was not granted to the SQL-Server Engine- Account. I added the Account of the Engine and the Agent, restarted both services. Picture of the added accounts to the user right

Et voilà! The deployment is working again! To make sure the permission will survive the next reboot, it was only necessary to add the Accounts via GPO to this right and everything is working again. You can test this behavior the revoking this right from the Agent-Account . The next job start will bring up the same error message as above. Good luck with fixing this issue.

Понравилась статья? Поделить с друзьями:
  • A minidump has been written to redacted black ops 2 как исправить
  • A lzh archive not found inpa как исправить
  • A low level exception occurred in importermpeg importer 39 как исправить
  • A low level exception occurred in adobe premiere как исправить
  • A lock file already exists in the repository which blocks this operation from completing ошибка