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

Insert Data into SQL table from Microsoft Word files

$
0
0

How to insert data into SQL table column from word file


Update to .Net 4 Client Profile Causes SQL CLR Security Error

$
0
0

For anyone who is suddenly getting SQL CLR security errors for no good reason.

Check windows update to see of there has been any updates to .Net 4 Client Profile.

I suddenly started getting security errors and removing the updates fixed it. 

 

SQL Server: System.Runtime.InteropServices.COMException: Logon failure: unknown user name or bad password.

$
0
0

We have a dll using #c which queries Active Directory. I installed it  on SQL SERVER 2008R2 and created CLR functions and all functions were working fine. But recently it will suddenly stop working sometimes, then I restart the SQL server and SSRS services, it will back to normal. OUr OS is Windows Server 2008R2 and .net 4.0.

I use CLR functions in a proc to check if a domain account is in a group account of AD. When the functions stopped working, I got error message below. No any other error messages in eventviewer or SQL error log. Can anyone shed some light what possible causes logon failure?

Thanks in advance,

System.Data.SqlClient.SqlException: An error occurred while getting new row from user defined Table Valued Function :
System.Runtime.InteropServices.COMException: Logon failure: unknown user name or bad password.

System.Runtime.InteropServices.COMException:
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_AdsObject()
   at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
   at System.DirectoryServices.DirectorySearcher.FindOne()
   at ADLibrary.ADLibraryClass.<vp_GetGroupsInUser>d__37.MoveNext()
.
Cursor is not open.
Cursor is not open.
Warning: Null value is eliminated by an aggregate or other SET operation.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.ReportingServices.DataExtensions.SqlCommandWrapperExtension.ExecuteReader(CommandBehavior behavior)
   at Microsoft.ReportingServices.OnDemandProcessing.RuntimeDataSet.RunEmbeddedQuery(Boolean& readerExtensionsSupported, Boolean& readerFieldProperties, List`1 queryParams, Object[] paramValues)


Automatic saving edits/inserts made in datagridview into sql

$
0
0

Hello guys I'm solving this issue:
I have datagridview and its connected to table in SQL and now if I made changes in it I would like to automatically save them on button click. As far as I was trying to solve this I made this part of code, but it does nothing:

   public void btn_uloz_sl_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM zajezd", spojeni);
            SDA.Fill(dt);
            spojeni.Close();
        }

Would somebody help me solve this problém out? thanks so much

ODBC Connection Error

$
0
0

hi,

anyone can help me. i have a issue to connection Apps to SQL 2012. using ODBC.

we already create the DNS user and DNS ODBC Data Source Administration, but always failed

Please advice

this is a message error :

2013.07.12 14:21:39 OCSQL: SQL code 0 : IM002 : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

2013.07.12 14:21:39 OCSQL: SQL code 0 : 01S00 : [Microsoft][ODBC Driver Manager] Invalid connection string attribute

2013.07.12 14:21:39 OCSQL: SQL code 0 : IM002 : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

2013.07.12 14:21:39 OCSQL: SQL code 0 : 01S00 : [Microsoft][ODBC Driver Manager] Invalid connection string attribute

2013.07.12 14:21:39 Failed to Connect to the Database

thanks for your support :)

SQL CLR problem with XmlSerializer

$
0
0

Hi all

    I have 3 different machines:

Machine 1 (mylocaldev) with WIN8 SQL2012 SP1
Machine 2 (globaldev) with WIN2008 SQL2012 SP1
Machine 3 (globaltest) with WIN2008 SQL2012 SP1

    On each SQL i have set of assembly:

Asm 1 - WSDL.EXE generated code from WebService1 with XmlSerializer
Asm 2 - WSDL.EXE generated code from WCFService1 with XmlSerializer
Asm 3 - assembly with stored procedures that invokes methods from Asm1 and Asm2

    On Machine 1 and 2 everything works fine. I can invoke WebService1 and WCFService1 without a problem. But on Machine 3 when I'm executing sp that invokes methods from WCFService1 I'm getting an error "Cannot load dynamically generated serialization assembly. In some hosting environments assembly load functionality is restricted, consider using pre-generated serializer." Also on Machine 3 invoking methods from WebService1 works fine.
    One important thing is that I took backup of my DB from Machine 3 and restored it on Machine 1 and everything works well so there is the same set of assemblies on working and not working environment. Anyone have an idea on what can be wrong here?


everything is a matter of probability...

Unable to create a socket in a SQL CLR stored procedure

$
0
0

Hello,

On a couple of machines (SQL Server 2008 R2 and 2012) our .NET stored procedure can no longer create a System.Net.Sockets.Socket object unless the assembly is created with UNSAFE.  The SP has worked fine for a number of years, until only very recently (and it's not due to a code change, it still works fine on other machines).

We get the following stack trace:

Attempt by method 'System.Configuration.TypeUtil.CreateInstanceRestricted(System.Type, System.Type)' to access method 'System.Diagnostics.SourceElementsCollection..ctor()' failed.

System.MethodAccessException:
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Configuration.TypeUtil.CreateInstanceRestricted(Type callingType, Type targetType)
   at System.Configuration.ConfigurationElement.CreateElement(Type type)
   at System.Configuration.ConfigurationElement.get_Item(ConfigurationProperty prop)
   at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
   at System.Diagnostics.TraceSource.Initialize()
   at System.Net.Logging.InitializeLogging()
   at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)

So I believe it's something to do network tracing (see Remarks under http://msdn.microsoft.com/en-us/library/2b86d684.aspx), somehow it's been enabled for SQL Server.  Does anybody know how it became enabled, and how it can be disabled?

Thanks in advance!

SQL CLR Issue - There was an error generating the XML Document

$
0
0

Weird issue follows:

I have created a SQL CLR that calls a WCF web service (.net 4.0) SQL Server 2012 both Express and Developer editions.

On my desktop I deploy the SQL CLR contaiing a Stored proc using DDL without using the XMLSerializer Class, to my 2012 SQL Server Express DB.  Here is the DDL.

ALTER DATABASE GnazzTest SET TRUSTWORTHY ON
GO

CREATE ASSEMBLY PaymentProcessing from 'C:\Git\webOrdering\Source\MA.PaymentProcessing.CLR\bin\Debug\MA.PaymentProcessing.CLR.dll' WITH PERMISSION_SET = UNSAFE;
Go

CREATE PROCEDURE uspSendPaymentProcessing(
@PayProc  As NVARCHAR(100),
@Gateway1AS NVARCHAR(100),
@Gateway2AS NVARCHAR(100),
@MerchantAS NVARCHAR(12),
@TranIDAS BIGINT,
@dataInAS NVARCHAR(MAX),
@dataOutAS NVARCHAR(MAX) OUTPUT)
AS
EXTERNAL NAME PaymentProcessing.StoredProcedures.SendPaymentProcessing
GO

I run the Stored proc installed inside of SQL 2012 Express on my desktop and every works ok.

However, when I tried to repeat the process on a remote server running SQL Server 2012.  I am forced to include the XMLSerializers assembly which I created with VS2012.

ALTER DATABASE PaymentProcessing SET TRUSTWORTHY ON
GO


CREATE ASSEMBLY [JGPaymentProcessing] from '\\SQLDEV\CLR\MA.PaymentProcessing.CLR.dll'  WITH PERMISSION_SET = UNSAFE;
GO
CREATE ASSEMBLY [JGPaymentProcessing.XmlSerializers.dll] from  '\\SQLDEV\CLR\MA.PaymentProcessing.CLR.XmlSerializers.dll'
GO

CREATE PROCEDURE uspSendPaymentProcessing(
@PayProc  As NVARCHAR(100),
@Gateway1AS NVARCHAR(100),
@Gateway2AS NVARCHAR(100),
@MerchantAS NVARCHAR(12),
@TranIDAS BIGINT,
@dataInAS NVARCHAR(MAX),
@dataOutAS NVARCHAR(MAX) OUTPUT)
AS
EXTERNAL NAME JGPaymentProcessing.StoredProcedures.SendPaymentProcessing
GO

When Running this stored proc on the remove server, I get the  "There was an error generating the XML Document" Message.

Here is the XML I am trying to get.  This is what is pulled from my WCF webservice when I Execute it through the WCF Test CLient.

@"<Response><ProcStatus>0</ProcStatus><TxRefIdx>1223</TxRefIdx><ActualRespCd>00</ActualRespCd><ApprovalStatus>1</ApprovalStatus><TxRefNum>1312312312</TxRefNum><RespCode>00</RespCode><RespTime>1312313123123</RespTime><AuthCode>XAUTHCODE</AuthCode><AVSRespCode>1</AVSRespCode><CVV2RespCode>1</CVV2RespCode></Response>"

Here is my Interface

  [ServiceContract]
  public interface IPaymentProcessingWAS
  {
    [OperationContract]
    PaymentResponseCLR AuthorizeClrHttp(AuthorizationRequestCLR request);

  }

 [DataContract]
  public class AuthorizationRequestCLR
  {
    [DataMember]
    public string Id { get; set; }

    [DataMember]
    public string MerchantId { get; set; }

    [DataMember]
    public string Company { get; set; }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string Zipcode { get; set; }

    [DataMember]
    public string Number { get; set; }

    [DataMember]
    public string Type { get; set; }

    [DataMember]
    public string VerificationCode { get; set; }

    [DataMember]
    public string ExpirationMonth { get; set; }

    [DataMember]
    public string ExpirationYear { get; set; }

    [DataMember]
    public string Amount { get; set; }
  }
}

  [DataContract]
  public class PaymentResponseCLR
  {
    [DataMember]
    public string Status { get; set; }

    [DataMember]
    public string XML { get; set; }

    public PaymentResponseCLR(string status, string xml)
    {
      Status = status;
      XML = xml;
    }
  }

Any Thoughts would be helpful.


How to dump all tables data from read only db to other db

$
0
0

Hello every one,

How to dump all tables data from read only db to other db having same structure?.

Is there any commands available in sql server or need to write console app in .net, please suggest me your ideas.

Thanks,


Siva Kumar Goru

Error in 3-Layer Project

$
0
0

Hi

I have a 3-Layer project, I want to add a user. I use Connection String in web.config and it seems that everything is ok

but when i run website i get this error.

 What should I do???!!!

:(((((

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)

SQL Server 2012 - one of my clr custom user function not working on one server, but works on all other servers

$
0
0

I detached and reattached a sql server 2005 database to several sql servers and modified the setting to get it to run as a sqlserver 2012 database.  I had to run a command to enable clr functions in order for all to work, but that did the trick on my production and QA servers and all seems well.  However on my development server one of my clr functions will not run.

I get a long error below shown below. - beneath that is the signature for the one function that fails.

On the production server, my database was attached to a clean install of the SQL Server 2012.  It runs fine.

On the QA machine, it was installed to a server that is already running several other applications.  I believe that was a clean install of sqlserver.  It runs fine.

On the DEV machine, it was installed to a server that is already running several other applications.    I believe that was a clean install of sqlserver.  It does not run and fails with the error below.

Below the error message I have pasted the VB.Net code for the single function that is failing.  Two other clr functions run fine even on the failing server.

=====================================================

ERROR RETURNED WHEN RUN AS A QUERY
=======================================

Msg 6522, Level 16, State 1, Procedure BillHistory_ListForBillWithLinkToJournal, Line 9
A .NET Framework error occurred during execution of user-defined routine or aggregate "FormatAction": 
System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception. ---> System.MethodAccessException: Attempt by method 'System.Configuration.TypeUtil.CreateInstanceRestricted(System.Type, System.Type)' to access method 'System.Diagnostics.SwitchElementsCollection..ctor()' failed. ---> System.Security.SecurityException: Request failed.
System.Security.SecurityException: 
   at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
   at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandleInternal rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)
   at System.Security.PermissionListSet.CheckSetDemandWithModification(PermissionSet pset, PermissionSet& alteredDemandSet, RuntimeMethodHandleInternal rmh)
   at System.Security.PermissionListSet.CheckSetDemand(PermissionSet pset, RuntimeMethodHandleInternal rmh)
   at System.Security.PermissionListSet.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet)
   at System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant)
System.MethodAccessException: 
   at System.RuntimeTypeHandle.CreateInstance(RuntimeT
...
System.TypeInitializationException: 
   at System.Data.SqlClient.SqlConnection..ctor()
   at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at MilegSqlclrFns.UserDefi...

===============================================================
SIGNATURE FOR THE  CLR FUNCTION THAT IS FAILING
=================================

 <SqlFunction(DataAccess:=DataAccessKind.Read, IsDeterministic:=True, isprecise:=True, Name:="FormatAction")> _
    Public Shared Function FormatAction(ByVal Action As String, ByVal HistoryDate As Date, ByVal cvFileName As String, ByVal cvLinkTemplate As String) As SqlString
 ...code snipped out - thought perhaps the signature was the problem...
    End Function

Replace sp_OACreate with CLR?

$
0
0

I'm currently using stored procedures to call 3rd party com objects.

I'm wanting to see if I can use something other than sp_OACreate and sp_OAMethod with the stored procedures.  I'm not sure but I suspect they may be causing problems on my server.  I've never used CLR but I've written lots of vba and vbscript.

Are CLR stored procedures something I could use to do this?  Any suggestions or helpful resources to get started would be greatly appreciated.

Thanks in advance.


Kevin

I need to write a CLR which returns the column names and if possible datatype which are outputted from a stored procedure.

$
0
0

I need to write a CLR which returns the column names and if possible datatype which are outputted from a stored procedure.

I do not need to collect any of the data which the stored procedure procedures?

Is this possible?


Mr Shaw

Error when making DDL change

$
0
0
We're suddenly getting an error, started today, seemingly CLR-related, when attempting DDL changes. The database in which this is occurring is part of an AlwaysOn Availability Group, published for replication, and has CDC enabled. Attempting to add a column to any replicated table throws the error below.

Before I start peeling back layers of the onion, has anybody seen this, or know what's causing it?

Msg 6522, Level 16, State 1, Procedure sp_MSscriptcustominsproc_sqlclr, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "sp_MSscriptcustominsproc_sqlclr": 
System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception. -> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception. -> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception. -> System.MethodAccessException: Attempt by method 'System.Configuration.TypeUtil.CreateInstanceRestricted(System.Type, System.Type)' to access method 'System.Diagnostics.SwitchElementsCollection..ctor()' failed. -> System.Security.SecurityException: Request failed.
System.Security.SecurityException: 
   at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
   at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandleInternal rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)
   at System.Security.PermissionListSet.CheckSetDemandWithModification(PermissionSet pset, PermissionSet& alteredDemandSet, RuntimeMethodHandleInternal rmh)
   at Sy
...
System.TypeInitializationException: 
   at System.Data.SqlClient.SqlConnection..ctor()
   at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at Microsoft.SqlServer.Replication.TransSqlClrCodeGenerators.FetchPublicationAndArticleNameFromArticleId(SqlInt32 articleId, SqlString& publication, SqlString& article)
   at Microsoft.SqlServer.Replication.TransSqlClrCodeGenerators.ScriptCustomProcedure(SqlInt32 articleId, SqlString publisher, SqlString publisher_type, CustomStoredProcedureType customStoredProcedureType)
   at Microsoft.SqlServer.Replication.T...
The statement has been terminated.

Tyler Krusenstjerna | Database Administrator

GET SQL SERVER HDD SERIAL USING WMI AND CLR INTEGRATION

$
0
0

hello experts,

after seeing an eample of sql clr integration , i tried writing

using System;
using System.Management;
using System.Collections;

namespace WmiControl
{
    public class WMI
    {
        public bool GetDiskSerial(string Computername)
        {
           
            try
            {
                ManagementScope scope = new ManagementScope(@"\\" + Computername + @"\root\cimv2");
                scope.Connect();
                ArrayList hdCollection;
                ManagementObjectSearcher searcher;
                if (GetDiskDrive(scope, out hdCollection, out searcher) || GetDiskSerial(scope, hdCollection, ref searcher))
                    return true;
                else
                    return false;
            }
            catch (ManagementException)
            {
                return false;
            }

        }

        private bool GetDiskSerial(ManagementScope scope, ArrayList hdCollection, ref ManagementObjectSearcher searcher)
        {
            try
            {


                ObjectQuery query1 = new ObjectQuery("SELECT * FROM Win32_PhysicalMedia");

                searcher = new ManagementObjectSearcher(scope, query1);
                int i = 0;
                string sDiskSerial = "";
                foreach (ManagementObject wmi_HD in searcher.Get())
                {
                    // get the hard drive from collection
                    // using index
                    if (i < hdCollection.Count)
                    {
                        HardDrive hd = (HardDrive)hdCollection[i];
                        if (wmi_HD["SerialNumber"] == null)
                            hd.SerialNo = "";
                        else
                            hd.SerialNo = wmi_HD["SerialNumber"].ToString();
                    }
                    ++i;
                }
                foreach (HardDrive hd in hdCollection)
                {
                    if (!String.IsNullOrEmpty(hd.SerialNo))
                    {
                        sDiskSerial = hd.SerialNo;
                        break;
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private bool GetDiskDrive(ManagementScope scope, out ArrayList hdCollection, out ManagementObjectSearcher searcher)
        {
            try
            {
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_DiskDrive");
                hdCollection = new ArrayList();
                searcher = new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject wmi_HD in searcher.Get())
                {
                    HardDrive hd = new HardDrive();
                    hd.Model = wmi_HD["Model"].ToString();
                    hd.Type = wmi_HD["InterfaceType"].ToString();
                    hdCollection.Add(hd);
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
                hdCollection = null;
                searcher = null;
                return false;
            }
        }
    }
    class HardDrive
    {
        private string model = null;
        private string type = null;
        private string serialNo = null;
        public string Model
        {
            get { return model; }
            set { model = value; }
        }
        public string Type
        {
            get { return type; }
            set { type = value; }
        }
        public string SerialNo
        {
            get { return serialNo; }
            set { serialNo = value; }
        }
    }
}

i am unable to create dll

after that i have to run this

use mf
go
CREATE ASSEMBLY CLRFunctions FROM 'D:\VS2010\WmiControl\WmiControl\WmiControl\bin\Debug\WmiControl.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE FUNCTION dbo.GetDiskSerial  
(  
 @Computername AS NVARCHAR(100)
)   
RETURNS bit
AS EXTERNAL NAME CLRFunctions.WMI.GetDiskSerial
GO

--ALTER DATABASE mf SET trustworthy ON


SQL CLR Stored Procedure calling WCF Service error

$
0
0

I have registered all needed assemblies and deployed my storedprocedure.

CREATE ASSEMBLY System_Runtime_Serialization FROM 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\System.Runtime.Serialization.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE ASSEMBLY System_Web FROM 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Web.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE ASSEMBLY System_IdentityModel FROM 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.dll'
WITH PERMISSION_SET = UNSAFE
GO
CREATE ASSEMBLY System_IdentityModel_Selectors FROM 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.Selectors.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE ASSEMBLY System_Messaging FROM 'c:\windows\Microsoft.net\Framework\v2.0.50727\System.Messaging.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE ASSEMBLY System_ServiceModel FROM 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\System.ServiceModel.dll'
WITH PERMISSION_SET = UNSAFE
GO

CREATE ASSEMBLY WCFStoredprocedures
FROM 'D:\MyStoredprocedures.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS;
GO

CREATE ASSEMBLY MyXmlSerializers
FROM
'D:\MyStoredprocedures.XmlSerializers.dll'
WITH PERMISSION_SET = SAFE;
GO

When I finally run it I get the below error. I tried to also make the proedure dll registered as UNSAFE but if I do that I get another error which is config entry point error. Please suggest on how to fix this. If I have to fix the config error I will have to go and get the already deployed WCF service config file and then how to use it in my current solution.
If that is not the issue how do I fix the below error. I had no problem calling a webservice but adding WCF Service is creating all problems.

Msg 6522, Level 16, State 1, Procedure StoredProcedureName, Line 0

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

System.TypeInitializationException: The type initializer for 'System.ServiceModel.ClientBase`1' threw an exception. ---> System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.

The protected resources (only available with full trust) were: All

The demanded resources were: Synchronization, ExternalThreading

System.Security.HostProtectionException:

   at System.ServiceModel.DiagnosticUtility.GetUtility()

   at System.ServiceModel.DiagnosticUtility.get_Utility()

   at System.ServiceModel.ClientBase`1..cctor()

System.TypeInitializationException:

   at System.ServiceModel.ClientBase`1.InitializeChannelFactoryRef()

   at System.ServiceModel.ClientBase`1..ctor()

   at MyStoredprocedures.ServiceReference1.SServiceClient..ctor()

   at StoredProcedures.SServiceSPcs()

.

(1 row(s) affected)

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?

SQL CLR Stored Procedure calling webservice Serialization error

$
0
0

This probably have been asked many times before and I have looked at most of the questions posted before posting here.

First thing I have followed the below blog to try and create a simple procedure that will call a webservice
http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/

I use VS2012 and SQL 2008. The difference in using VS2012 is that it doesnt allow to create a sql database project that will allow Add webreference directly. So I created a class library for which I can add web reference complied the DLL and then added it to my SQL Database project for which I added new item CLR c# storedprocedure and then using the namespace of the webservice writted the code as per the blog and then complied my Storedprocedure DLL with the XML serializer DLL for the CLR database project.

I had also faced unsupported version errors during deploying the assemblies in SQL when I directly use SGEN to pregenerate it. SO i followed the steps from the blog that asks to unload project set the filed below and then generated the XML Serializer dll

<SGenUseProxyTypes>false</SGenUseProxyTypes><GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>
Following this registered my assemblies without any problem in SQL.

Finally when I execute my storedprocedure in SQL I get this below error. I am clueless on why it should be so complex to create a WCF call via stroed procedure using VS2012. I am not sure now as to how to get over this issue. Kindly help. Please dont post other post urls as I have had spent enough time reviewing the forums for different solutions and I am currently blocked.

Msg 6522, Level 16, State 1, Procedure WeatherSP, Line 0

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

System.InvalidOperationException: Cannot load dynamically generated serialization assembly. In some hosting environments assembly load functionality is restricted, consider using pre-generated serializer. Please see inner exception for more information. ---> System.IO.FileLoadException: LoadFrom(), LoadFile(), Load(byte[]) and LoadModule() have been disabled by the host.

System.IO.FileLoadException:

   at System.Reflection.Assembly.nLoadImage(Byte[] rawAssembly, Byte[] rawSymbolStore, Evidence evidence, StackCrawlMark& stackMark, Boolean fIntrospection)

   at System.Reflection.Assembly.Load(Byte[] rawAssembly, Byte[] rawSymbolStore, Evidence securityEvidence)

   at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)

   at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)

   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, Stri

...

System.InvalidOperationException:

   at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence)

   at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)

   at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)

   at System.Xml.Serialization.XmlSerializer.GetSerializersFromCache(XmlMapping[] mappings, Type type)

   at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)

   at System.Web.Services.Protocols.SoapClientType..ctor(Type type)

   at System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()

   at WCFS...

(1 row(s) affected)

deploy failed an old CLR User-Defined

$
0
0
Hi all
I deployed a CLR User-Defined Function to my DB 1 year ago.
Today I want to change this function but VS shows deploy failed.
Project build successfully.
When I delete this function (ShamsiDate.cs) and add a test function (Function1.cs) , Deploy is Successfull.
but when I add ShamsiDate.cs again , VS shows deploy failed.
What should I do?

Each problem has a solution.

Bing Maps webservice

$
0
0

I'm trying to implement a SQL CLR to acess the Bing Maps webservices, as my previous implmentation was using the Mappoint webservices but my understanding is that the former is approximately 70% more efficient then the latter.

My current code looks like:

[Microsoft.SqlServer.Server.

SqlFunction()]

 

publicstaticstring geocode(

 

string AddressLine,

 

string PrimaryCity,

 

string PostalCode)

{

 

string key = "Aj-dTA3-7M8PgO-ZzXCTZSYYF4C8Ft-sYN5HfAieFpH_quLgRwoV7YJg_6_T_1Sd";

 

GeocodeRequest geocodeRequest = newGeocodeRequest();

 

// Set the credentials using a valid Bing Maps Key

geocodeRequest.Credentials =

newCredentials();

geocodeRequest.Credentials.ApplicationId = key;

 

 

//set address

 

Address address = newAddress();

address.AddressLine = AddressLine;

address.PostalTown = PrimaryCity;

address.PostalCode = PostalCode;

address.CountryRegion =

"United Kingdom";

geocodeRequest.Address = address;

 

// Set the options to only return high confidence results

 

ConfidenceFilter[] filters = newConfidenceFilter[1];

filters[0] =

newConfidenceFilter();

filters[0].MinimumConfidence =

Confidence.High;

 

GeocodeOptions geocodeOptions = newGeocodeOptions();

geocodeOptions.Filters = filters;

geocodeRequest.Options = geocodeOptions;

 

// Provide the logon credentials

 

 

// Make the geocode request

 

GeocodeService geocodeService = newGeocodeService();

 

string proxy = "xxx";

 

string port = "xxx";

 

string domain = "xxx";

 

string proxyUserName = "xxxx";

 

string proxyPassword = "xxxx";

 

WebProxy ProxyServer = newWebProxy(proxy,

 

int.Parse(port));

ProxyServer.Credentials =

newNetworkCredential(proxyUserName,

proxyPassword,

domain);

geocodeService.Proxy = ProxyServer;

geocodeService.Proxy.Credentials =

newNetworkCredential(proxyUserName, proxyPassword);

 

GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);

 

// Create the WKT representation of the geocoded result

 

string WKT = string.Empty;

 

if (geocodeResponse.Results.Length > 0)

{

WKT =

"POINT(" +

geocodeResponse.Results[0].Locations[0].Longitude.ToString() +

" " +

geocodeResponse.Results[0].Locations[0].Latitude.ToString() +

")";

}

 

else

{

WKT =

"POINT EMPTY";

}

 

// Return the result to SQL Server

 

return WKT;

}


When calling this service from a test web application I receive the correct long and lat values but when this is complied and called from SQL Server 2008 I get the following error:

Msg 6522,Level 16,State 2, Line 1

A .NET Framework error occurred during execution ofuser-defined routine oraggregate"Geocode":

System.Configuration.SettingsPropertyNotFoundException: The settings property 'BingMapsGeocoding_BingmapsGeocoder_GeocodeService' was not found.

System.Configuration.SettingsPropertyNotFoundException:

   at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)

   at System.Configuration.SettingsBase.get_Item(String propertyName)

   at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)

   at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)

   at BingMapsGeocoding.Properties.Settings.get_BingMapsGeocoding_BingmapsGeocoder_GeocodeService()

   at BingMapsGeocoding.BingmapsGeocoder.GeocodeService..ctor()

   at BingMapsGeocoding.Geocoder.geocode(String AddressLine, String PrimaryCity, String PostalCode)


Appreciate any help on this.

Viewing all 780 articles
Browse latest View live


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