-
Notifications
You must be signed in to change notification settings - Fork 0
/
TE_Scripts.cs
1503 lines (1174 loc) · 64.8 KB
/
TE_Scripts.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TabularEditor.TOMWrapper;
using TabularEditor.Scripting;
using Microsoft.VisualBasic;
using GeneralFunctions;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using BenchmarkDotNet.Disassemblers;
namespace TE_Scripting
{
public class TE_Scripts
{
void timeIntelligenceCalcGroupCreation()
{
//#r "Microsoft.VisualBasic"
//using Microsoft.VisualBasic;
//
// CHANGELOG:
// '2021-05-01 / B.Agullo /
// '2021-05-17 / B.Agullo / added affected measure table
// '2021-06-19 / B.Agullo / data label measures
// '2021-07-10 / B.Agullo / added flag expression to avoid breaking already special format strings
// '2021-09-23 / B.Agullo / added code to prompt for parameters (code credit to Daniel Otykier)
// '2021-09-27 / B.Agullo / added code for general name
// '2022-10-11 / B.Agullo / added MMT and MWT calc item groups
// '2023-01-24 / B.Agullo / added Date Range Measure and completed dynamic label for existing items
//
// by Bernat Agulló
// twitter: @AgulloBernat
// www.esbrina-ba.com/blog
//
// REFERENCE:
// Check out https://www.esbrina-ba.com/time-intelligence-the-smart-way/ where this script is introduced
//
// FEATURED:
// this script featured in GuyInACube https://youtu.be/_j0iTUo2HT0
//
// THANKS:
// shout out to Johnny Winter for the base script and SQLBI for daxpatterns.com
//select the measures that you want to be affected by the calculation group
//before running the script.
//measure names can also be included in the following array (no need to select them)
string[] preSelectedMeasures = { }; //include measure names in double quotes, like: {"Profit","Total Cost"};
//AT LEAST ONE MEASURE HAS TO BE AFFECTED!,
//either by selecting it or typing its name in the preSelectedMeasures Variable
//
// ----- do not modify script below this line -----
//
string affectedMeasures = "{";
int i = 0;
for (i = 0; i < preSelectedMeasures.GetLength(0); i++)
{
if (affectedMeasures == "{")
{
affectedMeasures = affectedMeasures + "\"" + preSelectedMeasures[i] + "\"";
}
else
{
affectedMeasures = affectedMeasures + ",\"" + preSelectedMeasures[i] + "\"";
};
};
if (Selected.Measures.Count != 0)
{
foreach (var m in Selected.Measures)
{
if (affectedMeasures == "{")
{
affectedMeasures = affectedMeasures + "\"" + m.Name + "\"";
}
else
{
affectedMeasures = affectedMeasures + ",\"" + m.Name + "\"";
};
};
};
//check that by either method at least one measure is affected
if (affectedMeasures == "{")
{
Error("No measures affected by calc group");
return;
};
string calcGroupName = String.Empty;
string columnName = String.Empty;
if (Model.CalculationGroups.Any(cg => cg.GetAnnotation("@AgulloBernat") == "Time Intel Calc Group"))
{
calcGroupName = Model.CalculationGroups.Where(cg => cg.GetAnnotation("@AgulloBernat") == "Time Intel Calc Group").First().Name;
}
else
{
calcGroupName = Interaction.InputBox("Provide a name for your Calc Group", "Calc Group Name", "Time Intelligence", 740, 400);
};
if (calcGroupName == String.Empty) return;
if (Model.CalculationGroups.Any(cg => cg.GetAnnotation("@AgulloBernat") == "Time Intel Calc Group"))
{
columnName = Model.Tables.Where(cg => cg.GetAnnotation("@AgulloBernat") == "Time Intel Calc Group").First().Columns.First().Name;
}
else
{
columnName = Interaction.InputBox("Provide a name for your Calc Group Column", "Calc Group Column Name", calcGroupName, 740, 400);
};
if (columnName == String.Empty) return;
string affectedMeasuresTableName = String.Empty;
if (Model.Tables.Any(t => t.GetAnnotation("@AgulloBernat") == "Time Intel Affected Measures Table"))
{
affectedMeasuresTableName = Model.Tables.Where(t => t.GetAnnotation("@AgulloBernat") == "Time Intel Affected Measures Table").First().Name;
}
else
{
affectedMeasuresTableName = Interaction.InputBox("Provide a name for affected measures table", "Affected Measures Table Name", calcGroupName + " Affected Measures", 740, 400);
};
if (affectedMeasuresTableName ==String.Empty) return;
string affectedMeasuresColumnName = String.Empty;
if (Model.Tables.Any(t => t.GetAnnotation("@AgulloBernat") == "Time Intel Affected Measures Table"))
{
affectedMeasuresColumnName = Model.Tables.Where(t => t.GetAnnotation("@AgulloBernat") == "Time Intel Affected Measures Table").First().Columns.First().Name;
}
else
{
affectedMeasuresColumnName = Interaction.InputBox("Provide a name for affected measures column", "Affected Measures Table Column Name", "Measure", 740, 400);
};
if (affectedMeasuresColumnName == String.Empty) return;
//string affectedMeasuresColumnName = "Measure";
string labelAsValueMeasureName = "Label as Value Measure";
string labelAsFormatStringMeasureName = "Label as format string";
// '2021-09-24 / B.Agullo / model object selection prompts!
var factTable = SelectTable(label: "Select your fact table");
if (factTable == null) return;
var factTableDateColumn = SelectColumn(factTable.Columns, label: "Select the main date column");
if (factTableDateColumn == null) return;
Table dateTableCandidate = null;
if (Model.Tables.Any
(x => x.GetAnnotation("@AgulloBernat") == "Time Intel Date Table"
|| x.Name == "Date"
|| x.Name == "Calendar"))
{
dateTableCandidate = Model.Tables.Where
(x => x.GetAnnotation("@AgulloBernat") == "Time Intel Date Table"
|| x.Name == "Date"
|| x.Name == "Calendar").First();
};
var dateTable =
SelectTable(
label: "Select your date table",
preselect: dateTableCandidate);
if (dateTable == null)
{
Error("You just aborted the script");
return;
}
else
{
dateTable.SetAnnotation("@AgulloBernat", "Time Intel Date Table");
};
Column dateTableDateColumnCandidate = null;
if (dateTable.Columns.Any
(x => x.GetAnnotation("@AgulloBernat") == "Time Intel Date Table Date Column" || x.Name == "Date"))
{
dateTableDateColumnCandidate = dateTable.Columns.Where
(x => x.GetAnnotation("@AgulloBernat") == "Time Intel Date Table Date Column" || x.Name == "Date").First();
};
var dateTableDateColumn =
SelectColumn(
dateTable.Columns,
label: "Select the date column",
preselect: dateTableDateColumnCandidate);
if (dateTableDateColumn == null)
{
Error("You just aborted the script");
return;
}
else
{
dateTableDateColumn.SetAnnotation("@AgulloBernat", "Time Intel Date Table Date Column");
};
Column dateTableYearColumnCandidate = null;
if (dateTable.Columns.Any(x => x.GetAnnotation("@AgulloBernat") == "Time Intel Date Table Year Column" || x.Name == "Year"))
{
dateTable.Columns.Where
(x => x.GetAnnotation("@AgulloBernat") == "Time Intel Date Table Year Column" || x.Name == "Year").First();
};
var dateTableYearColumn =
SelectColumn(
dateTable.Columns,
label: "Select the year column",
preselect: dateTableYearColumnCandidate);
if (dateTableYearColumn == null)
{
Error("You just abourted the script");
return;
}
else
{
dateTableYearColumn.SetAnnotation("@AgulloBernat", "Time Intel Date Table Year Column");
};
//these names are for internal use only, so no need to be super-fancy, better stick to datpatterns.com model
string ShowValueForDatesMeasureName = "ShowValueForDates";
string dateWithSalesColumnName = "DateWith" + factTable.Name;
// '2021-09-24 / B.Agullo / I put the names back to variables so I don't have to tough the script
string factTableName = factTable.Name;
string factTableDateColumnName = factTableDateColumn.Name;
string dateTableName = dateTable.Name;
string dateTableDateColumnName = dateTableDateColumn.Name;
string dateTableYearColumnName = dateTableYearColumn.Name;
// '2021-09-24 / B.Agullo / this is for internal use only so better leave it as is
string flagExpression = "UNICHAR( 8204 )";
string calcItemProtection = "<CODE>"; //default value if user has selected no measures
string calcItemFormatProtection = "<CODE>"; //default value if user has selected no measures
// check if there's already an affected measure table
if (Model.Tables.Any(t => t.GetAnnotation("@AgulloBernat") == "Time Intel Affected Measures Table"))
{
//modifying an existing calculated table is not risk-free
Info("Make sure to include measure names to the table " + affectedMeasuresTableName);
}
else
{
// create calculated table containing all names of affected measures
// this is why you need to enable
if (affectedMeasures != "{")
{
affectedMeasures = affectedMeasures + "}";
string affectedMeasureTableExpression =
"SELECTCOLUMNS(" + affectedMeasures + ",\"" + affectedMeasuresColumnName + "\",[Value])";
var affectedMeasureTable =
Model.AddCalculatedTable(affectedMeasuresTableName, affectedMeasureTableExpression);
affectedMeasureTable.FormatDax();
affectedMeasureTable.Description =
"Measures affected by " + calcGroupName + " calculation group.";
affectedMeasureTable.SetAnnotation("@AgulloBernat", "Time Intel Affected Measures Table");
// this causes error
// affectedMeasureTable.Columns[affectedMeasuresColumnName].SetAnnotation("@AgulloBernat","Time Intel Affected Measures Table Column");
affectedMeasureTable.IsHidden = true;
};
};
//if there where selected or preselected measures, prepare protection code for expresion and formatstring
string affectedMeasuresValues = "VALUES('" + affectedMeasuresTableName + "'[" + affectedMeasuresColumnName + "])";
calcItemProtection =
"SWITCH(" +
" TRUE()," +
" SELECTEDMEASURENAME() IN " + affectedMeasuresValues + "," +
" <CODE> ," +
" ISSELECTEDMEASURE([" + labelAsValueMeasureName + "])," +
" <LABELCODE> ," +
" SELECTEDMEASURE() " +
")";
calcItemFormatProtection =
"SWITCH(" +
" TRUE() ," +
" SELECTEDMEASURENAME() IN " + affectedMeasuresValues + "," +
" <CODE> ," +
" ISSELECTEDMEASURE([" + labelAsFormatStringMeasureName + "])," +
" <LABELCODEFORMATSTRING> ," +
" SELECTEDMEASUREFORMATSTRING() " +
")";
string dateColumnWithTable = "'" + dateTableName + "'[" + dateTableDateColumnName + "]";
string yearColumnWithTable = "'" + dateTableName + "'[" + dateTableYearColumnName + "]";
string factDateColumnWithTable = "'" + factTableName + "'[" + factTableDateColumnName + "]";
string dateWithSalesWithTable = "'" + dateTableName + "'[" + dateWithSalesColumnName + "]";
string calcGroupColumnWithTable = "'" + calcGroupName + "'[" + columnName + "]";
//check to see if a table with this name already exists
//if it doesnt exist, create a calculation group with this name
if (!Model.Tables.Contains(calcGroupName))
{
var cg = Model.AddCalculationGroup(calcGroupName);
cg.Description = "Calculation group for time intelligence. Availability of data is taken from " + factTableName + ".";
cg.SetAnnotation("@AgulloBernat", "Time Intel Calc Group");
};
//set variable for the calc group
Table calcGroup = Model.Tables[calcGroupName];
//if table already exists, make sure it is a Calculation Group type
if (calcGroup.SourceType.ToString() != "CalculationGroup")
{
Error("Table exists in Model but is not a Calculation Group. Rename the existing table or choose an alternative name for your Calculation Group.");
return;
};
//adds the two measures that will be used for label as value, label as format string
var labelAsValueMeasure = calcGroup.AddMeasure(labelAsValueMeasureName, "");
labelAsValueMeasure.Description = "Use this measure to show the year evaluated in tables";
var labelAsFormatStringMeasure = calcGroup.AddMeasure(labelAsFormatStringMeasureName, "0");
labelAsFormatStringMeasure.Description = "Use this measure to show the year evaluated in charts";
//by default the calc group has a column called Name. If this column is still called Name change this in line with specfied variable
if (calcGroup.Columns.Contains("Name"))
{
calcGroup.Columns["Name"].Name = columnName;
};
calcGroup.Columns[columnName].Description = "Select value(s) from this column to apply time intelligence calculations.";
calcGroup.Columns[columnName].SetAnnotation("@AgulloBernat", "Time Intel Calc Group Column");
//Only create them if not in place yet (reruns)
if (!Model.Tables[dateTableName].Columns.Any(C => C.GetAnnotation("@AgulloBernat") == "Date with Data Column"))
{
string DateWithSalesCalculatedColumnExpression =
dateColumnWithTable + " <= MAX ( " + factDateColumnWithTable + ")";
Column dateWithDataColumn = dateTable.AddCalculatedColumn(dateWithSalesColumnName, DateWithSalesCalculatedColumnExpression);
dateWithDataColumn.SetAnnotation("@AgulloBernat", "Date with Data Column");
};
if (!Model.Tables[dateTableName].Measures.Any(M => M.Name == ShowValueForDatesMeasureName))
{
string ShowValueForDatesMeasureExpression =
"VAR LastDateWithData = " +
" CALCULATE ( " +
" MAX ( " + factDateColumnWithTable + " ), " +
" REMOVEFILTERS () " +
" )" +
"VAR FirstDateVisible = " +
" MIN ( " + dateColumnWithTable + " ) " +
"VAR Result = " +
" FirstDateVisible <= LastDateWithData " +
"RETURN " +
" Result ";
var ShowValueForDatesMeasure = dateTable.AddMeasure(ShowValueForDatesMeasureName, ShowValueForDatesMeasureExpression);
ShowValueForDatesMeasure.FormatDax();
};
//defining expressions and formatstring for each calc item
string CY =
"/*CY*/ " +
"SELECTEDMEASURE()";
string CYlabel =
"SELECTEDVALUE(" + yearColumnWithTable + ")";
string PY =
"/*PY*/ " +
"IF (" +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE ( " +
" " + CY + ", " +
" CALCULATETABLE ( " +
" DATEADD ( " + dateColumnWithTable + " , -1, YEAR ), " +
" " + dateWithSalesWithTable + " = TRUE " +
" ) " +
" ) " +
") ";
string PYlabel =
"/*PY*/ " +
"IF (" +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE ( " +
" " + CYlabel + ", " +
" CALCULATETABLE ( " +
" DATEADD ( " + dateColumnWithTable + " , -1, YEAR ), " +
" " + dateWithSalesWithTable + " = TRUE " +
" ) " +
" ) " +
") ";
string YOY =
"/*YOY*/ " +
"VAR ValueCurrentPeriod = " + CY + " " +
"VAR ValuePreviousPeriod = " + PY + " " +
"VAR Result = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod - ValuePreviousPeriod" +
" ) " +
"RETURN " +
" Result ";
string YOYlabel =
"/*YOY*/ " +
"VAR ValueCurrentPeriod = " + CYlabel + " " +
"VAR ValuePreviousPeriod = " + PYlabel + " " +
"VAR Result = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod & \" vs \" & ValuePreviousPeriod" +
" ) " +
"RETURN " +
" Result ";
string YOYpct =
"/*YOY%*/ " +
"VAR ValueCurrentPeriod = " + CY + " " +
"VAR ValuePreviousPeriod = " + PY + " " +
"VAR CurrentMinusPreviousPeriod = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod - ValuePreviousPeriod" +
" ) " +
"VAR Result = " +
"DIVIDE ( " +
" CurrentMinusPreviousPeriod," +
" ValuePreviousPeriod" +
") " +
"RETURN " +
" Result";
string YOYpctLabel =
"/*YOY%*/ " +
"VAR ValueCurrentPeriod = " + CYlabel + " " +
"VAR ValuePreviousPeriod = " + PYlabel + " " +
"VAR Result = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod & \" vs \" & ValuePreviousPeriod & \" (%)\"" +
" ) " +
"RETURN " +
" Result";
string YTD =
"/*YTD*/" +
"IF (" +
" [" + ShowValueForDatesMeasureName + "]," +
" CALCULATE (" +
" " + CY + "," +
" DATESYTD (" + dateColumnWithTable + " )" +
" )" +
") ";
string YTDlabel = CYlabel + "& \" YTD\"";
string PYTD =
"/*PYTD*/" +
"IF ( " +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE ( " +
" " + YTD + "," +
" CALCULATETABLE ( " +
" DATEADD ( " + dateColumnWithTable + ", -1, YEAR ), " +
" " + dateWithSalesWithTable + " = TRUE " +
" )" +
" )" +
") ";
string PYTDlabel = PYlabel + "& \" YTD\"";
string YOYTD =
"/*YOYTD*/" +
"VAR ValueCurrentPeriod = " + YTD + " " +
"VAR ValuePreviousPeriod = " + PYTD + " " +
"VAR Result = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod - ValuePreviousPeriod" +
" ) " +
"RETURN " +
" Result ";
string YOYTDlabel =
"/*YOYTD*/" +
"VAR ValueCurrentPeriod = " + YTDlabel + " " +
"VAR ValuePreviousPeriod = " + PYTDlabel + " " +
"VAR Result = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod & \" vs \" & ValuePreviousPeriod" +
" ) " +
"RETURN " +
" Result ";
string YOYTDpct =
"/*YOYTD%*/" +
"VAR ValueCurrentPeriod = " + YTD + " " +
"VAR ValuePreviousPeriod = " + PYTD + " " +
"VAR CurrentMinusPreviousPeriod = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod - ValuePreviousPeriod" +
" ) " +
"VAR Result = " +
"DIVIDE ( " +
" CurrentMinusPreviousPeriod," +
" ValuePreviousPeriod" +
") " +
"RETURN " +
" Result";
string YOYTDpctLabel =
"/*YOY%*/ " +
"VAR ValueCurrentPeriod = " + YTDlabel + " " +
"VAR ValuePreviousPeriod = " + PYTDlabel + " " +
"VAR Result = " +
"IF ( " +
" NOT ISBLANK ( ValueCurrentPeriod ) && NOT ISBLANK ( ValuePreviousPeriod ), " +
" ValueCurrentPeriod & \" vs \" & ValuePreviousPeriod & \" (%)\"" +
" ) " +
"RETURN " +
" Result";
string MAT =
" /*TAM*/" +
" IF (" +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE (" +
" SELECTEDMEASURE()," +
" DATESINPERIOD (" +
" " + dateColumnWithTable + " ," +
" MAX ( " + dateColumnWithTable + " )," +
" -1," +
" YEAR" +
" )" +
" " +
" )" +
" )";
string MATlabel =
" /*TAM*/" +
" IF (" +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE (" +
" \"Year ending \" & FORMAT(MAX( 'Date'[Date] ),\"d-MMM-yyyy\",\"en-US\")," +
" DATESINPERIOD (" +
" " + dateColumnWithTable + " ," +
" MAX ( " + dateColumnWithTable + " )," +
" -1," +
" YEAR" +
" )" +
" " +
" )" +
" )";
string MATminus1 =
" /*TAM*/" +
" IF (" +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE (" +
" SELECTEDMEASURE()," +
" DATESINPERIOD (" +
" " + dateColumnWithTable + "," +
" LASTDATE( DATEADD( " + dateColumnWithTable + ", - 1, YEAR ) )," +
" -1," +
" YEAR" +
" )" +
" )" +
" )";
string MATminus1label =
"/*MAT-1*/" +
" IF (" +
" [" + ShowValueForDatesMeasureName + "], " +
" CALCULATE (" +
" \"Year ending \" & FORMAT(MAX( 'Date'[Date] ),\"d-MMM-yyyy\",\"en-US\")," +
" DATESINPERIOD (" +
" " + dateColumnWithTable + "," +
" LASTDATE( DATEADD( " + dateColumnWithTable + ", - 1, YEAR ) )," +
" -1," +
" YEAR" +
" )" +
" )" +
" )";
;
string MATvsMATminus1 =
" /*MAT vs MAT-1*/\r\n" +
" VAR MAT = " + MAT + "\r\n" +
" VAR MAT_1 =" + MATminus1 + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MAT ) || ISBLANK( MAT_1 ), BLANK(), MAT - MAT_1 )";
string MATvsMATminus1label = "/*MAT vs MAT-1*/" +
" VAR MAT = " + MATlabel + "\r\n" +
" VAR MAT_1 =" + MATminus1label + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MAT ) || ISBLANK( MAT_1 ), BLANK(), MAT & \" vs \" & MAT_1 )";
string MATvsMATminus1pct =
" /*MAT vs MAT-1(%)*/" +
" VAR MAT = " + MAT + "\r\n" +
" VAR MAT_1 =" + MATminus1 + "\r\n" +
" RETURN" +
" IF(" +
" ISBLANK( MAT ) || ISBLANK( MAT_1 )," +
" BLANK()," +
" DIVIDE( MAT - MAT_1, MAT_1 )" +
" )";
string MATvsMATminus1pctlabel = "/*MAT vs MAT-1 (%)*/" +
" VAR MAT = " + MATlabel + "\r\n" +
" VAR MAT_1 =" + MATminus1label + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MAT ) || ISBLANK( MAT_1 ), BLANK(), MAT & \" vs \" & MAT_1 & \" (%)\" )";
string MMT = String.Format(
@"/*MMT*/
IF(
[{0}],
CALCULATE( SELECTEDMEASURE( ), DATESINPERIOD( {1}, MAX( {1} ), -1, MONTH ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable);
string MMTlabel = String.Format(
@"/*MMT*/
IF(
[{0}],
CALCULATE( {2}, DATESINPERIOD( {1}, MAX( {1} ), -1, MONTH ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable, "\"Month ending \" & FORMAT(MAX( 'Date'[Date] ),\"d-MMM-yyyy\",\"en-US\")");
string MMTminus1 = String.Format(
@"/*MMT*/
IF(
[{0}],
CALCULATE( SELECTEDMEASURE( ), DATESINPERIOD( {1}, LASTDATE( DATEADD( {1}, -1, MONTH ) ), -1, MONTH ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable);
string MMTminus1label = "/*MMT-1*/" +
String.Format(
@"/*MMT*/
IF(
[{0}],
CALCULATE( {2}, DATESINPERIOD( {1}, LASTDATE( DATEADD( {1}, -1, MONTH ) ), -1, MONTH ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable, "\"Month ending \" & FORMAT(MAX( 'Date'[Date] ),\"d-MMM-yyyy\",\"en-US\")");
string MMTvsMMTminus1 =
" /*MMT vs MMT-1*/\r\n" +
" VAR MMT = " + MMT + "\r\n" +
" VAR MMT_1 =" + MMTminus1 + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MMT ) || ISBLANK( MMT_1 ), BLANK(), MMT - MMT_1 )";
string MMTvsMMTminus1label =
" /*MMT vs MMT-1*/\r\n" +
" VAR MMT = " + MMTlabel + "\r\n" +
" VAR MMT_1 =" + MMTminus1label + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MMT ) || ISBLANK( MMT_1 ), BLANK(), MMT & \" vs \" & MMT_1 )";
string MMTvsMMTminus1pct =
" /*MMT vs MMT-1(%)*/" +
" VAR MMT = " + MMT + "\r\n" +
" VAR MMT_1 =" + MMTminus1 + "\r\n" +
" RETURN" +
" IF(" +
" ISBLANK( MMT ) || ISBLANK( MMT_1 )," +
" BLANK()," +
" DIVIDE( MMT - MMT_1, MMT_1 )" +
" )";
string MMTvsMMTminus1pctlabel =
" /*MMT vs MMT-1(%)*/" +
" VAR MMT = " + MMTlabel + "\r\n" +
" VAR MMT_1 =" + MMTminus1label + "\r\n" +
" RETURN" +
" IF( ISBLANK( MMT ) || ISBLANK( MMT_1 ), BLANK(), MMT & \" vs \" & MMT_1 & \" (%)\")";
string MWT = String.Format(
@"/*MWT*/
IF(
[{0}],
CALCULATE( SELECTEDMEASURE( ), DATESINPERIOD( {1}, MAX( {1} ), -7, DAY ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable);
string MWTlabel = "/*MWT*/" +
String.Format(
@"/*MWT*/
IF(
[{0}],
CALCULATE( {2}, DATESINPERIOD( {1}, MAX( {1} ), -7, DAY ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable, "\"Week ending \" & FORMAT(MAX( 'Date'[Date] ),\"d-MMM-yyyy\",\"en-US\")"); ;
string MWTminus1 = String.Format(
@"/*MWT*/
IF(
[{0}],
CALCULATE( SELECTEDMEASURE( ), DATESINPERIOD( {1}, LASTDATE( DATEADD( {1}, -7, DAY ) ), -7, DAY ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable);
string MWTminus1label = "/*MWT-1*/" +
String.Format(
@"/*MWT*/
IF(
[{0}],
CALCULATE( {2}, DATESINPERIOD( {1}, LASTDATE( DATEADD( {1}, -7, DAY ) ), -7, DAY ) )
)", ShowValueForDatesMeasureName, dateColumnWithTable, "\"Week ending \" & FORMAT(MAX( 'Date'[Date] ),\"d-MMM-yyyy\",\"en-US\")");
string MWTvsMWTminus1 =
" /*MWT vs MWT-1*/\r\n" +
" VAR MWT = " + MWT + "\r\n" +
" VAR MWT_1 =" + MWTminus1 + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MWT ) || ISBLANK( MWT_1 ), BLANK(), MWT - MWT_1 )";
string MWTvsMWTminus1label =
" /*MWT vs MWT-1*/\r\n" +
" VAR MWT = " + MWTlabel + "\r\n" +
" VAR MWT_1 =" + MWTminus1label + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MWT ) || ISBLANK( MWT_1 ), BLANK(), MWT & \" vs \" & MWT_1 )";
string MWTvsMWTminus1pct =
" /*MWT vs MWT-1(%)*/" +
" VAR MWT = " + MWT + "\r\n" +
" VAR MWT_1 =" + MWTminus1 + "\r\n" +
" RETURN" +
" IF(" +
" ISBLANK( MWT ) || ISBLANK( MWT_1 )," +
" BLANK()," +
" DIVIDE( MWT - MWT_1, MWT_1 )" +
" )";
string MWTvsMWTminus1pctlabel =
"/*MWT vs MWT-1 (%)*/" +
" VAR MWT = " + MWTlabel + "\r\n" +
" VAR MWT_1 =" + MWTminus1label + "\r\n" +
" RETURN \r\n" +
" IF( ISBLANK( MWT ) || ISBLANK( MWT_1 ), BLANK(), MWT & \" vs \" & MWT_1 & \" (%)\")";
string defFormatString = "SELECTEDMEASUREFORMATSTRING()";
//if the flag expression is already present in the format string, do not change it, otherwise apply % format.
string pctFormatString =
"IF(" +
"\n FIND( " + flagExpression + ", SELECTEDMEASUREFORMATSTRING(), 1, - 1 ) <> -1," +
"\n SELECTEDMEASUREFORMATSTRING()," +
"\n \"#,##0.# %\"" +
"\n)";
//the order in the array also determines the ordinal position of the item
string[,] calcItems =
{
{"CY", CY, defFormatString, "Current year", CYlabel},
{"PY", PY, defFormatString, "Previous year", PYlabel},
{"YOY", YOY, defFormatString, "Year-over-year", YOYlabel},
{"YOY%", YOYpct, pctFormatString, "Year-over-year%", YOYpctLabel},
{"YTD", YTD, defFormatString, "Year-to-date", YTDlabel},
{"PYTD", PYTD, defFormatString, "Previous year-to-date", PYTDlabel},
{"YOYTD", YOYTD, defFormatString, "Year-over-year-to-date", YOYTDlabel},
{"YOYTD%", YOYTDpct, pctFormatString, "Year-over-year-to-date%", YOYTDpctLabel},
{"MAT", MAT, defFormatString, "Moving Anual Total", MATlabel},
{"MAT-1", MATminus1, defFormatString, "Moving Anual Total -1 year", MATminus1label},
{"MAT vs MAT-1", MATvsMATminus1, defFormatString, "Moving Anual Total vs Moving Anual Total -1 year", MATvsMATminus1label},
{"MAT vs MAT-1(%)", MATvsMATminus1pct, pctFormatString, "Moving Anual Total vs Moving Anual Total -1 year (%)", MATvsMATminus1pctlabel},
{"MMT", MMT, defFormatString, "Moving Monthly Total", MMTlabel},
{"MMT-1", MMTminus1, defFormatString, "Moving Monthly Total -1 month", MMTminus1label},
{"MMT vs MMT-1", MMTvsMMTminus1, defFormatString, "Moving Monthly Total vs Moving Monthly Total -1 month", MMTvsMMTminus1label},
{"MMT vs MMT-1(%)", MMTvsMMTminus1pct, pctFormatString, "Moving Monthly Total vs Moving Monthly Total -1 month (%)", MMTvsMMTminus1pctlabel},
{"MWT", MWT, defFormatString, "Moving Weekly Total", MWTlabel},
{"MWT-1", MWTminus1, defFormatString, "Moving Weekly Total -1 week", MWTminus1label},
{"MWT vs MWT-1", MWTvsMWTminus1, defFormatString, "Moving Weekly Total vs Moving Weekly Total -1 month", MWTvsMWTminus1label},
{"MWT vs MWT-1(%)", MWTvsMWTminus1pct, pctFormatString, "Moving Weekly Total vs Moving Weekly Total -1 week (%)", MWTvsMWTminus1pctlabel}
};
int j = 0;
//create calculation items for each calculation with formatstring and description
foreach (var cg in Model.CalculationGroups)
{
if (cg.Name == calcGroupName)
{
for (j = 0; j < calcItems.GetLength(0); j++)
{
string itemName = calcItems[j, 0];
string itemExpression = calcItemProtection.Replace("<CODE>", calcItems[j, 1]);
itemExpression = itemExpression.Replace("<LABELCODE>", calcItems[j, 4]);
string itemFormatExpression = calcItemFormatProtection.Replace("<CODE>", calcItems[j, 2]);
itemFormatExpression = itemFormatExpression.Replace("<LABELCODEFORMATSTRING>", "\"\"\"\" & " + calcItems[j, 4] + " & \"\"\"\"");
//if(calcItems[j,2] != defFormatString) {
// itemFormatExpression = calcItemFormatProtection.Replace("<CODE>",calcItems[j,2]);
//};
string itemDescription = calcItems[j, 3];
if (!cg.CalculationItems.Contains(itemName))
{
var nCalcItem = cg.AddCalculationItem(itemName, itemExpression);
nCalcItem.FormatStringExpression = itemFormatExpression;
nCalcItem.FormatDax();
nCalcItem.Ordinal = j;
nCalcItem.Description = itemDescription;
};
};
};
};
}
void createMeasureFromCalcGroupWithFieldParameter()
{
////uncoment the following three lines in TabularEditor
//#r "Microsoft.VisualBasic"
//using Microsoft.VisualBasic;
//using System.Windows.Forms;
/* '2023-01-26 / B.Agullo / creates a field parameter of measures filtered by calc group and values of a column with a name defined by a measure evaluated in the filtered value and calc item */
/* DYNAMIC HEADER FIELD PARAMETER SCRIPT */
/* select measures and execute, you will need to run it twice */
/* first time to create aux calc group, second time to actually create measuree*/
/* remove aux calc group before going to production, do the right thing */
string auxCgTag = "@AgulloBernat";
string auxCgTagValue = "CG to extract format strings";
string auxCalcGroupName = "DELETE AUX CALC GROUP";
string auxCalcItemName = "Get Format String";
string baseMeasureAnnotationName = "Base Measure";
string calcItemAnnotationName = "Calc Item";
string calcItemSortOrderName = "Sort Order";
string calcItemSortOrderValue = String.Empty;
string filterValueAnnotationName = String.Empty;
string dynamicNameAnnotationName = "Dynamic Name";
string scriptAnnotationName = "Script";
string scriptAnnotationValue = "Create Measures with a Calculation Group "+ DateTime.Now.ToString("yyyyMMddHHmmss");
bool generateFieldParameter;
DialogResult dialogResult = MessageBox.Show("Generate Field Parameter?", "Field Parameter", MessageBoxButtons.YesNo);
generateFieldParameter = (dialogResult == DialogResult.Yes);
/*check if any measures are selected*/
if (Selected.Measures.Count == 0)
{
Error("No measures selected");
return;
}
/*find any regular CGs (excluding the one we might have created)*/
var regularCGs = Model.Tables.Where(
x => x.ObjectType == ObjectType.CalculationGroupTable
& x.GetAnnotation(auxCgTag) != auxCgTagValue);
if (regularCGs.Count() == 0)
{
Error("No Calculation Groups Found");
return;
};
//the lambda expression will be avaluated for all calc groups to find a matching calc group
//CalculationGroupTable auxCg = Fx.SelectCalculationGroup(model:Model,lambdaExpression:lambda,selectFirst:true, showErrorIfNoTablesFound:false);
bool calcGroupWasCreated = false;
//the calc group will only be created if not found, and when so the boolean will point to it
CalculationGroupTable auxCg = Fx.AddCalculationGroupExt(model: Model, calcGroupWasCreated: out calcGroupWasCreated,
defaultName: auxCalcGroupName, customCalcGroupName: false, annotationName: auxCgTag, annotationValue: auxCgTagValue);
if (calcGroupWasCreated)
{
CalculationItem cItem = Fx.AddCalculationItemExt(cg: auxCg, calcItemName: auxCalcItemName, valueExpression: "SELECTEDMEASUREFORMATSTRING()");
auxCg.IsHidden = true;
Info("Save changes to the model, recalculate the model, and launch the script again.");
return;
}
//to avoid showing the aux calc group in the list
Func<Table, bool> lambda = (x) => x.GetAnnotation(auxCgTag) != auxCgTagValue;
CalculationGroupTable regularCg = Fx.SelectCalculationGroup(model: Model, lambdaExpression: lambda);
if (regularCg == null) return;
Table filterTable = Fx.SelectTableExt(model: Model, excludeCalcGroups: true, label:"Select table of filter field",showErrorIfNoSelection:true);
if(filterTable == null) return;
Column filterColumn = SelectColumn(filterTable,label:"Select filter Field");
if (filterColumn == null) return;
filterValueAnnotationName = filterColumn.Name;
String filterQuery = String.Format("EVALUATE DISTINCT({0})", filterColumn.DaxObjectFullName);
List<String> filterValues = new List<String>();
using (var filterReader = Model.Database.ExecuteReader(filterQuery))
{
while (filterReader.Read())
{