MSBA-279 · Lesson 9 of 12 · 23 min
Code-reading questions
▶ Video coming soon A video version of this lesson is on the way.
Signe's error log after two practice sets showed something odd. She knew plug-ins better than anyone at Lumenvale, yet four of her misses were on plug-in code questions. Rupert asked her to talk through one aloud. She glanced at the listing, recognized the pattern, picked the answer she would have written herself and moved on. The listing had a detail her own code never had: the step was registered on Create, and the code read a pre-image. "You answered the code in your head," Rupert said, "not the code on the screen."
Early reports from AB-400 candidates describe many questions built around code: a listing with gaps to fill from drop-down lists, or lines to choose and arrange in order. This lesson gives a method for reading such questions and works through original examples in each language the exam uses: C# for plug-ins and connector code, JavaScript for client scripts, TypeScript for components and code apps, HTTP for the Web API, and expressions for Power Fx and flows. None of the code needs to be run; the skill is reading it.
A method for code questions
The method has five steps. Read the goal: what must the code achieve? Identify the context: for a plug-in, the message, table and stage; for a script, the event; for a component, the lifecycle method; for an HTTP request, the method and address. Read the whole listing, including lines after the gap, because later lines often show which variable names or types the gap must produce. Eliminate options that could not compile, use a member that does not exist on that object, or break a platform rule such as calling the Web API from a plug-in. Choose the option that achieves the goal without extra assumptions.
Step two is the one Signe skipped. A plug-in listing without its registration is ambiguous; the stem will always say how the step is registered, and that detail decides between options that are otherwise all valid C#.
Plug-in code
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var target = (Entity)context.InputParameters["Target"];
// Registered on Update of lcc_equipmentloan, PreOperation, synchronous,
// filtering attributes: lcc_returnedon. Pre-image alias "pre" with lcc_duedate.
var returnedOn = target.GetAttributeValue<DateTime?>("lcc_returnedon");
var dueDate = /* GAP 1 */;
if (returnedOn.HasValue && dueDate.HasValue && returnedOn.Value > dueDate.Value)
{
/* GAP 2 */ = true;
}
}Worked problem
Practice listing 1: reading a plug-in
GAP 1 options: (a) target.GetAttributeValue<DateTime?>("lcc_duedate"); (b) context.PreEntityImages["pre"].GetAttributeValue<DateTime?>("lcc_duedate"); (c) context.PostEntityImages["post"].GetAttributeValue<DateTime?>("lcc_duedate"). GAP 2 options: (d) target["lcc_islate"]; (e) a call to service.Update with a new Entity; (f) context.OutputParameters["lcc_islate"].
Show solution
- Context: Update, PreOperation, filtering on lcc_returnedon only.
- The Target on Update holds only changed columns. The due date did not change, so (a) usually returns null.
- PreOperation has no post-image, so (c) fails. The pre-image registered with lcc_duedate gives the value: (b).
- In PreOperation, setting a column on the Target saves it with the operation; no extra update is needed, and an update call would cause another pipeline run.
Answer: GAP 1 is (b), the pre-image. GAP 2 is (d), setting the column on the Target. Option (e) works but is wasteful and risks recursion; (f) is for custom API responses.
Client script code
var Lumenvale = Lumenvale || {};
Lumenvale.Loan = {
onLoad: function (executionContext) {
var formContext = executionContext.getFormContext();
formContext.getAttribute("lcc_duedate").addOnChange(Lumenvale.Loan.checkDue);
Lumenvale.Loan.checkDue(executionContext);
},
checkDue: function (executionContext) {
var formContext = executionContext.getFormContext();
var due = formContext.getAttribute("lcc_duedate").getValue();
var control = formContext.getControl("lcc_duedate");
if (due && due < new Date()) {
/* GAP */
} else {
control.clearNotification("pastdue");
}
}
};Worked problem
Practice listing 2: reading a client script
Which line fills the gap so a message appears on the due date field and can later be cleared by the else branch? Options: (a) formContext.ui.setFormNotification("Due date is in the past", "WARNING", "pastdue"); (b) control.setNotification("Due date is in the past", "pastdue"); (c) Xrm.Navigation.openAlertDialog({ text: "Due date is in the past" }); (d) Xrm.Page.getControl("lcc_duedate").setNotification("Due date is in the past").
Show solution
- Goal: a message on the field, clearable by clearNotification with the ID "pastdue".
- clearNotification on the control clears a control notification with that ID, so the matching call is setNotification on the same control with the same ID.
- (a) is a form-level notification, cleared by clearFormNotification instead.
- (c) is a dialog, not a field message. (d) uses deprecated Xrm.Page and no ID.
Answer: (b). Note also that the handler is added with addOnChange in OnLoad; if the same function were also registered on the field's OnChange in the designer, it would run twice.
Component and code app code
export class RoomCapacity implements ComponentFramework.StandardControl<IInputs, IOutputs> {
private notify: () => void;
private booked = 0;
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void,
state: ComponentFramework.Dictionary, container: HTMLDivElement): void {
this.notify = notifyOutputChanged;
// build elements in container
}
public updateView(context: ComponentFramework.Context<IInputs>): void {
this.booked = context.parameters.booked.raw ?? 0;
// render this.booked
}
private onUserChange(value: number): void {
this.booked = value;
/* GAP */
}
public getOutputs(): IOutputs {
return { booked: this.booked };
}
public destroy(): void { }
}The gap is this.notify(). Without it, the platform never calls getOutputs, so the form never receives the new value; the component shows the change only on its own surface. Other plausible options, such as calling updateView directly or setting context.parameters.booked.raw, are distractors: updateView is called by the platform, and parameters are inputs from the host, not a way to write back.
const result = await Lcc_equipmentitemsService.getAll({
select: ["lcc_name", "lcc_tagnumber", "lcc_status"],
filter: "lcc_status eq 1",
orderBy: ["lcc_name asc"],
maxPageSize: 50,
});
const items = result.data ?? [];A question on listing 4 might ask what limits the columns returned (the select list), how many rows the first page holds at most (50), or why the call fails for a user who can open the app (the user lacks read privilege on the table, because generated services call Dataverse as the signed-in user). The generated service name follows the table name, which is why the exam describes it rather than testing exact spelling.
Web API requests
PATCH [Organization URI]/api/data/v9.2/contacts(lcc_studentnumber='S1004417')
Content-Type: application/json
If-Match: *
{
"firstname": "Amara",
"lastname": "Quill"
}Read the headers. PATCH to a key address normally performs an upsert. An If-Match header with an asterisk as its value means "only if a row exists", turning it into update-only, so if no contact has that student number the request fails with a not-found error instead of creating one. An If-None-Match header with an asterisk would mean create-only. Without either header, the request creates or updates. Questions on this listing ask which header prevents accidental creation or which response to expect when the row is missing.
GET [Organization URI]/api/data/v9.2/lcc_workorders?$select=lcc_name,lcc_status&$filter=lcc_priority eq 1&$top=20
Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"The Prefer header asks for formatted values, so choice columns return their labels as annotations next to the numeric values. That is the answer to a question asking how to show "In progress" rather than 2 without a second request for metadata.
Expressions and Power Fx
if(
equals(triggerOutputs()?['body/lcc_priority'], 1),
addHours(utcNow(), 4),
addDays(utcNow(), 3)
)The expression reads the priority from the trigger's body. If it is 1, the deadline is four hours from now; otherwise three days. The question's trap is usually the reference: triggerOutputs()?['body/...'] reads the trigger, while outputs('Get_row')?['body/...'] would read a later action. Signe's two flow misses in her cold attempt were exactly this: an option that referred to the wrong action's output.
Self.Selected.Item.'Status Reason' = 'Status Reason (Work Orders)'.Completed &&
IsBlank(Self.Selected.Item.'Completion Photo')In modern commanding, a visibility formula refers to the selected record through Self.Selected.Item. The button appears only for completed work orders that lack a photo. A distractor might use a client script that hides the button on load, which would not respond to selection changes in a grid.
Connector code
public class Script : ScriptBase
{
public override async Task<HttpResponseMessage> ExecuteAsync()
{
var response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken)
.ConfigureAwait(false);
if (this.Context.OperationId == "GetTrackingEvents" && response.IsSuccessStatusCode)
{
var body = JObject.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
foreach (var ev in body["events"])
{
ev["occurredAtUtc"] = DateTime.Parse(ev["occurredAt"].ToString()).ToUniversalTime().ToString("o");
}
response.Content = CreateJsonContent(body.ToString());
}
return response;
}
}Questions on connector code test three facts. The class derives from ScriptBase and overrides ExecuteAsync. Requests are sent with this.Context.SendAsync, not with a new HttpClient. And the code branches on OperationId, because one script serves every operation in the connector. An option that creates an HttpClient, or that runs the transformation for every operation, is the distractor.
Ordering questions
Build list questions often ask for steps rather than lines. The method is the same: identify the context, then use dependencies to fix the order. Something must exist before it can be referenced; a key must be active before it is used; a component must be built before it is pushed.
| Task | Correct order |
|---|---|
| Release a PCF component | pac pcf init; write the code; npm run build; test in the harness; add to a solution project; build the solution; import |
| Register a plug-in step with an image | Build and sign the assembly or package; register it; register the step (message, table, stage, mode, filtering); register the image with an alias and columns |
| Publish events to a queue | Create the Service Bus queue and access policy; register the service endpoint; register a step on the endpoint; read from the queue in the consumer |
| Sync by alternate key | Define the key; wait for the index to become active; send upserts addressed by the key |
More listings to practice
The listings below cover patterns that appear less often but are easy marks once seen. Read each with the same five steps before reading the explanation.
var rows = new List<Entity>();
foreach (var reading in batch)
{
var e = new Entity("lcc_alarmevent");
e["lcc_name"] = reading.Code;
e["partitionid"] = reading.BuildingCode;
e["ttlinseconds"] = 30 * 24 * 60 * 60;
rows.Add(e);
}
var request = new CreateMultipleRequest
{
Targets = new EntityCollection(rows) { EntityName = "lcc_alarmevent" }
};
service.Execute(request);Three details make this listing a good question. CreateMultiple takes an EntityCollection whose EntityName must be set, because every row must be of the same table; an option that mixes tables in one collection is wrong. The partitionid column groups related rows in an elastic table, here by building, which makes later queries for one building efficient. The ttlinseconds column sets each row's time-to-live, here 30 days, after which the platform deletes it. A question might ask what happens to a row after 30 days (it is removed automatically), or why the request fails when one row is a different table (the collection must be one table).
Xrm.WebApi.retrieveMultipleRecords(
"lcc_workorder",
"?$select=lcc_name,lcc_duedate&$filter=_lcc_location_value eq " + roomId + " and statecode eq 0&$orderby=lcc_duedate asc",
10
).then(function (result) {
result.entities.forEach(function (row) {
console.log(row.lcc_name, row.lcc_duedate);
});
if (result.nextLink) {
// more rows are available
}
});The third argument, 10, is the maximum page size, so the first call returns at most ten rows and a nextLink when more exist. The filter refers to the lookup with its value property, _lcc_location_value, which is how a lookup's GUID is filtered in the Web API. Options that filter on lcc_location directly, or that expect all rows in one call, are distractors. A good follow-up question asks how to fetch the next page: call retrieveMultipleRecords again with the nextLink.
if (context.Depth > 1)
{
trace.Trace("Called from another operation at depth {0}; skipping.", context.Depth);
return;
}Depth guards are a common answer and a common trap. They stop a plug-in that updates its own table from calling itself endlessly, but they also stop it from running when another plug-in or a flow legitimately triggers the update, because those calls arrive at a higher depth too. Filtering attributes and avoiding self-updates are the better first defense; the Depth check is a backstop. A question that says "the plug-in no longer runs when the record is updated by an integration" may be pointing at exactly this guard.
Telltale lines by language
Under time pressure, a few lines in each language tell you what a listing is about before you read it in detail. Spotting them quickly is a pacing skill.
| Language or format | Telltale lines | Usually tests |
|---|---|---|
| C# plug-in | IPluginExecutionContext, PreEntityImages, InvalidPluginExecutionException | Stage, images, Target contents, errors |
| C# external code | ServiceClient, CreateMultipleRequest, UpsertRequest | Bulk operations, alternate keys, throttling |
| C# connector code | ScriptBase, ExecuteAsync, Context.SendAsync, OperationId | Connector custom code rules |
| JavaScript client script | getFormContext, addOnChange, setNotification, Xrm.WebApi | Events, notifications, data calls |
| TypeScript component | StandardControl, notifyOutputChanged, getOutputs | Lifecycle and outputs |
| TypeScript code app | Generated service names, getAll with select and filter | Data sources and query options |
| HTTP | PATCH with a key address, If-Match, Prefer headers | Upsert behavior and annotations |
| Expressions | triggerOutputs, outputs, items, coalesce | Which output is referenced |
Signe added one habit to her method after the November 13 set. Before reading any options on a code item, she said aloud, quietly, the context in five words or fewer: "Update, PreOperation, pre-image exists" or "OnChange, field notification, clear by ID". On the November 20 rehearsal, the habit cost her perhaps ten seconds per code item and caught one of the two slips she would otherwise have made.
Pacing code items
Code items take longer than standalone scenario items, and the time is worth spending, because a build list or code completion item is usually scored as a whole: one line out of place and the item earns nothing. Signe budgeted about two and a half minutes for a code item against about a minute and a half for a short scenario, and recovered the difference on the simpler recall items. If a listing is long, she read the comments and the registration first, then the lines around each gap, then the rest, rather than starting at line one and reading every line with equal care.
When two completions both look valid, the deciding detail is almost always in the context rather than the syntax: the stage, the event, the host or the header. Go back to step two of the method and ask what the context rules out. If nothing does, choose the option that relies on fewer assumptions, such as reading from a registered image rather than retrieving the row again, or using a platform method rather than hand-written HTTP.
Common mistakes
MistakeAnswering from the code you would write instead of the code on the screen.
InsteadIdentify the registration, event or host first, then read the whole listing.
MistakeReading an unchanged column from the Target in an Update plug-in.
InsteadRead it from a pre-image; the Target holds only changed columns.
MistakeMixing field and form notification methods.
InsteadsetNotification pairs with clearNotification on a control; setFormNotification pairs with clearFormNotification.
MistakeCreating an HttpClient in connector custom code.
InsteadUse this.Context.SendAsync.
Summary and key terms
- Code questions reward reading the listing on the screen, with its registration or event, not recalling your own code.
- Use five steps: goal, context, whole listing, eliminate rule-breakers, choose the option with fewest assumptions.
- Plug-ins: Target has changed columns only; pre-images for the rest; set Target columns in PreOperation.
- Client scripts use formContext and paired notification methods; components must call notifyOutputChanged.
- Web API headers change behavior; flow expressions depend on which output they reference; connector code uses Context.SendAsync and OperationId.
- Build list
- A question format in which you select items and arrange them in order.
- Filtering attributes
- The columns whose change makes an Update plug-in step fire.
- If-Match
- An HTTP header that makes a request apply only when the resource exists or matches an ETag.
- Formatted value
- The display label returned for a choice, lookup or date, requested with a Prefer header.
- ScriptBase
- The base class for custom connector code.
- OperationId
- The identifier of a connector operation, used to branch custom code.
Practice problems
Work each problem on paper first, then reveal the answer to check.
In a PreOperation Update step, how do you save an extra column with the operation?
Show answer
Set it on the Target entity.
Which header makes a PATCH by key update-only?
Show answer
If-Match, with an asterisk as its value.
How does custom connector code send the request to the back end?
Show answer
this.Context.SendAsync.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.