Skip to content

Instantly share code, notes, and snippets.

@samaguire
Last active March 18, 2022 09:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samaguire/e8f60ea57e967070a5325559ae245f9d to your computer and use it in GitHub Desktop.
Save samaguire/e8f60ea57e967070a5325559ae245f9d to your computer and use it in GitHub Desktop.
C# script for use in Tabular Editor 3/2.13+ to format all DAX expressions in a Tabular model (including Power BI Desktop).
/*
Formatting of calculated tables and calculated columns is unsupported in Power BI Desktop as at 25 Aug 2021
and will be ignored if unsupported features are not enabled in Tabular Editor
*/
// Begin Options
var useShortFormat = true;
var insertSpaceAfterFunctionName = false;
var insertLineBreakOnFirstLine = true;
// End Options
foreach (var m in Model.AllMeasures) { FormatDax(m); }
foreach (var i in Model.AllCalculationItems) { FormatDax(i); }
foreach (var t in Model.Tables.OfType<CalculatedTable>().Where(x => !x.Name.Contains("DateTableTemplate_") && !x.Name.Contains("LocalDateTable_"))) { FormatDax(t); }
foreach (var c in Model.AllColumns.OfType<CalculatedColumn>().Where(x => !x.DaxTableName.Contains("DateTableTemplate_") && !x.DaxTableName.Contains("LocalDateTable_"))) { FormatDax(c); }
CallDaxFormatter(shortFormat: useShortFormat, skipSpaceAfterFunctionName: !insertSpaceAfterFunctionName);
if (insertLineBreakOnFirstLine)
{
foreach (var m in Model.AllMeasures) { m.Expression = "\r\n" + m.Expression; }
foreach (var i in Model.AllCalculationItems) { i.Expression = "\r\n" + i.Expression; }
foreach (var t in Model.Tables.OfType<CalculatedTable>().Where(x => !x.Name.Contains("DateTableTemplate_") && !x.Name.Contains("LocalDateTable_"))) { t.Expression = "\r\n" + t.Expression; }
foreach (var c in Model.AllColumns.OfType<CalculatedColumn>().Where(x => !x.DaxTableName.Contains("DateTableTemplate_") && !x.DaxTableName.Contains("LocalDateTable_"))) { c.Expression = "\r\n" + c.Expression; }
}
Info("Script finished.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment