Giter Site home page Giter Site logo

madeiradata / clrhttprequest Goto Github PK

View Code? Open in Web Editor NEW
15.0 4.0 16.0 116 KB

SQL Server CLR function for running REST methods over HTTP

License: MIT License

C# 84.78% TSQL 15.22%
sqlserver sqlserver-2016 clr sqlclr rest-api restful-api restful-webservices http http-requests webrequest

clrhttprequest's Introduction

ClrHttpRequest

SQL Server CLR function for running REST methods over HTTP.

To download the latest version, please visit the Releases page.

This project is a fork of the project initially published By Eilert Hjelmeseth, 2018/10/11 here: http://www.sqlservercentral.com/articles/SQLCLR/177834/

Eilert's GitHub project: https://github.com/eilerth/sqlclr-http-request

My version extends the project by adding the following:

  • Usage of TLS1.2 security protocol (nowadays a global standard).
  • Two new authentication methods:
    • Authorization-Basic-Credentials (Basic authorization using Base64 credentials)
    • Authorization-Network-Credentials (creates a new NetworkCredential object and assigns it to the Credentials property of the request)
  • Added support for using a Proxy with a new "Proxy" header in the form of URI:PORT. For example: <Header Name="Proxy">https://acmeproxy:4321</Header>
  • Addition of a proper PreDeployment script which takes care of CLR assembly signing without requiring the TRUSTWORTHY database setting.
  • Added UTF8 encoding support instead of ASCII.
  • Added support for case-insensitive headers.

The following code was added in clr_http_request.cs, line 19:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

The following code was added in line 79 to add support for special headers:

	case "Authorization-Basic-Credentials":
		request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(headerValue)));
		break;
	case "Authorization-Network-Credentials":
		var netCredValues = headerValue.Split(':');
		if (netCredValues.Length < 2)
		{
			throw new FormatException("When specifying Authorization-Network-Credentials headers, please set the value in a format of username:password");
		}
		request.Credentials = new NetworkCredential(netCredValues[0], netCredValues[1]);
		break;
	case "Proxy":
		var proxyValues = headerValue.Split(':');
		if (proxyValues.Length < 2)
		{
			throw new FormatException("When specifying the PROXY header, please set the value in a format of URI:PORT");
		}
		int proxyPort;
		if (!int.TryParse(proxyValues[1], out proxyPort))
		{
			throw new FormatException("When specifying the PROXY header in the format of URI:PORT, the PORT must be numeric");
		}
		WebProxy myproxy = new WebProxy(proxyValues[0], proxyPort);
		myproxy.BypassProxyOnLocal = false;
		request.Proxy = myproxy;
		break;

These changes allow the SQL Server function to work with advanced services such as Zendesk. For example:

-- Credentials info: Username (email address) must be followed by /token when using API key
DECLARE @credentials NVARCHAR(4000) = 'agent@company_domain.com/token:api_token_key_here'
DECLARE @headers NVARCHAR(4000) = '<Headers><Header Name="Content-Type">application/json</Header><Header Name="Authorization-Basic-Credentials">' + @credentials + '</Header></Headers>'

-- Global Zendesk Settings:
DECLARE @zendesk_address NVARCHAR(400) = 'https://your_subdomain_here.zendesk.com'

-- Look for existing tickets based on @RequesterEmail:
SET @uri = @zendesk_address + '/api/v2/search.json?query=type:ticket status<solved requester:' + @RequesterEmail

DECLARE @tickets NVARCHAR(MAX), @ticket NVARCHAR(MAX)

-- This is where the magic happens:
SET @tickets = [dbo].[clr_http_request]
        (
            'GET',
            @uri,
            NULL,
            @headers,
            300000,
            0,
            0
        ).value('/Response[1]/Body[1]', 'NVARCHAR(MAX)')

-- check if ticket exists based on @Subject:
SELECT @ticket = [value]
FROM OPENJSON(@tickets, '$.results')
WHERE JSON_VALUE([value], '$.subject') = @Subject
AND JSON_VALUE([value], '$.status') IN ('new', 'open', 'pending')

SELECT uri = JSON_VALUE(@ticket, '$.url'), submitter = JSON_VALUE(@ticket, '$.submitter_id')

For more use cases visit here: https://github.com/EitanBlumin/ClrHttpRequest/blob/master/UseCases.md

For more info on using the Zendesk API, visit here: https://developer.zendesk.com/rest_api/docs/core/introduction

clrhttprequest's People

Contributors

eitanblumin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

clrhttprequest's Issues

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.clr_http_request", or the name is ambiguous.

I freshly installed your SQLCLR script and I was looking for testing it.

In your Use Cases page I tried the Stack Overflow API query but it returns me:

Msg 4121, Level 16, State 1, Line 2
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.clr_http_request", or the name is ambiguous.

I changed [dbo].[clr_http_request] to [dbo].[ClrHttpRequest] and tried to delete [dbo] but no joy

Timeout or Wrong Connection

About year all worked fine (thanks a lot!) , but "The something strange in was-asked-site . Ghost bastards?" : all requests to site begun to finished with errors. Probably some changes in site was made. But Postman and KataonStudio return proper result still (with 200-Ok code). This problem concerns onli this site, not others. Does is need to correct anything in clrhttprequest source? Thanks for you advises! Good luck!

Problem is :

I send to Web-API from MS SQL Servers (2012, 2017, 2019) :

declare @response xml;
set @response = [dbo].[clr_http_request](N'POST', 
    N'http://cb-api.ozonru.me/v1/product/info/prices',  
    N'{"page": 1, "page_size": 10}', 
    N'<Headers>
     <Header Name="Client-Id">836</Header>
     <Header Name="Api-Key">0296d4f2-70a1-4c09-b507-904fd05567b9</Header>
     <Header Name="Content-Type">application/json</Header>
     </Headers>',  
    5000, 
    1,
    0);  
select @response;

Get the error:
Message 6522, level 16, state 1, line 19
A .NET Framework error occurred during execution of user-defined routine or aggregate "clr_http_request":
System.Net.WebException: Time is out
System.Net.WebException:
in System.Net.HttpWebRequest.GetResponse()
in UserDefinedFunctions.clr_http_request(SqlString requestMethod, SqlString url, SqlString parameters, SqlString headers, SqlInt32 timeout, SqlBoolean autoDecompress, SqlBoolean convertResponseToBas64)

multipart/form-data

Just wondering if it is possible to post multipart/form-data using this CLR.

Support for SQL2008

This CLR assembly currently doesn't work on SQL 2008 R2 and older.

In order to make this CLR assembly compatible with that, it must be re-written to be compatible with .NET Framework 3.5 SP1.

sp_add_trusted_assembly

Hey great lib, glad I found you before trying to do the same! ๐Ÿ‘

I think this release steps are missing

declare @a varbinary(max) = 0x4D5A...

declare @hash varbinary(64) = HASHBYTES('SHA2_512',@a)

EXEC sys.sp_add_trusted_assembly @hash = @Hash, @description = N'ClrHttpRequest'

The request was aborted: Could not create SSL/TLS secure channel.

Hello,

I correctly registered the file that I downloaded from here but when I run the GET query I receive this error:

Msg 6522, Level 16, State 1, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "clr_http_request": 
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
System.Net.WebException: 
at System.Net.HttpWebRequest.GetResponse()
at UserDefinedFunctions.clr_http_request(String requestMethod, String url, String parameters, String headers, Int32 timeout, Boolean autoDecompress, Boolean convertResponseToBas64)

I'm on SQL Server 2019, I believe the C# request needs to be updated

I also noticed that on SQLServerCentral the .zip file contains the .DLL , here on GitHub there is no .DLL ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.