I have a table that is getting updated from multiple places, so I cannot call signalr hub from those APIs and I have a grid in the UI which I need to refresh wherever the table gets updated, so as a solution I am using Signalr as a message broker.
Issue: How can I call the signalr hub when we update the table.
Solution 1: One solution I got is to call the signalr hub from the trigger, but its not working for me.
Here is the sample code:
DECLARE #httpRequest NVARCHAR(MAX);
DECLARE #httpObject NVARCHAR(MAX);
SET #httpRequest = N'POST https://localhost:3000/chat HTTP/1.1' +
N'Content-Type:application/json'+
N'{"message":"'+#message+'"}';
EXEC sp_OACreate 'MSXML2.ServerXMLHTTP', #httpObject OUT;
EXEC sp_OAMethod #httpObject, 'open', NULL, 'post', #httpRequest, 'false';
EXEC sp_OAMethod #httpObject, 'setOption', NULL, 'UseSSL', 'true';
EXEC sp_OAMethod #httpObject, 'send';
EXEC sp_OAGetProperty #httpObject, 'status';
EXEC sp_OADestroy #httpObject;
Is there any better way to solve it?
I tried RabbitMQ as well but the issue remains same, I need to refresh the grid wherever the table gets updated.
Related
How do I find the ssl certificate path? That one installed by VisualStudio, to be more expecific when we use .NET Core and run "dotnet dev-certs https --trust" at the console...
Could you guys help me pls?
Everything I've tried drop me in the certificate name only. I could not see the path to set on that pattern 'LOCAL_MACHINE\My\'Certificate Name'.
I want to pass it ike a parameter on the SQL code below:
EXEC #hResult = sp_OAMethod
#Object,
'setOption',
NULL,
3,
'LOCAL_MACHINE\My\'Certificate Name';
Just because I'm trying to call a API using SQL Server and I need to use that SSL certificate to run my tests.
Could you guys help me pls?
The return message I've got untill now says that it's not a valid certificate but I think it's bacause I'm not finding the full path.
I don't know if I made this clear... Just summarazing... I need to do this by sql and I need to know how to use SSL certificate path as a parameter.
There follows the code I'm using:
begin
declare #test as int;
declare #Object as int;
declare #hResult as nvarchar(256)
declare #Response as nvarchar(256)
exec #test = sp_OACreate 'MSXML2.XMLHTTP', #Object out;
select #test, #Object;
EXEC #hResult = sp_OAMethod
#Object,
'setOption',
NULL,
3,
'LOCAL_MACHINE\My\'Certificate Name';
exec #test = sp_OAMethod #Object, 'open', null, 'get',
'https://localhost:44351/api/v1/account/3215', 'false'
select #test
exec #test = sp_OAMethod #Object, 'send'
IF #test <> 0
BEGIN
EXEC sp_OAGetErrorInfo #object
RETURN
END
exec sp_OAMethod #Object, 'responseText', #Response OUTPUT;
end
print #Response
I had the same problem using the same VS-generated cert. I could find the cert called "localhost" in the certmgr ("Personal"->"Certificates"->localhost), installed when I began the project. I added this line:
EXEC #hr = sp_OAMethod #Object,'setOption',NULL,3,'LOCAL_MACHINE\My\localhost';
and it worked.
However, i found I could change the line to anything and it still worked, ie:
EXEC #hr = sp_OAMethod #Object,'setOption',NULL,3,'LOCAL_MACHINE\My\bogusfake';
So I cannot promise that will work for you, nor explain how/why, but I am able to proceed with the project of posting from a stored procedure to a local api. The only difference I see between my code and yours is I didn't surround the cert name in quotes.
I have the following issue. running the sql below on our server it returns the expected results. Running the same on another server it returns no values.
Did the following:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
USE tempdb
GO
IF OBJECT_ID('tempdb..#xml') IS NOT NULL DROP TABLE #xml
CREATE TABLE #xml ( yourXML XML )
GO
DECLARE #URL VARCHAR(8000)
--DECLARE #QS varchar(50)
-- & or ? depending if there are other query strings
-- Use this for when there is other query strings:
--SELECT #QS = '&date='+convert(varchar(25),getdate(),126)
-- Use this for when there is NO other query strings:
-- SELECT #QS = '?date='+convert(varchar(25),getdate(),126)
SELECT #URL = 'http://exampleURL' -- + #QS
DECLARE #Response varchar(8000)
DECLARE #XML xml
DECLARE #Obj int
DECLARE #Result int
DECLARE #HTTPStatus int
DECLARE #ErrorMsg varchar(MAX)
EXEC #Result = sp_OACreate 'MSXML2.XMLHttp', #Obj OUT
EXEC #Result = sp_OAMethod #Obj, 'open', NULL, 'GET', #URL, false
EXEC #Result = sp_OAMethod #Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
EXEC #Result = sp_OAMethod #Obj, send, NULL, ''
EXEC #Result = sp_OAGetProperty #Obj, 'status', #HTTPStatus OUT
INSERT #xml ( yourXML )
EXEC #Result = sp_OAGetProperty #Obj, 'responseXML.xml'--, #Response OUT
declare #input XML=(
SELECT
yourXML
from
#xml)
SELECT
Item.value('(Code)[1]', 'nvarchar(max)') as Code,
Item.value('(Description)[1]', 'varchar(max)') as Description,
Item.value('(ImageUrl)[1]', 'nvarchar(max)') as ImageUrl
from
#input.nodes('//product') AS T(Item)
Within the second server the #input returns null. There is a proxy to access the site on the server and it operates with sql server 2008.
Any ideas why the null values?
I just had a similar issue, a query using Ole Automation suddenly returns null without any error. After changing 'MSXML2.XMLHttp' to 'MSXML2.ServerXMLHTTP', it started to work again.
To know more about the difference between these two, see this article and Microsoft documentation. I copied some from Microsoft site, in case both sites are down in the future.
The ServerXMLHTTP object offers functionality similar to that of the XMLHTTP object. Unlike XMLHTTP, however, the ServerXMLHTTP object does not rely on the WinInet control for HTTP access to remote XML documents. ServerXMLHTTP uses a new HTTP client stack. Designed for server applications, this server-safe subset of WinInet offers the following advantages:
Reliability — The HTTP client stack offers longer uptimes. WinInet features that are not critical for server applications, such as URL caching, auto-discovery of proxy servers, HTTP/1.1 chunking, offline support, and support for Gopher and FTP protocols are not included in the new HTTP subset.
Security — The HTTP client stack does not allow a user-specific state to be shared with another user's session. ServerXMLHTTP provides support for client certificates.
So, it seems that my issue was that I had no access over the internet from my SQL server, so I had to use the below line to set the proxy.
exec #Result = sp_OAMethod #Obj, 'setProxy', NULL, '2', 'http://myProxy'
Once this was sorted, I managed to get my results.
I want to call a Webservice when a row inserted into a table.
So I enable Ole Automation Procedures, call Webservice like below and everything goes fine.
--enabling 'Ole Automation Procedures'
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
--calling Webservice
create PROCEDURE callwebservice
#url varchar(128)=null
AS
Declare #Object as Int;
Declare #ResponseText as varchar(8000);
Exec sp_OACreate 'MSXML2.ServerXMLHttp.3.0', #Object OUT;
Exec sp_OAMethod #Object, 'open', NULL, 'get', #url ,'false'
Exec sp_OAMethod #Object, 'send'
Exec sp_OAGetProperty #Object, 'ResponseText', #ResponseText OUTPUT
Exec sp_OADestroy #Object
return
But, Since Webservice call is extremely lengthy, I need to do it with Service Broker. so I create a new stored-procedure and pass it as an activation parameter of my Queue like this:
--declare procedure
create procedure handleNewMessageInQueue
as
begin
DECLARE #TargetDlgHandle UNIQUEIDENTIFIER
DECLARE #ReplyMessage xml
DECLARE #ReplyMessageName
BEGIN TRAN;
receive top(1)
#TargetDlgHandle =Conversation_handle
,#ReplyMessage = Message_Body
,#ReplyMessageName = Message_Type_Name
from newUserQueue;
if #ReplyMessageName = '//goodType'
begin
exec callwebservice 'http://path/to/my/webservice'
end
commit tran;
end
--declare queue
create queue myQueue
with ACTIVATION (
PROCEDURE_NAME = handleNewMessageInQueue,
MAX_QUEUE_READERS =100,
EXECUTE AS owner
);
But this time, no request sent. I checked and I realize that the sp_OACreate method does not create the Object since the value of #Object is null after execution of it. Also when I call sp_OAGetErrorInfo to get error info, everything is null
I'm using SQL Server 2016
I appreciate if you can find the problem here.
EDIT
I found that if I enable TRUSTWORTHY on that database everything goes fine. but enabling it can open security hole.
is there any better way to do that?
Currently I have nice solutions for REST (via clr/assembly) and SOAP (via sp_OA based stored procedure) but XML-RPC is still a question to access directly from SQL Server T-SQL code.
Please advise which variants exist for this purpose.
I need to avoid application layer because all logic is already in a stored procedure inside the database, and just recordset is needed to be supplied.
I have consumed XML from an HTTP call within t-sql using the xmlhttp COM object, which looks something like:
Declare #Object as Int;
Declare #ResponseText as Varchar(8000);
Exec sp_OACreate 'MSXML2.XMLHTTP', #Object OUT;
Exec sp_OAMethod #Object, 'open',
NULL, 'get',
'http://www.webservicex.com /stockquote.asmx?symbol=MSFT', 'false'
Exec sp_OAMethod #Object, 'send'
Exec sp_OAMethod #Object, 'responseText', #ResponseText OUTPUT
Select #ResponseText
Exec sp_OADestroy #Object
The xml in #ResponseText can then be shredded via traditional tsql methods.
This isn't a particularly robust method; Using an SSIS package or CLR integration would most likely yield a better solution, but this is one way to keep it all within t-sql.
See: http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/eac9c027-db71-48ae-872d-381359d7fb51/
Is there a way to call out from a TSQL stored procedure or function to a webservice?
Yes , you can create like this
CREATE PROCEDURE CALLWEBSERVICE(#Para1 ,#Para2)
AS
BEGIN
Declare #Object as Int;
Declare #ResponseText as Varchar(8000);
Exec sp_OACreate 'MSXML2.XMLHTTP', #Object OUT;
Exec sp_OAMethod #Object, 'open', NULL, 'get', 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT','false'
Exec sp_OAMethod #Object, 'send'
Exec sp_OAMethod #Object, 'responseText', #ResponseText OUTPUT
Select #ResponseText
Exec sp_OADestroy #Object
END
Sure you can, but this is a terrible idea.
As web-service calls may take arbitrary amounts of time, and randomly fail, depending on how many games of counterstrike are being played on your network at the time, you can't tell how long this is going to take.
At the bare minimum you're looking at probably half a second by the time it builds the XML, sends the HTTP request to the remote server, which then has to parse the XML and send a response back.
Whichever application did the INSERT INTO BLAH query which caused the web-service to fire is going to have to wait for it to finish. Unless this is something that only happens in the background like a daily scheduled task, your app's performance is going to bomb
The web service-invoking code runs inside SQL server, and uses up it's resources. As it's going to take a long time to wait for the HTTP request, you'll end up using up a lot of resources, which will again hurt the performance of your server.
Not in T-SQL code itself, but with SQL Server 2005 and above, they've enabled the ability to write CLR stored procedures, which are essentially functions in .NET code and then expose them as stored procedures for consumption. You have most of the .NET framework at your fingertips for this, so I can see consumption of a web service possible through this.
It is a little lengthy to discuss in detail here, but here's a link to an MSDN article on the topic.
I would not do this for heavy traffic or mission critical stuff, HOWEVER, if you do NOT need to receive feedback from a service, then it is actually a great thing to do.
Here is an example of what I have done.
Triggers Insert and Update on a Table
Trigger called Stored Proc that is passes the JSON data of the transaction to a Web Api Endpoint that then Inserts into a MongoDB in AWS.
Don't do old XML
JSON
EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', #Object OUT;
EXEC sp_OAMethod #Object, 'Open', NULL, 'POST', 'http://server/api/method', 'false'
EXEC sp_OAMethod #Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
DECLARE #len INT = len(#requestBody)
Full example:
Alter Procedure yoursprocname
#WavName varchar(50),
#Dnis char(4)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Object INT;
DECLARE #Status INT;
DECLARE #requestBody NVARCHAR(MAX) = '{
"WavName": "{WavName}",
"Dnis": "{Dnis}"
}'
SET #requestBody = REPLACE(#requestBody, '{WavName}', #WavName)
SET #requestBody = REPLACE(#requestBody, '{Dnis}', #Dnis)
EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', #Object OUT;
EXEC sp_OAMethod #Object, 'Open', NULL, 'POST', 'http://server/api/method', 'false'
EXEC sp_OAMethod #Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
DECLARE #len INT = len(#requestBody)
EXEC sp_OAMethod #Object, 'setRequestHeader', null, 'Content-Length', #len
EXEC sp_OAMethod #Object, 'send', null, #requestBody
EXEC sp_OAGetProperty #Object, 'Status', #Status OUT
EXEC sp_OADestroy #Object
In earlier versions of Sql, you could use either an extended stored proc or xp_cmdshell to shell out and call a webservice.
Not that either of these sound like a decent architecture - but sometimes you have to do crazy stuff.
You can do it with the embedded VB objects.
First you create one VB object of type 'MSXML2.XMLHttp', and you use this one object for all of your queries (if you recreate it each time expect a heavy performance penalty).
Then you feed that object, some parameters, into a stored procedure that invokes sp_OAMethod on the object.
Sorry for the inprecise example, but a quick google search should reveal how the vb-script method is done.
--
But the CLR version is much....MUCH easier.
The problem with invoking webservices is that they cannot keep pace with the DB engine. You'll get lots of errors where it just cannot keep up.
And remember, web SERVICES require a new connection each time. Multiplicity comes into play. You don't want to open 5000 socket connections to service a function call on a table. Thats looney!
In that case you'd have to create a custom aggregate function, and use THAT as an argument to pass to your webservice, which would return a result set...then you'd have to collate that. Its really an awkward way of getting data.
Here'a an example to get some data from a webservice. In this case parse a user agent string to JSON.
--first configure MSSQL to enable calling out to a webservice (1=true, 0=false)
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
CREATE PROCEDURE CallWebAPI_ParseUserAgent #UserAgent VARCHAR(512)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Object INT;
DECLARE #ResponseText AS VARCHAR(8000);
DECLARE #url VARCHAR(512)
SET #url = 'http://www.useragentstring.com/?getJSON=all&uas=' + #UserAgent;
EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', #Object OUT;
EXEC sp_OAMethod #Object, 'Open', NULL, 'GET', #url, 'false'
EXEC sp_OAMethod #Object, 'setRequestHeader', NULL, 'Content-Type', 'application/json'
EXEC sp_OAMethod #Object, 'send'
EXEC sp_OAMethod #Object, 'responseText', #ResponseText OUTPUT
SELECT #ResponseText
EXEC sp_OADestroy #Object
END
--example how to call the API
CallWebAPI_ParseUserAgent 'Mozilla/5.0 (Windows NT 6.2; rv:53.0) Gecko/20100101 Firefox/53.0'
If you're working with sql 2000 compatibility levels and cannot do clr integration, see http://www.vishalseth.com/post/2009/12/22/Call-a-webservice-from-TSQL-(Stored-Procedure)-using-MSXML.aspx
I been working for big/global companies around the world, using Oracle databases. We are consuming web services all time thru DB with store procedures and no issues, even those ones with heavy traffic. All of them for internal use, I mean with no access to internet, only inside the plant. I would recommend to use it but being really careful about how you design it