2024 Power Apps Coding Standards For Canvas Apps
2024 Power Apps Coding Standards For Canvas Apps
Table Of Contents 2
Theming Variables Sample Code.................................................................................................................................... 21
Branding Templates ....................................................................................................................................................... 23
Error-Handling......................................................................................................................................................... 34
Enable Formula-Level Error Management ..................................................................................................................... 34
Patch Function Error-Handling ....................................................................................................................................... 35
Power Apps Forms Error-Handling................................................................................................................................. 36
Power Automate Flow Error-Handling ........................................................................................................................... 37
If Error Function ............................................................................................................................................................. 37
Handling Unexpected Errors .......................................................................................................................................... 38
Table Of Contents 3
Improving Code Readability ..................................................................................................................................... 47
Apply Automatic Formatting .......................................................................................................................................... 47
Use The WITH Function To Improve Readability ........................................................................................................... 47
Choose Consistent Logical Operators ............................................................................................................................ 48
Join Text Strings & Variables .......................................................................................................................................... 49
Remove IF Statements When The Result Is A True Or False Value................................................................................ 49
Substitute The Self Operator For The Current Control Name ....................................................................................... 50
Flatten Nested IFs .......................................................................................................................................................... 50
Alphabetical Order In Patch & UpdateContext Functions ............................................................................................. 51
Simplify Logical Comparisons When Evaluating A Boolean ........................................................................................... 52
Table Of Contents 4
Introduction
Welcome to the Power Apps Coding Standards For Canvas Apps.
In this guide you will find 50+ pages of coding rules, guidelines and best practices I use everyday to create Power Apps
Canvas apps. I have spent the last 3 years building Power Apps every day. Now I want to share the knowledge I've gained
in this set of easy-to-understand, actionable examples.
Power Apps already has an official set of canvas coding standards released back in 2018. So why did I make my own? A
few reasons:
• I wanted an updated set of standards and guidelines for 2024 that includes all of the latest features
• These coding standards can be continuously improved as new Power Apps features hit “general availability” in
2024, 2025, 2026 and beyond
• Readers can leave a comments on my website describing their own best practices which I can incorporate into
future versions
I hope you enjoy my Power Apps Coding Standards For Canvas Apps.
Introduction 5
Naming Conventions
Screen Names
A screen name should clearly describe its purpose in 2-3 words ending with word “Screen.” Use proper-case. A screen-
reader will speak the screen name to visually-impaired users when the screen loads.
Control Names
A control name should show the control-type, the purpose and the screen. Use camel-case and underscores for spacing.
For example, the control named txt_OrderForm_FirstName is a text input that captures first name on the app’s Order
Form Screen.
Naming Conventions 6
A list of standard control prefixes can be found below.
Variable Names
A variable name should show the scope of the variable and its purpose. Use camel-case with no spaces between each
word. For example, the variable gblUserEmail is a global variable which holds the current user’s email address.
Naming Conventions 7
Collection Names
A collection name should contain the original datasource and describe its purpose. Use camel-case with no spaces
between each word. For example, the collection colDvInvoices is a collection of invoices from Dataverse.
Dataverse Dv
SharePoint Sp
SQL Sql
Salesforce Sf
Naming Conventions 8
Variable Type Standards
Variable Scope
A variable’s scope determines where it can be referenced in the app. If the variable is required on multiple screens use a
global variable. Otherwise, use a local or context variable instead. Choose the proper variable type by determining its
scope.
One-time With Function Variable is only available within the with function
Imagine a large canvas app with many screens that only uses global variables. When updating a variable’s value the
developer must be aware of its impact across all screens. If the developer does not correctly determine how to use a
variable there are unintended consequences (i.e. a software bug).
Local variables can only be used on one screen. Developers have an easier time assessing the impact to a single screen
as opposed to many screens. Higher quality code can be written at a faster pace.
One-time variables are not persistently stored in memory. After the With function is executed the variable is cleared
from memory and cannot be accessed outside of the function.
// Global varable
Set(
gblSalesTaxAmount,
Value(txt_OrderForm_SubtotalAmount.Text) * 0.13
);
// Local variables
UpdateContext(
{
locLineItemsCount: 0,
locShowConfirmationMenu: false,
locOrderFormMode=Blank()
}
);
// One-time variable
With(
{varBusinessContact: LookUp('Sales Orders', ID=ThisItem.ID)},
Concatenate(
varBusinessContact.FirstName,
" ",
varBusinessContact.LastName
);
Whether or not to write comments is an ongoing debate in the software development community. Do write comments
into Power Apps code. Do not use comments as an excuse to write code with poor readability.
• Do write comments that describe the intent of a code section. Intent means the goal.
• Do not write comments that simply restate what a line of code does. Writing clean code means other
developers should be able to understand its function.
Commenting Code 11
Line Comments vs. Block Comments
Power Apps has two comment styles: line comments and block comments. Line comments are made on a single-line
and block comments can be made across multiple lines.
Line // [comment goes here] // Validate the work order to ensure it will not be rejected upon
submission.
Block /* /*
[comments go here] Work Order Details Screen:
*/ - Uses a single form to create, edit and view a record to minimize
the number of controls in the app
- Emails a signed PDF to the employee’s manager after the form is
submitted so it can be stored as backup
*/
Commenting Style
Use these commenting conventions to ensure a consistent style:
• Place comments on a separate line above the code section they are describing.
• Do not write in-line comments beside on the same line as a piece of code.
• Start comments with a capital letter
• End comment text with a period
Commenting Code 12
App Settings
General Tab
Choose an icon before sharing an app with users. Make it consistent with company branding. Custom images must be
245px x 245px and .jpg or .png format.
Turn on the Debug Published App setting to enable better telemetry in Power Apps Monitor while the app is in
development. Turn-off this setting when an app is pushed to production. It has a negative impact on will app
performance but it is necessary for debugging during development.
App Settings 13
Display Tab
PC & laptop users expect Power Apps to be responsive. Use responsive design unless the app is a proof-of-concept or
there is not enough time in the budget.
Choose portrait orientation for mobile devices since they are held vertically in one-hand. Tablet apps can be either
landscape or portrait depending on its use case. Will the user be walking around performing inspections while using the
app? Then use portrait mode. Will the user be seated at a table while using the app? Then use landscape mode. Can’t
decide which orientation to use? Design a responsive app that can change its orientation.
This table shows the recommended default display settings for each type. Start with these defaults and change them if
you have a good reason.
PC/Laptop Landscape No No No
All Landscape No No No
Preview-features will be turned on for all Power Apps soon. It is recommended to turn all preview options on unless a
feature is known to have a bug.
Experimental features might break, change or disappear at any-time. These features frequently have bugs or are
incomplete. Do not use experimental features in productions apps unless they have been throughly tested. Never use
Retired features.
Do not enable the preview features Keep Recently Visited Screens In Memory or Expanded Media Support or SaveData
on Power Apps Mobile Apps
App Settings 14
Support Tab
Power Apps authoring version determines which features and functionality are available in Power Apps Studio. While
working on an app it is recommended to not change the authoring version because it can potentially introduce bugs for
existing feature. If the authoring version is updated during development the app must be retested to ensure it operates
as expected.
App Settings 15
Reviewing Canvas Apps
App Checker
App checker identifies potential issues within a canvas app. A red dot will appear when there are formula errors or
runtime errors to notify the developer a fix is needed. The red dot will not appear for rules, accessibility and
performance errors.
Fix all issues identified in the app checker before publishing an app to production. This includes accessibility errors and
performance errors. Sometimes it is not possible to clear all errors due to an error with the app checker itself. Have a
strong justification for any errors that were not fixed.
The Power Apps Code Review Tool is an automated code review tool built by Microsoft. A canvas app loaded into the
review tool is analyzed against a checklist and is given a pass or fail score for each item. Failed items will tell the
developer what code must be fixed.
Aim for a score of 90% with the code review tool. It is not necessary to achieve 100% because there are occasionally
good reasons to avoid best practices. For example, the review tool may recommend using the concurrent function to
execute parallel data requests. This technique can be problematic if the app is using too much memory on a mobile
device and causes Power Apps to crash.
The Power Apps source code tool is useful for manual code reviews. It unpacks an msapp file an allows the developer to
review all code for a specific screen in a single file YAML file. This is useful because the developer does not have to click
into each individual property of a canvas control to read the code. They can simply scan the YAML from top to bottom.
Use Visual Studio Code to read the unpacked canvas app code. The C# syntax highlighter is preferred over the YAML
highlighter because Power Apps code is more similar to C#.
Functional testing of an app should be performed by someone other than the original developer. Ask another developer
on the team to Having a dedicated QA tester on the project team is recommended. Or, if no dedicated QA Tester is
available ask another developer to engage in peer-testing. Another person is more likely to uncover issues with an app's
behaviour.
All apps must undergo user acceptance testing before being launched into production. Select a small, representative
group of end users and ask them to test an app against a test script.
gblAppFonts Heading fonts, body fonts and sizes used in the app
Keep a copy of each styled control on a hidden screen. It is more efficient to re-use controls instead of setting up a new
control with a style every time.
// COLOR PALETTE
Set(
gblAppColors,
{
// Primary Colors
Primary1: ColorValue("#30475E"), // Navy Blue
Primary2: ColorValue("#F05454"), // Light Red
Primary3: ColorValue("#222831"), // Dark Blue
Primary4: ColorValue("#DDDDDD"), // Light Gray
// Accent Colors
Black: ColorValue("#000000"),
Cyan: ColorValue("#17A2B8"),
Green: ColorValue("#28A745"),
Orange: ColorValue("#FD7E14"),
Red: ColorValue("#DC3545"),
Teal: ColorValue("#20C997"),
White: ColorValue("#FFFFFF"),
Yellow: ColorValue("#FFC107"),
// Neutral Colors
GrayDark: ColorValue("#484644"),
GrayMediumDark: ColorValue("#8A8886"),
GrayMedium: ColorValue("#B3b0AD"),
GrayMediumLight: ColorValue("#D2D0CE"),
GrayLight: ColorValue("#F3F2F1")
}
);
// ICONS
Set(
gblAppIcons,
{
// SVG icon code is stored in an ‘Import from Excel’ table named AppIcons
Checklist: LookUp(AppIcons, Name="Checklist", DataURI),
Checkmark: LookUp(AppIcons, Name="Checkmark", DataURI)
}
)
Branding Template
Branding Templates
Another option is to use a pre-built-theming template. The Power Apps Branding Template by Sancho Harker is the best
solution available for these reasons:
• Quick to setup – choose 3 colors and the theme will automatically create a theme based on
• Fully-customizable – override any control property with a custom value if the default style is not desired
• Applies to new controls – any new control inserted into the app will use the theme colors and properties
• No premium license required – theming information is stored in the msapp itself whereas the Center Of
Excellence Theme Editor uses Dataverse
Perform data validation to ensure a form is properly filled-in before submission. Check the following items:
Give the user feedback when the form does not pass validation. There are 2 feedback strategies to choose from:
1. Validate On Submission – check if the form passed validation when the user presses the submit button
2. Real-Time Validation – check if a field passed validation as the user types. Once a field meets all data validation
criteria immediately indicate it passed.
• List the fields that failed validation and why at the top of the form
• Highlight any fields that failed validation in red
• Display an error message beside any fields that failed
Do not disable a form’s submit button until validation passes. If you use this pattern visually indicate why the submit
button is disabled on the screen at all times.
Error-handling for Power Apps form control and patch forms are performed differently. If using a Power Apps form
control, catch errors using the OnSuccess and OnFailure properties. For a patch form, wrap the Patch function in an
IfError function to detect an error.
Gallery data does not automatically refresh when connected to a cloud datasource (SharePoint List, Dataverse, etc.) but
no CRUD operations were performed before entering the screen. In this scenario update, the gallery before the screen
is loaded using the Refresh function.
Consider giving users the ability to manually refresh a cloud datasource by pressing a refresh button/icon.
Allow users to filter large datasets and get the results they want. Users should be able to filter on multiple fields at once.
Users should be able to filter on multiple fields at once. Use this coding pattern in the items property of a gallery to
support multiple dropdown filters. The code can also be adapted for other control types (combobox, datepicker, etc).
Giving a user the ability to select the sort column and order is recommended but not required.
Open Power Apps advanced settings and turn on formula-level error management. It enables the IfError function, the
IsError function and the app’s OnError property to be used.
Error-Handling 34
Patch Function Error-Handling
Check for errors anytime data is written to a datasource with the Patch function or Collect function. Even if the
submitted record(s) are validated, good connectivity and the correct user permissions cannot be assumed. This is not
necessary for local collections stored in memory.
Error-Handling 35
Power Apps Forms Error-Handling
Write any code should be executed after a Power Apps form is submitted in its OnSuccess and OnFailure properties. If
form submission is successful, use the OnSuccess property to control what happens next. Otherwise, use the OnFailure
property to display an error message that tells the user what went wrong.
Do not write any code after the SubmitForm function used to submit the form. If form submission fails Power Apps will
still move onto the next line of code. This can result in loss of data.
Error-Handling 36
Power Automate Flow Error-Handling
When a Power Automate flow triggered from Power Apps its response must be checked for errors. Flows can fail due to
poor connectivity. They can also return a failure response or a result with the incorrect schema. If Power Apps does not
know the flow failed it will continue as normal.
If Error Function
Use the IfError function to handle calculations that require a different value when an error occurs. In this example, if
gblTasksTotal equals 0 the IfError function will return 0 instead of throwing a “divide by zero” error.
Error-Handling 37
Handling Unexpected Errors
An app’s OnError property is triggered when an unexpected error occurs. An unexpected error is any error that is not
handled using the IfError or IsError function.
Use this code to quickly locate the source of unexpected errors and fix them. Do not leave this on in a production app
since the error message is helpful for a developer but is confusing to a user.
If you want to log the unexpected errors in a production app use the Trace function and Azure Application Insights to
silently log the errors.
Error-Handling 38
Optimizing App Performance
Load Multiple Datasets Concurrently
Making connector calls sequentially is slow because the current connector call must be completed before the next one
starts. The Concurrent function allows Power Apps to load data faster by simultaneously processing multiple connector
calls at once. Only use the Concurrent function to retrieve data stored in cloud. There is no advantage to using
concurrent when working with data already on the device (i.e. variables and collections).
Refer to the official Power Apps documentation to determine which Power Fx functions can be delegated. The
supported functions are different for SharePoint, Dataverse & SQL. A warning will appear in the app checker when a
function cannot be delegated.
Dataverse views are not subject to delegation rules. Use Dataverse views to write filter criteria that cannot be delegated
using Power Apps formulas.
Filter(
'Device Orders',
'Device Orders (Views)'.'Active Device Orders'
)
// Store the currency exchange rates table in memory for quicker access
ClearCollect(
colCurrencyExchangeRates,
'Currency Exchange Rates',
)
Use the ShowColumns function to select only specific columns and drop the rest from the collection. Enable explict
column selection to fetch only table columns used in the app when connecting to Dataverse.
Time to first screen metrics can be found in the app’s Analytics page. Go to the maker portal, click on the three dots
beside the app, select Analytics (preview), then choose Performance.
Use a gallery to display repetitive controls. Each control in a gallery only counts as 1 control no matter how many times
it is shown.
Each Contact has a related Account (i.e. an organization). To display the Account Name we insert a label into the gallery
with this code in the text property. As a result one additional connector call must be made for each row in the gallery.
If there are 100 rows in the gallery, there will be 101 total connector calls total (1 gallery +100 rows).
The solution to the N+1 problem for Dataverse is quite simple. Dataverse automatically fetches the required data in
related tables during the connector call for Contacts.
SharePoint lists are not a relational database and cannot return all related data in one connector call. We cannot
eliminate N+1 but we can reduce the number of connector calls to SharePoint. Collect all data in the Accounts and
Contacts prior to opening the gallery screen. Then add a new column called “Account Name” to the Contacts table by
joining it with the Accounts table. Display the resulting collection in the items property of the gallery.
Value(txt_InterestRate.Text)/100 * Value(txt_LoanAmount.Text) /
(1 - (1 + Value(txt_InterestRate.Text)/100)^-Value(txt_NumberOfPayments.Text))
The mortgage calculation formula cannot be interpreted at-a-glance. It takes effort to parse. Compare it to the formula
below using the With function. The formula is now human-readable because any complexity moved into one-time
variables.
ClearCollect(
colCustomers,
{State: "NY", Status: "Active"}
);
// And operator
Filter(
colCustomers,
State = "NY"
And Status="Active"
);
// And() function
Filter(
colCustomers,
And(
State = "NY",
Status="Active"
)
);
// && operator
Filter(
colCustomers,
State = "NY"
&& Status="Active"
)
// set variables
Set(gblUserName, User().FullName);
Set(gblStreetAddress, "123 Chestnut Street");
Set(gblBankAccountBalance, 5000);
Set(gblDailyWithdrawlLimit, 1000);
Set(gblWithdrawlAmount, 100);
// Nested IFs
If(
gblWithdrawlAmount > gblBankAccountBalance,
Notify("Insufficent funds", NotificationType.Error),
If(
gblWithdrawlAmount > gblDailyWithdrawlLimit,
Notify("Daily withdrawl limit exceeded", NotificationType.Error),
Notify("You have Withdrawn $"&gblWithdrawlAmount, NotificationType.Success)
)
);
// Flattened IFs
If(
gblWithdrawlAmount > gblBankAccountBalance,
Notify("Insufficent funds", NotificationType.Error),
gblWithdrawlAmount > gblDailyWithdrawlLimit,
Notify("Daily withdrawl limit exceeded", NotificationType.Error),
Notify("You have withdrawn $"&gblWithdrawlAmount, NotificationType.Success)
);
Set(gblIsBankAccountActive, true);
// logical comparison
If(
gblIsBankAccountActive=true,
Navigate('Withdraw Funds Screen'),
Notify("Bank account is not active", NotificationType.Error)
);