schweg.xyzAndrew Schwegler
Selected work / 02

Technical guide

Secure API calls with C# & SQL.

A mission in secure integration.

Interactive controls require the page scripts. If they do not appear, reload this page. Static reference notes remain available below.

A Starfleet-themed learning guide to C#, SQL Server and outbound HTTP. This interactive console is a local simulation: it never connects to a database or executes SQL.

Mission control / Local simulation

SQL CLR permissions

Choose a permission boundary.

SAFE restricts access to external resources. Outbound network access is unavailable.

Ready. Select a permission level, then run the demonstration.

The integration boundary

What belongs in the application layer?

Prefer a dedicated application or service for outbound API calls when practical. Keep secrets outside database code, validate requests and responses, and define timeouts and error handling.

How do permissions differ?

SAFE is restricted. EXTERNAL_ACCESS permits specified external resource access when deployment and trust requirements are met. UNSAFE is a much broader permission level and should not be the default.

A note on the original guide

The original includes a command console, a mission animation and expandable technical explanations. The learning interaction runs entirely in your browser. Check platform documentation before applying any example in a real environment.

Reference notes & original examples

Historical code examples retained from the Starfleet-themed guide. They are reading material, not commands executed by this page or a production deployment recipe. Verify platform support, trust, authorization and outbound-network policy before using any example.

A Starfleet guide to the integration boundary.

The stored procedure supplies a document payload, the C# example sends an HTTP request, and the remote service supplies a response. The interactive console above models permission outcomes only: it never executes SQL, renders the payload or sends the request.

The C# example

using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public partial class DocumentFabricationProtocol
{
    // A single, static HttpClient is mission-critical for performance.
    private static readonly HttpClient client = new HttpClient();

    [SqlFunction(DataAccess = DataAccessKind.None, SystemDataAccess = SystemDataAccessKind.None)]
    public static SqlString CreateDocument(SqlString apiUrl, SqlString htmlPayload)
    {
        // Protocol 1.1: Verify fabrication station coordinates.
        if (apiUrl.IsNull || !Uri.TryCreate(apiUrl.Value, UriKind.Absolute, out Uri uri))
            return new SqlString("Error: Invalid API coordinates.");

        // Protocol 2.4: Secure channels only.
        if (uri.Scheme != Uri.UriSchemeHttps)
            return new SqlString("Error: Unsecure channel.");

        // Protocol 2.5: Verify destination is a trusted Starfleet fabricator.
        if (!uri.Host.EndsWith(".starfleet.local", StringComparison.OrdinalIgnoreCase))
            return new SqlString("Error: Untrusted destination.");

        try
        {
            // Prepare the schematic (HTML) for transport.
            var content = new StringContent(htmlPayload.Value, Encoding.UTF8, "application/json");

            // Transmit data via POST and await response.
            Task<HttpResponseMessage> responseTask = client.PostAsync(uri, content);
            HttpResponseMessage response = responseTask.GetAwaiter().GetResult();

            response.EnsureSuccessStatusCode();

            // Confirmation that API placed file in buffer. Archival is handled by SSU.
            return new SqlString("Success: Schematic received by fabricator.");
        }
        catch (Exception ex) {
            return new SqlString($"Fabrication Error: {ex.Message}");
        }
    }
}

The T-SQL command

CREATE PROCEDURE dbo.usp_GenerateArchivedDocument
    @HtmlContent NVARCHAR(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    -- Set target fabrication station coordinates. Store this in a config table, not here!
    DECLARE @ApiEndpoint NVARCHAR(2048) = N'https://api.example.invalid/api/createpdf';
    DECLARE @Status NVARCHAR(MAX);

    -- Log the attempt.
    PRINT 'Authorizing transmission to ' + @ApiEndpoint;

    BEGIN TRY
        -- Execute the CLR function, passing the coordinates and the schematic.
        SELECT @Status = dbo.CreateDocument(@ApiEndpoint, @HtmlContent);

        -- Verify mission success.
        IF (@Status LIKE 'Success:%')
        BEGIN
            PRINT 'Confirmation received. Document fabrication initiated.';
        END
        ELSE
        BEGIN
            -- Report failure to the bridge.
            THROW 50001, @Status, 1;
        END
    END TRY
    BEGIN CATCH
        PRINT 'RED ALERT: Mission failed. An unknown anomaly occurred during transmission.';
        THROW;
    END CATCH
END

Assembly registration example

-- Load the compiled .dll file into SQL Server.
-- The DLL must be on a path accessible by the SQL Server service account.
CREATE ASSEMBLY DocumentFabricationAssembly
FROM 'C:\Example\CLR\DocumentFabricationProtocol.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS;
GO

-- Create the SQL function that maps to the C# method.
-- Note the parameter types match the C# SqlString types.
CREATE FUNCTION dbo.CreateDocument(
    @apiUrl NVARCHAR(2048),
    @htmlPayload NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS EXTERNAL NAME DocumentFabricationAssembly.[DocumentFabricationProtocol].CreateDocument;
GO

Read the permission-boundary notes or return to the local demonstration to compare SAFE, EXTERNAL_ACCESS and UNSAFE. There is no second transmission form hidden in this reference section.

Next project

The Slayer’s guide to SQL migration