Sample code for 30+ languages & platforms
SQL Server

OneDrive -- Create a Sharing Link

See more OneDrive Examples

Creates a sharing link for a file.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @iTmp1 int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    -- This example requires the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

    -- Use your client ID, client secret, and tenant ID in the following lines
    DECLARE @json int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @json OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @json, 'UpdateString', @success OUT, 'client_id', '2871da2c-8176-4b7f-869b-2311aa82e743'
    EXEC sp_OAMethod @json, 'UpdateString', @success OUT, 'client_secret', '2hu9Q~r5QuryUcEkNbg1btLtnfU1VUXzhSCG6brH'
    EXEC sp_OAMethod @json, 'UpdateString', @success OUT, 'scope', 'https://graph.microsoft.com/.default'
    EXEC sp_OAMethod @json, 'UpdateString', @success OUT, 'token_endpoint', 'https://login.microsoftonline.com/114d7ed6-71bf-4dbe-a866-748364121bf2/oauth2/v2.0/token'

    DECLARE @http int
    EXEC @hr = sp_OACreate 'Chilkat.Http', @http OUT

    EXEC sp_OAMethod @json, 'Emit', @sTmp0 OUT
    EXEC sp_OASetProperty @http, 'AuthToken', @sTmp0

    -- Sends a POST such as the following:

    -- 	POST https://graph.microsoft.com/v1.0/users/{user-id}/drive/root:/{item-path}:/createLink
    -- 	Content-type: application/json
    -- 
    -- 	{
    -- 	  "type": "view",
    -- 	  "scope": "anonymous"
    -- 	}

    -- This example will create a shareable link for /Pictures/three_penguins.jpg
    EXEC sp_OAMethod @http, 'SetUrlVar', @success OUT, 'item_path', 'Pictures/three_penguins.jpg'
    EXEC sp_OAMethod @http, 'SetUrlVar', @success OUT, 'user_id', '4fe732c3-322e-4a6b-b729-2fd1eb5c6104'

    -- Create the JSON request body:
    DECLARE @jsonReqBody int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @jsonReqBody OUT

    -- See https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createlink 
    -- for information about link types and scope types.
    EXEC sp_OAMethod @jsonReqBody, 'UpdateString', @success OUT, 'type', 'view'
    EXEC sp_OAMethod @jsonReqBody, 'UpdateString', @success OUT, 'scope', 'anonymous'

    DECLARE @resp int
    EXEC @hr = sp_OACreate 'Chilkat.HttpResponse', @resp OUT

    EXEC sp_OAMethod @http, 'HttpJson', @success OUT, 'POST', 'https://graph.microsoft.com/v1.0/users/{$user_id}/drive/root:/{$item_path}:/createLink', @jsonReqBody, 'application/json', @resp
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @http, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @json
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @jsonReqBody
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END

    EXEC sp_OASetProperty @json, 'EmitCompact', 0
    EXEC sp_OAGetProperty @resp, 'BodyStr', @sTmp0 OUT
    EXEC sp_OAMethod @json, 'Load', @success OUT, @sTmp0

    -- If the response status code was not 200 or 201, then it failed.
    EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
    EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp1 OUT
    IF (@iTmp0 <> 201) and (@iTmp1 <> 200)
      BEGIN
        EXEC sp_OAMethod @json, 'Emit', @sTmp0 OUT
        PRINT @sTmp0

        EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
        PRINT 'Response Status Code = ' + @iTmp0

        PRINT 'Failed.'
        EXEC @hr = sp_OADestroy @json
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @jsonReqBody
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END

    EXEC sp_OAMethod @json, 'Emit', @sTmp0 OUT
    PRINT @sTmp0

    -- A sample successful JSON response:

    -- 	{
    -- 	  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#permission",
    -- 	  "@odata.type": "#microsoft.graph.permission",
    -- 	  "id": "gIwOOCCzbeRlnx54vk7MlxqQDN0",
    -- 	  "link": {
    -- 	    "application": {
    -- 	      "id": "441c9990"
    -- 	    },
    -- 	    "type": "view",
    -- 	    "webUrl": "https://1drv.ms/u/s!AhXMdJvr_DM6pghxw0E-5oJX9Hrz"
    -- 	  },
    -- 	  "roles": [
    -- 	    "read"
    -- 	  ],
    -- 	  "shareId": "s!AhXMdJvr_DM6pghxw0E-5oJX9Hrz"
    -- 	}

    -- Get the webUrl like this:
    DECLARE @webUrl nvarchar(4000)
    EXEC sp_OAMethod @json, 'StringOf', @webUrl OUT, 'link.webUrl'

    -- Test by downloading using an HTTP object with no authentication:
    DECLARE @http2 int
    EXEC @hr = sp_OACreate 'Chilkat.Http', @http2 OUT

    DECLARE @sbHtml int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbHtml OUT

    EXEC sp_OAMethod @http2, 'DownloadSb', @success OUT, @webUrl, 'utf-8', @sbHtml
    IF @success <> 1
      BEGIN
        EXEC sp_OAGetProperty @http2, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0

        PRINT 'Download of Shared URL failed.'
        EXEC @hr = sp_OADestroy @json
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @jsonReqBody
        EXEC @hr = sp_OADestroy @resp
        EXEC @hr = sp_OADestroy @http2
        EXEC @hr = sp_OADestroy @sbHtml
        RETURN
      END

    EXEC sp_OAMethod @sbHtml, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    -- The shared URL is not actually the data of the file itself, but is HTML
    -- that can be shared, and will display the file.  For example:

    -- <html>
    --     <head>
    --         <title>Microsoft OneDrive - Access files anywhere. Create docs with free Office Online.</title><meta name="title" content="Microsoft OneDrive - Access files anywhere. Create docs with free Office Online."/><meta name="description" content="Store photos and docs online. Access them from any PC, Mac or phone. Create and work together on Word, Excel or PowerPoint documents."/><meta property="og:title" content="penguins.jpg"/><meta property="og:image" content="https&#58;//storage.live.com/Items/3A33FCEB9B74CC15&#37;214872&#37;3ACustomThumbnailSource&#37;2CHighRes&#37;2CDefault&#63;width&#61;1024&#38;height&#61;768&#38;authKey&#61;&#37;21AHHDQT7mglf0evM"/><meta property="og:image:width" content="1024"/><meta property="og:image:height" content="768"/><meta property="og:url" content="https&#58;//onedrive.live.com/redir&#63;resid&#61;3A33FCEB9B74CC15&#33;4872&#38;authkey&#61;&#33;AHHDQT7mglf0evM"/><meta property="og:description" content="JPG Image"/><meta property="twitter:site" content="&#64;OneDrive"/><meta property="twitter:card" content="photo"/><meta property="twitter:image" content="https&#58;//storage.live.com/Items/3A33FCEB9B74CC15&#37;214872&#37;3ACustomThumbnailSource&#37;2CHighRes&#37;2CDefault&#63;width&#61;1024&#38;height&#61;768&#38;authKey&#61;&#37;21AHHDQT7mglf0evM"/><meta property="twitter:image:width" content="1024"/><meta property="twitter:image:height" content="768"/>
    --         <noscript><meta http-equiv="refresh" content="0;url=https://onedrive.live.com/&#63;cid&#61;3a33fceb9b74cc15&#38;id&#61;3A33FCEB9B74CC15&#37;214872&#38;sff&#61;1&#38;authkey&#61;&#33;AHHDQT7mglf0evM" /></noscript>
    --         <script type="text/javascript">//<![CDATA[
    -- var _d=document,_dh=_d.getElementsByTagName("head")[0];function _ge(a){return _d.getElementById(a)}var $U={a:"^((ftp|http|https):)?//",b:"(^(\\s?ftp:|\\s?http:|\\s?https:|\\s?//))",primaryAjaxDelimiter:"#",pairDelimiter:"&",keyValueDelimiter:"=",queryDelimiter:"?",isAbsoluteUrl:function(a){var b=new RegExp($U.a,"i"),c=new RegExp($U.b,"i");return b.test(a)||c.test(a)},getHost:function(c){var a=$U.a+"([^:/]*([:][^@/]*)?[@])?([-.a-z0-9]*)[^-.a-z0-9]?",b=new RegExp(a,"i");return urlHost=(String(c).search(b)<0?"":RegExp.$5).toLowerCase()},doesMatchHost:function(b,e){var f="^(mailto|tel|sms):",g=new RegExp(f,"i"),c=$U.isAbsoluteUrl(b),a=$U.getHost(b),i=g.test(b),d="."+e,h=a.substr(a.length-d.length)==d||a==""&&!c||a.charAt(0)=="#"||a==e;return (!c||h)&&!i},isLinkABookmark:function(a,b){b=b||_d;var d=b.createElement("span");d.innerHTML='<a href="#"></a>';var f=d.firstChild.href,c=a.indexOf("#"),e=a.indexOf("javascript:");if(c>-1)if(c==0||a.indexOf(f)==0)return 1;if(e==0)return 1;return 0},getUrlFragment:function(c){var a="",b=c.indexOf("#");if(b>-1)a=c.substr(b+1);return a},getHashUrl:function(){var c,e=window.location,a=e.href,b=a.indexOf($U.primaryAjaxDelimiter),d=b==-1?"":a.substr(b+1);if(d)c=$U.getNormalizedUrl(a,$U.primaryAjaxDelimiter);return c},getNormalizedUrl:function(a,c){c=c||$U.primaryAjaxDelimiter;var f="",e=$U.getAjaxIndex(a,c);if(e>-1){f=a.substr(e+1);a=a.substr(0,e)}var b="",d=a.indexOf($U.queryDelimiter);if(d>-1){b=a.substr(d+1);a=a.substr(0,d)}b=$U.serialize($U.deserialize(f?f:b));if(b)a=[a,$U.queryDelimiter,b].join("");a=a.replace(/[!]/g,"%21");return a},getAjaxIndex:function(a,d){var h=-1,c=a.indexOf(d);while(c!=-1){var b=c+1,e=a.indexOf(d,b),j=a.indexOf($U.pairDelimiter,b),k=a.indexOf($U.queryDelimiter,b),g=a.indexOf($U.keyValueDelimiter,b),i=[e,j,k,g].sort(function(a,b){return a==-1?1:b==-1?-1:a-b}),f=i[0];if(f==-1)break;else if(f==g){h=c;break}else c=e}return h},getCurrentUrl:function(){return $U.getHashUrl()||window.location.href},deserialize:function(f){var c={};if(f){var e=f.split($U.pairDelimiter),g=e.length,a=0;for(;a<g;a++){var j=e[a],b=j.split($U.keyValueDelimiter),i=b[0];b.splice(0,1);var h=b.join($U.keyValueDelimiter);try{c[i]=decodeURIComponent(h)}catch(d){if(!(d instanceof URIError))throw d;c={};break}}}return c},serialize:function(d){var a=[];for(var c in d){var b=d[c];b=b?b:"";a.push(c,$U.keyValueDelimiter,encodeURIComponent(b).replace(/[^\w.%-]/g,function(b){var a=b.charCodeAt(0).toString(16);return "%"+(a.length==1?"0"+a:a).toUpperCase()}),$U.pairDelimiter)}if(a.length>0)a.pop();return a.join("")}}
    -- //]]></script>
    --         
    -- <script type="text/javascript">//<![CDATA[
    -- var $PF={"d":"live.com","ru":"https\u003a\u002f\u002fonedrive.live.com\u002f\u003fcid\u003d3a33fceb9b74cc15\u0026id\u003d3A33FCEB9B74CC15\u0025214872\u0026sff\u003d1\u0026authkey\u003d\u0021AHHDQT7mglf0evM"};
    --     (function(){var b=window,a=b.$PF=b.$PF||{},p=":",k="&colon",j="&#",g="&",d="=",f="?",e="#",n="!",o="!",l=new RegExp("[^a-z0-9-.+:]","i"),m=new RegExp("^[a-z0-9-.+]+:","i");a.isProtocolAllowed=function v(d){d=(d||"").toLowerCase();var b="",g=d.length,f;for(var e=0;e<g;e++){f=d.charCodeAt(e);if(f>32&&f<127)b+=d.charAt(e)}var a=b.indexOf(p);if(a==-1)a=b.indexOf(k);if(a==-1)a=b.indexOf(j);var c=b.substr(0,a+1);return !l.test(c)&&(!m.test(c)||c=="http:"||c=="https:"||c=="ftp:")};a.isInternalUrl=function y(b){try{return !!b&&$U.doesMatchHost(b,a.d)&&a.isProtocolAllowed(b)}catch(c){return false}};a.getHashUrl=function z(){var c,h=b.location,d=h.href,g=d.indexOf(e),f=g==-1?"":d.substr(g+1);if(f){var i=e;c=d;if(f.indexOf(o)==0)if(f.length>1){c=d.substr(d.indexOf(f)+1);i=n}else c=c.substr(0,g);if(c.indexOf("/")==0)c=[h.protocol,"//",h.host,c].join("");c=a.getNormalizedUrl(c,i)}return c};a.getCurrentUrl=function x(){var c=a.getHashUrl();return a.isInternalUrl(c)?c:b.location.href};a.getAppFrameWindow=function u(){try{return (!a.m||a.merged)&&_ge(a.fid).contentWindow}catch(b){return undefined}};a.getAppFrameDocument=function t(){try{return a.getAppFrameWindow().document}catch(b){return undefined}};function q(a,e){var k=-1,c=a.indexOf(e);while(c!=-1){var b=c+1,h=a.indexOf(e,b),m=a.indexOf(g,b),n=a.indexOf(f,b),j=a.indexOf(d,b),l=[h,m,n,j].sort(function(a,b){return a==-1?1:b==-1?-1:a-b}),i=l[0];if(i==-1)break;else if(i==j){k=c;break}else c=h}return k}a.getNormalizedUrl=function w(a,c){c=c||e;var h="",g=q(a,c);if(g>-1){h=a.substr(g+1);a=a.substr(0,g)}var b="",d=a.indexOf(f);if(d>-1){b=a.substr(d+1);a=a.substr(0,d)}b=s(r(h?h:b));if(b)a=[a,f,b].join("");a=a.replace(/[!]/g,"%21");return a};function r(h){var c={};if(h){var f=h.split(g),i=f.length,a=0;for(;a<i;a++){var l=f[a],b=l.split(d),k=b[0];b.splice(0,1);var j=b.join(d);try{c[k]=decodeURIComponent(j)}catch(e){if(!(e instanceof URIError))throw e;c={};break}}}return c}function s(e){var a=[];for(var c in e){var b=e[c];b=b?b:"";a.push(c,d,encodeURIComponent(b).replace(/[^\w.%-]/g,function(b){var a=b.charCodeAt(0).toString(16);return "%"+(a.length==1?"0"+a:a).toUpperCase()}),g)}if(a.length>0)a.pop();return a.join("")}if(!a.f)try{var c=a.getHashUrl()||a.ru;if(c){var h=document.location;try{if(b!=b.top){document.domain=a.d;if(c.indexOf("login."+a.d)>-1||c.indexOf("account."+a.d)>-1||c.indexOf(b.top.document.location.protocol)!=0)h=b.top.document.location}}catch(i){}if(a.isInternalUrl(c))h.replace(c)}}catch(i){}})();
    -- 
    -- //]]></script>
    -- 
    --     </head>
    -- </html>

    EXEC @hr = sp_OADestroy @json
    EXEC @hr = sp_OADestroy @http
    EXEC @hr = sp_OADestroy @jsonReqBody
    EXEC @hr = sp_OADestroy @resp
    EXEC @hr = sp_OADestroy @http2
    EXEC @hr = sp_OADestroy @sbHtml


END
GO