Quantcast
Channel: .NET Framework inside SQL Server forum
Viewing all 780 articles
Browse latest View live

More records (table with one Varchar Max column) causes deadlock with windows services

$
0
0

Hi,

I have a windows service for sending emails by reading email contents from a table including the body (Varchar Max with 40000bytes of data). The windows service will update the status of each record after sending email. My issue exists only of I have records more than say 7500 in the table. That is my windows service will work fine with all updates to table if the number of records in the table is less than 7500 records. If the number of records exceeds 7500 then it cause a deadlock in the table and my windows service will fail to send email. Please help with your suggestions...


SQLServer2012: Load CLR Assembly Targeting Framework 2.0

$
0
0

Hi

i have a .Net Assembly (say Dummy.dll) that depend on a few CLR 2.0 Assemblies (DepA.dll, DepB.dll) that depend on v2.0 System Assemblies.

I need to load this Assembly (and all dependencies) into SQLServer supporting V.2005 to V.2012. I'm unable to recompile the dependencies (DepA.dll, DepB.dll, they are compiled for 2.0 and depend on 2.0 System Assmblies).

With SQLServer V2005-V2008R2 i do the following tasks to install Dummy.dll.:

- Enable clr
- Set Database Trustworthy
- CREATE ASSEMBLY  for all unsupported System Assemblies WITH permission_set = UNSAFE
- CREATE ASSEMBLY  for all dependend assemblies DepA.dll, DepB.dll WITH permission_set = UNSAFE
- CREATE ASSEMBLY Dummy.dll WITH permission_set = UNSAFE

This Works.

I use the same Assembly (Dummy.dll) in a 4.0 WinForm and in a Asp.Net 4.0 Application. Because the 4.0 CLR is backward compatible that works without any problems.
I am not able to load the Assembly (Dummy.dll) nor the dependencies nor the unsupported system assemblies into SQLServer 2012.
How is this possible ?

If the 4.0 Runtime in SqlServer 2012 is not backward compatible, is it possible to force SQLServer 2012 to use the 2.0 Runtime ?

My approach is:
1. For System Assemblies: Load the corresponding 4.0 assemblies instead of the 2.0, 3.0, 3.5 ones.
2. For dependend Assemblies: Try to load them (hope that this works)
3. For Dummy.dll: Try to load the 2.0 Version, if not working, recompile for 4.0 and load that.

I failed already at Step 1

Instead of creating the CLR 2.0 System Assemblies i tried to load the corresponding 4.0 ones.
This works for Sytem.Web.dll but not for WindowsBase.dll.

In SqlServer 2008R2 i load the assembly using the following Statement (on x64):

CREATE ASSEMBLY [WindowsBase] FROM 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll' WITH permission_set = UNSAFE

This Works.

In SqlServer 2012 i used the following Statement:

CREATE ASSEMBLY [WindowsBase] FROM 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll' WITH permission_set = UNSAFE




That gives me the following Error:

Msg 6218, Level 16, State 2, Line 3
CREATE ASSEMBLY for assembly 'WindowsBase' failed because assembly 'WindowsBase' failed verification. Check if the referenced assemblies are up-to-date and trusted (for external_access or unsafe) to execute in the database. CLR Verifier error messages if any will follow this message
[ : MS.Internal.ResourceIDHelper::GetResourceIDFromRelativePath][mdToken=0x6000001][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.SecurityCriticalDataForSet`1[T]::.ctor][mdToken=0x6000002][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.SecurityCriticalDataForSet`1[T]::get_Value][mdToken=0x6000003][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.SecurityCriticalDataForSet`1[T]::set_Value][mdToken=0x6000004][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::.cctor][mdToken=0x6000012][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::CheckUnmanagedCodePermission][mdToken=0x6000005][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::DemandUnmanagedCode][mdToken=0x6000006][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::DemandRightsManagementPermission][mdToken=0x6000007][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::DemandCompoundFileIOPermission][mdToken=0x6000008][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::DemandPathDiscovery][mdToken=0x6000009][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::RunClassConstructor][mdToken=0x600000a][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::SizeOf][mdToken=0x600000b][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::SizeOf][mdToken=0x600000c][Offset 0x00000000] Die Codegröße ist 0 (null).
[ : MS.Internal.WindowsBase.SecurityHelper::ThrowExceptionForHR][mdT...

I don't know how to get arround this. I tried to load the V3.0 Version, that produces the follwing (expected) error:


Msg 6586, Level 16, State 1, Line 1
Assembly 'WindowsBase' could not be installed because existing policy would keep it from being used.

Any suggestions ?

Thanks Stefan

ALTER ASSEMBLY and Continuous Integration

$
0
0

I have a small assembly of scalar SQL functions built in .NET that I've manually integrated to SQL Server with CREATE ASSEMBLY and then CREATE FUNCTION.  However, as part of my continuous integration and deploy process, I'd like to update the assembly with every build using ALTER ASSEMBLY.

I've already taken care to guard against an unchanged MvID in the SQL batch I execute to do the update, but whenever a new build runs (and the MvID apparently changes), I get the following error:

ALTER ASSEMBLY failed because the required method "Xxx" in type "Yyy" was not found with the same signature in the updated assembly.

But the signature hasn't changed!  The signature is still just "DateTime? Yyy(DateTime?)".

I've found very little information about this error in particular.  Any suggestions?

Unable to add the PresentationFramework assembly

$
0
0

Hello

I am in the process of creating a CLR Function. One of the assemblies that I need to use for my CLR function is the PresentationFramework assembly.

When I try to add the assembly to my SQL database I get the following error:

Create failed for SqlAssembly 'PresentationFramework'.

Assembly 'presentationcore, version=3.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35'. was not found in the SQL catalog.

I tried adding the assembly from the following location (this is the same location that I successfully added the PresentationCore assembly from):

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0

I have already added the PresentationCore assembly to SQL and when I query sys.assemblies I can see it there with the same version number and publickeytoken as specified in the error:

name principal_id assembly_id clr_name permission_set permission_set_desc is_visible create_date modify_date is_user_defined
PresentationCore 1 65592 presentationcore, version=3.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35, processorarchitecture=x863 UNSAFE_ACCESS 1 2013-06-14 14:39:00.213 2013-06-14 14:39:00.213 1

The version of SQL I am using is 10.50.1600.

Please can someone explain why SQL is throwing this exception and provide me with a solution.

Many thanks

Dan

hi

$
0
0

hi
i am new in this laguange and i  wantto be agreat programmer of the ASP.NET language

help me out

AddWithValue issue - Update the current field content

$
0
0

I have a shopping cart where when an item is "Removed" from the cart, the corresponding Database field "NewTotal" is updated with the amount removed. So, ifNewTotal is currently (5) and the amount being returned to inventory is (3), then the NEW "NewTotal" amount should be (8)

I am using the following code.  If I use SQL Server Management Studio to run the query, it performs as expected; but in the code page it does not... what am I doing wrong.. I suspect the issue is with the "AddWithValue" definition?

Thank you in advance!

Dim strSQL02 AsString = "Update [ClinicTest2].[dbo].[ICDbS_Products] SET "& _
"NewTotal = (NewTotal +'"& QtyToRemove &"')" & _
"WHERE ProductNoID = '"& ItemNumber &"'"

Dim myCommand02 AsNewSqlCommand(strSQL02, objConn02)

myCommand02.Parameters.AddWithValue("@NewTotal","@NewTotal"+ QtyToRemove)

SSRS Subscription - Custom Email delivery extension

$
0
0

Can some one please send my way some sample code for putting together a custom email delivery extension in SSRS.. I know it can be done but not sure how to pull all the values I need i.e. the processed report, the user email id's, delivery parameters like subject that are specified in the subscription ?

I would appreciate if you can atleast point me to a nice tutorial atleast.

Thanks

Compatible SQLCLR version for various SQL server

$
0
0

Hi, I could not find any documentation on what SQL CLR version is supported on various SQL Servers.

We have a project which uses CLRs stored procedures and is expected to support almost all SQL Servers starting from SQL Server 2005 Express (Including  SQL Server 2012 - 32 & 64 bit).

Can someone provide that information or point to the resource where I can find that information?

Any help is appreciated.

Thanks.


FBA and getting the context back to SQL? URGENT!

$
0
0

Hi there,

I have setup the 2008r2 FBA example with Adventureworks. Everything is working, the shared datasource has stored creds.

As we are trying to enforce security at the DB level, the problem is how does SQL know which user has authenticated in? I have tried running SYSTEM_USER, SUSER_SNAME, SUSER_NAME, SESSION_USER but they all come back with the stored creds or dbo.

If I include user_id which is a built in reference through report builder, it comes up with the user logged into Reporting (fba user) which is great, but how do you pass this info back into SQL?

Appreciate any help...

Kind Regards,

Vince

SQL Server 2008 indexed view

$
0
0
Can some one explain.? whats the use of indexed view and how it works. please provoide a step by step example.

Can't connect teradata from sql clr code

$
0
0

I try to create SQLCLR proc that access teradata server and i get this error:
"System.IO.FileLoadException: LoadFrom(), LoadFile(), Load(byte[]) and LoadModule() have been disabled by the host." i google about this error and i found that i need create .XmlSerializers.dll and add this to the DB. i did that and still i get same error. the code work stably with oracle and MSSQL, but I can't add teradata.

I'm use Teradata.Client.Provider namespace from the assembly 'Teradata.Client.Provider".

The server version is 2012.

How to activate sql 2012 std license

$
0
0

Hello Microsoft,

Kindly help me with the step by step activation of sql 2012 std.

I have the authorisation and license number(s)

Urgent help.

Best Regards

John Ablordeppey

HAVILAH Supplies Ltd

SQL CLR stored procedures & functions

$
0
0

Hi, I am using SQL Server 2008 R2. I am new to writing SQL CLR stored procedures & functions. Was wondering if there's a good book or an online resource that I could refer to as a beginner.

Thanks....

CLR user function in SQL Server 2008 R2

$
0
0

Hi, I am working on learning to CLR functions and wrote this code snippet in VB.Net.

<SqlFunction(DataAccess:=DataAccessKind.None, IsDeterministic:=True, _
                     IsPrecise:=True, Name:="RegExMatches", _
                     SystemDataAccess:=SystemDataAccessKind.None, _
            FillRowMethodName:="NextMatchedRow")> _
        Public Shared Function RegExMatches(ByVal pattern As SqlString, _
                                             ByVal input As SqlString, _
                                             ByVal Options As SqlInt32) _
                              As IEnumerable
            If (input.IsNull OrElse pattern.IsNull) Then
                Return Nothing
            End If
            Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
            RegexOption = Options
            Return Regex.Matches(input.Value, pattern.Value, RegexOption)
        End Function

Now I am trying to create an Equivalent function in SQL Server 2008 R2 & get error.

CREATE FUNCTION RegExMatches
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options INT
   )
RETURNS TABLE (
	[String] [nvarchar](MAX) NULL
) 
AS EXTERNAL NAME RegExFunction.[UserDefinedFunction].RegExMatches
GO

Error Message:

CREATE FUNCTION failed because the parameter count for the FillRow method should be one more than the SQL declaration for the table valued CLR function.

How do I re-write the above function in T-SQL.

Thanks in advance.............. 

SQL CLR

$
0
0

Window 2008 R2 /  SQL2008 R2 / Visual Studios 2010

I have been following this tutorial

http://pogo69.wordpress.com/2011/05/10/crm-web-services-from-sql-server-transact-sql-sqlclr/

When trying to execute the stored procedure I keep running into different errors. Following the threads on each error I have now come to a grinding halt with the below error

Msg 10314, Level 16, State 11, Line 4

An error occurred in the Microsoft .NET Framework while trying to load assembly id 65545. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:

System.IO.FileLoadException: Could not load file or assembly 'SqltoCRMTest, Version=1.0.4931.35492, Culture=neutral, PublicKeyToken=0975e549cb952069' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417) ---> System.Security.Policy.PolicyException: Required permissions cannot be acquired.

System.Security.Policy.PolicyException:

   at System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Boolean checkExecutionPermission)

   at System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Int32& securitySpecialFlags, Boolean checkExecutionPermission)

System.IO.FileLoadException:

   at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)

   at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)

   at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)

   at System.Reflection.Assembly.Load(String assemblyString)


Dont ask me .. i dont know


Problem with loading custom assembly (Sql 2012 Express)

$
0
0

Hello

I wanted to develop my own dll, which would be installed in sql srv 2012.

The goal of the library is to alow for communication between sql server and th "R" (is a free software environment for statistical computing: http://www.r-project.org/)

For that purpose I used R.Net (http://rdotnet.codeplex.com/), which provides R.Net.dll (which I install as a reference in my c# project)

The project (output.dll) is compiled for 'Any CPU' and for ".Net 4 Client Profile" and it works - I am able to load it by console application and successfully run calculations using "R"

Now I would like to install this assembly inside sql server and create stored procedures out of methods (decorated with [SqlProcedure()]) to do the same calculations triggered by SQL (instead of Console Application) and here is where I am getting problems:

1/ Installing Assembly (Sql2R) in db:

create assembly "Sql2R" from 'filepath\output.dll'
with permission_set=unsafe;

-> OK (Db is set as Thrustworthy )

2/ create procedure, which consumes method deliovered inside output.dll -> OK

example:

create procedure clr_getTimeRange
    @left decimal =0.1
    ,@right decimal =0.9
    ,@outputVal decimal out
as
external name
    [Sql2R].[Sql2R.CLR].[getTimeRange]
go

3/ Executing Stored procedure:

USE [myDB]
GO
DECLARE    @return_value int,
        @outputVal decimal(18, 0)

EXEC    @return_value = [dbo].[clr_getTimeRange]
        @left = 0.1,
        @right = 0.9
        ,@outputVal = @outputVal OUTPUT

SELECT    @outputVal as N'@outputVal'

SELECT    'Return Value' = @return_value
GO

gives me an ERROR:

Msg 10314, Level 16, State 11, Line 5
An error occurred in the Microsoft .NET Framework while trying to load assembly id 65552. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
System.IO.FileLoadException: Nie można załadować pliku lub zestawu 'output, Version=1.0.0.0, Culture=neutral, PublicKeyToken=aceaeaec68776e20' lub jednej z jego zależności. Podana nazwa zestawu lub ścieżka bazowa kodu jest niepoprawna. (Wyjątek od HRESULT: 0x80131047 -> Which means it cannot load file or assembly or one of it's dependency. Given path or name is incorrect)
System.IO.FileLoadException:
   w System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   w System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks)
   w System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   w System.Reflection.Assembly.Load(String assemblyString)

I tried to do this in 2 ways:

a/ registed assembly in sql server. But at some stage, when running the procedure, I got error that the assembly tries to load [RDotNet.dll], which is not acceptable (It says I am not allowed to access remote dll neither used as a reference while building or by dynamical loading (Invoke is also not allowed)).

To work this around, I merged my custom dll and RDotNet dll (with ilmerge) to one dll: output.dll, which I added as a reference

Additionally I signed the dll with keyPair.snk, so that there is no error about missig strong name

However, this still gets me nowhere

The question is what I am doing wrong and what should be the correct way of implementing a dll, which consumes external services

Thank you very much for spending time on reading this and for any hints. I guess I am blocked now and I can nly rely on your help

Kind Regards

Clogg


CLR Dependency on .dll file

$
0
0

Hello all, 

My organization is planning on using SQLCLR for the first time ever in the next few months. I have a .NET project that produces a .dll file which I store on the server and then create an assembly from it. 

I have been doing extensive testing on our development server and will soon be deploying to production. However, I am faced with an unknown.

The production database (on a separate server) is copied nightly to a development database (on a different server). The .dll file is in a different location on both the servers.

So my question is, will the assembly copy correctly from production back to development? Does the assembly retain any dependencies on the .dll file that was used to create it? If the database is copied to a different server, and the .dll file is in a different location there, will that affect an assembly that has already been created? Or is an assembly complete in itself once it has been created?

I'm not sure of any way to test this before deploying to production. Hope this question makes sense. Thanks so much for any responses.

Dylan

ParamVariable in User-Defined Function

$
0
0

I want to create own function Coalesce for the checking of the empty string - I need used for it the ParamArrays in a definition of the function.
Original function Coalesce has the defined parameter as (any number of parameters of) Expression (any type).

I created a new User-Defined function:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server

Partial Public Class UserDefinedFunctions

    <Microsoft.SqlServer.Server.SqlFunction()> _
    Public Shared Function NCoalesce(ByVal ParamArray value() As SqlString) As SqlString
        For Each exp As Object In value
            If String.IsNullOrEmpty(exp) Then
                Continue For
            Else
                Return exp
            End If
        Next
    End Function

End Class


I get a error during build:
Deploy error : Could not create a type for parameter System.Data.SqlTypes.SqlString[] value


BetaIQ

System.TypeInitializationException in ctor of System.Data.SqlClient.SqlConnection in DatabaseAssembly

$
0
0

Hi all,

since today morning we facing following exception in our DatabaseAssembly (MSSQL 2012) when we create a new instance of SqlConnection [using (SqlConnection conn = new SqlConnection("context connection=true"))]

System.TypeInitializationException: Der Typeninitialisierer für "System.Data.SqlClient.SqlConnection" hat eine Ausnahme verursacht. ---> System.TypeInitializationException: Der Typeninitialisierer für "System.Data.SqlClient.SqlConnectionFactory" hat eine Ausnahme verursacht. ---> System.TypeInitializationException: Der Typeninitialisierer für "System.Data.SqlClient.SqlPerformanceCounters" hat eine Ausnahme verursacht. ---> System.MethodAccessException: Fehler beim Versuch der Methode"System.Configuration.TypeUtil.CreateInstanceRestricted(System.Type, System.Type)", auf Methode "System.Diagnostics.SwitchElementsCollection..ctor()" zuzugreifen. ---> System.Security.SecurityException: Fehler bei der Anfrage.

System.Security.SecurityException:

   bei System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)

   bei System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandleInternal rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)

   bei System.Security.PermissionListSet.CheckSetDemandWithModification(PermissionSet pset, PermissionSet& alteredDemandSet, RuntimeMethodHandleInternal rmh)

   bei System.Security.PermissionListSet.CheckSetDemand(PermissionSet pset, RuntimeMethodHandleInternal rmh)

   bei System.Security.PermissionListSet.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet)

...

The only changes came from the Microsoft .Net 4.5 updates today morning.

Any solutions?

SQL Server notifying running .NET program of database updates

$
0
0

I have a database which can be updated from several instances of a C# .NET program. I wish to have each of those programs notified when rows in a table change.

An obvious (but possibly quite wrong) approach might be to register a callback function within the .NET program with the CLR Stored Trigger in the SQL Server, so that it gets called when the trigger fires.

Is this the correct/possible way, or is there a better alternative?

Polling the table for changes doesn't seem like a very efficient mechanism.

Thanks

Viewing all 780 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>