-
Notifications
You must be signed in to change notification settings - Fork 40
/
modSanitize.bas
832 lines (694 loc) · 31.9 KB
/
modSanitize.bas
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
Attribute VB_Name = "modSanitize"
'---------------------------------------------------------------------------------------
' Module : modSanitize
' Author : Adam Waller
' Date : 12/4/2020
' Purpose : Functions to sanitize files to remove non-essential metadata
'---------------------------------------------------------------------------------------
Option Compare Database
Option Private Module
Option Explicit
Private Const ModuleName = "modSanitize"
' Array of lines to skip
Private m_SkipLines() As Long
Private m_lngSkipIndex As Long
Private m_colBlocks As Collection
'---------------------------------------------------------------------------------------
' Procedure : SanitizeFile
' Author : Adam Waller
' Date : 11/4/2020
' Purpose : Rewritten version of sanitize function. Returns hash of content as well
' : as saving to the specified path.
'---------------------------------------------------------------------------------------
'
Public Function SanitizeFile(strPath As String, blnReturnHash As Boolean) As String
Dim strFile As String
Dim varLines As Variant
Dim lngLine As Long
Dim cData As clsConcat
Dim strLine As String
Dim strTLine As String
Dim blnInsideIgnoredBlock As Boolean
Dim intIndent As Integer
Dim blnIsReport As Boolean
Dim blnIsPassThroughQuery As Boolean
Dim curStart As Currency
Dim strTempFile As String
Dim strContent As String
If DebugMode(True) Then On Error GoTo 0 Else On Error Resume Next
' Read text from file, and split into lines
If HasUcs2Bom(strPath) Then
strFile = ReadFile(strPath, "Unicode")
Else
' ADP projects may contain mixed Unicode content
If CurrentProject.ProjectType = acADP Then
strTempFile = GetTempFile
ConvertUcs2Utf8 strPath, strTempFile, False
strFile = ReadFile(strTempFile)
DeleteFile strTempFile
Else
If DbVersion <= 4 Then
' Access 2000 format exports using system codepage
' See issue #217
strFile = ReadFile(strPath, GetSystemEncoding)
Else
' Newer versions export as UTF-8
strFile = ReadFile(strPath)
End If
End If
End If
Perf.OperationStart "Sanitize File"
varLines = Split(strFile, vbCrLf)
If Options.SanitizeLevel = eslNone Then GoTo Build_Output
' Set up index of lines to skip
ReDim m_SkipLines(0 To UBound(varLines)) As Long
m_lngSkipIndex = 0
Set m_colBlocks = New Collection
' Initialize concatenation class to include line breaks
' after each line that we add when building new file text.
curStart = Perf.MicroTimer
' Using a do loop since we may adjust the line counter
' during a loop iteration.
Do While lngLine <= UBound(varLines)
' Get unmodified and trimmed line
strLine = varLines(lngLine)
strTLine = Trim$(strLine)
' Improve performance by reducing comparisons
If Len(strTLine) > 3 And blnInsideIgnoredBlock Then
SkipLine lngLine
ElseIf Len(strTLine) > 60 And StartsWith(strTLine, "0x") Then
' Add binary data line. No need to test this line further.
Else
' Run the rest of the tests
Select Case strTLine
' File version
Case "Version =21"
' Change version down to 20 to allow import into Access 2010.
' (Haven't seen any significant issues with this.)
varLines(lngLine) = "Version =20"
' Print settings blocks to ignore
Case "PrtMip = Begin", _
"PrtDevMode = Begin", _
"PrtDevModeW = Begin", _
"PrtDevNames = Begin", _
"PrtDevNamesW = Begin"
' Set flag to ignore lines inside this block.
blnInsideIgnoredBlock = True
SkipLine lngLine
' Aggressive sanitize blocks
Case "GUID = Begin", _
"NameMap = Begin", _
"dbLongBinary ""DOL"" = Begin", _
"dbBinary ""GUID"" = Begin"
If Options.AggressiveSanitize Then
blnInsideIgnoredBlock = True
SkipLine lngLine
End If
' Single lines to ignore (#249)
Case "NoSaveCTIWhenDisabled =1", _
"AllowPivotTableView =0", _
"AllowPivotChartView =0"
SkipLine lngLine
' Publish option (used in Queries)
Case "dbByte ""PublishToWeb"" =""1""", _
"PublishOption =1"
If Options.StripPublishOption Then SkipLine lngLine
' End of block section
Case "End"
If blnInsideIgnoredBlock Then
' Reached the end of the ignored block.
blnInsideIgnoredBlock = False
SkipLine lngLine
Else
' Check for theme color index
CloseBlock
End If
' See if this file is from a report object
Case "Begin Report"
' Turn flag on to ignore Right and Bottom lines
blnIsReport = True
BeginBlock
' Beginning of main section
Case "Begin"
BeginBlock
If blnIsPassThroughQuery And Options.AggressiveSanitize Then
' Ignore remaining content. (See Issue #182)
Do While lngLine < UBound(varLines)
SkipLine lngLine
lngLine = lngLine + 1
Loop
Exit Do
End If
' Code section behind form or report object
Case "CodeBehindForm"
' Keep everything from this point on
Exit Do
Case Else
If blnInsideIgnoredBlock Then
' Skip content inside ignored blocks.
SkipLine lngLine
ElseIf StartsWith(strTLine, "Checksum =") Then
' Ignore Checksum lines, since they will change.
SkipLine lngLine
ElseIf StartsWith(strTLine, "BaseInfo =") Then
' BaseInfo is used with combo boxes, similar to RowSource.
' Since the value could span multiple lines, we need to
' check the indent level of the following lines to see how
' many lines to skip.
SkipLine lngLine
intIndent = GetIndent(strLine)
' Preview the next line, and check the indent level
Do While GetIndent(varLines(lngLine + 1)) > intIndent
' Skip previewed line and move to next line
SkipLine lngLine + 1
lngLine = lngLine + 1
Loop
ElseIf blnIsReport And StartsWith(strLine, " Right =") Then
' Ignore this line. (Not important, and frequently changes.)
SkipLine lngLine
ElseIf blnIsReport And StartsWith(strLine, " Bottom =") Then
' Turn flag back off now that we have ignored these two lines.
SkipLine lngLine
blnIsReport = False
ElseIf StartsWith(strTLine, "Begin ") Then
' Include block type name for controls
BeginBlock Mid$(strTLine, 7)
ElseIf EndsWith(strTLine, " = Begin") Then
BeginBlock
Else
' All other lines will be added.
' Check for color properties
If InStr(1, strTLine, " =") > 1 Then CheckColorProperties strTLine, lngLine
' Check for pass-through query connection string
If StartsWith(strLine, "dbMemo ""Connect"" =""") Then
' Not just an empty value (See issue #337)
If Len(strLine) > 20 Then
blnIsPassThroughQuery = True
End If
End If
End If
End Select
End If
' Increment counter to next line
lngLine = lngLine + 1
Loop
' Ensure that we correctly processed the nested block sequence.
If m_colBlocks.Count > 0 Then Log.Error eelWarning, Replace(Replace( _
"Found ${BlockCount} unclosed blocks after sanitizing ${File}.", _
"${BlockCount}", m_colBlocks.Count), _
"${File}", strPath), ModuleName & ".SanitizeFile"
Build_Output:
' Build the final output
strContent = BuildOutput(varLines)
WriteFile strContent, strPath
' Return hash of content
If blnReturnHash Then SanitizeFile = GetStringHash(strContent, True)
' Log performance
Set m_colBlocks = Nothing
Perf.OperationEnd
Log.Add " Sanitized in " & Format$(Perf.MicroTimer - curStart, "0.000") & " seconds.", Options.ShowDebug
' Log any errors
CatchAny eelError, "Error sanitizing file " & FSO.GetFileName(strPath), ModuleName & ".SanitizeFile"
End Function
'---------------------------------------------------------------------------------------
' Procedure : BuildOutput
' Author : Adam Waller
' Date : 6/4/2021
' Purpose : Splitting this out into its own sub to reduce complexity.
'---------------------------------------------------------------------------------------
'
Private Function BuildOutput(varLines As Variant) As String
Dim cData As clsConcat
Dim lngSkip As Long
Dim lngLine As Long
' Check index of skipped lines
If m_lngSkipIndex = 0 Then
' No lines to skip
ReDim m_SkipLines(0 To 0)
m_SkipLines(0) = UBound(varLines) + 1
Else
' Trim and sort index array
ReDim Preserve m_SkipLines(0 To m_lngSkipIndex - 1)
QuickSort m_SkipLines
End If
' Use concatenation class to maximize performance
Set cData = New clsConcat
With cData
.AppendOnAdd = vbCrLf
' Loop through array of lines in source file
For lngLine = 0 To UBound(varLines)
' Iterate the sorted skipped lines index to keep up with main loop
' (Using parallel loops to optimize performance)
If m_SkipLines(lngSkip) < lngLine Then
If lngSkip < UBound(m_SkipLines) Then lngSkip = lngSkip + 1
End If
' Add content, unless the line is flagged to skip
If m_SkipLines(lngSkip) <> lngLine Then .Add CStr(varLines(lngLine))
Next lngLine
' Remove last vbcrlf
cData.Remove Len(vbCrLf)
' Return assembled output
BuildOutput = .GetStr
End With
End Function
'---------------------------------------------------------------------------------------
' Procedure : SkipLine
' Author : Adam Waller
' Date : 6/4/2021
' Purpose : Skip this line in the final output file
'---------------------------------------------------------------------------------------
'
Private Function SkipLine(lngLine As Long)
m_SkipLines(m_lngSkipIndex) = lngLine
m_lngSkipIndex = m_lngSkipIndex + 1
End Function
'---------------------------------------------------------------------------------------
' Procedure : BeginBlock
' Author : Adam Waller
' Date : 6/4/2021
' Purpose : Add a dictionary object to represent the block
'---------------------------------------------------------------------------------------
'
Private Sub BeginBlock(Optional strType As String)
Dim dBlock As Dictionary
If m_colBlocks Is Nothing Then Set m_colBlocks = New Collection
Set dBlock = New Dictionary
If strType <> vbNullString Then dBlock.Add "Type", strType
m_colBlocks.Add dBlock
End Sub
'---------------------------------------------------------------------------------------
' Procedure : CloseBlock
' Author : Adam Waller
' Date : 6/4/2021
' Purpose : Determine if the block used any theme-based dynamic colors that should
' : be skipped in the output file. (See issue #183)
'---------------------------------------------------------------------------------------
'
Private Sub CloseBlock()
Dim varBase As Variant
Dim intCnt As Integer
Dim dBlock As Dictionary
Dim strKey As String
' Skip if we are not using aggressive color sanitize
If Options.SanitizeColors <= eslNone Then Exit Sub
' Bail out if we don't have a block to review
If m_colBlocks.Count = 0 Then Exit Sub
Set dBlock = m_colBlocks(m_colBlocks.Count)
' Skip if we are not using themes for this control (UseTheme=0)
' (Applies to "CommandButton", "Tab", "ToggleButton")
If dBlock.Exists("UseTheme") Then Exit Sub
' Build array of base properties
varBase = Array("Back", "AlternateBack", "Border", _
"Fore", "Gridline", "HoverFore", _
"Hover", "PressedFore", "Pressed", _
"DatasheetFore", "DatasheetBack", "DatasheetGridlines")
' Loop through properties, checking for index
For intCnt = 0 To UBound(varBase)
strKey = varBase(intCnt) & "ThemeColorIndex"
If dBlock.Exists(strKey) Then
If dBlock(strKey) <> NO_THEME_INDEX Then
' Check for corresponding color property
strKey = varBase(intCnt) & "Color"
If dBlock.Exists(strKey) Then
' Skip the dynamic color line
SkipLine dBlock(strKey)
End If
End If
Else
Select Case dBlock("Type")
Case "Section", "FormHeader", "FormFooter"
' Some controls like form sections don't use color values
' if a theme index is specified. If a color value exists,
' we should preserve it.
Case Else
' Most controls automatically use theme indexes
' unless otherwise specified.
' As discussed in #183, this can be affected by incomplete
' component definition blocks.
If Options.SanitizeColors = eslAdvancedBeta Then
strKey = varBase(intCnt) & "Color"
If dBlock.Exists(strKey) Then
' Skip the dynamic color line
SkipLine dBlock(strKey)
End If
End If
End Select
End If
Next intCnt
' Remove this block
m_colBlocks.Remove m_colBlocks.Count
End Sub
'---------------------------------------------------------------------------------------
' Procedure : CheckColorProperties
' Author : Adam Waller
' Date : 6/4/2021
' Purpose : Use an index to reference color properties so we can determine any lines
' : that we need to discard after finishing the block.
'---------------------------------------------------------------------------------------
'
Private Sub CheckColorProperties(strTLine As String, lngLine As Long)
Dim dBlock As Dictionary
Dim varParts As Variant
Dim lngCnt As Long
Dim lngID As Long
Dim strID As String
Dim lngValue As Long
Dim lngColor As Long
' Skip if not using this option
If Options.SanitizeColors <= eslNone Then Exit Sub
' Exit if we are not inside a block
If Not m_colBlocks Is Nothing Then lngCnt = m_colBlocks.Count
If lngCnt = 0 Then Exit Sub
Set dBlock = m_colBlocks(m_colBlocks.Count)
' Split on property/value
varParts = Split(strTLine, " =")
Select Case varParts(0)
' Theme color index properties
Case "BackThemeColorIndex", "AlternateBackThemeColorIndex", "BorderThemeColorIndex", _
"ForeThemeColorIndex", "GridlineThemeColorIndex", "HoverForeThemeColorIndex", _
"HoverThemeColorIndex", "PressedForeThemeColorIndex", "PressedThemeColorIndex", _
"DatasheetBackThemeColorIndex", "DatasheetForeThemeColorIndex", "DatasheetGridlinesThemeColorIndex"
' Save to dictionary if using a theme index color
dBlock.Add varParts(0), varParts(1)
' Matching color properties
Case "BackColor", "AlternateBackColor", "BorderColor", _
"ForeColor", "GridlineColor", "HoverForeColor", _
"HoverColor", "PressedForeColor", "PressedColor", _
"DatasheetBackColor", "DatasheetForeColor", "DatasheetGridlinesColor"
' Check for system color constants
If IsNumeric(varParts(1)) Then lngColor = varParts(1)
If lngColor < 0 Then
' Using a system color constant or other Access constant value.
' https://stackoverflow.com/a/30396550/4121863
' Leave this color value intact.
Else
' Save line of color property
dBlock.Add varParts(0), lngLine
End If
Case "UseTheme"
' You can tell certain controls to not use the theme. (Buttons, Tabs, Toggles)
If varParts(1) = 0 Then dBlock.Add varParts(0), 0
Case Else
' Check for other related dynamic color properties/indexes
If StartsWith(strTLine, "DatasheetGridlinesColor") Then
' May include the index number in the property name. (I.e. DatasheetGridlinesColor12 =0)
' Convert to a more consistent identifier, using the index suffix as the value.
dBlock.Add "DatasheetGridlinesThemeColorIndex", Mid$(varParts(0), 24)
End If
End Select
End Sub
'---------------------------------------------------------------------------------------
' Procedure : SanitizeXML
' Author : Adam Waller
' Date : 4/29/2021
' Purpose : Remove non-essential data that changes every time the file is exported.
' : Optionally returns a hash of the file content. (To save reading the file
' : back again afterwards to compute the hash.)
'---------------------------------------------------------------------------------------
'
Public Function SanitizeXML(strPath As String, blnReturnHash As Boolean) As String
Dim curStart As Currency
Dim cData As clsConcat
Dim strFile As String
Dim strText As String
Dim strTLine As String
Dim strLine As String
Dim lngLine As Long
Dim lngData As Long
Dim lngPos As Long
Dim lngLen As Long
Dim rxLine As VBScript_RegExp_55.RegExp
Dim objMatches As VBScript_RegExp_55.MatchCollection
Dim varLines As Variant
If DebugMode(True) Then On Error GoTo 0 Else On Error Resume Next
Set cData = New clsConcat
cData.AppendOnAdd = vbCrLf
Set rxLine = New VBScript_RegExp_55.RegExp
' Read text from file
If HasUcs2Bom(strPath) Then
' Table data macro XML is exported as UTF-16 LE BOM
strFile = ReadFile(strPath, "Unicode")
Else
strFile = ReadFile(strPath)
End If
Perf.OperationStart "Sanitize XML"
curStart = Perf.MicroTimer
' Exporting Table Def as XML does not properly encode ampersand character (See #314)
' Most likely if any ampersands are encoded correctly, all of them will be.
With New VBScript_RegExp_55.RegExp
.Multiline = True
.Global = True
' Match & " > < etc...
.Pattern = "&[A-z]{2,6};"
If Not .Test(strFile) Then
' Properly encode any embedded ampersand characters to make valid XML
strFile = Replace(strFile, "&", "&")
End If
End With
' When exporting table data, the schema is only required when the table contains
' a calculated field. See if we are working with a table data file, and if it
' contains a calculated field.
lngData = InStr(1, strFile, "<dataroot xmlns:xsi=")
If lngData > 0 Then
' Looks like a table data export file
Dim expr As Variant
Dim exprs As Variant
' Search for any field data types such as calculated, complex (e.g. attachments or
' multi-valued fields, binary fields that might require the schema to be retained
' to ensure that the import work correctly)
exprs = Array(""" od:expression=""", """ od:jetType=""complex""", """ od:jetType=""oleobject""")
For Each expr In exprs
lngPos = InStr(1, strFile, expr)
If lngPos > 0 And lngPos < lngData Then
Exit For
End If
Next
If lngPos > 0 And lngPos < lngData Then
' Keep the schema in the export file
Else
' Trim off the schema, and just include the data.
' Also remove the closing root tag from the end of the file.
lngLen = (Len(strFile) - lngData) - Len("</root>" & vbCrLf)
strFile = Mid(strFile, lngData, lngLen)
End If
End If
' Split into array of lines
varLines = Split(FormatXML(strFile), vbCrLf)
' Using a do loop since we may adjust the line counter
' during a loop iteration.
Do While lngLine <= UBound(varLines)
' Get unmodified and trimmed line
strLine = varLines(lngLine)
strTLine = TrimTabs(Trim$(strLine))
' Look for specific lines
Select Case True
' Discard blank lines
Case strTLine = vbNullString
' Remove generated timestamp in header
Case StartsWith(strTLine, "<dataroot ")
'<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2020-04-27T10:28:32">
'<dataroot generated="2021-04-29T17:27:33" xmlns:od="urn:schemas-microsoft-com:officedata">
With rxLine
.Pattern = "( generated="".+?"")"
If .Test(strLine) Then
' Replace timestamp with empty string.
Set objMatches = .Execute(strLine)
strText = Replace(strLine, objMatches(0).SubMatches(0), vbNullString, , 1)
cData.Add strText
Else
' Did not contain a timestamp. Keep the whole line
cData.Add strLine
End If
End With
' Remove non-critical single lines that are not consistent between systems
'Case StartsWith(strTLine, "<od:tableProperty name=""NameMap""")
' If Not Options.AggressiveSanitize Then cData.Add strLine
' Remove multi-line sections
Case StartsWith(strTLine, "<od:tableProperty name=""NameMap"""), _
StartsWith(strTLine, "<od:tableProperty name=""GUID"""), _
StartsWith(strTLine, "<od:fieldProperty name=""GUID""")
If Options.AggressiveSanitize Then
Do While Not EndsWith(strTLine, "/>")
lngLine = lngLine + 1
If lngLine <= UBound(varLines) Then
strTLine = TrimTabs(Trim$(varLines(lngLine)))
Else
strTLine = vbNullString
Exit Do
End If
Loop
Else
' Keep line and continue
cData.Add strLine
End If
' Publish to web sections
Case StartsWith(strTLine, "<od:tableProperty name=""PublishToWeb""")
If Not Options.StripPublishOption Then cData.Add strLine
' Keep everything else
Case Else
cData.Add strLine
End Select
' Move to next line
lngLine = lngLine + 1
Loop
Perf.OperationEnd
' Write out sanitized XML file
WriteFile cData.GetStr, strPath
' Return hash, if requested
If blnReturnHash Then SanitizeXML = GetStringHash(cData.GetStr, True)
' Show stats if debug turned on.
Log.Add " Sanitized in " & Format$(Perf.MicroTimer - curStart, "0.000") & " seconds.", Options.ShowDebug
' Log any errors
CatchAny eelError, "Error sanitizing XML file " & FSO.GetFileName(strPath), ModuleName & ".SanitizeXML"
End Function
'---------------------------------------------------------------------------------------
' Procedure : TrimTabs
' Author : Adam Waller
' Date : 4/29/2021
' Purpose : Trim off tabs from beginning and end of string
'---------------------------------------------------------------------------------------
'
Public Function TrimTabs(strText As String) As String
Dim dblStart As Double
Dim dblEnd As Double
Dim dblPos As Double
' Look for leading tabs
dblStart = 1
For dblPos = 1 To Len(strText)
If Mid$(strText, dblPos, 1) <> vbTab Then
dblStart = dblPos
Exit For
End If
Next dblPos
' Look for trailing tabs
dblEnd = 1
If Right$(strText, 1) = vbTab Then
For dblPos = Len(strText) To 1 Step -1
If Mid$(strText, dblPos, 1) <> vbTab Then
dblEnd = dblPos + 1
Exit For
End If
Next dblPos
Else
' No trailing tabs
dblEnd = Len(strText) + 1
End If
' Return string
TrimTabs = Mid$(strText, dblStart, dblEnd - dblStart)
End Function
'---------------------------------------------------------------------------------------
' Procedure : StartsWith
' Author : Adam Waller
' Date : 11/5/2020
' Purpose : See if a string begins with a specified string.
'---------------------------------------------------------------------------------------
'
Public Function StartsWith(strText As String, strStartsWith As String, Optional Compare As VbCompareMethod = vbBinaryCompare) As Boolean
StartsWith = (InStr(1, strText, strStartsWith, Compare) = 1)
End Function
'---------------------------------------------------------------------------------------
' Procedure : EndsWith
' Author : Adam Waller
' Date : 4/29/2021
' Purpose : See if a string ends with a specified string.
'---------------------------------------------------------------------------------------
'
Public Function EndsWith(strText As String, strEndsWith As String, Optional Compare As VbCompareMethod = vbBinaryCompare) As Boolean
EndsWith = (StrComp(Right$(strText, Len(strEndsWith)), strEndsWith, Compare) = 0)
'EndsWith = (InStr(1, strText, strEndsWith, Compare) = len(strtext len(strendswith) 1)
End Function
'---------------------------------------------------------------------------------------
' Procedure : GetIndent
' Author : Adam Waller
' Date : 11/5/2020
' Purpose : Returns the number of spaces until the first non-space character.
'---------------------------------------------------------------------------------------
'
Public Function GetIndent(strLine As Variant) As Integer
Dim strChar As String
strChar = Left$(Trim(strLine), 1)
If strLine <> vbNullString Then GetIndent = InStr(1, strLine, strChar) - 1
End Function
'---------------------------------------------------------------------------------------
' Procedure : FormatXML
' Author : Adam Waller
' Date : 4/22/2021
' Purpose : Format XML content for consistent and readable output.
'---------------------------------------------------------------------------------------
'
Private Function FormatXML(strSourceXML As String, _
Optional blnOmitDeclaration As Boolean) As String
' XSLT stylesheet that allow us to control indenting and also get a better indent result.
' For testing and adjusting, you can use https://www.online-toolz.com/tools/xslt-validator-tester-online.php
Const strIndentXslt As String = "<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" version=""1.0""><xsl:output method=""xml""/><xsl:template match=""@*""><xsl:copy/></xsl:template><xsl:template match=""text()""><xsl:value-of select=""normalize-space(.)"" /></xsl:template><xsl:template match=""*""><xsl:param name=""indent"" select=""''""/><xsl:text>
</xsl:text><xsl:value-of select=""$indent"" /><xsl:copy><xsl:apply-templates select=""@*|*|text()""><xsl:with-param name=""indent"" select=""concat($indent, ' ')""/></xsl:apply-templates></xsl:copy><xsl:if test=""count(../*)>0 and ../*[last()]=.""><xsl:text>
</xsl:text><xsl:value-of select=""substring($indent,3)"" /></xsl:if></xsl:template></xsl:stylesheet>"
' This constant has the `omit-xml-declaration="yes"` added to remove XML declarations.
Const strIndentXsltNoDeclarations As String = "<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" version=""1.0""><xsl:output method=""xml"" omit-xml-declaration=""yes""/><xsl:template match=""@*""><xsl:copy/></xsl:template><xsl:template match=""text()""><xsl:value-of select=""normalize-space(.)"" /></xsl:template><xsl:template match=""*""><xsl:param name=""indent"" select=""''""/><xsl:text>
</xsl:text><xsl:value-of select=""$indent"" /><xsl:copy><xsl:apply-templates select=""@*|*|text()""><xsl:with-param name=""indent"" select=""concat($indent, ' ')""/></xsl:apply-templates></xsl:copy><xsl:if test=""count(../*)>0 and ../*[last()]=.""><xsl:text>
</xsl:text><xsl:value-of select=""substring($indent,3)"" /></xsl:if></xsl:template></xsl:stylesheet>"
Dim objInput As MSXML2.DOMDocument60
Dim objTransform As MSXML2.DOMDocument60
Dim objOutput As MSXML2.DOMDocument60
Dim strOutput As String
' Skip processing if no content to format
If strSourceXML = vbNullString Then Exit Function
Perf.OperationStart "Format XML"
' Trap any errors with parsing or formatting the XML
If DebugMode(True) Then On Error GoTo 0 Else On Error Resume Next
Set objInput = New MSXML2.DOMDocument60
Set objTransform = New MSXML2.DOMDocument60
Set objOutput = New MSXML2.DOMDocument60
' Set up transform
If blnOmitDeclaration Then
objTransform.LoadXML strIndentXsltNoDeclarations
Else
objTransform.LoadXML strIndentXslt
End If
' Set up DOM documents
objInput.LoadXML strSourceXML
' Transform the input
objInput.transformNodeToObject objTransform, objOutput
strOutput = objOutput.XML
' Check for any errors parsing the XML
If CatchAny(eelError, "Error parsing XML content", ModuleName & ".FormatXML") Then
' Fall back to input XML
strOutput = strSourceXML
' Output XML to log file
Log.Spacer False
Log.Add strSourceXML, False
Log.Spacer False
End If
' Return formatted output
Perf.OperationEnd
FormatXML = strOutput
End Function
'---------------------------------------------------------------------------------------
' Procedure : CustomIndent
' Author : Adam Waller
' Date : 2/16/2022
' Purpose : Convert tabbed indents to two spaces for more compact display
'---------------------------------------------------------------------------------------
'
Private Function CustomIndent(strText As String, Optional intSpaces As Integer = 2) As String
Dim lngLine As Long
Dim varLines As Variant
Dim strLine As String
Dim lngPos As Long
' Split content into lines
varLines = Split(strText, vbCrLf)
' Rebuild while converting tabs to
With New clsConcat
.AppendOnAdd = vbCrLf
' Loop through lines
For lngLine = 0 To UBound(varLines)
strLine = varLines(lngLine)
For lngPos = 1 To Len(strLine)
If Mid$(strLine, lngPos, 1) <> vbTab Then
' Replace any leading tabs with space indent
.Add Space$(intSpaces * (lngPos - 1)), Mid$(strLine, lngPos)
Exit For
End If
Next lngPos
Next lngLine
' Return result after trimming off last return
If lngLine > 0 Then .Remove 2
CustomIndent = .GetStr
End With
End Function