From 2b284b6c7e9f3c609ca2764a6892f9389c30c3f4 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Fri, 27 Oct 2023 10:35:26 -0700 Subject: [PATCH 1/8] fix presentation samples --- .../cs/Program.cs | 524 +++++++++--------- .../cs/Program.cs | 54 +- 2 files changed, 290 insertions(+), 288 deletions(-) diff --git a/samples/presentation/create_by_providing_a_file_name/cs/Program.cs b/samples/presentation/create_by_providing_a_file_name/cs/Program.cs index 9aa90187..b709b998 100644 --- a/samples/presentation/create_by_providing_a_file_name/cs/Program.cs +++ b/samples/presentation/create_by_providing_a_file_name/cs/Program.cs @@ -1,4 +1,3 @@ -#nullable disable using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Drawing; using DocumentFormat.OpenXml.Packaging; @@ -6,289 +5,280 @@ using D = DocumentFormat.OpenXml.Drawing; using P = DocumentFormat.OpenXml.Presentation; -namespace CreatePresentationDocument -{ - class Program - { - static void Main(string[] args) - { - string filepath = @"C:\Users\username\Documents\PresentationFromFilename.pptx"; - CreatePresentation(filepath); - } - public static void CreatePresentation(string filepath) - { - // Create a presentation at a specified file path. The presentation document type is pptx, by default. - PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); - PresentationPart presentationPart = presentationDoc.AddPresentationPart(); - presentationPart.Presentation = new Presentation(); +CreatePresentation(args[0]); - CreatePresentationParts(presentationPart); +static void CreatePresentation(string filepath) +{ + // Create a presentation at a specified file path. The presentation document type is pptx, by default. + PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); + PresentationPart presentationPart = presentationDoc.AddPresentationPart(); + presentationPart.Presentation = new Presentation(); - //Dispose the presentation handle - presentationDoc.Dispose(); - } + CreatePresentationParts(presentationPart); - private static void CreatePresentationParts(PresentationPart presentationPart) - { - SlideMasterIdList slideMasterIdList1 = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" }); - SlideIdList slideIdList1 = new SlideIdList(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" }); - SlideSize slideSize1 = new SlideSize() { Cx = 9144000, Cy = 6858000, Type = SlideSizeValues.Screen4x3 }; - NotesSize notesSize1 = new NotesSize() { Cx = 6858000, Cy = 9144000 }; - DefaultTextStyle defaultTextStyle1 = new DefaultTextStyle(); + //Dispose the presentation handle + presentationDoc.Dispose(); +} - presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1, defaultTextStyle1); +static void CreatePresentationParts(PresentationPart presentationPart) +{ + SlideMasterIdList slideMasterIdList1 = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" }); + SlideIdList slideIdList1 = new SlideIdList(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" }); + SlideSize slideSize1 = new SlideSize() { Cx = 9144000, Cy = 6858000, Type = SlideSizeValues.Screen4x3 }; + NotesSize notesSize1 = new NotesSize() { Cx = 6858000, Cy = 9144000 }; + DefaultTextStyle defaultTextStyle1 = new DefaultTextStyle(); - SlidePart slidePart1; - SlideLayoutPart slideLayoutPart1; - SlideMasterPart slideMasterPart1; - ThemePart themePart1; + presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1, defaultTextStyle1); + SlidePart slidePart1; + SlideLayoutPart slideLayoutPart1; + SlideMasterPart slideMasterPart1; + ThemePart themePart1; - slidePart1 = CreateSlidePart(presentationPart); - slideLayoutPart1 = CreateSlideLayoutPart(slidePart1); - slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1); - themePart1 = CreateTheme(slideMasterPart1); - slideMasterPart1.AddPart(slideLayoutPart1, "rId1"); - presentationPart.AddPart(slideMasterPart1, "rId1"); - presentationPart.AddPart(themePart1, "rId5"); - } + slidePart1 = CreateSlidePart(presentationPart); + slideLayoutPart1 = CreateSlideLayoutPart(slidePart1); + slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1); + themePart1 = CreateTheme(slideMasterPart1); - private static SlidePart CreateSlidePart(PresentationPart presentationPart) - { - SlidePart slidePart1 = presentationPart.AddNewPart("rId2"); - slidePart1.Slide = new Slide( - new CommonSlideData( - new ShapeTree( - new P.NonVisualGroupShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, - new P.NonVisualGroupShapeDrawingProperties(), - new ApplicationNonVisualDrawingProperties()), - new GroupShapeProperties(new TransformGroup()), - new P.Shape( - new P.NonVisualShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" }, - new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), - new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), - new P.ShapeProperties(), - new P.TextBody( - new BodyProperties(), - new ListStyle(), - new Paragraph(new EndParagraphRunProperties() { Language = "en-US" }))))), - new ColorMapOverride(new MasterColorMapping())); - return slidePart1; - } + slideMasterPart1.AddPart(slideLayoutPart1, "rId1"); + presentationPart.AddPart(slideMasterPart1, "rId1"); + presentationPart.AddPart(themePart1, "rId5"); +} - private static SlideLayoutPart CreateSlideLayoutPart(SlidePart slidePart1) - { - SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart("rId1"); - SlideLayout slideLayout = new SlideLayout( - new CommonSlideData(new ShapeTree( - new P.NonVisualGroupShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, - new P.NonVisualGroupShapeDrawingProperties(), - new ApplicationNonVisualDrawingProperties()), - new GroupShapeProperties(new TransformGroup()), - new P.Shape( - new P.NonVisualShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "" }, - new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), - new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), - new P.ShapeProperties(), - new P.TextBody( - new BodyProperties(), - new ListStyle(), - new Paragraph(new EndParagraphRunProperties()))))), +static SlidePart CreateSlidePart(PresentationPart presentationPart) +{ + SlidePart slidePart1 = presentationPart.AddNewPart("rId2"); + slidePart1.Slide = new Slide( + new CommonSlideData( + new ShapeTree( + new P.NonVisualGroupShapeProperties( + new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, + new P.NonVisualGroupShapeDrawingProperties(), + new ApplicationNonVisualDrawingProperties()), + new GroupShapeProperties(new TransformGroup()), + new P.Shape( + new P.NonVisualShapeProperties( + new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" }, + new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), + new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), + new P.ShapeProperties(), + new P.TextBody( + new BodyProperties(), + new ListStyle(), + new Paragraph(new EndParagraphRunProperties() { Language = "en-US" }))))), new ColorMapOverride(new MasterColorMapping())); - slideLayoutPart1.SlideLayout = slideLayout; - return slideLayoutPart1; - } + return slidePart1; +} - private static SlideMasterPart CreateSlideMasterPart(SlideLayoutPart slideLayoutPart1) - { - SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart("rId1"); - SlideMaster slideMaster = new SlideMaster( - new CommonSlideData(new ShapeTree( - new P.NonVisualGroupShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, - new P.NonVisualGroupShapeDrawingProperties(), - new ApplicationNonVisualDrawingProperties()), - new GroupShapeProperties(new TransformGroup()), - new P.Shape( - new P.NonVisualShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" }, - new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), - new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })), - new P.ShapeProperties(), - new P.TextBody( - new BodyProperties(), - new ListStyle(), - new Paragraph())))), - new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1, Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2, Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2, Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4, Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6, Hyperlink = D.ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink }, - new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }), - new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle())); - slideMasterPart1.SlideMaster = slideMaster; +static SlideLayoutPart CreateSlideLayoutPart(SlidePart slidePart1) +{ + SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart("rId1"); + SlideLayout slideLayout = new SlideLayout( + new CommonSlideData(new ShapeTree( + new P.NonVisualGroupShapeProperties( + new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, + new P.NonVisualGroupShapeDrawingProperties(), + new ApplicationNonVisualDrawingProperties()), + new GroupShapeProperties(new TransformGroup()), + new P.Shape( + new P.NonVisualShapeProperties( + new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "" }, + new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), + new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), + new P.ShapeProperties(), + new P.TextBody( + new BodyProperties(), + new ListStyle(), + new Paragraph(new EndParagraphRunProperties()))))), + new ColorMapOverride(new MasterColorMapping())); + slideLayoutPart1.SlideLayout = slideLayout; + return slideLayoutPart1; +} + +static SlideMasterPart CreateSlideMasterPart(SlideLayoutPart slideLayoutPart1) +{ + SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart("rId1"); + SlideMaster slideMaster = new SlideMaster( + new CommonSlideData(new ShapeTree( + new P.NonVisualGroupShapeProperties( + new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, + new P.NonVisualGroupShapeDrawingProperties(), + new ApplicationNonVisualDrawingProperties()), + new GroupShapeProperties(new TransformGroup()), + new P.Shape( + new P.NonVisualShapeProperties( + new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" }, + new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), + new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })), + new P.ShapeProperties(), + new P.TextBody( + new BodyProperties(), + new ListStyle(), + new Paragraph())))), + new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1, Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2, Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2, Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4, Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6, Hyperlink = D.ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink }, + new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }), + new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle())); + slideMasterPart1.SlideMaster = slideMaster; - return slideMasterPart1; - } + return slideMasterPart1; +} - private static ThemePart CreateTheme(SlideMasterPart slideMasterPart1) - { - ThemePart themePart1 = slideMasterPart1.AddNewPart("rId5"); - D.Theme theme1 = new D.Theme() { Name = "Office Theme" }; +static ThemePart CreateTheme(SlideMasterPart slideMasterPart1) +{ + ThemePart themePart1 = slideMasterPart1.AddNewPart("rId5"); + D.Theme theme1 = new D.Theme() { Name = "Office Theme" }; - D.ThemeElements themeElements1 = new D.ThemeElements( - new D.ColorScheme( - new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }), - new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }), - new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }), - new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }), - new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }), - new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }), - new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }), - new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }), - new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }), - new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }), - new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }), - new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" })) - { Name = "Office" }, - new D.FontScheme( - new D.MajorFont( - new D.LatinFont() { Typeface = "Calibri" }, - new D.EastAsianFont() { Typeface = "" }, - new D.ComplexScriptFont() { Typeface = "" }), - new D.MinorFont( - new D.LatinFont() { Typeface = "Calibri" }, - new D.EastAsianFont() { Typeface = "" }, - new D.ComplexScriptFont() { Typeface = "" })) - { Name = "Office" }, - new D.FormatScheme( - new D.FillStyleList( - new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }), - new D.GradientFill( - new D.GradientStopList( - new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 0 }, - new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 35000 }, - new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 }, - new D.SaturationModulation() { Val = 350000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 100000 } - ), - new D.LinearGradientFill() { Angle = 16200000, Scaled = true }), - new D.NoFill(), - new D.PatternFill(), - new D.GroupFill()), - new D.LineStyleList( - new D.Outline( - new D.SolidFill( - new D.SchemeColor( - new D.Shade() { Val = 95000 }, - new D.SaturationModulation() { Val = 105000 }) - { Val = D.SchemeColorValues.PhColor }), - new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) - { - Width = 9525, - CapType = D.LineCapValues.Flat, - CompoundLineType = D.CompoundLineValues.Single, - Alignment = D.PenAlignmentValues.Center - }, - new D.Outline( - new D.SolidFill( - new D.SchemeColor( - new D.Shade() { Val = 95000 }, - new D.SaturationModulation() { Val = 105000 }) - { Val = D.SchemeColorValues.PhColor }), - new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) - { - Width = 9525, - CapType = D.LineCapValues.Flat, - CompoundLineType = D.CompoundLineValues.Single, - Alignment = D.PenAlignmentValues.Center - }, - new D.Outline( - new D.SolidFill( - new D.SchemeColor( - new D.Shade() { Val = 95000 }, - new D.SaturationModulation() { Val = 105000 }) - { Val = D.SchemeColorValues.PhColor }), - new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) - { - Width = 9525, - CapType = D.LineCapValues.Flat, - CompoundLineType = D.CompoundLineValues.Single, - Alignment = D.PenAlignmentValues.Center - }), - new D.EffectStyleList( - new D.EffectStyle( - new D.EffectList( - new D.OuterShadow( - new D.RgbColorModelHex( - new D.Alpha() { Val = 38000 }) - { Val = "000000" }) - { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })), - new D.EffectStyle( - new D.EffectList( - new D.OuterShadow( - new D.RgbColorModelHex( - new D.Alpha() { Val = 38000 }) - { Val = "000000" }) - { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })), - new D.EffectStyle( - new D.EffectList( - new D.OuterShadow( - new D.RgbColorModelHex( - new D.Alpha() { Val = 38000 }) - { Val = "000000" }) - { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))), - new D.BackgroundFillStyleList( - new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }), - new D.GradientFill( - new D.GradientStopList( - new D.GradientStop( - new D.SchemeColor(new D.Tint() { Val = 50000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 0 }, - new D.GradientStop( - new D.SchemeColor(new D.Tint() { Val = 50000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 0 }, - new D.GradientStop( - new D.SchemeColor(new D.Tint() { Val = 50000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 0 }), - new D.LinearGradientFill() { Angle = 16200000, Scaled = true }), - new D.GradientFill( - new D.GradientStopList( - new D.GradientStop( - new D.SchemeColor(new D.Tint() { Val = 50000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 0 }, - new D.GradientStop( - new D.SchemeColor(new D.Tint() { Val = 50000 }, - new D.SaturationModulation() { Val = 300000 }) - { Val = D.SchemeColorValues.PhColor }) - { Position = 0 }), - new D.LinearGradientFill() { Angle = 16200000, Scaled = true }))) - { Name = "Office" }); + D.ThemeElements themeElements1 = new D.ThemeElements( + new D.ColorScheme( + new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }), + new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }), + new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }), + new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }), + new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }), + new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }), + new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }), + new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }), + new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }), + new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }), + new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }), + new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" })) + { Name = "Office" }, + new D.FontScheme( + new D.MajorFont( + new D.LatinFont() { Typeface = "Calibri" }, + new D.EastAsianFont() { Typeface = "" }, + new D.ComplexScriptFont() { Typeface = "" }), + new D.MinorFont( + new D.LatinFont() { Typeface = "Calibri" }, + new D.EastAsianFont() { Typeface = "" }, + new D.ComplexScriptFont() { Typeface = "" })) + { Name = "Office" }, + new D.FormatScheme( + new D.FillStyleList( + new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }), + new D.GradientFill( + new D.GradientStopList( + new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 0 }, + new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 35000 }, + new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 }, + new D.SaturationModulation() { Val = 350000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 100000 } + ), + new D.LinearGradientFill() { Angle = 16200000, Scaled = true }), + new D.NoFill(), + new D.PatternFill(), + new D.GroupFill()), + new D.LineStyleList( + new D.Outline( + new D.SolidFill( + new D.SchemeColor( + new D.Shade() { Val = 95000 }, + new D.SaturationModulation() { Val = 105000 }) + { Val = D.SchemeColorValues.PhColor }), + new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) + { + Width = 9525, + CapType = D.LineCapValues.Flat, + CompoundLineType = D.CompoundLineValues.Single, + Alignment = D.PenAlignmentValues.Center + }, + new D.Outline( + new D.SolidFill( + new D.SchemeColor( + new D.Shade() { Val = 95000 }, + new D.SaturationModulation() { Val = 105000 }) + { Val = D.SchemeColorValues.PhColor }), + new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) + { + Width = 9525, + CapType = D.LineCapValues.Flat, + CompoundLineType = D.CompoundLineValues.Single, + Alignment = D.PenAlignmentValues.Center + }, + new D.Outline( + new D.SolidFill( + new D.SchemeColor( + new D.Shade() { Val = 95000 }, + new D.SaturationModulation() { Val = 105000 }) + { Val = D.SchemeColorValues.PhColor }), + new D.PresetDash() { Val = D.PresetLineDashValues.Solid }) + { + Width = 9525, + CapType = D.LineCapValues.Flat, + CompoundLineType = D.CompoundLineValues.Single, + Alignment = D.PenAlignmentValues.Center + }), + new D.EffectStyleList( + new D.EffectStyle( + new D.EffectList( + new D.OuterShadow( + new D.RgbColorModelHex( + new D.Alpha() { Val = 38000 }) + { Val = "000000" }) + { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })), + new D.EffectStyle( + new D.EffectList( + new D.OuterShadow( + new D.RgbColorModelHex( + new D.Alpha() { Val = 38000 }) + { Val = "000000" }) + { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })), + new D.EffectStyle( + new D.EffectList( + new D.OuterShadow( + new D.RgbColorModelHex( + new D.Alpha() { Val = 38000 }) + { Val = "000000" }) + { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))), + new D.BackgroundFillStyleList( + new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }), + new D.GradientFill( + new D.GradientStopList( + new D.GradientStop( + new D.SchemeColor(new D.Tint() { Val = 50000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 0 }, + new D.GradientStop( + new D.SchemeColor(new D.Tint() { Val = 50000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 0 }, + new D.GradientStop( + new D.SchemeColor(new D.Tint() { Val = 50000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 0 }), + new D.LinearGradientFill() { Angle = 16200000, Scaled = true }), + new D.GradientFill( + new D.GradientStopList( + new D.GradientStop( + new D.SchemeColor(new D.Tint() { Val = 50000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 0 }, + new D.GradientStop( + new D.SchemeColor(new D.Tint() { Val = 50000 }, + new D.SaturationModulation() { Val = 300000 }) + { Val = D.SchemeColorValues.PhColor }) + { Position = 0 }), + new D.LinearGradientFill() { Angle = 16200000, Scaled = true }))) + { Name = "Office" }); - theme1.Append(themeElements1); - theme1.Append(new D.ObjectDefaults()); - theme1.Append(new D.ExtraColorSchemeList()); + theme1.Append(themeElements1); + theme1.Append(new D.ObjectDefaults()); + theme1.Append(new D.ExtraColorSchemeList()); - themePart1.Theme = theme1; - return themePart1; + themePart1.Theme = theme1; + return themePart1; - } - } } \ No newline at end of file diff --git a/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs b/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs index f87499df..fd2ff345 100644 --- a/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs +++ b/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs @@ -1,37 +1,49 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using System; using System.Linq; +if (args.Length >= 2) +{ + RetrieveNumberOfSlides(args[0], args[1]); +} +else +{ + RetrieveNumberOfSlides(args[0]); +} + static int RetrieveNumberOfSlides(string fileName, - bool includeHidden = true) + string includeHidden = "true") { int slidesCount = 0; - using (PresentationDocument doc = - PresentationDocument.Open(fileName, false)) + using (PresentationDocument doc = PresentationDocument.Open(fileName, false)) { - // Get the presentation part of the document. - PresentationPart presentationPart = doc.PresentationPart; - if (presentationPart != null) + if (doc is not null && doc.PresentationPart is not null) { - if (includeHidden) + // Get the presentation part of the document. + PresentationPart presentationPart = doc.PresentationPart; + if (presentationPart is not null) { - slidesCount = presentationPart.SlideParts.Count(); - } - else - { - // Each slide can include a Show property, which if hidden - // will contain the value "0". The Show property may not - // exist, and most likely will not, for non-hidden slides. - var slides = presentationPart.SlideParts.Where( - (s) => (s.Slide != null) && - ((s.Slide.Show == null) || (s.Slide.Show.HasValue && - s.Slide.Show.Value))); - slidesCount = slides.Count(); + if (includeHidden.ToLower() == "true") + { + slidesCount = presentationPart.SlideParts.Count(); + } + else + { + // Each slide can include a Show property, which if hidden + // will contain the value "0". The Show property may not + // exist, and most likely will not, for non-hidden slides. + var slides = presentationPart.SlideParts.Where( + (s) => (s.Slide is not null) && + ((s.Slide.Show is null) || (s.Slide.Show.HasValue && s.Slide.Show.Value))); + + slidesCount = slides.Count(); + } } } } + + Console.WriteLine($"Slide Count: {slidesCount}"); + return slidesCount; } \ No newline at end of file From 5944149bbefc80a2e12ad32f3aa3d341f2037796 Mon Sep 17 00:00:00 2001 From: Tom Jebo Date: Fri, 27 Oct 2023 19:43:22 -0700 Subject: [PATCH 2/8] cs files updated for nullable enable --- .../cs/Program.cs | 2 +- .../word/accept_all_revisions/cs/Program.cs | 25 +++++++++------- samples/word/add_tables/cs/Program.cs | 10 ++++--- .../word/change_text_a_table/cs/Program.cs | 11 ++++--- .../cs/Program.cs | 22 ++++++++++---- .../cs/Program.cs | 4 +-- .../cs/Program.cs | 9 ++++-- .../cs/Program.cs | 13 ++++++-- .../cs/Program.cs | 18 ++++++----- samples/word/extract_styles/cs/Program.cs | 25 ++++++++-------- samples/word/insert_a_comment/cs/Program.cs | 13 +++++--- samples/word/insert_a_picture/cs/Program.cs | 12 ++++++-- samples/word/insert_a_table/cs/Program.cs | 7 +++-- samples/word/remove_hidden_text/cs/Program.cs | 26 ++++++++++++++-- .../cs/Program.cs | 7 +++-- samples/word/replace_the_header/cs/Program.cs | 19 ++++++++++-- .../replace_the_styles_parts/cs/Program.cs | 30 +++++++++++-------- .../word/replace_the_theme_part/cs/Program.cs | 7 +++-- .../cs/Program.cs | 7 +++-- samples/word/retrieve_comments/cs/Program.cs | 7 +++-- .../cs/Program.cs | 11 +++++-- .../word/set_a_custom_property/cs/Program.cs | 23 ++++++++------ .../set_the_font_for_a_text_run/cs/Program.cs | 7 +++-- samples/word/validate/cs/Program.cs | 28 +++++++++++++---- 24 files changed, 236 insertions(+), 107 deletions(-) diff --git a/samples/presentation/create_by_providing_a_file_name/cs/Program.cs b/samples/presentation/create_by_providing_a_file_name/cs/Program.cs index b709b998..bc21e9e6 100644 --- a/samples/presentation/create_by_providing_a_file_name/cs/Program.cs +++ b/samples/presentation/create_by_providing_a_file_name/cs/Program.cs @@ -281,4 +281,4 @@ static ThemePart CreateTheme(SlideMasterPart slideMasterPart1) themePart1.Theme = theme1; return themePart1; -} \ No newline at end of file +} diff --git a/samples/word/accept_all_revisions/cs/Program.cs b/samples/word/accept_all_revisions/cs/Program.cs index bef0e76b..0ca65ef0 100644 --- a/samples/word/accept_all_revisions/cs/Program.cs +++ b/samples/word/accept_all_revisions/cs/Program.cs @@ -1,5 +1,4 @@ -#nullable disable -using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.Collections.Generic; @@ -10,11 +9,16 @@ using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(fileName, true)) { + if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + Body body = wdDoc.MainDocumentPart.Document.Body; // Handle the formatting changes. List changes = body.Descendants() - .Where(c => c.Author.Value == authorName).Cast().ToList(); + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList(); foreach (OpenXmlElement change in changes) { @@ -24,14 +28,14 @@ // Handle the deletions. List deletions = body .Descendants() - .Where(c => c.Author.Value == authorName) + .Where(c => c.Author is not null && c.Author.Value == authorName) .Cast().ToList(); deletions.AddRange(body.Descendants() - .Where(c => c.Author.Value == authorName).Cast().ToList()); + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); deletions.AddRange(body.Descendants() - .Where(c => c.Author.Value == authorName).Cast().ToList()); + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); foreach (OpenXmlElement deletion in deletions) { @@ -41,13 +45,13 @@ // Handle the insertions. List insertions = body.Descendants() - .Where(c => c.Author.Value == authorName).Cast().ToList(); + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList(); insertions.AddRange(body.Descendants() - .Where(c => c.Author.Value == authorName).Cast().ToList()); + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); insertions.AddRange(body.Descendants() - .Where(c => c.Author.Value == authorName).Cast().ToList()); + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); foreach (OpenXmlElement insertion in insertions) { @@ -61,7 +65,8 @@ } else { - insertion.NextSibling().InsertAfterSelf(new Run(run.OuterXml)); + OpenXmlElement? nextSibling = insertion.NextSibling() ?? throw new System.NullReferenceException("NextSibling is null."); + nextSibling.InsertAfterSelf(new Run(run.OuterXml)); } } diff --git a/samples/word/add_tables/cs/Program.cs b/samples/word/add_tables/cs/Program.cs index 0ebbb446..afcfe21b 100644 --- a/samples/word/add_tables/cs/Program.cs +++ b/samples/word/add_tables/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -10,12 +8,16 @@ static void AddTable(string fileName, string[,] data) { using (var document = WordprocessingDocument.Open(fileName, true)) { + if (document.MainDocumentPart is null || document.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } var doc = document.MainDocumentPart.Document; - Table table = new Table(); + Table table = new(); - TableProperties props = new TableProperties( + TableProperties props = new( new TableBorders( new TopBorder { diff --git a/samples/word/change_text_a_table/cs/Program.cs b/samples/word/change_text_a_table/cs/Program.cs index e494c04f..51404c14 100644 --- a/samples/word/change_text_a_table/cs/Program.cs +++ b/samples/word/change_text_a_table/cs/Program.cs @@ -1,17 +1,20 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; // Change the text in a table in a word processing document. -static void ChangeTextInCell(string filepath, string txt) +static void ChangeTextInCell(string filePath, string txt) { // Use the file name and path passed in as an argument to // open an existing document. using (WordprocessingDocument doc = - WordprocessingDocument.Open(filepath, true)) + WordprocessingDocument.Open(filePath, true)) { + if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + // Find the first table in the document. Table table = doc.MainDocumentPart.Document.Body.Elements().First(); diff --git a/samples/word/change_the_print_orientation/cs/Program.cs b/samples/word/change_the_print_orientation/cs/Program.cs index 25ba5bdd..663ed791 100644 --- a/samples/word/change_the_print_orientation/cs/Program.cs +++ b/samples/word/change_the_print_orientation/cs/Program.cs @@ -1,4 +1,4 @@ -#nullable disable +#nullable enable using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; @@ -9,7 +9,7 @@ namespace ChangePrintOrientation { class Program { - static void Main(string[] args) + static void Main() { SetPrintOrientation(@"C:\Users\Public\Documents\ChangePrintOrientation.docx", PageOrientationValues.Landscape); @@ -25,14 +25,21 @@ public static void SetPrintOrientation( { bool documentChanged = false; + if (document.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + var docPart = document.MainDocumentPart; + + var sections = docPart.Document.Descendants(); foreach (SectionProperties sectPr in sections) { bool pageOrientationChanged = false; - PageSize pgSz = sectPr.Descendants().FirstOrDefault(); + PageSize pgSz = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageSize elements in the section."); if (pgSz != null) { // No Orient property? Create it now. Otherwise, just @@ -73,8 +80,8 @@ public static void SetPrintOrientation( pgSz.Width = height; pgSz.Height = width; - PageMargin pgMar = - sectPr.Descendants().FirstOrDefault(); + PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageMargin elements in the section."); + if (pgMar != null) { // Rotate margins. Printer settings control how far you @@ -82,6 +89,11 @@ public static void SetPrintOrientation( // settings, this code rotates 90 degrees. You could easily // modify this behavior, or make it a parameter for the // procedure. + if (pgMar.Top is null || pgMar.Bottom is null || pgMar.Left is null || pgMar.Right is null) + { + throw new System.NullReferenceException("One or more of the PageMargin elements is null."); + } + var top = pgMar.Top.Value; var bottom = pgMar.Bottom.Value; var left = pgMar.Left.Value; diff --git a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs index dc7a226a..e4e70a2c 100644 --- a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs +++ b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using System.IO; @@ -14,7 +12,7 @@ static void ConvertDOCMtoDOCX(string fileName) WordprocessingDocument.Open(fileName, true)) { // Access the main document part. - var docPart = document.MainDocumentPart; + var docPart = document.MainDocumentPart ?? throw new System.NullReferenceException("MainDocumentPart is null."); // Look for the vbaProject part. If it is there, delete it. var vbaPart = docPart.VbaProjectPart; diff --git a/samples/word/create_and_add_a_character_style/cs/Program.cs b/samples/word/create_and_add_a_character_style/cs/Program.cs index 7b57a2a3..86da2019 100644 --- a/samples/word/create_and_add_a_character_style/cs/Program.cs +++ b/samples/word/create_and_add_a_character_style/cs/Program.cs @@ -1,4 +1,3 @@ -#nullable disable using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -8,7 +7,7 @@ static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart string styleid, string stylename, string aliases = "") { // Get access to the root element of the styles part. - Styles styles = styleDefinitionsPart.Styles; + Styles styles = styleDefinitionsPart.Styles ?? throw new System.NullReferenceException("Styles is null."); // Create a new character style and specify some of the attributes. Style style = new Style() @@ -52,6 +51,12 @@ static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc) { StyleDefinitionsPart part; + + if (doc.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart is null."); + } + part = doc.MainDocumentPart.AddNewPart(); Styles root = new Styles(); root.Save(part); diff --git a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs index 408aa16d..6134fc68 100644 --- a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs +++ b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs @@ -1,4 +1,3 @@ -#nullable disable using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -8,11 +7,13 @@ static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart string styleid, string stylename, string aliases = "") { // Access the root element of the styles part. - Styles styles = styleDefinitionsPart.Styles; - if (styles == null) + Styles? styles = styleDefinitionsPart.Styles; + + if (styles is null) { styleDefinitionsPart.Styles = new Styles(); styleDefinitionsPart.Styles.Save(); + styles = styleDefinitionsPart.Styles; } // Create a new paragraph style element and specify some of the attributes. @@ -76,6 +77,12 @@ static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc) { StyleDefinitionsPart part; + + if (doc.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart is null."); + } + part = doc.MainDocumentPart.AddNewPart(); Styles root = new Styles(); root.Save(part); diff --git a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs index 3f5afcda..5128a96e 100644 --- a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs +++ b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; @@ -14,6 +12,12 @@ static void DeleteComments(string fileName, // Get an existing Wordprocessing document. using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { + + if (document.MainDocumentPart is null || document.MainDocumentPart.WordprocessingCommentsPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or WordprocessingCommentsPart is null."); + } + // Set commentPart to the document WordprocessingCommentsPart, // if it exists. WordprocessingCommentsPart commentPart = @@ -35,8 +39,8 @@ static void DeleteComments(string fileName, commentsToDelete = commentsToDelete. Where(c => c.Author == author).ToList(); } - IEnumerable commentIds = - commentsToDelete.Select(r => r.Id.Value); + IEnumerable commentIds = + commentsToDelete.Where(r => r.Id is not null && r.Id.HasValue).Select(r => r.Id?.Value); // Delete each comment in commentToDelete from the // Comments collection. @@ -54,7 +58,7 @@ static void DeleteComments(string fileName, // deleted comment in the main document. List commentRangeStartToDelete = doc.Descendants(). - Where(c => commentIds.Contains(c.Id.Value)).ToList(); + Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)).ToList(); foreach (CommentRangeStart c in commentRangeStartToDelete) { c.Remove(); @@ -63,7 +67,7 @@ static void DeleteComments(string fileName, // Delete CommentRangeEnd for each deleted comment in the main document. List commentRangeEndToDelete = doc.Descendants(). - Where(c => commentIds.Contains(c.Id.Value)).ToList(); + Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)).ToList(); foreach (CommentRangeEnd c in commentRangeEndToDelete) { c.Remove(); @@ -72,7 +76,7 @@ static void DeleteComments(string fileName, // Delete CommentReference for each deleted comment in the main document. List commentRangeReferenceToDelete = doc.Descendants(). - Where(c => commentIds.Contains(c.Id.Value)).ToList(); + Where(c => c.Id is not null && c.Id.HasValue && commentIds.Contains(c.Id.Value)).ToList(); foreach (CommentReference c in commentRangeReferenceToDelete) { c.Remove(); diff --git a/samples/word/extract_styles/cs/Program.cs b/samples/word/extract_styles/cs/Program.cs index 7d6aa6cf..2741bf01 100644 --- a/samples/word/extract_styles/cs/Program.cs +++ b/samples/word/extract_styles/cs/Program.cs @@ -1,4 +1,3 @@ -#nullable disable using DocumentFormat.OpenXml.Packaging; using System.IO; using System.Xml; @@ -11,33 +10,33 @@ static XDocument ExtractStylesPart( bool getStylesWithEffectsPart = true) { // Declare a variable to hold the XDocument. - XDocument styles = null; + XDocument? styles = null; // Open the document for read access and get a reference. using (var document = WordprocessingDocument.Open(fileName, false)) { + if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or one or both of the Styles parts is null."); + } + // Get a reference to the main document part. var docPart = document.MainDocumentPart; // Assign a reference to the appropriate part to the // stylesPart variable. - StylesPart stylesPart = null; + StylesPart? stylesPart = null; if (getStylesWithEffectsPart) stylesPart = docPart.StylesWithEffectsPart; else stylesPart = docPart.StyleDefinitionsPart; - // If the part exists, read it into the XDocument. - if (stylesPart != null) - { - using (var reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read))) - { - // Create the XDocument. - styles = XDocument.Load(reader); - } - } + using var reader = XmlNodeReader.Create( + stylesPart.GetStream(FileMode.Open, FileAccess.Read)); + + // Create the XDocument. + styles = XDocument.Load(reader); } // Return the XDocument instance. return styles; diff --git a/samples/word/insert_a_comment/cs/Program.cs b/samples/word/insert_a_comment/cs/Program.cs index 428f0440..9cf53d00 100644 --- a/samples/word/insert_a_comment/cs/Program.cs +++ b/samples/word/insert_a_comment/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; @@ -14,10 +12,16 @@ static void AddCommentOnFirstParagraph(string fileName, using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { + + if (document.MainDocumentPart is null || document.MainDocumentPart.WordprocessingCommentsPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + // Locate the first paragraph in the document. Paragraph firstParagraph = document.MainDocumentPart.Document.Descendants().First(); - Comments comments = null; + Comments? comments = null; string id = "0"; // Verify that the document contains a @@ -28,7 +32,8 @@ static void AddCommentOnFirstParagraph(string fileName, if (comments.HasChildren) { // Obtain an unused ID. - id = (comments.Descendants().Select(e => int.Parse(e.Id.Value)).Max() + 1).ToString(); + id = (comments.Descendants().Select(e => { if (e.Id is not null && e.Id.Value is not null) { return int.Parse(e.Id.Value); } + else { throw new System.NullReferenceException("Comment id and/or value are null."); } } ).Max() + 1).ToString(); } } else diff --git a/samples/word/insert_a_picture/cs/Program.cs b/samples/word/insert_a_picture/cs/Program.cs index e053faf6..5a5958e6 100644 --- a/samples/word/insert_a_picture/cs/Program.cs +++ b/samples/word/insert_a_picture/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -13,6 +11,11 @@ static void InsertAPicture(string document, string fileName) using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true)) { + if (wordprocessingDocument.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart is null."); + } + MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); @@ -92,6 +95,11 @@ static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId EditId = "50D07946" }); + if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + // Append the reference to body, the element should be in a Run. wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element))); } \ No newline at end of file diff --git a/samples/word/insert_a_table/cs/Program.cs b/samples/word/insert_a_table/cs/Program.cs index 2d51522b..92fa20c2 100644 --- a/samples/word/insert_a_table/cs/Program.cs +++ b/samples/word/insert_a_table/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -86,6 +84,11 @@ static void CreateTable(string fileName) // Append the table row to the table. table.Append(tr); + if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + // Append the table to the document. doc.MainDocumentPart.Document.Body.Append(table); } diff --git a/samples/word/remove_hidden_text/cs/Program.cs b/samples/word/remove_hidden_text/cs/Program.cs index e770c63d..b12b1515 100644 --- a/samples/word/remove_hidden_text/cs/Program.cs +++ b/samples/word/remove_hidden_text/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using System.IO; using System.Xml; @@ -16,16 +14,38 @@ static void WDDeleteHiddenText(string docName) XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", wordmlNamespace); + if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + // Get the document part from the package. // Load the XML in the document part into an XmlDocument instance. XmlDocument xdoc = new XmlDocument(nt); xdoc.Load(wdDoc.MainDocumentPart.GetStream()); - XmlNodeList hiddenNodes = xdoc.SelectNodes("//w:vanish", nsManager); + XmlNodeList? hiddenNodes = xdoc.SelectNodes("//w:vanish", nsManager); + + if (hiddenNodes is null) + { + return; // No hidden text. + } + foreach (System.Xml.XmlNode hiddenNode in hiddenNodes) { + if (hiddenNode.ParentNode is null || hiddenNode.ParentNode.ParentNode is null || hiddenNode.ParentNode.ParentNode.ParentNode is null) + { + continue; + } + XmlNode topNode = hiddenNode.ParentNode.ParentNode; XmlNode topParentNode = topNode.ParentNode; topParentNode.RemoveChild(topNode); + + if (topParentNode.ParentNode is null) + { + continue; + } + if (!(topParentNode.HasChildNodes)) { topParentNode.ParentNode.RemoveChild(topParentNode); diff --git a/samples/word/remove_the_headers_and_footers/cs/Program.cs b/samples/word/remove_the_headers_and_footers/cs/Program.cs index 4041455d..e21640f7 100644 --- a/samples/word/remove_the_headers_and_footers/cs/Program.cs +++ b/samples/word/remove_the_headers_and_footers/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; @@ -11,6 +9,11 @@ static void RemoveHeadersAndFooters(string filename) // from the document. using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true)) { + if (doc.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart is null."); + } + // Get a reference to the main document part. var docPart = doc.MainDocumentPart; diff --git a/samples/word/replace_the_header/cs/Program.cs b/samples/word/replace_the_header/cs/Program.cs index 21699f92..09df1040 100644 --- a/samples/word/replace_the_header/cs/Program.cs +++ b/samples/word/replace_the_header/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.Collections.Generic; @@ -11,6 +9,11 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filepathTo, true)) { + if (wdDoc.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart is null."); + } + MainDocumentPart mainPart = wdDoc.MainDocumentPart; // Delete the existing header part. @@ -27,7 +30,12 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(filepathFrom, true)) { - DocumentFormat.OpenXml.Packaging.HeaderPart firstHeader = + if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or HeaderParts is null."); + } + + DocumentFormat.OpenXml.Packaging.HeaderPart? firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); @@ -38,6 +46,11 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) } } + if (mainPart.Document.Body is null) + { + throw new System.NullReferenceException("Body is null."); + } + // Get SectionProperties and Replace HeaderReference with new Id. IEnumerable sectPrs = mainPart.Document.Body.Elements(); diff --git a/samples/word/replace_the_styles_parts/cs/Program.cs b/samples/word/replace_the_styles_parts/cs/Program.cs index 2d8bd2c5..a9211097 100644 --- a/samples/word/replace_the_styles_parts/cs/Program.cs +++ b/samples/word/replace_the_styles_parts/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using System.IO; using System.Xml; @@ -31,12 +29,17 @@ static void ReplaceStylesPart(string fileName, XDocument newStyles, bool setStyl // Open the document for write access and get a reference. using (var document = WordprocessingDocument.Open(fileName, true)) { + if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or one or both of the Styles parts is null."); + } + // Get a reference to the main document part. var docPart = document.MainDocumentPart; // Assign a reference to the appropriate part to the // stylesPart variable. - StylesPart stylesPart = null; + StylesPart? stylesPart = null; if (setStylesWithEffectsPart) stylesPart = docPart.StylesWithEffectsPart; else @@ -56,7 +59,7 @@ static void ReplaceStylesPart(string fileName, XDocument newStyles, bool setStyl static XDocument ExtractStylesPart(string fileName, bool getStylesWithEffectsPart = true) { // Declare a variable to hold the XDocument. - XDocument styles = null; + XDocument? styles = null; // Open the document for read access and get a reference. using (var document = WordprocessingDocument.Open(fileName, false)) @@ -64,23 +67,24 @@ static XDocument ExtractStylesPart(string fileName, bool getStylesWithEffectsPar // Get a reference to the main document part. var docPart = document.MainDocumentPart; + if (docPart is null || docPart.StyleDefinitionsPart is null || docPart.StylesWithEffectsPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or one or both of the Styles parts is null."); + } + // Assign a reference to the appropriate part to the // stylesPart variable. - StylesPart stylesPart = null; + StylesPart? stylesPart = null; if (getStylesWithEffectsPart) stylesPart = docPart.StylesWithEffectsPart; else stylesPart = docPart.StyleDefinitionsPart; - // If the part exists, read it into the XDocument. - if (stylesPart is not null) + using (var reader = XmlNodeReader.Create( + stylesPart.GetStream(FileMode.Open, FileAccess.Read))) { - using (var reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read))) - { - // Create the XDocument. - styles = XDocument.Load(reader); - } + // Create the XDocument. + styles = XDocument.Load(reader); } } // Return the XDocument instance. diff --git a/samples/word/replace_the_theme_part/cs/Program.cs b/samples/word/replace_the_theme_part/cs/Program.cs index 5e7bd178..d816e0b6 100644 --- a/samples/word/replace_the_theme_part/cs/Program.cs +++ b/samples/word/replace_the_theme_part/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using System.IO; @@ -9,6 +7,11 @@ static void ReplaceTheme(string document, string themeFile) using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) { + if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null || wordDoc.MainDocumentPart.ThemePart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body and/or ThemePart is null."); + } + MainDocumentPart mainPart = wordDoc.MainDocumentPart; // Delete the old document part. diff --git a/samples/word/retrieve_application_property_values/cs/Program.cs b/samples/word/retrieve_application_property_values/cs/Program.cs index 0497b46b..8af57a3e 100644 --- a/samples/word/retrieve_application_property_values/cs/Program.cs +++ b/samples/word/retrieve_application_property_values/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using System; @@ -15,6 +13,11 @@ static void Main(string[] args) using (WordprocessingDocument document = WordprocessingDocument.Open(FILENAME, false)) { + if (document.ExtendedFilePropertiesPart is null) + { + throw new System.NullReferenceException("ExtendedFilePropertiesPart is null."); + } + var props = document.ExtendedFilePropertiesPart.Properties; if (props.Company != null) diff --git a/samples/word/retrieve_comments/cs/Program.cs b/samples/word/retrieve_comments/cs/Program.cs index 8b753514..42525482 100644 --- a/samples/word/retrieve_comments/cs/Program.cs +++ b/samples/word/retrieve_comments/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; @@ -9,6 +7,11 @@ static void GetCommentsFromDocument(string fileName) using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, false)) { + if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.WordprocessingCommentsPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or WordprocessingCommentsPart is null."); + } + WordprocessingCommentsPart commentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart; diff --git a/samples/word/search_and_replace_text_a_part/cs/Program.cs b/samples/word/search_and_replace_text_a_part/cs/Program.cs index 1e9e730e..4000b683 100644 --- a/samples/word/search_and_replace_text_a_part/cs/Program.cs +++ b/samples/word/search_and_replace_text_a_part/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using System.IO; using System.Text.RegularExpressions; @@ -9,7 +7,14 @@ static void SearchAndReplace(string document) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) { - string docText = null; + string? docText = null; + + + if (wordDoc.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) { docText = sr.ReadToEnd(); diff --git a/samples/word/set_a_custom_property/cs/Program.cs b/samples/word/set_a_custom_property/cs/Program.cs index c5e5d610..2b9bee5d 100644 --- a/samples/word/set_a_custom_property/cs/Program.cs +++ b/samples/word/set_a_custom_property/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.CustomProperties; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.VariantTypes; @@ -17,11 +15,14 @@ static string SetCustomProperty( // add a custom property to a document. The method returns the original // value, if it existed. - string returnValue = null; + string? returnValue = string.Empty; var newProp = new CustomDocumentProperty(); bool propSet = false; + + string? propertyValueString = propertyValue.ToString() ?? throw new System.ArgumentNullException("propertyValue can't be converted to a string."); + // Calculate the correct type. switch (propertyType) { @@ -44,7 +45,7 @@ static string SetCustomProperty( case PropertyTypes.NumberInteger: if ((propertyValue) is int) { - newProp.VTInt32 = new VTInt32(propertyValue.ToString()); + newProp.VTInt32 = new VTInt32(propertyValueString); propSet = true; } @@ -53,14 +54,14 @@ static string SetCustomProperty( case PropertyTypes.NumberDouble: if (propertyValue is double) { - newProp.VTFloat = new VTFloat(propertyValue.ToString()); + newProp.VTFloat = new VTFloat(propertyValueString); propSet = true; } break; case PropertyTypes.Text: - newProp.VTLPWSTR = new VTLPWSTR(propertyValue.ToString()); + newProp.VTLPWSTR = new VTLPWSTR(propertyValueString); propSet = true; break; @@ -106,10 +107,10 @@ static string SetCustomProperty( // This will trigger an exception if the property's Name // property is null, but if that happens, the property is damaged, // and probably should raise an exception. +#pragma warning disable CS8602 // Dereference of a possibly null reference. var prop = - props.Where( - p => ((CustomDocumentProperty)p).Name.Value - == propertyName).FirstOrDefault(); + props.FirstOrDefault(p => ((CustomDocumentProperty)p).Name.Value == propertyName); +#pragma warning restore CS8602 // Dereference of a possibly null reference. // Does the property exist? If so, get the return value, // and then delete the property. @@ -118,6 +119,10 @@ static string SetCustomProperty( returnValue = prop.InnerText; prop.Remove(); } + else + { + throw new System.ArgumentException("propertyName property was not found or damaged."); + } // Append the new property, and // fix up all the property ID values. diff --git a/samples/word/set_the_font_for_a_text_run/cs/Program.cs b/samples/word/set_the_font_for_a_text_run/cs/Program.cs index 78b7407d..a1bd5547 100644 --- a/samples/word/set_the_font_for_a_text_run/cs/Program.cs +++ b/samples/word/set_the_font_for_a_text_run/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; @@ -18,6 +16,11 @@ static void SetRunFont(string fileName) Ascii = "Arial" }); + if (package.MainDocumentPart is null) + { + throw new System.NullReferenceException("MainDocumentPart is null."); + } + Run r = package.MainDocumentPart.Document.Descendants().First(); r.PrependChild(rPr); diff --git a/samples/word/validate/cs/Program.cs b/samples/word/validate/cs/Program.cs index a2359471..4520305b 100644 --- a/samples/word/validate/cs/Program.cs +++ b/samples/word/validate/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; using DocumentFormat.OpenXml.Wordprocessing; @@ -21,8 +19,14 @@ static void ValidateWordDocument(string filepath) Console.WriteLine("Description: " + error.Description); Console.WriteLine("ErrorType: " + error.ErrorType); Console.WriteLine("Node: " + error.Node); - Console.WriteLine("Path: " + error.Path.XPath); - Console.WriteLine("Part: " + error.Part.Uri); + if (error.Path is not null) + { + Console.WriteLine("Path: " + error.Path.XPath); + } + if (error.Part is not null) + { + Console.WriteLine("Part: " + error.Part.Uri); + } Console.WriteLine("-------------------------------------------"); } @@ -44,6 +48,12 @@ static void ValidateCorruptedWordDocument(string filepath) using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true)) { + + if (wordprocessingDocument.MainDocumentPart is null || wordprocessingDocument.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } + // Insert some text into the body, this would cause Schema Error Body body = wordprocessingDocument.MainDocumentPart.Document.Body; Run run = new Run(new Text("some text")); @@ -61,8 +71,14 @@ static void ValidateCorruptedWordDocument(string filepath) Console.WriteLine("Description: " + error.Description); Console.WriteLine("ErrorType: " + error.ErrorType); Console.WriteLine("Node: " + error.Node); - Console.WriteLine("Path: " + error.Path.XPath); - Console.WriteLine("Part: " + error.Part.Uri); + if (error.Path is not null) + { + Console.WriteLine("Path: " + error.Path.XPath); + } + if (error.Part is not null) + { + Console.WriteLine("Part: " + error.Part.Uri); + } Console.WriteLine("-------------------------------------------"); } From dc486c2661194762f51603c187b43e8d6ac80577 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Fri, 27 Oct 2023 15:27:52 -0700 Subject: [PATCH 3/8] fix nullable issues in spreadsheet --- .../insert_a_new_worksheet/cs/Program.cs | 13 ++-- .../merge_two_adjacent_cells/cs/Program.cs | 29 +++---- .../open_for_read_only_access/cs/Program.cs | 12 +-- .../open_from_a_stream/cs/Program.cs | 62 +++++++++------ .../cs/Program.cs | 15 ++-- .../cs/Program.cs | 21 +++-- .../cs/Program.cs | 77 +++++++++++-------- .../cs/Program.cs | 31 ++++---- .../cs/Program.cs | 46 ++++------- 9 files changed, 172 insertions(+), 134 deletions(-) diff --git a/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs b/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs index a96728e8..e44a56d4 100644 --- a/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs +++ b/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs @@ -1,27 +1,28 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.Linq; +InsertWorksheet(args[0]); + // Given a document name, inserts a new worksheet. static void InsertWorksheet(string docName) { // Open the document for editing. using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) { + WorkbookPart workbookPart = spreadSheet.WorkbookPart ?? spreadSheet.AddWorkbookPart(); // Add a blank WorksheetPart. - WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart(); + WorksheetPart newWorksheetPart = workbookPart.AddNewPart(); newWorksheetPart.Worksheet = new Worksheet(new SheetData()); - Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild(); - string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart); + Sheets sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart); // Get a unique ID for the new worksheet. uint sheetId = 1; if (sheets.Elements().Count() > 0) { - sheetId = sheets.Elements().Select(s => s.SheetId.Value).Max() + 1; + sheetId = (sheets.Elements().Select(s => s.SheetId?.Value).Max() + 1) ?? (uint)sheets.Elements().Count() + 1; } // Give the new worksheet a name. diff --git a/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs b/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs index 008e6878..ace15a7a 100644 --- a/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs +++ b/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; @@ -8,6 +6,8 @@ using System.Linq; using System.Text.RegularExpressions; +MergeTwoCells(args[0], args[1], args[2], args[3]); + // Given a document name, a worksheet name, and the names of two adjacent cells, merges the two cells. // When two cells are merged, only the content from one cell is preserved: // the upper-left cell for left-to-right languages or the upper-right cell for right-to-left languages. @@ -16,8 +16,8 @@ static void MergeTwoCells(string docName, string sheetName, string cell1Name, st // Open the document for editing. using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true)) { - Worksheet worksheet = GetWorksheet(document, sheetName); - if (worksheet == null || string.IsNullOrEmpty(cell1Name) || string.IsNullOrEmpty(cell2Name)) + Worksheet? worksheet = GetWorksheet(document, sheetName); + if (worksheet is null || string.IsNullOrEmpty(cell1Name) || string.IsNullOrEmpty(cell2Name)) { return; } @@ -88,7 +88,7 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName string columnName = GetColumnName(cellName); uint rowIndex = GetRowIndex(cellName); - IEnumerable rows = worksheet.Descendants().Where(r => r.RowIndex.Value == rowIndex); + IEnumerable rows = worksheet.Descendants().Where(r => r.RowIndex?.Value == rowIndex); // If the Worksheet does not contain the specified row, create the specified row. // Create the specified cell in that row, and insert the row into the Worksheet. @@ -98,33 +98,36 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName Cell cell = new Cell() { CellReference = new StringValue(cellName) }; row.Append(cell); worksheet.Descendants().First().Append(row); + worksheet.Save(); } else { Row row = rows.First(); - IEnumerable cells = row.Elements().Where(c => c.CellReference.Value == cellName); + IEnumerable cells = row.Elements().Where(c => c.CellReference?.Value == cellName); // If the row does not contain the specified cell, create the specified cell. if (cells.Count() == 0) { Cell cell = new Cell() { CellReference = new StringValue(cellName) }; row.Append(cell); + worksheet.Save(); } } } // Given a SpreadsheetDocument and a worksheet name, get the specified worksheet. -static Worksheet GetWorksheet(SpreadsheetDocument document, string worksheetName) +static Worksheet? GetWorksheet(SpreadsheetDocument document, string worksheetName) { - IEnumerable sheets = document.WorkbookPart.Workbook.Descendants().Where(s => s.Name == worksheetName); - WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id); - if (sheets.Count() == 0) - return null; - else - return worksheetPart.Worksheet; + WorkbookPart workbookPart = document.WorkbookPart ?? document.AddWorkbookPart(); + IEnumerable sheets = workbookPart.Workbook.Descendants().Where(s => s.Name == worksheetName); + + string? id = sheets.First().Id; + WorksheetPart? worksheetPart = id is not null ? (WorksheetPart)workbookPart.GetPartById(id) : null; + + return worksheetPart?.Worksheet; } // Given a cell name, parses the specified cell to get the column name. diff --git a/samples/spreadsheet/open_for_read_only_access/cs/Program.cs b/samples/spreadsheet/open_for_read_only_access/cs/Program.cs index 9095974f..aef17368 100644 --- a/samples/spreadsheet/open_for_read_only_access/cs/Program.cs +++ b/samples/spreadsheet/open_for_read_only_access/cs/Program.cs @@ -1,4 +1,3 @@ -#nullable disable using DocumentFormat.OpenXml.Packaging; static void OpenSpreadsheetDocumentReadonly(string filepath) @@ -6,10 +5,13 @@ static void OpenSpreadsheetDocumentReadonly(string filepath) // Open a SpreadsheetDocument based on a filepath. using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false)) { - // Attempt to add a new WorksheetPart. - // The call to AddNewPart generates an exception because the file is read-only. - WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(); + if (spreadsheetDocument.WorkbookPart is not null) + { + // Attempt to add a new WorksheetPart. + // The call to AddNewPart generates an exception because the file is read-only. + WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(); - // The rest of the code will not be called. + // The rest of the code will not be called. + } } } \ No newline at end of file diff --git a/samples/spreadsheet/open_from_a_stream/cs/Program.cs b/samples/spreadsheet/open_from_a_stream/cs/Program.cs index d9a5dbe4..72d655f3 100644 --- a/samples/spreadsheet/open_from_a_stream/cs/Program.cs +++ b/samples/spreadsheet/open_from_a_stream/cs/Program.cs @@ -1,39 +1,53 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.IO; using System.Linq; +FileStream fileStream = new(args[0], FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); +OpenAndAddToSpreadsheetStream(fileStream); + static void OpenAndAddToSpreadsheetStream(Stream stream) { // Open a SpreadsheetDocument based on a stream. - SpreadsheetDocument spreadsheetDocument = - SpreadsheetDocument.Open(stream, true); + SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stream, true); - // Add a new worksheet. - WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(); - newWorksheetPart.Worksheet = new Worksheet(new SheetData()); - newWorksheetPart.Worksheet.Save(); + if (spreadsheetDocument is not null) + { + // Get or create the WorkbookPart + WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart(); - Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild(); - string relationshipId = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart); + // Add a new worksheet. + WorksheetPart newWorksheetPart = workbookPart.AddNewPart(); + newWorksheetPart.Worksheet = new Worksheet(new SheetData()); + newWorksheetPart.Worksheet.Save(); - // Get a unique ID for the new worksheet. - uint sheetId = 1; - if (sheets.Elements().Count() > 0) - { - sheetId = sheets.Elements().Select(s => s.SheetId.Value).Max() + 1; - } + Workbook workbook = workbookPart.Workbook ?? new Workbook(); - // Give the new worksheet a name. - string sheetName = "Sheet" + sheetId; + if (workbookPart.Workbook is null) + { + workbookPart.Workbook = workbook; + } - // Append the new worksheet and associate it with the workbook. - Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName }; - sheets.Append(sheet); - spreadsheetDocument.WorkbookPart.Workbook.Save(); + Sheets sheets = workbook.GetFirstChild() ?? workbook.AppendChild(new Sheets()); + string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart); - // Dispose the document handle. - spreadsheetDocument.Dispose(); + // Get a unique ID for the new worksheet. + uint sheetId = 1; + + if (sheets.Elements().Count() > 0) + { + sheetId = (sheets.Elements().Select(s => s.SheetId?.Value).Max() + 1) ?? (uint)sheets.Elements().Count() + 1; + } + + // Give the new worksheet a name. + string sheetName = "Sheet" + sheetId; + + // Append the new worksheet and associate it with the workbook. + Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName }; + sheets.Append(sheet); + workbookPart.Workbook.Save(); + + // Dispose the document handle. + spreadsheetDocument.Dispose(); + } } \ No newline at end of file diff --git a/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs b/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs index 5d2e1789..7ccb802a 100644 --- a/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs +++ b/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs @@ -1,11 +1,12 @@ -#nullable disable - using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Linq; +ReadExcelFileDOM(args[0]); +ReadExcelFileSAX(args[0]); + // The DOM approach. // Note that the code below works only for cells that contain numeric values. // @@ -13,18 +14,20 @@ static void ReadExcelFileDOM(string fileName) { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false)) { - WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; + WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart(); WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); SheetData sheetData = worksheetPart.Worksheet.Elements().First(); - string text; + string? text; + foreach (Row r in sheetData.Elements()) { foreach (Cell c in r.Elements()) { - text = c.CellValue.Text; + text = c?.CellValue?.Text; Console.Write(text + " "); } } + Console.WriteLine(); Console.ReadKey(); } @@ -35,7 +38,7 @@ static void ReadExcelFileSAX(string fileName) { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false)) { - WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; + WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart(); WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); OpenXmlReader reader = OpenXmlReader.Create(worksheetPart); diff --git a/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs b/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs index 4da81755..3ae2c819 100644 --- a/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs @@ -1,10 +1,10 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; +GetDefinedNames(args[0]); + static Dictionary GetDefinedNames(String fileName) { @@ -20,14 +20,25 @@ static Dictionary var wbPart = document.WorkbookPart; // Retrieve a reference to the defined names collection. - DefinedNames definedNames = wbPart.Workbook.DefinedNames; + DefinedNames? definedNames = wbPart?.Workbook?.DefinedNames; // If there are defined names, add them to the dictionary. - if (definedNames != null) + if (definedNames is not null) { foreach (DefinedName dn in definedNames) - returnValue.Add(dn.Name.Value, dn.Text); + { + if (dn?.Name?.Value is not null && dn?.Text is not null) + { + returnValue.Add(dn.Name.Value, dn.Text); + } + } } } + + foreach (var pair in returnValue) + { + Console.WriteLine("{0} {1}", pair.Key, pair.Value); + } + return returnValue; } \ No newline at end of file diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs index da22b9c8..3e538cff 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs @@ -1,13 +1,19 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; using System.Linq; -static List GetHiddenRowsOrCols( - string fileName, string sheetName, bool detectRows) +if (args.Length >= 3) +{ + GetHiddenRowsOrCols(args[0], args[1], args[2]); +} +else +{ + GetHiddenRowsOrCols(args[0], args[1]); +} + +static List GetHiddenRowsOrCols(string fileName, string sheetName, string detectRows = "false") { // Given a workbook and a worksheet name, return // either a list of hidden row numbers, or a list @@ -17,45 +23,56 @@ static List GetHiddenRowsOrCols( List itemList = new List(); - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) + using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { - WorkbookPart wbPart = document.WorkbookPart; - - Sheet theSheet = wbPart.Workbook.Descendants(). - Where((s) => s.Name == sheetName).FirstOrDefault(); - if (theSheet == null) - { - throw new ArgumentException("sheetName"); - } - else + if (document is not null) { - // The sheet does exist. - WorksheetPart wsPart = - (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); - Worksheet ws = wsPart.Worksheet; + WorkbookPart wbPart = document.WorkbookPart ?? document.AddWorkbookPart(); - if (detectRows) + Sheet? theSheet = wbPart.Workbook.Descendants().FirstOrDefault((s) => s.Name == sheetName); + + if (theSheet is null) { - // Retrieve hidden rows. - itemList = ws.Descendants(). - Where((r) => r.Hidden != null && r.Hidden.Value). - Select(r => r.RowIndex.Value).ToList(); + throw new ArgumentException("sheetName"); } else { - // Retrieve hidden columns. - var cols = ws.Descendants(). - Where((c) => c.Hidden != null && c.Hidden.Value); - foreach (Column item in cols) + string id = theSheet.Id?.ToString() ?? string.Empty; + // The sheet does exist. + WorksheetPart? wsPart = wbPart.GetPartById(id) as WorksheetPart; + Worksheet? ws = wsPart?.Worksheet; + + if (ws is not null) { - for (uint i = item.Min.Value; i <= item.Max.Value; i++) + if (detectRows.ToLower() == "true") + { + // Retrieve hidden rows. + itemList = ws.Descendants() + .Where((r) => r?.Hidden is not null && r.Hidden.Value) + .Select(r => r.RowIndex?.Value) + .Cast() + .ToList(); + } + else { - itemList.Add(i); + // Retrieve hidden columns. + var cols = ws.Descendants().Where((c) => c?.Hidden is not null && c.Hidden.Value); + + foreach (Column item in cols) + { + if (item.Min is not null && item.Max is not null) + { + for (uint i = item.Min.Value; i <= item.Max.Value; i++) + { + itemList.Add(i); + } + } + } } } } } } + return itemList; } \ No newline at end of file diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs index d364d7d1..e377843d 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs @@ -1,28 +1,33 @@ -#nullable disable using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.Collections.Generic; using System.Linq; +GetHiddenSheets(args[0]); + static List GetHiddenSheets(string fileName) { List returnVal = new List(); - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) + using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { - WorkbookPart wbPart = document.WorkbookPart; - var sheets = wbPart.Workbook.Descendants(); + WorkbookPart? wbPart = document.WorkbookPart; + + if (wbPart is not null) + { + var sheets = wbPart.Workbook.Descendants(); - // Look for sheets where there is a State attribute defined, - // where the State has a value, - // and where the value is either Hidden or VeryHidden. - var hiddenSheets = sheets.Where((item) => item.State != null && - item.State.HasValue && - (item.State.Value == SheetStateValues.Hidden || - item.State.Value == SheetStateValues.VeryHidden)); + // Look for sheets where there is a State attribute defined, + // where the State has a value, + // and where the value is either Hidden or VeryHidden. + var hiddenSheets = sheets.Where((item) => item.State is not null && + item.State.HasValue && + (item.State.Value == SheetStateValues.Hidden || + item.State.Value == SheetStateValues.VeryHidden)); - returnVal = hiddenSheets.ToList(); + returnVal = hiddenSheets.ToList(); + } } + return returnVal; } \ No newline at end of file diff --git a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs index eca31fae..2e1050a5 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs @@ -1,40 +1,22 @@ -#nullable disable - using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; +using System.Collections.Generic; -namespace GetAllWorkheets -{ - class Program - { - const string DEMOFILE = - @"C:\Users\Public\Documents\SampleWorkbook.xlsx"; - - static void Main(string[] args) - { - var results = GetAllWorksheets(DEMOFILE); - foreach (Sheet item in results) - { - Console.WriteLine(item.Name); - } - } +GetAllWorksheets(args[0]); - // Retrieve a List of all the sheets in a workbook. - // The Sheets class contains a collection of - // OpenXmlElement objects, each representing one of - // the sheets. - public static Sheets GetAllWorksheets(string fileName) - { - Sheets theSheets = null; +// Retrieve a List of all the sheets in a workbook. +// The Sheets class contains a collection of +// OpenXmlElement objects, each representing one of +// the sheets. +static Sheets? GetAllWorksheets(string fileName) +{ + Sheets? theSheets = null; - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) - { - WorkbookPart wbPart = document.WorkbookPart; - theSheets = wbPart.Workbook.Sheets; - } - return theSheets; - } + using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) + { + theSheets = document?.WorkbookPart?.Workbook.Sheets; } + + return theSheets; } \ No newline at end of file From ec2b10fabaf67ba38ab941fceef97b7ea394a655 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 31 Oct 2023 09:40:43 -0700 Subject: [PATCH 4/8] make word examples executable --- .../cs/Program.cs | 2 - .../word/accept_all_revisions/cs/Program.cs | 104 ++++++----- samples/word/add_tables/cs/Program.cs | 114 ++++++------ .../word/change_text_a_table/cs/Program.cs | 8 +- .../cs/Program.cs | 176 +++++++++--------- .../cs/Program.cs | 7 +- .../cs/Program.cs | 83 +++++---- .../cs/Program.cs | 127 ++++++------- .../cs/Program.cs | 5 +- samples/word/extract_styles/cs/Program.cs | 22 ++- samples/word/insert_a_comment/cs/Program.cs | 46 ++--- samples/word/insert_a_picture/cs/Program.cs | 5 +- samples/word/insert_a_table/cs/Program.cs | 2 + samples/word/remove_hidden_text/cs/Program.cs | 54 +++--- .../cs/Program.cs | 2 + samples/word/replace_the_header/cs/Program.cs | 36 ++-- .../replace_the_styles_parts/cs/Program.cs | 2 + .../word/replace_the_theme_part/cs/Program.cs | 8 +- .../cs/Program.cs | 38 ++-- samples/word/retrieve_comments/cs/Program.cs | 10 +- .../cs/Program.cs | 2 + .../set_the_font_for_a_text_run/cs/Program.cs | 2 + samples/word/validate/cs/Program.cs | 2 + 23 files changed, 444 insertions(+), 413 deletions(-) diff --git a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs index 2e1050a5..a72be727 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs @@ -1,7 +1,5 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; -using System; -using System.Collections.Generic; GetAllWorksheets(args[0]); diff --git a/samples/word/accept_all_revisions/cs/Program.cs b/samples/word/accept_all_revisions/cs/Program.cs index 0ca65ef0..87436c68 100644 --- a/samples/word/accept_all_revisions/cs/Program.cs +++ b/samples/word/accept_all_revisions/cs/Program.cs @@ -4,74 +4,76 @@ using System.Collections.Generic; using System.Linq; -string fileName = args[0]; -string authorName = args[1]; +AcceptAllRevisions(args[0], args[1]); -using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(fileName, true)) +static void AcceptAllRevisions(string fileName, string authorName) { - if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) + using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(fileName, true)) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); - } + if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } - Body body = wdDoc.MainDocumentPart.Document.Body; + Body body = wdDoc.MainDocumentPart.Document.Body; - // Handle the formatting changes. - List changes = body.Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList(); + // Handle the formatting changes. + List changes = body.Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList(); - foreach (OpenXmlElement change in changes) - { - change.Remove(); - } + foreach (OpenXmlElement change in changes) + { + change.Remove(); + } - // Handle the deletions. - List deletions = body - .Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName) - .Cast().ToList(); + // Handle the deletions. + List deletions = body + .Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName) + .Cast().ToList(); - deletions.AddRange(body.Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); + deletions.AddRange(body.Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); - deletions.AddRange(body.Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); + deletions.AddRange(body.Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); - foreach (OpenXmlElement deletion in deletions) - { - deletion.Remove(); - } + foreach (OpenXmlElement deletion in deletions) + { + deletion.Remove(); + } - // Handle the insertions. - List insertions = - body.Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList(); + // Handle the insertions. + List insertions = + body.Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList(); - insertions.AddRange(body.Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); + insertions.AddRange(body.Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); - insertions.AddRange(body.Descendants() - .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); + insertions.AddRange(body.Descendants() + .Where(c => c.Author is not null && c.Author.Value == authorName).Cast().ToList()); - foreach (OpenXmlElement insertion in insertions) - { - // Found new content. - // Promote them to the same level as node, and then delete the node. - foreach (var run in insertion.Elements()) + foreach (OpenXmlElement insertion in insertions) { - if (run == insertion.FirstChild) + // Found new content. + // Promote them to the same level as node, and then delete the node. + foreach (var run in insertion.Elements()) { - insertion.InsertAfterSelf(new Run(run.OuterXml)); + if (run == insertion.FirstChild) + { + insertion.InsertAfterSelf(new Run(run.OuterXml)); + } + else + { + OpenXmlElement? nextSibling = insertion.NextSibling() ?? throw new System.NullReferenceException("NextSibling is null."); + nextSibling.InsertAfterSelf(new Run(run.OuterXml)); + } } - else - { - OpenXmlElement? nextSibling = insertion.NextSibling() ?? throw new System.NullReferenceException("NextSibling is null."); - nextSibling.InsertAfterSelf(new Run(run.OuterXml)); - } - } - insertion.RemoveAttribute("rsidR", "https://schemas.openxmlformats.org/wordprocessingml/2006/main"); - insertion.RemoveAttribute("rsidRPr", "https://schemas.openxmlformats.org/wordprocessingml/2006/main"); - insertion.Remove(); + insertion.RemoveAttribute("rsidR", "https://schemas.openxmlformats.org/wordprocessingml/2006/main"); + insertion.RemoveAttribute("rsidRPr", "https://schemas.openxmlformats.org/wordprocessingml/2006/main"); + insertion.Remove(); + } } } \ No newline at end of file diff --git a/samples/word/add_tables/cs/Program.cs b/samples/word/add_tables/cs/Program.cs index afcfe21b..ae1c1862 100644 --- a/samples/word/add_tables/cs/Program.cs +++ b/samples/word/add_tables/cs/Program.cs @@ -2,73 +2,81 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +AddTable(args[0], args[1]); + // Take the data from a two-dimensional array and build a table at the // end of the supplied document. -static void AddTable(string fileName, string[,] data) +static void AddTable(string fileName, string json) { - using (var document = WordprocessingDocument.Open(fileName, true)) + // read the data from the json file + var data = System.Text.Json.JsonSerializer.Deserialize(json); + + if (data is not null) { - if (document.MainDocumentPart is null || document.MainDocumentPart.Document.Body is null) + using (var document = WordprocessingDocument.Open(fileName, true)) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); - } + if (document.MainDocumentPart is null || document.MainDocumentPart.Document.Body is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + } - var doc = document.MainDocumentPart.Document; + var doc = document.MainDocumentPart.Document; - Table table = new(); + Table table = new(); - TableProperties props = new( - new TableBorders( - new TopBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new BottomBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new LeftBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new RightBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new InsideHorizontalBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new InsideVerticalBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - })); + TableProperties props = new( + new TableBorders( + new TopBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new BottomBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new LeftBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new RightBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new InsideHorizontalBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new InsideVerticalBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + })); - table.AppendChild(props); + table.AppendChild(props); - for (var i = 0; i <= data.GetUpperBound(0); i++) - { - var tr = new TableRow(); - for (var j = 0; j <= data.GetUpperBound(1); j++) + for (var i = 0; i < data.Length; i++) { - var tc = new TableCell(); - tc.Append(new Paragraph(new Run(new Text(data[i, j])))); + var tr = new TableRow(); + for (var j = 0; j < data[i].Length; j++) + { + var tc = new TableCell(); + tc.Append(new Paragraph(new Run(new Text(data[i][j])))); - // Assume you want columns that are automatically sized. - tc.Append(new TableCellProperties( - new TableCellWidth { Type = TableWidthUnitValues.Auto })); + // Assume you want columns that are automatically sized. + tc.Append(new TableCellProperties( + new TableCellWidth { Type = TableWidthUnitValues.Auto })); - tr.Append(tc); + tr.Append(tc); + } + table.Append(tr); } - table.Append(tr); + doc.Body.Append(table); + doc.Save(); } - doc.Body.Append(table); - doc.Save(); } } \ No newline at end of file diff --git a/samples/word/change_text_a_table/cs/Program.cs b/samples/word/change_text_a_table/cs/Program.cs index 51404c14..cb017be0 100644 --- a/samples/word/change_text_a_table/cs/Program.cs +++ b/samples/word/change_text_a_table/cs/Program.cs @@ -2,13 +2,14 @@ using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; +ChangeTextInCell(args[0], args[1]); + // Change the text in a table in a word processing document. static void ChangeTextInCell(string filePath, string txt) { // Use the file name and path passed in as an argument to // open an existing document. - using (WordprocessingDocument doc = - WordprocessingDocument.Open(filePath, true)) + using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) { if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) { @@ -16,8 +17,7 @@ static void ChangeTextInCell(string filePath, string txt) } // Find the first table in the document. - Table table = - doc.MainDocumentPart.Document.Body.Elements
().First(); + Table table = doc.MainDocumentPart.Document.Body.Elements
().First(); // Find the second row in the table. TableRow row = table.Elements().ElementAt(1); diff --git a/samples/word/change_the_print_orientation/cs/Program.cs b/samples/word/change_the_print_orientation/cs/Program.cs index 663ed791..b0ea6b9b 100644 --- a/samples/word/change_the_print_orientation/cs/Program.cs +++ b/samples/word/change_the_print_orientation/cs/Program.cs @@ -5,115 +5,111 @@ using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; -namespace ChangePrintOrientation +SetPrintOrientation(args[0], args[1]); + +// Given a document name, set the print orientation for +// all the sections of the document. +static void SetPrintOrientation(string fileName, string no) { - class Program + PageOrientationValues newOrientation = no.ToLower() switch + { + "landscape" => PageOrientationValues.Landscape, + "portrait" => PageOrientationValues.Portrait, + _ => throw new System.ArgumentException("Invalid argument: " + no) + }; + + using (var document = + WordprocessingDocument.Open(fileName, true)) { - static void Main() + bool documentChanged = false; + + if (document.MainDocumentPart is null) { - SetPrintOrientation(@"C:\Users\Public\Documents\ChangePrintOrientation.docx", - PageOrientationValues.Landscape); + throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); } - // Given a document name, set the print orientation for - // all the sections of the document. - public static void SetPrintOrientation( - string fileName, PageOrientationValues newOrientation) - { - using (var document = - WordprocessingDocument.Open(fileName, true)) - { - bool documentChanged = false; + var docPart = document.MainDocumentPart; - if (document.MainDocumentPart is null) - { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); - } - var docPart = document.MainDocumentPart; + var sections = docPart.Document.Descendants(); + foreach (SectionProperties sectPr in sections) + { + bool pageOrientationChanged = false; - var sections = docPart.Document.Descendants(); + PageSize pgSz = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageSize elements in the section."); + if (pgSz != null) + { + // No Orient property? Create it now. Otherwise, just + // set its value. Assume that the default orientation + // is Portrait. + if (pgSz.Orient == null) + { + // Need to create the attribute. You do not need to + // create the Orient property if the property does not + // already exist, and you are setting it to Portrait. + // That is the default value. + if (newOrientation != PageOrientationValues.Portrait) + { + pageOrientationChanged = true; + documentChanged = true; + pgSz.Orient = + new EnumValue(newOrientation); + } + } + else + { + // The Orient property exists, but its value + // is different than the new value. + if (pgSz.Orient.Value != newOrientation) + { + pgSz.Orient.Value = newOrientation; + pageOrientationChanged = true; + documentChanged = true; + } + } - foreach (SectionProperties sectPr in sections) + if (pageOrientationChanged) { - bool pageOrientationChanged = false; + // Changing the orientation is not enough. You must also + // change the page size. + var width = pgSz.Width; + var height = pgSz.Height; + pgSz.Width = height; + pgSz.Height = width; + + PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageMargin elements in the section."); - PageSize pgSz = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageSize elements in the section."); - if (pgSz != null) + if (pgMar != null) { - // No Orient property? Create it now. Otherwise, just - // set its value. Assume that the default orientation - // is Portrait. - if (pgSz.Orient == null) + // Rotate margins. Printer settings control how far you + // rotate when switching to landscape mode. Not having those + // settings, this code rotates 90 degrees. You could easily + // modify this behavior, or make it a parameter for the + // procedure. + if (pgMar.Top is null || pgMar.Bottom is null || pgMar.Left is null || pgMar.Right is null) { - // Need to create the attribute. You do not need to - // create the Orient property if the property does not - // already exist, and you are setting it to Portrait. - // That is the default value. - if (newOrientation != PageOrientationValues.Portrait) - { - pageOrientationChanged = true; - documentChanged = true; - pgSz.Orient = - new EnumValue(newOrientation); - } + throw new System.NullReferenceException("One or more of the PageMargin elements is null."); } - else - { - // The Orient property exists, but its value - // is different than the new value. - if (pgSz.Orient.Value != newOrientation) - { - pgSz.Orient.Value = newOrientation; - pageOrientationChanged = true; - documentChanged = true; - } - } - - if (pageOrientationChanged) - { - // Changing the orientation is not enough. You must also - // change the page size. - var width = pgSz.Width; - var height = pgSz.Height; - pgSz.Width = height; - pgSz.Height = width; - PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageMargin elements in the section."); + var top = pgMar.Top.Value; + var bottom = pgMar.Bottom.Value; + var left = pgMar.Left.Value; + var right = pgMar.Right.Value; - if (pgMar != null) - { - // Rotate margins. Printer settings control how far you - // rotate when switching to landscape mode. Not having those - // settings, this code rotates 90 degrees. You could easily - // modify this behavior, or make it a parameter for the - // procedure. - if (pgMar.Top is null || pgMar.Bottom is null || pgMar.Left is null || pgMar.Right is null) - { - throw new System.NullReferenceException("One or more of the PageMargin elements is null."); - } - - var top = pgMar.Top.Value; - var bottom = pgMar.Bottom.Value; - var left = pgMar.Left.Value; - var right = pgMar.Right.Value; - - pgMar.Top = new Int32Value((int)left); - pgMar.Bottom = new Int32Value((int)right); - pgMar.Left = - new UInt32Value((uint)System.Math.Max(0, bottom)); - pgMar.Right = - new UInt32Value((uint)System.Math.Max(0, top)); - } - } + pgMar.Top = new Int32Value((int)left); + pgMar.Bottom = new Int32Value((int)right); + pgMar.Left = + new UInt32Value((uint)System.Math.Max(0, bottom)); + pgMar.Right = + new UInt32Value((uint)System.Math.Max(0, top)); } } - if (documentChanged) - { - docPart.Document.Save(); - } } } + if (documentChanged) + { + docPart.Document.Save(); + } } -} \ No newline at end of file +} diff --git a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs index e4e70a2c..b9a23829 100644 --- a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs +++ b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs @@ -2,21 +2,22 @@ using DocumentFormat.OpenXml.Packaging; using System.IO; +ConvertDOCMtoDOCX(args[0]); + // Given a .docm file (with macro storage), remove the VBA // project, reset the document type, and save the document with a new name. static void ConvertDOCMtoDOCX(string fileName) { bool fileChanged = false; - using (WordprocessingDocument document = - WordprocessingDocument.Open(fileName, true)) + using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { // Access the main document part. var docPart = document.MainDocumentPart ?? throw new System.NullReferenceException("MainDocumentPart is null."); // Look for the vbaProject part. If it is there, delete it. var vbaPart = docPart.VbaProjectPart; - if (vbaPart != null) + if (vbaPart is not null) { // Delete the vbaProject part and then save the document. docPart.DeletePart(vbaPart); diff --git a/samples/word/create_and_add_a_character_style/cs/Program.cs b/samples/word/create_and_add_a_character_style/cs/Program.cs index 86da2019..a3a2de4d 100644 --- a/samples/word/create_and_add_a_character_style/cs/Program.cs +++ b/samples/word/create_and_add_a_character_style/cs/Program.cs @@ -1,58 +1,65 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +CreateAndAddCharacterStyle(args[0], args[1], args[2], args[3]); + // Create a new character style with the specified style id, style name and aliases and // add it to the specified style definitions part. -static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart, - string styleid, string stylename, string aliases = "") +static void CreateAndAddCharacterStyle(string filePath, string styleid, string stylename, string aliases = "") { - // Get access to the root element of the styles part. - Styles styles = styleDefinitionsPart.Styles ?? throw new System.NullReferenceException("Styles is null."); - - // Create a new character style and specify some of the attributes. - Style style = new Style() + using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true)) { - Type = StyleValues.Character, - StyleId = styleid, - CustomStyle = true - }; + // Get access to the root element of the styles part. + Styles? styles = wordprocessingDocument?.MainDocumentPart?.StyleDefinitionsPart?.Styles ?? AddStylesPartToPackage(wordprocessingDocument).Styles; - // Create and add the child elements (properties of the style). - Aliases aliases1 = new Aliases() { Val = aliases }; - StyleName styleName1 = new StyleName() { Val = stylename }; - LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" }; - if (aliases != "") - style.Append(aliases1); - style.Append(styleName1); - style.Append(linkedStyle1); + if (styles is not null) + { + // Create a new character style and specify some of the attributes. + Style style = new Style() + { + Type = StyleValues.Character, + StyleId = styleid, + CustomStyle = true + }; - // Create the StyleRunProperties object and specify some of the run properties. - StyleRunProperties styleRunProperties1 = new StyleRunProperties(); - Bold bold1 = new Bold(); - Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; - RunFonts font1 = new RunFonts() { Ascii = "Tahoma" }; - Italic italic1 = new Italic(); - // Specify a 24 point size. - FontSize fontSize1 = new FontSize() { Val = "48" }; - styleRunProperties1.Append(font1); - styleRunProperties1.Append(fontSize1); - styleRunProperties1.Append(color1); - styleRunProperties1.Append(bold1); - styleRunProperties1.Append(italic1); + // Create and add the child elements (properties of the style). + Aliases aliases1 = new Aliases() { Val = aliases }; + StyleName styleName1 = new StyleName() { Val = stylename }; + LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountPara" }; + if (aliases != "") + style.Append(aliases1); + style.Append(styleName1); + style.Append(linkedStyle1); - // Add the run properties to the style. - style.Append(styleRunProperties1); + // Create the StyleRunProperties object and specify some of the run properties. + StyleRunProperties styleRunProperties1 = new StyleRunProperties(); + Bold bold1 = new Bold(); + Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; + RunFonts font1 = new RunFonts() { Ascii = "Tahoma" }; + Italic italic1 = new Italic(); + // Specify a 24 point size. + FontSize fontSize1 = new FontSize() { Val = "48" }; + styleRunProperties1.Append(font1); + styleRunProperties1.Append(fontSize1); + styleRunProperties1.Append(color1); + styleRunProperties1.Append(bold1); + styleRunProperties1.Append(italic1); - // Add the style to the styles part. - styles.Append(style); + // Add the run properties to the style. + style.Append(styleRunProperties1); + + // Add the style to the styles part. + styles.Append(style); + } + } } // Add a StylesDefinitionsPart to the document. Returns a reference to it. -static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc) +static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc) { StyleDefinitionsPart part; - if (doc.MainDocumentPart is null) + if (doc?.MainDocumentPart is null) { throw new System.NullReferenceException("MainDocumentPart is null."); } diff --git a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs index 6134fc68..20eb61ab 100644 --- a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs +++ b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs @@ -1,84 +1,85 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +CreateAndAddParagraphStyle(args[0], args[1], args[2], args[3]); + // Create a new paragraph style with the specified style ID, primary style name, and aliases and // add it to the specified style definitions part. -static void CreateAndAddParagraphStyle(StyleDefinitionsPart styleDefinitionsPart, - string styleid, string stylename, string aliases = "") +static void CreateAndAddParagraphStyle(string filePath, string styleid, string stylename, string aliases = "") { - // Access the root element of the styles part. - Styles? styles = styleDefinitionsPart.Styles; - - if (styles is null) + using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filePath, true)) { - styleDefinitionsPart.Styles = new Styles(); - styleDefinitionsPart.Styles.Save(); - styles = styleDefinitionsPart.Styles; - } + // Access the root element of the styles part. + Styles? styles = wordprocessingDocument?.MainDocumentPart?.StyleDefinitionsPart?.Styles ?? AddStylesPartToPackage(wordprocessingDocument).Styles; - // Create a new paragraph style element and specify some of the attributes. - Style style = new Style() - { - Type = StyleValues.Paragraph, - StyleId = styleid, - CustomStyle = true, - Default = false - }; + if (styles is not null) + { + + // Create a new paragraph style element and specify some of the attributes. + Style style = new Style() + { + Type = StyleValues.Paragraph, + StyleId = styleid, + CustomStyle = true, + Default = false + }; - // Create and add the child elements (properties of the style). - Aliases aliases1 = new Aliases() { Val = aliases }; - AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off }; - BasedOn basedon1 = new BasedOn() { Val = "Normal" }; - LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" }; - Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off }; - PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On }; - StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off }; - SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off }; - StyleName styleName1 = new StyleName() { Val = stylename }; - NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" }; - UIPriority uipriority1 = new UIPriority() { Val = 1 }; - UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On }; - if (aliases != "") - style.Append(aliases1); - style.Append(autoredefine1); - style.Append(basedon1); - style.Append(linkedStyle1); - style.Append(locked1); - style.Append(primarystyle1); - style.Append(stylehidden1); - style.Append(semihidden1); - style.Append(styleName1); - style.Append(nextParagraphStyle1); - style.Append(uipriority1); - style.Append(unhidewhenused1); + // Create and add the child elements (properties of the style). + Aliases aliases1 = new Aliases() { Val = aliases }; + AutoRedefine autoredefine1 = new AutoRedefine() { Val = OnOffOnlyValues.Off }; + BasedOn basedon1 = new BasedOn() { Val = "Normal" }; + LinkedStyle linkedStyle1 = new LinkedStyle() { Val = "OverdueAmountChar" }; + Locked locked1 = new Locked() { Val = OnOffOnlyValues.Off }; + PrimaryStyle primarystyle1 = new PrimaryStyle() { Val = OnOffOnlyValues.On }; + StyleHidden stylehidden1 = new StyleHidden() { Val = OnOffOnlyValues.Off }; + SemiHidden semihidden1 = new SemiHidden() { Val = OnOffOnlyValues.Off }; + StyleName styleName1 = new StyleName() { Val = stylename }; + NextParagraphStyle nextParagraphStyle1 = new NextParagraphStyle() { Val = "Normal" }; + UIPriority uipriority1 = new UIPriority() { Val = 1 }; + UnhideWhenUsed unhidewhenused1 = new UnhideWhenUsed() { Val = OnOffOnlyValues.On }; + if (aliases != "") + style.Append(aliases1); + style.Append(autoredefine1); + style.Append(basedon1); + style.Append(linkedStyle1); + style.Append(locked1); + style.Append(primarystyle1); + style.Append(stylehidden1); + style.Append(semihidden1); + style.Append(styleName1); + style.Append(nextParagraphStyle1); + style.Append(uipriority1); + style.Append(unhidewhenused1); - // Create the StyleRunProperties object and specify some of the run properties. - StyleRunProperties styleRunProperties1 = new StyleRunProperties(); - Bold bold1 = new Bold(); - Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; - RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" }; - Italic italic1 = new Italic(); - // Specify a 12 point size. - FontSize fontSize1 = new FontSize() { Val = "24" }; - styleRunProperties1.Append(bold1); - styleRunProperties1.Append(color1); - styleRunProperties1.Append(font1); - styleRunProperties1.Append(fontSize1); - styleRunProperties1.Append(italic1); + // Create the StyleRunProperties object and specify some of the run properties. + StyleRunProperties styleRunProperties1 = new StyleRunProperties(); + Bold bold1 = new Bold(); + Color color1 = new Color() { ThemeColor = ThemeColorValues.Accent2 }; + RunFonts font1 = new RunFonts() { Ascii = "Lucida Console" }; + Italic italic1 = new Italic(); + // Specify a 12 point size. + FontSize fontSize1 = new FontSize() { Val = "24" }; + styleRunProperties1.Append(bold1); + styleRunProperties1.Append(color1); + styleRunProperties1.Append(font1); + styleRunProperties1.Append(fontSize1); + styleRunProperties1.Append(italic1); - // Add the run properties to the style. - style.Append(styleRunProperties1); + // Add the run properties to the style. + style.Append(styleRunProperties1); - // Add the style to the styles part. - styles.Append(style); + // Add the style to the styles part. + styles.Append(style); + } + } } // Add a StylesDefinitionsPart to the document. Returns a reference to it. -static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc) +static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc) { StyleDefinitionsPart part; - if (doc.MainDocumentPart is null) + if (doc?.MainDocumentPart is null) { throw new System.NullReferenceException("MainDocumentPart is null."); } diff --git a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs index 5128a96e..da0120b5 100644 --- a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs +++ b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs @@ -4,10 +4,11 @@ using System.Collections.Generic; using System.Linq; +DeleteComments(args[0], args[1]); + // Delete comments by a specific author. Pass an empty string for the // author to delete all comments, by all authors. -static void DeleteComments(string fileName, - string author = "") +static void DeleteComments(string fileName, string author = "") { // Get an existing Wordprocessing document. using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) diff --git a/samples/word/extract_styles/cs/Program.cs b/samples/word/extract_styles/cs/Program.cs index 2741bf01..9341a814 100644 --- a/samples/word/extract_styles/cs/Program.cs +++ b/samples/word/extract_styles/cs/Program.cs @@ -3,18 +3,24 @@ using System.Xml; using System.Xml.Linq; +if (args.Length >= 2) +{ + ExtractStylesPart(args[0], args[1]); +} +else +{ + ExtractStylesPart(args[0]); +} + // Extract the styles or stylesWithEffects part from a // word processing document as an XDocument instance. -static XDocument ExtractStylesPart( - string fileName, - bool getStylesWithEffectsPart = true) +static XDocument ExtractStylesPart(string fileName, string getStylesWithEffectsPart = "true") { // Declare a variable to hold the XDocument. XDocument? styles = null; // Open the document for read access and get a reference. - using (var document = - WordprocessingDocument.Open(fileName, false)) + using (var document = WordprocessingDocument.Open(fileName, false)) { if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) { @@ -27,13 +33,13 @@ static XDocument ExtractStylesPart( // Assign a reference to the appropriate part to the // stylesPart variable. StylesPart? stylesPart = null; - if (getStylesWithEffectsPart) + + if (getStylesWithEffectsPart.ToLower() == "true") stylesPart = docPart.StylesWithEffectsPart; else stylesPart = docPart.StyleDefinitionsPart; - using var reader = XmlNodeReader.Create( - stylesPart.GetStream(FileMode.Open, FileAccess.Read)); + using var reader = XmlNodeReader.Create(stylesPart.GetStream(FileMode.Open, FileAccess.Read)); // Create the XDocument. styles = XDocument.Load(reader); diff --git a/samples/word/insert_a_comment/cs/Program.cs b/samples/word/insert_a_comment/cs/Program.cs index 9cf53d00..a04445dc 100644 --- a/samples/word/insert_a_comment/cs/Program.cs +++ b/samples/word/insert_a_comment/cs/Program.cs @@ -3,46 +3,48 @@ using System; using System.Linq; +AddCommentOnFirstParagraph(args[0], args[1], args[2], args[3]); + // Insert a comment on the first paragraph. -static void AddCommentOnFirstParagraph(string fileName, - string author, string initials, string comment) +static void AddCommentOnFirstParagraph(string fileName, string author, string initials, string comment) { // Use the file name and path passed in as an // argument to open an existing Wordprocessing document. - using (WordprocessingDocument document = - WordprocessingDocument.Open(fileName, true)) + using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { - - if (document.MainDocumentPart is null || document.MainDocumentPart.WordprocessingCommentsPart is null) + if (document.MainDocumentPart is null/* || document.MainDocumentPart.WordprocessingCommentsPart is null*/) { throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); } + WordprocessingCommentsPart wordprocessingCommentsPart = document.MainDocumentPart.WordprocessingCommentsPart ?? document.MainDocumentPart.AddNewPart(); + // Locate the first paragraph in the document. - Paragraph firstParagraph = - document.MainDocumentPart.Document.Descendants().First(); - Comments? comments = null; + Paragraph firstParagraph = document.MainDocumentPart.Document.Descendants().First(); + wordprocessingCommentsPart.Comments ??= new Comments(); string id = "0"; // Verify that the document contains a // WordProcessingCommentsPart part; if not, add a new one. if (document.MainDocumentPart.GetPartsOfType().Count() > 0) { - comments = document.MainDocumentPart.WordprocessingCommentsPart.Comments; - if (comments.HasChildren) + if (wordprocessingCommentsPart.Comments.HasChildren) { // Obtain an unused ID. - id = (comments.Descendants().Select(e => { if (e.Id is not null && e.Id.Value is not null) { return int.Parse(e.Id.Value); } - else { throw new System.NullReferenceException("Comment id and/or value are null."); } } ).Max() + 1).ToString(); + id = (wordprocessingCommentsPart.Comments.Descendants().Select(e => + { + if (e.Id is not null && e.Id.Value is not null) + { + return int.Parse(e.Id.Value); + } + else + { + throw new System.NullReferenceException("Comment id and/or value are null."); + } + }) + .Max() + 1).ToString(); } } - else - { - // No WordprocessingCommentsPart part exists, so add one to the package. - WordprocessingCommentsPart commentPart = document.MainDocumentPart.AddNewPart(); - commentPart.Comments = new Comments(); - comments = commentPart.Comments; - } // Compose a new Comment and add it to the Comments part. Paragraph p = new Paragraph(new Run(new Text(comment))); @@ -55,8 +57,8 @@ static void AddCommentOnFirstParagraph(string fileName, Date = DateTime.Now }; cmt.AppendChild(p); - comments.AppendChild(cmt); - comments.Save(); + wordprocessingCommentsPart.Comments.AppendChild(cmt); + wordprocessingCommentsPart.Comments.Save(); // Specify the text range for the Comment. // Insert the new CommentRangeStart before the first run of paragraph. diff --git a/samples/word/insert_a_picture/cs/Program.cs b/samples/word/insert_a_picture/cs/Program.cs index 5a5958e6..7cdfc36c 100644 --- a/samples/word/insert_a_picture/cs/Program.cs +++ b/samples/word/insert_a_picture/cs/Program.cs @@ -6,10 +6,11 @@ using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; using PIC = DocumentFormat.OpenXml.Drawing.Pictures; +InsertAPicture(args[0], args[1]); + static void InsertAPicture(string document, string fileName) { - using (WordprocessingDocument wordprocessingDocument = - WordprocessingDocument.Open(document, true)) + using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true)) { if (wordprocessingDocument.MainDocumentPart is null) { diff --git a/samples/word/insert_a_table/cs/Program.cs b/samples/word/insert_a_table/cs/Program.cs index 92fa20c2..e7e5a9f1 100644 --- a/samples/word/insert_a_table/cs/Program.cs +++ b/samples/word/insert_a_table/cs/Program.cs @@ -2,6 +2,8 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +CreateTable(args[0]); + // Insert a table into a word processing document. static void CreateTable(string fileName) { diff --git a/samples/word/remove_hidden_text/cs/Program.cs b/samples/word/remove_hidden_text/cs/Program.cs index b12b1515..9f9bffef 100644 --- a/samples/word/remove_hidden_text/cs/Program.cs +++ b/samples/word/remove_hidden_text/cs/Program.cs @@ -2,6 +2,8 @@ using System.IO; using System.Xml; +WDDeleteHiddenText(args[0]); + static void WDDeleteHiddenText(string docName) { // Given a document name, delete all the hidden text. @@ -22,37 +24,43 @@ static void WDDeleteHiddenText(string docName) // Get the document part from the package. // Load the XML in the document part into an XmlDocument instance. XmlDocument xdoc = new XmlDocument(nt); - xdoc.Load(wdDoc.MainDocumentPart.GetStream()); - XmlNodeList? hiddenNodes = xdoc.SelectNodes("//w:vanish", nsManager); - - if (hiddenNodes is null) + using (Stream stream = wdDoc.MainDocumentPart.GetStream()) { - return; // No hidden text. - } + xdoc.Load(stream); + XmlNodeList? hiddenNodes = xdoc.SelectNodes("//w:vanish", nsManager); - foreach (System.Xml.XmlNode hiddenNode in hiddenNodes) - { - if (hiddenNode.ParentNode is null || hiddenNode.ParentNode.ParentNode is null || hiddenNode.ParentNode.ParentNode.ParentNode is null) - { - continue; - } - - XmlNode topNode = hiddenNode.ParentNode.ParentNode; - XmlNode topParentNode = topNode.ParentNode; - topParentNode.RemoveChild(topNode); - - if (topParentNode.ParentNode is null) + if (hiddenNodes is null) { - continue; + return; // No hidden text. } - if (!(topParentNode.HasChildNodes)) + foreach (System.Xml.XmlNode hiddenNode in hiddenNodes) { - topParentNode.ParentNode.RemoveChild(topParentNode); + if (hiddenNode.ParentNode is null || hiddenNode.ParentNode.ParentNode is null || hiddenNode.ParentNode.ParentNode.ParentNode is null) + { + continue; + } + + XmlNode topNode = hiddenNode.ParentNode.ParentNode; + XmlNode topParentNode = topNode.ParentNode; + topParentNode.RemoveChild(topNode); + + if (topParentNode.ParentNode is null) + { + continue; + } + + if (!topParentNode.HasChildNodes) + { + topParentNode.ParentNode.RemoveChild(topParentNode); + } } } - // Save the document XML back to its document part. - xdoc.Save(wdDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)); + using (Stream stream2 = wdDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)) + { + // Save the document XML back to its document part. + xdoc.Save(stream2); + } } } \ No newline at end of file diff --git a/samples/word/remove_the_headers_and_footers/cs/Program.cs b/samples/word/remove_the_headers_and_footers/cs/Program.cs index e21640f7..dc4a9b3a 100644 --- a/samples/word/remove_the_headers_and_footers/cs/Program.cs +++ b/samples/word/remove_the_headers_and_footers/cs/Program.cs @@ -2,6 +2,8 @@ using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; +RemoveHeadersAndFooters(args[0]); + // Remove all of the headers and footers from a document. static void RemoveHeadersAndFooters(string filename) { diff --git a/samples/word/replace_the_header/cs/Program.cs b/samples/word/replace_the_header/cs/Program.cs index 09df1040..9e4bf23e 100644 --- a/samples/word/replace_the_header/cs/Program.cs +++ b/samples/word/replace_the_header/cs/Program.cs @@ -3,12 +3,19 @@ using System.Collections.Generic; using System.Linq; +AddHeaderFromTo(args[0], args[1]); + static void AddHeaderFromTo(string filepathFrom, string filepathTo) { // Replace header in target document with header of source document. - using (WordprocessingDocument - wdDoc = WordprocessingDocument.Open(filepathTo, true)) + using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(filepathTo, true)) + using (WordprocessingDocument wdDocSource = WordprocessingDocument.Open(filepathFrom, true)) { + if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null) + { + throw new System.NullReferenceException("MainDocumentPart and/or HeaderParts is null."); + } + if (wdDoc.MainDocumentPart is null) { throw new System.NullReferenceException("MainDocumentPart is null."); @@ -20,30 +27,20 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) mainPart.DeleteParts(mainPart.HeaderParts); // Create a new header part. - DocumentFormat.OpenXml.Packaging.HeaderPart headerPart = - mainPart.AddNewPart(); + DocumentFormat.OpenXml.Packaging.HeaderPart headerPart = mainPart.AddNewPart(); // Get Id of the headerPart. string rId = mainPart.GetIdOfPart(headerPart); // Feed target headerPart with source headerPart. - using (WordprocessingDocument wdDocSource = - WordprocessingDocument.Open(filepathFrom, true)) - { - if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null) - { - throw new System.NullReferenceException("MainDocumentPart and/or HeaderParts is null."); - } - DocumentFormat.OpenXml.Packaging.HeaderPart? firstHeader = - wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); + DocumentFormat.OpenXml.Packaging.HeaderPart? firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); - wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); + wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault(); - if (firstHeader != null) - { - headerPart.FeedData(firstHeader.GetStream()); - } + if (firstHeader is not null) + { + headerPart.FeedData(firstHeader.GetStream()); } if (mainPart.Document.Body is null) @@ -52,8 +49,7 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) } // Get SectionProperties and Replace HeaderReference with new Id. - IEnumerable sectPrs = - mainPart.Document.Body.Elements(); + IEnumerable sectPrs = mainPart.Document.Body.Elements(); foreach (var sectPr in sectPrs) { // Delete existing references to headers. diff --git a/samples/word/replace_the_styles_parts/cs/Program.cs b/samples/word/replace_the_styles_parts/cs/Program.cs index a9211097..7b427de1 100644 --- a/samples/word/replace_the_styles_parts/cs/Program.cs +++ b/samples/word/replace_the_styles_parts/cs/Program.cs @@ -3,6 +3,8 @@ using System.Xml; using System.Xml.Linq; +ReplaceStyles(args[0], args[1]); + // Replace the styles in the "to" document with the styles in // the "from" document. static void ReplaceStyles(string fromDoc, string toDoc) diff --git a/samples/word/replace_the_theme_part/cs/Program.cs b/samples/word/replace_the_theme_part/cs/Program.cs index d816e0b6..b1742640 100644 --- a/samples/word/replace_the_theme_part/cs/Program.cs +++ b/samples/word/replace_the_theme_part/cs/Program.cs @@ -1,11 +1,12 @@ using DocumentFormat.OpenXml.Packaging; using System.IO; +ReplaceTheme(args[0], args[1]); + // This method can be used to replace the theme part in a package. static void ReplaceTheme(string document, string themeFile) { - using (WordprocessingDocument wordDoc = - WordprocessingDocument.Open(document, true)) + using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) { if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null || wordDoc.MainDocumentPart.ThemePart is null) { @@ -21,8 +22,7 @@ static void ReplaceTheme(string document, string themeFile) ThemePart themePart = mainPart.AddNewPart(); using (StreamReader streamReader = new StreamReader(themeFile)) - using (StreamWriter streamWriter = - new StreamWriter(themePart.GetStream(FileMode.Create))) + using (StreamWriter streamWriter = new StreamWriter(themePart.GetStream(FileMode.Create))) { streamWriter.Write(streamReader.ReadToEnd()); } diff --git a/samples/word/retrieve_application_property_values/cs/Program.cs b/samples/word/retrieve_application_property_values/cs/Program.cs index 8af57a3e..f595460c 100644 --- a/samples/word/retrieve_application_property_values/cs/Program.cs +++ b/samples/word/retrieve_application_property_values/cs/Program.cs @@ -1,34 +1,26 @@ using DocumentFormat.OpenXml.Packaging; using System; -namespace GetApplicationProperty +GetApplicationProperty(args[0]); + +static void GetApplicationProperty(string fileName) { - class Program + using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false)) { - private const string FILENAME = - @"C:\Users\Public\Documents\DocumentProperties.docx"; - - static void Main(string[] args) + if (document.ExtendedFilePropertiesPart is null) { - using (WordprocessingDocument document = - WordprocessingDocument.Open(FILENAME, false)) - { - if (document.ExtendedFilePropertiesPart is null) - { - throw new System.NullReferenceException("ExtendedFilePropertiesPart is null."); - } + throw new System.NullReferenceException("ExtendedFilePropertiesPart is null."); + } - var props = document.ExtendedFilePropertiesPart.Properties; + var props = document.ExtendedFilePropertiesPart.Properties; - if (props.Company != null) - Console.WriteLine("Company = " + props.Company.Text); + if (props.Company is not null) + Console.WriteLine("Company = " + props.Company.Text); - if (props.Lines != null) - Console.WriteLine("Lines = " + props.Lines.Text); + if (props.Lines is not null) + Console.WriteLine("Lines = " + props.Lines.Text); - if (props.Manager != null) - Console.WriteLine("Manager = " + props.Manager.Text); - } - } + if (props.Manager is not null) + Console.WriteLine("Manager = " + props.Manager.Text); } -} \ No newline at end of file +} diff --git a/samples/word/retrieve_comments/cs/Program.cs b/samples/word/retrieve_comments/cs/Program.cs index 42525482..3c3ef4f1 100644 --- a/samples/word/retrieve_comments/cs/Program.cs +++ b/samples/word/retrieve_comments/cs/Program.cs @@ -2,20 +2,20 @@ using DocumentFormat.OpenXml.Wordprocessing; using System; +GetCommentsFromDocument(args[0]); + static void GetCommentsFromDocument(string fileName) { - using (WordprocessingDocument wordDoc = - WordprocessingDocument.Open(fileName, false)) + using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, false)) { if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.WordprocessingCommentsPart is null) { throw new System.NullReferenceException("MainDocumentPart and/or WordprocessingCommentsPart is null."); } - WordprocessingCommentsPart commentsPart = - wordDoc.MainDocumentPart.WordprocessingCommentsPart; + WordprocessingCommentsPart commentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart; - if (commentsPart != null && commentsPart.Comments != null) + if (commentsPart is not null && commentsPart.Comments is not null) { foreach (Comment comment in commentsPart.Comments.Elements()) { diff --git a/samples/word/search_and_replace_text_a_part/cs/Program.cs b/samples/word/search_and_replace_text_a_part/cs/Program.cs index 4000b683..41f402a2 100644 --- a/samples/word/search_and_replace_text_a_part/cs/Program.cs +++ b/samples/word/search_and_replace_text_a_part/cs/Program.cs @@ -2,6 +2,8 @@ using System.IO; using System.Text.RegularExpressions; +SearchAndReplace(args[0]); + // To search and replace content in a document part. static void SearchAndReplace(string document) { diff --git a/samples/word/set_the_font_for_a_text_run/cs/Program.cs b/samples/word/set_the_font_for_a_text_run/cs/Program.cs index a1bd5547..0bc3ebb0 100644 --- a/samples/word/set_the_font_for_a_text_run/cs/Program.cs +++ b/samples/word/set_the_font_for_a_text_run/cs/Program.cs @@ -2,6 +2,8 @@ using DocumentFormat.OpenXml.Wordprocessing; using System.Linq; +SetRunFont(args[0]); + // Set the font for a text run. static void SetRunFont(string fileName) { diff --git a/samples/word/validate/cs/Program.cs b/samples/word/validate/cs/Program.cs index 4520305b..0be30b95 100644 --- a/samples/word/validate/cs/Program.cs +++ b/samples/word/validate/cs/Program.cs @@ -3,6 +3,8 @@ using DocumentFormat.OpenXml.Wordprocessing; using System; +ValidateCorruptedWordDocument(args[0]); + static void ValidateWordDocument(string filepath) { using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true)) From 06a0984830f5f3f3fd8fd0497011f52a6f656d82 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Wed, 1 Nov 2023 12:42:37 -0700 Subject: [PATCH 5/8] make recommended changes --- .../retrieve_the_number_of_slides/cs/Program.cs | 12 ++++++------ .../cs/Program.cs | 8 ++++---- samples/word/extract_styles/cs/Program.cs | 8 ++++---- samples/word/retrieve_comments/cs/Program.cs | 2 +- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs b/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs index fd2ff345..e9db870d 100644 --- a/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs +++ b/samples/presentation/retrieve_the_number_of_slides/cs/Program.cs @@ -1,18 +1,18 @@ using DocumentFormat.OpenXml.Packaging; using System; +using System.IO.Enumeration; using System.Linq; -if (args.Length >= 2) +if (args is [ { } fileName, {} includeHidden]) { - RetrieveNumberOfSlides(args[0], args[1]); + RetrieveNumberOfSlides(fileName, includeHidden); } -else +else if (args is [{ } fileName2]) { - RetrieveNumberOfSlides(args[0]); + RetrieveNumberOfSlides(fileName2); } -static int RetrieveNumberOfSlides(string fileName, - string includeHidden = "true") +static int RetrieveNumberOfSlides(string fileName, string includeHidden = "true") { int slidesCount = 0; diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs index 3e538cff..f51fdaba 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs @@ -4,13 +4,13 @@ using System.Collections.Generic; using System.Linq; -if (args.Length >= 3) +if (args is [{ } fileName, { } sheetName, { } detectRows]) { - GetHiddenRowsOrCols(args[0], args[1], args[2]); + GetHiddenRowsOrCols(fileName, sheetName, detectRows); } -else +else if (args is [{ } fileName2, { } sheetName2]) { - GetHiddenRowsOrCols(args[0], args[1]); + GetHiddenRowsOrCols(fileName2, sheetName2); } static List GetHiddenRowsOrCols(string fileName, string sheetName, string detectRows = "false") diff --git a/samples/word/extract_styles/cs/Program.cs b/samples/word/extract_styles/cs/Program.cs index 9341a814..4cdb188f 100644 --- a/samples/word/extract_styles/cs/Program.cs +++ b/samples/word/extract_styles/cs/Program.cs @@ -3,13 +3,13 @@ using System.Xml; using System.Xml.Linq; -if (args.Length >= 2) +if (args is [{ } fileName, { } getStyleWithEffectsPart]) { - ExtractStylesPart(args[0], args[1]); + ExtractStylesPart(fileName, getStyleWithEffectsPart); } -else +else if (args is [{ } fileName2]) { - ExtractStylesPart(args[0]); + ExtractStylesPart(fileName2); } // Extract the styles or stylesWithEffects part from a diff --git a/samples/word/retrieve_comments/cs/Program.cs b/samples/word/retrieve_comments/cs/Program.cs index 3c3ef4f1..a6a49d2e 100644 --- a/samples/word/retrieve_comments/cs/Program.cs +++ b/samples/word/retrieve_comments/cs/Program.cs @@ -10,7 +10,7 @@ static void GetCommentsFromDocument(string fileName) { if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.WordprocessingCommentsPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or WordprocessingCommentsPart is null."); + throw new System.InvalidOperationException("MainDocumentPart and/or WordprocessingCommentsPart is null."); } WordprocessingCommentsPart commentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart; From cac83457b57631c0cb748455a66cbe9918ed5136 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 2 Nov 2023 11:37:01 -0700 Subject: [PATCH 6/8] replace NullableRefernceExceptions with ArgumentNullExceptions --- samples/presentation/add_comment/cs/Program.cs | 4 ++-- samples/word/accept_all_revisions/cs/Program.cs | 5 +++-- samples/word/add_tables/cs/Program.cs | 3 ++- samples/word/change_text_a_table/cs/Program.cs | 3 ++- .../change_the_print_orientation/cs/Program.cs | 9 +++++---- .../cs/Program.cs | 3 ++- .../create_and_add_a_character_style/cs/Program.cs | 3 ++- .../create_and_add_a_paragraph_style/cs/Program.cs | 3 ++- .../cs/Program.cs | 2 +- samples/word/extract_styles/cs/Program.cs | 3 ++- samples/word/insert_a_comment/cs/Program.cs | 4 ++-- samples/word/insert_a_picture/cs/Program.cs | 5 +++-- samples/word/insert_a_table/cs/Program.cs | 3 ++- samples/word/remove_hidden_text/cs/Program.cs | 3 ++- .../remove_the_headers_and_footers/cs/Program.cs | 3 ++- samples/word/replace_the_header/cs/Program.cs | 7 ++++--- .../word/replace_the_styles_parts/cs/Program.cs | 5 +++-- samples/word/replace_the_theme_part/cs/Program.cs | 3 ++- .../cs/Program.cs | 2 +- samples/word/retrieve_comments/cs/Program.cs | 2 +- .../search_and_replace_text_a_part/cs/Program.cs | 3 ++- samples/word/set_a_custom_property/cs/Program.cs | 14 +++++--------- .../word/set_the_font_for_a_text_run/cs/Program.cs | 3 ++- samples/word/validate/cs/Program.cs | 2 +- 24 files changed, 55 insertions(+), 42 deletions(-) diff --git a/samples/presentation/add_comment/cs/Program.cs b/samples/presentation/add_comment/cs/Program.cs index 9d81e847..598cac82 100644 --- a/samples/presentation/add_comment/cs/Program.cs +++ b/samples/presentation/add_comment/cs/Program.cs @@ -100,14 +100,14 @@ static SlidePart GetFirstSlide(PresentationDocument? presentationDocument) string? relId = slideId?.RelationshipId; if (relId is null) { - throw new NullReferenceException("The first slide does not contain a relationship ID."); + throw new ArgumentNullException("The first slide does not contain a relationship ID."); } // Get the slide part by the relationship ID. SlidePart? slidePart = part?.GetPartById(relId) as SlidePart; if (slidePart is null) { - throw new NullReferenceException("The slide part is null."); + throw new ArgumentNullException("The slide part is null."); } return slidePart; diff --git a/samples/word/accept_all_revisions/cs/Program.cs b/samples/word/accept_all_revisions/cs/Program.cs index 87436c68..6cd98b48 100644 --- a/samples/word/accept_all_revisions/cs/Program.cs +++ b/samples/word/accept_all_revisions/cs/Program.cs @@ -1,6 +1,7 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.Collections.Generic; using System.Linq; @@ -12,7 +13,7 @@ static void AcceptAllRevisions(string fileName, string authorName) { if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } Body body = wdDoc.MainDocumentPart.Document.Body; @@ -66,7 +67,7 @@ static void AcceptAllRevisions(string fileName, string authorName) } else { - OpenXmlElement? nextSibling = insertion.NextSibling() ?? throw new System.NullReferenceException("NextSibling is null."); + OpenXmlElement? nextSibling = insertion.NextSibling() ?? throw new ArgumentNullException("NextSibling is null."); nextSibling.InsertAfterSelf(new Run(run.OuterXml)); } } diff --git a/samples/word/add_tables/cs/Program.cs b/samples/word/add_tables/cs/Program.cs index ae1c1862..d65f3f67 100644 --- a/samples/word/add_tables/cs/Program.cs +++ b/samples/word/add_tables/cs/Program.cs @@ -1,6 +1,7 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; AddTable(args[0], args[1]); @@ -17,7 +18,7 @@ static void AddTable(string fileName, string json) { if (document.MainDocumentPart is null || document.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } var doc = document.MainDocumentPart.Document; diff --git a/samples/word/change_text_a_table/cs/Program.cs b/samples/word/change_text_a_table/cs/Program.cs index cb017be0..f90b3714 100644 --- a/samples/word/change_text_a_table/cs/Program.cs +++ b/samples/word/change_text_a_table/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.Linq; ChangeTextInCell(args[0], args[1]); @@ -13,7 +14,7 @@ static void ChangeTextInCell(string filePath, string txt) { if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } // Find the first table in the document. diff --git a/samples/word/change_the_print_orientation/cs/Program.cs b/samples/word/change_the_print_orientation/cs/Program.cs index b0ea6b9b..fa520b53 100644 --- a/samples/word/change_the_print_orientation/cs/Program.cs +++ b/samples/word/change_the_print_orientation/cs/Program.cs @@ -3,6 +3,7 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.Linq; SetPrintOrientation(args[0], args[1]); @@ -25,7 +26,7 @@ static void SetPrintOrientation(string fileName, string no) if (document.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } var docPart = document.MainDocumentPart; @@ -37,7 +38,7 @@ static void SetPrintOrientation(string fileName, string no) { bool pageOrientationChanged = false; - PageSize pgSz = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageSize elements in the section."); + PageSize pgSz = (sectPr.Descendants().FirstOrDefault()) ?? throw new ArgumentNullException("There are no PageSize elements in the section."); if (pgSz != null) { // No Orient property? Create it now. Otherwise, just @@ -78,7 +79,7 @@ static void SetPrintOrientation(string fileName, string no) pgSz.Width = height; pgSz.Height = width; - PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new System.NullReferenceException("There are no PageMargin elements in the section."); + PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new ArgumentNullException("There are no PageMargin elements in the section."); if (pgMar != null) { @@ -89,7 +90,7 @@ static void SetPrintOrientation(string fileName, string no) // procedure. if (pgMar.Top is null || pgMar.Bottom is null || pgMar.Left is null || pgMar.Right is null) { - throw new System.NullReferenceException("One or more of the PageMargin elements is null."); + throw new ArgumentNullException("One or more of the PageMargin elements is null."); } var top = pgMar.Top.Value; diff --git a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs index b9a23829..33a31ef4 100644 --- a/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs +++ b/samples/word/convert_from_the_docm_to_the_docx_file_format/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; +using System; using System.IO; ConvertDOCMtoDOCX(args[0]); @@ -13,7 +14,7 @@ static void ConvertDOCMtoDOCX(string fileName) using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true)) { // Access the main document part. - var docPart = document.MainDocumentPart ?? throw new System.NullReferenceException("MainDocumentPart is null."); + var docPart = document.MainDocumentPart ?? throw new ArgumentNullException("MainDocumentPart is null."); // Look for the vbaProject part. If it is there, delete it. var vbaPart = docPart.VbaProjectPart; diff --git a/samples/word/create_and_add_a_character_style/cs/Program.cs b/samples/word/create_and_add_a_character_style/cs/Program.cs index a3a2de4d..1a86e82b 100644 --- a/samples/word/create_and_add_a_character_style/cs/Program.cs +++ b/samples/word/create_and_add_a_character_style/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; CreateAndAddCharacterStyle(args[0], args[1], args[2], args[3]); @@ -61,7 +62,7 @@ static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc) if (doc?.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } part = doc.MainDocumentPart.AddNewPart(); diff --git a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs index 20eb61ab..2d605ff1 100644 --- a/samples/word/create_and_add_a_paragraph_style/cs/Program.cs +++ b/samples/word/create_and_add_a_paragraph_style/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; CreateAndAddParagraphStyle(args[0], args[1], args[2], args[3]); @@ -81,7 +82,7 @@ static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument? doc) if (doc?.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } part = doc.MainDocumentPart.AddNewPart(); diff --git a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs index da0120b5..2437ac09 100644 --- a/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs +++ b/samples/word/delete_comments_by_all_or_a_specific_author/cs/Program.cs @@ -16,7 +16,7 @@ static void DeleteComments(string fileName, string author = "") if (document.MainDocumentPart is null || document.MainDocumentPart.WordprocessingCommentsPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or WordprocessingCommentsPart is null."); + throw new ArgumentNullException("MainDocumentPart and/or WordprocessingCommentsPart is null."); } // Set commentPart to the document WordprocessingCommentsPart, diff --git a/samples/word/extract_styles/cs/Program.cs b/samples/word/extract_styles/cs/Program.cs index 4cdb188f..516e7c86 100644 --- a/samples/word/extract_styles/cs/Program.cs +++ b/samples/word/extract_styles/cs/Program.cs @@ -1,4 +1,5 @@ using DocumentFormat.OpenXml.Packaging; +using System; using System.IO; using System.Xml; using System.Xml.Linq; @@ -24,7 +25,7 @@ static XDocument ExtractStylesPart(string fileName, string getStylesWithEffectsP { if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or one or both of the Styles parts is null."); + throw new ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is null."); } // Get a reference to the main document part. diff --git a/samples/word/insert_a_comment/cs/Program.cs b/samples/word/insert_a_comment/cs/Program.cs index a04445dc..95fbe650 100644 --- a/samples/word/insert_a_comment/cs/Program.cs +++ b/samples/word/insert_a_comment/cs/Program.cs @@ -14,7 +14,7 @@ static void AddCommentOnFirstParagraph(string fileName, string author, string in { if (document.MainDocumentPart is null/* || document.MainDocumentPart.WordprocessingCommentsPart is null*/) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } WordprocessingCommentsPart wordprocessingCommentsPart = document.MainDocumentPart.WordprocessingCommentsPart ?? document.MainDocumentPart.AddNewPart(); @@ -39,7 +39,7 @@ static void AddCommentOnFirstParagraph(string fileName, string author, string in } else { - throw new System.NullReferenceException("Comment id and/or value are null."); + throw new ArgumentNullException("Comment id and/or value are null."); } }) .Max() + 1).ToString(); diff --git a/samples/word/insert_a_picture/cs/Program.cs b/samples/word/insert_a_picture/cs/Program.cs index 7cdfc36c..4d786ce0 100644 --- a/samples/word/insert_a_picture/cs/Program.cs +++ b/samples/word/insert_a_picture/cs/Program.cs @@ -1,6 +1,7 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.IO; using A = DocumentFormat.OpenXml.Drawing; using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing; @@ -14,7 +15,7 @@ static void InsertAPicture(string document, string fileName) { if (wordprocessingDocument.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; @@ -98,7 +99,7 @@ static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } // Append the reference to body, the element should be in a Run. diff --git a/samples/word/insert_a_table/cs/Program.cs b/samples/word/insert_a_table/cs/Program.cs index e7e5a9f1..376d3141 100644 --- a/samples/word/insert_a_table/cs/Program.cs +++ b/samples/word/insert_a_table/cs/Program.cs @@ -1,6 +1,7 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; CreateTable(args[0]); @@ -88,7 +89,7 @@ static void CreateTable(string fileName) if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } // Append the table to the document. diff --git a/samples/word/remove_hidden_text/cs/Program.cs b/samples/word/remove_hidden_text/cs/Program.cs index 9f9bffef..88fd856d 100644 --- a/samples/word/remove_hidden_text/cs/Program.cs +++ b/samples/word/remove_hidden_text/cs/Program.cs @@ -1,4 +1,5 @@ using DocumentFormat.OpenXml.Packaging; +using System; using System.IO; using System.Xml; @@ -18,7 +19,7 @@ static void WDDeleteHiddenText(string docName) if (wdDoc.MainDocumentPart is null || wdDoc.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } // Get the document part from the package. diff --git a/samples/word/remove_the_headers_and_footers/cs/Program.cs b/samples/word/remove_the_headers_and_footers/cs/Program.cs index dc4a9b3a..bd18865f 100644 --- a/samples/word/remove_the_headers_and_footers/cs/Program.cs +++ b/samples/word/remove_the_headers_and_footers/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.Linq; RemoveHeadersAndFooters(args[0]); @@ -13,7 +14,7 @@ static void RemoveHeadersAndFooters(string filename) { if (doc.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } // Get a reference to the main document part. diff --git a/samples/word/replace_the_header/cs/Program.cs b/samples/word/replace_the_header/cs/Program.cs index 9e4bf23e..aac671ab 100644 --- a/samples/word/replace_the_header/cs/Program.cs +++ b/samples/word/replace_the_header/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.Collections.Generic; using System.Linq; @@ -13,12 +14,12 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) { if (wdDocSource.MainDocumentPart is null || wdDocSource.MainDocumentPart.HeaderParts is null) { - throw new System.NullReferenceException("MainDocumentPart and/or HeaderParts is null."); + throw new ArgumentNullException("MainDocumentPart and/or HeaderParts is null."); } if (wdDoc.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } MainDocumentPart mainPart = wdDoc.MainDocumentPart; @@ -45,7 +46,7 @@ static void AddHeaderFromTo(string filepathFrom, string filepathTo) if (mainPart.Document.Body is null) { - throw new System.NullReferenceException("Body is null."); + throw new ArgumentNullException("Body is null."); } // Get SectionProperties and Replace HeaderReference with new Id. diff --git a/samples/word/replace_the_styles_parts/cs/Program.cs b/samples/word/replace_the_styles_parts/cs/Program.cs index 7b427de1..2c94bb90 100644 --- a/samples/word/replace_the_styles_parts/cs/Program.cs +++ b/samples/word/replace_the_styles_parts/cs/Program.cs @@ -1,4 +1,5 @@ using DocumentFormat.OpenXml.Packaging; +using System; using System.IO; using System.Xml; using System.Xml.Linq; @@ -33,7 +34,7 @@ static void ReplaceStylesPart(string fileName, XDocument newStyles, bool setStyl { if (document.MainDocumentPart is null || document.MainDocumentPart.StyleDefinitionsPart is null || document.MainDocumentPart.StylesWithEffectsPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or one or both of the Styles parts is null."); + throw new ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is null."); } // Get a reference to the main document part. @@ -71,7 +72,7 @@ static XDocument ExtractStylesPart(string fileName, bool getStylesWithEffectsPar if (docPart is null || docPart.StyleDefinitionsPart is null || docPart.StylesWithEffectsPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or one or both of the Styles parts is null."); + throw new ArgumentNullException("MainDocumentPart and/or one or both of the Styles parts is null."); } // Assign a reference to the appropriate part to the diff --git a/samples/word/replace_the_theme_part/cs/Program.cs b/samples/word/replace_the_theme_part/cs/Program.cs index b1742640..fbb4b42f 100644 --- a/samples/word/replace_the_theme_part/cs/Program.cs +++ b/samples/word/replace_the_theme_part/cs/Program.cs @@ -1,4 +1,5 @@ using DocumentFormat.OpenXml.Packaging; +using System; using System.IO; ReplaceTheme(args[0], args[1]); @@ -10,7 +11,7 @@ static void ReplaceTheme(string document, string themeFile) { if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null || wordDoc.MainDocumentPart.ThemePart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body and/or ThemePart is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body and/or ThemePart is null."); } MainDocumentPart mainPart = wordDoc.MainDocumentPart; diff --git a/samples/word/retrieve_application_property_values/cs/Program.cs b/samples/word/retrieve_application_property_values/cs/Program.cs index f595460c..20fd8b8d 100644 --- a/samples/word/retrieve_application_property_values/cs/Program.cs +++ b/samples/word/retrieve_application_property_values/cs/Program.cs @@ -9,7 +9,7 @@ static void GetApplicationProperty(string fileName) { if (document.ExtendedFilePropertiesPart is null) { - throw new System.NullReferenceException("ExtendedFilePropertiesPart is null."); + throw new ArgumentNullException("ExtendedFilePropertiesPart is null."); } var props = document.ExtendedFilePropertiesPart.Properties; diff --git a/samples/word/retrieve_comments/cs/Program.cs b/samples/word/retrieve_comments/cs/Program.cs index a6a49d2e..03406339 100644 --- a/samples/word/retrieve_comments/cs/Program.cs +++ b/samples/word/retrieve_comments/cs/Program.cs @@ -10,7 +10,7 @@ static void GetCommentsFromDocument(string fileName) { if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.WordprocessingCommentsPart is null) { - throw new System.InvalidOperationException("MainDocumentPart and/or WordprocessingCommentsPart is null."); + throw new System.ArgumentNullException("MainDocumentPart and/or WordprocessingCommentsPart is null."); } WordprocessingCommentsPart commentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart; diff --git a/samples/word/search_and_replace_text_a_part/cs/Program.cs b/samples/word/search_and_replace_text_a_part/cs/Program.cs index 41f402a2..d09e6f9b 100644 --- a/samples/word/search_and_replace_text_a_part/cs/Program.cs +++ b/samples/word/search_and_replace_text_a_part/cs/Program.cs @@ -1,4 +1,5 @@ using DocumentFormat.OpenXml.Packaging; +using System; using System.IO; using System.Text.RegularExpressions; @@ -14,7 +15,7 @@ static void SearchAndReplace(string document) if (wordDoc.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) diff --git a/samples/word/set_a_custom_property/cs/Program.cs b/samples/word/set_a_custom_property/cs/Program.cs index 2b9bee5d..5132f515 100644 --- a/samples/word/set_a_custom_property/cs/Program.cs +++ b/samples/word/set_a_custom_property/cs/Program.cs @@ -92,29 +92,25 @@ static string SetCustomProperty( using (var document = WordprocessingDocument.Open(fileName, true)) { var customProps = document.CustomFilePropertiesPart; - if (customProps == null) + if (customProps is null) { // No custom properties? Add the part, and the // collection of properties now. customProps = document.AddCustomFilePropertiesPart(); - customProps.Properties = - new DocumentFormat.OpenXml.CustomProperties.Properties(); + customProps.Properties = new Properties(); } var props = customProps.Properties; - if (props != null) + if (props is not null) { // This will trigger an exception if the property's Name // property is null, but if that happens, the property is damaged, // and probably should raise an exception. -#pragma warning disable CS8602 // Dereference of a possibly null reference. - var prop = - props.FirstOrDefault(p => ((CustomDocumentProperty)p).Name.Value == propertyName); -#pragma warning restore CS8602 // Dereference of a possibly null reference. + var prop = props.FirstOrDefault(p => ((CustomDocumentProperty)p).Name!.Value == propertyName); // Does the property exist? If so, get the return value, // and then delete the property. - if (prop != null) + if (prop is not null) { returnValue = prop.InnerText; prop.Remove(); diff --git a/samples/word/set_the_font_for_a_text_run/cs/Program.cs b/samples/word/set_the_font_for_a_text_run/cs/Program.cs index 0bc3ebb0..c885f445 100644 --- a/samples/word/set_the_font_for_a_text_run/cs/Program.cs +++ b/samples/word/set_the_font_for_a_text_run/cs/Program.cs @@ -1,5 +1,6 @@ using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System; using System.Linq; SetRunFont(args[0]); @@ -20,7 +21,7 @@ static void SetRunFont(string fileName) if (package.MainDocumentPart is null) { - throw new System.NullReferenceException("MainDocumentPart is null."); + throw new ArgumentNullException("MainDocumentPart is null."); } Run r = package.MainDocumentPart.Document.Descendants().First(); diff --git a/samples/word/validate/cs/Program.cs b/samples/word/validate/cs/Program.cs index 0be30b95..b511d765 100644 --- a/samples/word/validate/cs/Program.cs +++ b/samples/word/validate/cs/Program.cs @@ -53,7 +53,7 @@ static void ValidateCorruptedWordDocument(string filepath) if (wordprocessingDocument.MainDocumentPart is null || wordprocessingDocument.MainDocumentPart.Document.Body is null) { - throw new System.NullReferenceException("MainDocumentPart and/or Body is null."); + throw new ArgumentNullException("MainDocumentPart and/or Body is null."); } // Insert some text into the body, this would cause Schema Error From c9a56a38125cf59a0d0f202abc5e8d59e427e117 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 2 Nov 2023 11:53:27 -0700 Subject: [PATCH 7/8] use .First() to prevent nullable value --- .../cs/Program.cs | 52 +++++++++---------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/samples/word/change_the_print_orientation/cs/Program.cs b/samples/word/change_the_print_orientation/cs/Program.cs index fa520b53..fa990838 100644 --- a/samples/word/change_the_print_orientation/cs/Program.cs +++ b/samples/word/change_the_print_orientation/cs/Program.cs @@ -38,36 +38,34 @@ static void SetPrintOrientation(string fileName, string no) { bool pageOrientationChanged = false; - PageSize pgSz = (sectPr.Descendants().FirstOrDefault()) ?? throw new ArgumentNullException("There are no PageSize elements in the section."); - if (pgSz != null) + PageSize pgSz = sectPr.Descendants().First(); + + // No Orient property? Create it now. Otherwise, just + // set its value. Assume that the default orientation + // is Portrait. + if (pgSz.Orient is null) { - // No Orient property? Create it now. Otherwise, just - // set its value. Assume that the default orientation - // is Portrait. - if (pgSz.Orient == null) + // Need to create the attribute. You do not need to + // create the Orient property if the property does not + // already exist, and you are setting it to Portrait. + // That is the default value. + if (newOrientation != PageOrientationValues.Portrait) { - // Need to create the attribute. You do not need to - // create the Orient property if the property does not - // already exist, and you are setting it to Portrait. - // That is the default value. - if (newOrientation != PageOrientationValues.Portrait) - { - pageOrientationChanged = true; - documentChanged = true; - pgSz.Orient = - new EnumValue(newOrientation); - } + pageOrientationChanged = true; + documentChanged = true; + pgSz.Orient = + new EnumValue(newOrientation); } - else + } + else + { + // The Orient property exists, but its value + // is different than the new value. + if (pgSz.Orient.Value != newOrientation) { - // The Orient property exists, but its value - // is different than the new value. - if (pgSz.Orient.Value != newOrientation) - { - pgSz.Orient.Value = newOrientation; - pageOrientationChanged = true; - documentChanged = true; - } + pgSz.Orient.Value = newOrientation; + pageOrientationChanged = true; + documentChanged = true; } if (pageOrientationChanged) @@ -81,7 +79,7 @@ static void SetPrintOrientation(string fileName, string no) PageMargin pgMar = (sectPr.Descendants().FirstOrDefault()) ?? throw new ArgumentNullException("There are no PageMargin elements in the section."); - if (pgMar != null) + if (pgMar is not null) { // Rotate margins. Printer settings control how far you // rotate when switching to landscape mode. Not having those From dd2e3438def4a840bed27b26674f68a3d616254c Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Thu, 2 Nov 2023 11:58:19 -0700 Subject: [PATCH 8/8] fix nullable issue --- samples/word/accept_all_revisions/cs/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/word/accept_all_revisions/cs/Program.cs b/samples/word/accept_all_revisions/cs/Program.cs index 6cd98b48..5cbc0f42 100644 --- a/samples/word/accept_all_revisions/cs/Program.cs +++ b/samples/word/accept_all_revisions/cs/Program.cs @@ -67,7 +67,7 @@ static void AcceptAllRevisions(string fileName, string authorName) } else { - OpenXmlElement? nextSibling = insertion.NextSibling() ?? throw new ArgumentNullException("NextSibling is null."); + OpenXmlElement nextSibling = insertion.NextSibling()!; nextSibling.InsertAfterSelf(new Run(run.OuterXml)); } }