Bug: VB.NET Compatibility Setting using LINQ

In my last post I showed how to change the target version of Word for a document using the Open XML SDK in order to ensure that “[Compatibility Mode]” does not appear in the document’s title bar. The code sample was in C#.

In this post I provide the code sample for VB.NET. Due to a bug in VB.NET Linq, it’s not possible to use the same “simple” approach as for C#. VB.NET Linq does not recognize the URI property as a property for the Compatibility Setting. The VB.NET equivalent of the C# approach (included near the end of the code sample, but commented out) causes an error.

So you have to go about it another way. Notice how it’s first necessary to create a new CompatibilitySetting, then set each property individually, rather than being able to create and set the properties in one efficient Linq command.

Private Sub AddSettingsToMainDocumentPart( _
                   ByVal part As MainDocumentPart)
  Dim hasSettings As Boolean = False
  Dim settings As Settings = Nothing
  Dim settingsParts As IEnumerable( _
      Of DocumentSettingsPart) = part.GetPartsOfType( _
                                Of DocumentSettingsPart)()
  Dim settingsPart As DocumentSettingsPart = Nothing
 'Check if document already has a settings part
  If settingsParts.Count < 1 Then
       settingsPart = part.AddNewPart( _
                      Of DocumentSettingsPart)()
   Else
       settingsPart = settingsParts(1)
       hasSettings = True
   End If
   If Not hasSettings Then
       settings = New Settings
   Else
       settings = settingsPart.Settings
   End If
   Dim compat As Compatibility = New Compatibility
   Dim compatSetting As CompatibilitySetting = _
       New CompatibilitySetting
   compatSetting.Name = New EnumValue( _
                       Of CompatSettingNameValues)( _
                          CompatSettingNameValues.CompatibilityMode)
   compatSetting.Val = "14"
   compatSetting.Uri = _
     "http://schemas.microsoft.com/office/word"
   compat.Append(compatSetting)
   Settings.Append(compat)
   settingsPart.Settings.Append(Settings)

   '''Using a Linq expression doesn't work due to bug
   'Dim compat As Compatibility = New Compatibility() {
   '    New CompatibilitySetting() {
   '        Name = New EnumValue( _
   '          Of CompatSettingNameValues)( _
                 CompatSettingNameValues.CompatibilityMode),
   '        Val("14"),
   '''PROBLEM HERE:
   '        Uri = "http://schemas.microsoft.com/office/word"
   '      }}

   settingsPart.Settings.Save()
End Sub


Leave a Reply