MSBA-272 · Lesson 8 of 12 · 19 min

Policies and code in connectors

▶ Video coming soon A video version of this lesson is on the way.

The Parcelwise connector worked, but it had rough edges that the definition alone could not smooth. Tracking events came back with Unix timestamps that makers could not read. The sandbox and production APIs lived on different hosts, and the connector pointed at only one. Parcelwise wanted a client identification header on every request. None of these justified writing a separate web service in front of the API. Custom connectors offer two lighter tools for this kind of adjustment: policies, which are configured from templates, and custom code, a small C# script that runs inside the connector. Signe's rule was to reach for a policy first and code only when no policy could do the job.

Where policies and code run

Both policies and code run inside the connector infrastructure, between the caller and the API. A request from a flow or app passes through the connector's policies and, for operations that have code enabled, through the script, before it is sent to the API. The response comes back the same way. Neither runs in Dataverse or in the caller, and neither needs any hosting of its own.

A horizontal path from a flow on the left to the Parcelwise API on the right. Between them, inside a box labeled custom connector, are request policies, then custom code, then the API call, and on the return path response policies. A note says policies are configured from templates and code is one C# script per connector.
Policies and code sit inside the connector, on the request and response path.

Policy templates

Policies are created on the connector's Definition page from a list of templates. Each template performs one kind of change and takes a few settings, such as a header name and value, and can be limited to particular operations and to the request or the response. The available templates include, among others, setting an HTTP header, setting a query string parameter, setting the host URL, routing a request to a different path, and converting between arrays and objects in a payload. Some templates are in preview, and the list grows, so Wiremu checked Microsoft's policy templates page for the current set before designing around one.

Policy templates Wiremu considered. Check Microsoft's current list before relying on one.
TemplateWhat it doesParcelwise use
Set HTTP headerAdds or overrides a header on the request or responseAdds the X-Parcelwise-Client header with the value Lumenvale on every request
Set host URLChanges the host the request is sent to, which can come from a connection parameterSends requests to the sandbox or the production host
Route requestSends an operation to a different path on the APIMaps the connector's Get shipment to the vendor's versioned path
Set query string parameterAdds or overrides a query parameterAdds a fixed locale parameter to tracking requests
Set header or query parameter value from URLCopies a value from the URL into a header or parameter (preview)Not used

The host URL problem deserved care. Parcelwise's sandbox and production APIs had different hosts, and Lumenvale's test environment had to call the sandbox while production called the real service. Wiremu added a connection parameter for the environment, offered as a choice when the connection was created, and a Set host URL policy that used it. The connection in Registrar Test was created with the sandbox choice and the one in Registrar Prod with the production choice. The flows did not know or care which host they were using.

Signe reminded him that the host in the connector also mattered for governance. Rupert's data policy allowed the Parcelwise connector by host URL pattern, so both hosts had to match the pattern, or one environment's flows would be blocked. They chose a pattern covering Parcelwise's API domain and nothing else, and Rupert approved it.

Connection parameters and environments

The environment choice Wiremu added for the host URL is an example of a connection parameter: a value requested when a connection is created, in addition to the credentials. Connection parameters are defined in the connector's properties, can be text or a fixed list of choices, and can be referenced by policies. They solve a problem that otherwise has no clean answer. A custom connector definition is the same in every environment, because it travels in the solution, but the connection is created separately in each environment, so a value that must differ between test and production belongs on the connection.

Signe warned against using connection parameters for anything secret beyond what the authentication settings already hold, and against offering free text where a choice would do. A typo in a free-text host would send requests to the wrong place; a two-item list of Sandbox and Production could not. The deployment notes for the Registrar Transcripts solution recorded which value each environment's Parcelwise connection should use, and the release checklist asked the person deploying to confirm it.

Wiremu asked whether the policies and the script traveled with the solution too. They do. Policies are stored in the connector's properties and the script with the connector, so exporting the solution captures both, and the repository copies made with pac connector download showed every change in pull requests. Nothing about the connector's behavior was configured by hand in test or production, which was the point.

When a policy is not enough

The timestamp problem had no policy template. Parcelwise returned each tracking event with a timestamp field holding seconds since 1970, and makers needed a date and time. Converting it in every flow with an expression was possible but error-prone, and makers would have to know to do it. The right place was the connector, and the tool was custom code.

Custom code is a C# script that the connector runs for operations where code is enabled. Microsoft documents a clear set of rules and limits for it, and Wiremu read them before writing a line.

Custom code rules from Microsoft's documentation at the time of the session.
Rule or limitDetail
Language and frameworkC#, compiled against .NET Standard 2.0
ShapeA class named Script that derives from ScriptBase and overrides ExecuteAsync
Scripts per connectorOne script, which can branch by operation ID
Script sizeUp to 1 MB
Time limitTwo minutes per execution for new connectors
Sending the requestUse this.Context.SendAsync; creating your own HttpClient is being blocked
Allowed namespacesA fixed list, including System, System.Net.Http, System.Text.RegularExpressions, System.Threading.Tasks, System.Xml.Linq and Newtonsoft.Json
GatewayNot supported with the on-premises data gateway
LoggingNot yet supported according to the current documentation

Writing the script

The script's ExecuteAsync method receives the incoming request through the Context object and must return an HTTP response. For most operations the script simply forwards the request with SendAsync and returns the response unchanged. For Get tracking events, it forwards the request, reads the JSON response, adds a readable timestamp to each event, and returns the modified response.

Connector code that adds an ISO 8601 date to each tracking event. The new property was also added to the response schema so makers see it.
public class Script : ScriptBase
{
    public override async Task<HttpResponseMessage> ExecuteAsync()
    {
        HttpResponseMessage response = await this.Context
            .SendAsync(this.Context.Request, this.CancellationToken)
            .ConfigureAwait(false);

        if (this.Context.OperationId != "GetTrackingEvents" || !response.IsSuccessStatusCode)
        {
            return response;
        }

        string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        JObject json = JObject.Parse(body);
        foreach (JToken ev in json["events"] ?? new JArray())
        {
            long seconds = ev.Value<long>("timestamp");
            ev["occurredAtUtc"] = DateTimeOffset.FromUnixTimeSeconds(seconds)
                .UtcDateTime.ToString("o");
        }

        response.Content = CreateJsonContent(json.ToString());
        return response;
    }
}

Three details mattered. First, the script checked the operation ID and returned other operations untouched, because there is one script for the whole connector. Second, it passed failed responses through unchanged, so a Parcelwise error reached the flow with its original status and message rather than being hidden by a parsing exception. Third, Wiremu added occurredAtUtc to the Get tracking events response schema in the definition. Code can add properties to a response, but the designers only offer makers the properties the schema describes.

In the connector's Code page, code is turned on for the connector and then enabled for specific operations. Wiremu enabled it only for Get tracking events. The other operations skipped the script entirely, which kept them faster and meant a bug in the script could affect only one operation.

Connector code compared with plug-in code

Wiremu now had C# running in two very different places, and Signe made him write down the differences so he would not mix up their rules.

Two places C# runs in Power Platform.
PointDataverse plug-inConnector custom code
RunsInside Dataverse, in the event pipelineInside the connector, between caller and API
Framework.NET Framework 4.6.2.NET Standard 2.0
Triggered byA registered step on a messageA call to an operation with code enabled
DiagnosticsTracing service and plug-in trace logNo logging yet; test the logic separately
Time limitShares the two-minute limit of the message operationTwo minutes per execution for new connectors
Typical jobBusiness rules on Dataverse dataReshaping requests and responses

Shaping errors as well as data

Parcelwise reported errors in its own JSON format, with a code and a message in nested properties. Flows that failed showed makers the raw body, which was hard to read. Wiremu considered using the script to turn every Parcelwise error into a simpler message, and Signe agreed that this counted as response shaping, with one condition: the HTTP status code had to stay the same. A flow's retry and error handling depend on the status, and a script that turned a 503 into a 400, or worse into a 200 with an error message inside, would break them. In the end he added only a top-level message property to error responses, copied from Parcelwise's nested one, and left everything else as it was.

Keeping data and credentials safe in code

Connector code sees the whole request, including the Authorization header that carries the connection's token or key. Signe set three rules. The script never copied a header or token into a response body. It never sent any part of a request to a host other than the API, which the platform's restrictions on namespaces and HttpClient already discouraged. And it never added data the API had not returned, so the response a maker saw was always a faithful reshaping of Parcelwise's answer. Those rules went into Lumenvale's pull request checklist for connectors, next to the rule about secrets in definitions.

Every policy and every line of code also adds a little time to each call. For Parcelwise this was negligible, but Signe noted that a script that parsed and rebuilt large responses could add noticeably to a flow that called it in a loop. Code that only touched the operations that needed it, and returned other responses untouched, kept the cost where it belonged.

Testing and maintaining code

The wizard's Test page runs the script with a real connection, which was how Wiremu checked the output against the Parcelwise sandbox. Because connector code cannot write logs at present, he could not trace inside the script as he did in plug-ins. Instead, he kept the conversion logic in a small static method that he copied into a unit test project and tested with saved sample responses, including an empty events list, a missing timestamp and a response with an error status. The script and its tests lived in the connectors folder of the repository and were deployed with pac connector commands, which accept a script file.

Signe added a warning about scope creep. Connector code is convenient, and it is tempting to add business logic to it: choosing a service level from the delivery address, retrying failed bookings, sending an email. She asked that connector code be limited to shaping requests and responses. Business logic belonged in Dataverse, in flows or in the API itself, where it could be seen, tested and secured properly. A connector that made decisions would surprise the next developer, and the two-minute limit and the lack of logging made it a poor home for anything complicated.

Worked problem

Policy or code?

Three more requests came in for the Parcelwise connector. (1) Send an Accept-Language header of en-CA on tracking requests. (2) Combine a street, city and postal code typed in separate fields into the single multi-line address string that a new Parcelwise endpoint expects. (3) Retry a booking up to five times if Parcelwise returns a server error.

Show solution
  1. Request 1 adds a fixed header: the Set HTTP header policy template does exactly this, limited to the tracking operation.
  2. Request 2 reshapes the request body in a way no template covers: custom code, enabled only for the new operation, with the new fields in the request schema.
  3. Request 3 is retry logic. Flows already offer a retry policy on each action, and a retry inside connector code would count against its time limit and hide failures. It belongs in the flow's action settings.

Answer: A policy for 1, connector code for 2, and the flow's own retry policy for 3.

Network considerations

Two network details in Microsoft's documentation affected Lumenvale's future plans. Custom code does not support the on-premises data gateway, as lesson 7 noted. And in environments linked to an Azure virtual network, calls made from connector code through SendAsync go to public endpoints rather than through the virtual network. Lumenvale had no virtual network integration for its Power Platform environments, but Rupert noted it in the design document for the building management alarm plan from MSBA-270, which might one day need private networking.

Common mistakes

  • MistakeWriting code for something a policy template already does.

    InsteadUse a policy first; use code only when no template fits.

  • MistakeCreating an HttpClient inside connector code.

    InsteadSend requests with this.Context.SendAsync.

  • MistakeEnabling code for every operation.

    InsteadEnable code only for operations that need it.

  • MistakeAdding properties in code without updating the response schema.

    InsteadDescribe new properties in the schema so makers can use them.

  • MistakePutting business decisions and retries in connector code.

    InsteadLimit code to shaping requests and responses; keep logic in Dataverse, flows or the API.

Summary and key terms

  • Policies and custom code run inside the connector, between the caller and the API.
  • Policy templates make common changes such as setting headers, query parameters and the host URL, or routing requests.
  • Custom code is one C# script per connector, a Script class derived from ScriptBase that overrides ExecuteAsync.
  • Code targets .NET Standard 2.0, is limited to 1 MB and two minutes, must use Context.SendAsync, and does not support the gateway or logging.
  • Enable code only where needed, keep it to request and response shaping, and test its logic outside the connector.
Policy template
A configurable, predefined transformation applied to connector requests or responses.
Set host URL
A policy template that changes the host a request is sent to.
ScriptBase
The base class that connector code derives from.
ExecuteAsync
The method connector code overrides to handle each request.
Context.SendAsync
The method connector code uses to send the request to the API.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. How many custom code scripts can a connector have?

    Show answer

    One, which can branch by operation ID.

  2. Which policy template lets one connector call sandbox and production hosts?

    Show answer

    Set host URL, driven by a connection parameter.

  3. Why must new properties added by code also appear in the response schema?

    Show answer

    The designers show makers only properties the schema describes.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz