/// <summary>
        /// Replaces text tag with hyperlink id. Hyperlink identified by Id hes to be a part of the slide.
        /// </summary>
        /// <param name="p">The paragraph (a:p).</param>
        /// <param name="tag">The tag to replace by newText, if null or empty do nothing; tag is a regex string.</param>
        /// <param name="newText">The new text to replace the tag with, if null replaced by empty string and not visible.</param>
        /// <param name="relationshipId">Hyperlink relationship Id. Relationship has to be existing on slide level.</param>
        /// <param name="fontName">Font name</param>
        /// <param name="fontSize">Font size. E.g. 800 is 8pt (small) font. If value is less than 100 it will be multiplied by 100 to keep up with PPT notation.</param>
        /// <returns></returns>
        internal static bool ReplaceTagWithHyperlink(A.Paragraph p, string tag, string newText, string relationshipId, string fontName = "Calibri", int fontSize = 800)
        {
            bool replaced = false;

            if (string.IsNullOrEmpty(tag))
            {
                return(replaced);
            }

            if (newText == null)
            {
                newText = string.Empty;
            }
            newText = RemoveInvalidXMLChars(newText);

            while (true)
            {
                // Search for the tag
                Match match = Regex.Match(GetTexts(p), tag);
                if (!match.Success)
                {
                    break;
                }

                p.RemoveAllChildren(); // remove exisitng children then add new

                A.HyperlinkOnClick link = new A.HyperlinkOnClick()
                {
                    Id = relationshipId
                };
                A.Run r = new A.Run();
                r.RunProperties = new A.RunProperties();
                A.Text at = new A.Text(newText);
                r.RunProperties.AppendChild(link);
                r.AppendChild(at);
                p.Append(r);

                var run = p.Descendants <A.Run>();
                foreach (var item in run)
                {
                    item.RunProperties.RemoveAllChildren <A.LatinFont>();
                    var latinFont = new A.LatinFont();
                    latinFont.Typeface = fontName;
                    item.RunProperties.AppendChild(latinFont);
                    item.RunProperties.FontSize = (fontSize > 99) ? fontSize : fontSize * 100; // e.g. translate value 8 (Power Point UI font size) to 800 for API
                }

                replaced = true;
            }

            return(replaced);
        }
        public static void FormatFLow(SlidePart slidePart)
        {
            if (slidePart != default(SlidePart))
            {
                IEnumerable <Shape> flowChartShapes = slidePart.Slide.Descendants <Shape>().Where(d => d.Descendants <NonVisualDrawingProperties>().Where(e => e.Name.InnerText.Contains(Constants._ARROW_)).Count() > 0);
                int           i       = 0;
                long          firstId = 0;
                D.Transform2D prevBox = new D.Transform2D();
                foreach (Shape shape in flowChartShapes)
                {
                    String title = String.Empty;
                    NonVisualDrawingProperties meta = shape.Descendants <NonVisualDrawingProperties>().FirstOrDefault();


                    //resize shape
                    D.Transform2D currentShapePos = shape.Descendants <D.Transform2D>().FirstOrDefault();

                    currentShapePos.Extents.Cx = 2775204;
                    currentShapePos.Extents.Cy = 1446936;
                    if (i == 0)
                    {
                        firstId = meta.Id;
                        currentShapePos.Offset.X = 458569;
                        currentShapePos.Offset.Y = 1712339;
                    }
                    else
                    {
                        currentShapePos.Offset.X = Convert.ToInt64((prevBox.Extents.Cx.Value - (prevBox.Extents.Cx.Value * 0.20)) + prevBox.Offset.X);
                        currentShapePos.Offset.Y = prevBox.Offset.Y;
                    }



                    prevBox = currentShapePos;


                    if (meta != default(NonVisualDrawingProperties))
                    {
                        long idToFind = (firstId + i) - (flowChartShapes.Count() + 1);//check

                        Shape titleShape = slidePart.Slide.Descendants <Shape>().Where(d => d.Descendants <NonVisualDrawingProperties>().First() != default(NonVisualDrawingProperties) &&
                                                                                       d.Descendants <NonVisualDrawingProperties>().First().Id == idToFind &&
                                                                                       d.Descendants <NonVisualDrawingProperties>().First().Name.InnerText.Contains(Constants._TEXTBOX_))
                                           .FirstOrDefault();
                        if (titleShape != default(Shape))
                        {
                            D.Paragraph data = titleShape.Descendants <D.Paragraph>().FirstOrDefault();

                            title = data != default(D.Paragraph) ? data.InnerText : title;
                        }

                        //slidePart.Slide.RemoveChild(titleShape);
                        titleShape.Remove();
                        slidePart.Slide.Save();

                        D.Paragraph paragraph = shape.Descendants <D.Paragraph>().FirstOrDefault();
                        if (paragraph != default(D.Paragraph))
                        {
                            paragraph.RemoveAllChildren();
                            slidePart.Slide.Save();
                            D.Run run1 = new D.Run();
                            paragraph.AppendChild(new D.ParagraphProperties()
                            {
                                Alignment = D.TextAlignmentTypeValues.Center
                            });
                            run1.AppendChild(new D.RunProperties()
                            {
                                Language = "en-US", Dirty = true
                            });
                            run1.Text = new D.Text(title);
                            paragraph.AppendChild(run1);
                        }
                        slidePart.Slide.Save();
                    }
                    i++;
                }
            }
        }
 /// <summary>
 /// Creates a run for an image to be inserted.
 /// </summary>
 /// <param name="relationshipId">Link of the part to embed.</param>
 /// <param name="imageFile">Image to embed.</param>
 /// <returns>A run with the image.</returns>
 private Run GetImageRun(String relationshipId, Bitmap imageFile)
 {
     long imageWidth = (long)((imageFile.Width / imageFile.HorizontalResolution) * 914400L);
     long imageHeight = (long)((imageFile.Height / imageFile.VerticalResolution) * 914400L);
     //Code from Microsoft: http://msdn.microsoft.com/en-us/library/office/bb497430(v=office.15).aspx
     var element =
      new Drawing(
      new DW.Inline(
          new DW.Extent() { Cx = imageWidth, Cy = imageHeight },
          new DW.EffectExtent()
          {
              LeftEdge = 0L,
              TopEdge = 0L,
              RightEdge = 0L,
              BottomEdge = 0L
          },
          new DW.DocProperties()
          {
              Id = (UInt32Value)1U,
              Name = "Picture 1"
          },
          new DW.NonVisualGraphicFrameDrawingProperties(
              new A.GraphicFrameLocks() { NoChangeAspect = true }),
          new A.Graphic(
              new A.GraphicData(
                  new PIC.Picture(
                      new PIC.NonVisualPictureProperties(
                          new PIC.NonVisualDrawingProperties()
                          {
                              Id = (UInt32Value)0U,
                              Name = "New Bitmap Image.jpg"
                          },
                          new PIC.NonVisualPictureDrawingProperties()),
                      new PIC.BlipFill(
                          new A.Blip(
                              new A.BlipExtensionList(
                                  new A.BlipExtension()
                                  {
                                      Uri =
                                        "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                  })
                          )
                          {
                              Embed = relationshipId,
                              CompressionState =
                              A.BlipCompressionValues.Print
                          },
                          new A.Stretch(
                              new A.FillRectangle())),
                      new PIC.ShapeProperties(
                          new A.Transform2D(
                              new A.Offset() { X = 0L, Y = 0L },
                              new A.Extents() { Cx = imageWidth, Cy = imageHeight }),
                          new A.PresetGeometry(
                              new A.AdjustValueList()
                          ) { Preset = A.ShapeTypeValues.Rectangle }))
              ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
      )
      {
          DistanceFromTop = (UInt32Value)0U,
          DistanceFromBottom = (UInt32Value)0U,
          DistanceFromLeft = (UInt32Value)0U,
          DistanceFromRight = (UInt32Value)0U,
      });
     Run run = new Run();
     run.AppendChild(element);
     return run;
 }
        /// <summary>
        /// Replaces a tag inside a paragraph (a:p) with parsed HTML
        /// </summary>
        /// <param name="p">The paragraph (a:p).</param>
        /// <param name="tag">The tag to replace by newText, if null or empty do nothing; tag is a regex string.</param>
        /// <param name="newText">The new text to replace the tag with, if null replaced by empty string and not visible.</param>
        /// <param name="fontName">Font name</param>
        /// <param name="fontSize">Font size. E.g. 800 is 8pt (small) font. If value is less than 100 it will be multiplied by 100 to keep up with PPT notation.</param>
        /// <param name="hyperlinks">URL Relationships dictionary. Relationship has to be defined on slide level.</param>
        /// <returns><c>true</c> if a tag has been found and replaced, <c>false</c> otherwise.</returns>
        internal static bool ReplaceTagWithHtml(A.Paragraph p, string tag, string newText, string fontName = null, int fontSize = 0, IDictionary <string, string> hyperlinks = null)
        {
            newText = CorrectUnhandledHtmlTags(newText); // e.g. deal with ul/li html tags
            bool isFirstLine = true;                     // avoiding unintentional empty line at the begining of the text
            bool replaced    = false;

            string[] closingTags = new string[] { "div", "p" }; // tags that force line break in PPTX paragraph

            if (string.IsNullOrEmpty(tag))
            {
                return(replaced);
            }

            if (newText == null)
            {
                newText = string.Empty;
            }
            newText = RemoveInvalidXMLChars(newText);

            while (true)
            {
                // Search for the tag
                Match match = Regex.Match(GetTexts(p), tag);
                if (!match.Success)
                {
                    break;
                }

                p.RemoveAllChildren(); // // remove exisitng children then add new

                HtmlParser hp = new HtmlParser(newText);
                MariGold.HtmlParser.IHtmlNode nodes = null;

                try
                {
                    nodes = hp.FindBodyOrFirstElement();
                }
                catch
                {
                    Console.WriteLine(String.Format("WARNING: HTML is empty or HTML schema has errors. Parsed HTML[]: [{0}]", newText));
                }

                while (nodes != null)
                {
                    foreach (var item in nodes.Children)
                    {
                        bool  skipLineBreak = false;
                        A.Run r             = new A.Run();
                        r.RunProperties = new A.RunProperties();

                        if (item.Html.Contains("<b>") || item.Html.Contains("<strong>"))
                        {
                            r.RunProperties.Bold = new DocumentFormat.OpenXml.BooleanValue(true);
                        }
                        if (item.Html.Contains("<i>") || item.Html.Contains("<em>"))
                        {
                            r.RunProperties.Italic = new DocumentFormat.OpenXml.BooleanValue(true);
                        }
                        if (item.Html.Contains("<u>") || item.Html.Contains("text-decoration: underline"))
                        {
                            r.RunProperties.Underline = new DocumentFormat.OpenXml.EnumValue <A.TextUnderlineValues>(A.TextUnderlineValues.Dash);
                        }
                        if (item.Html.Contains("<a"))
                        {
                            string uriId = null;
                            try
                            {
                                string url = PptxSlide.ParseHttpUrls(item.Html).First().Value;
                                uriId = hyperlinks.Where(q => q.Value == url).FirstOrDefault().Key;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("URL is no available");
                            }
                            if (uriId != null)
                            {
                                A.HyperlinkOnClick link = new A.HyperlinkOnClick()
                                {
                                    Id = uriId
                                };
                                r.RunProperties.AppendChild(link);
                            }
                        }

                        A.Text at = new A.Text(PptxTemplater.TextTransformationHelper.HtmlToPlainTxt(item.InnerHtml) + " "); // clear not interpreted html tags
                        if (at.InnerText.Trim() == "" && isFirstLine)
                        {
                            at          = new A.Text(); // avoid excessive new lines
                            isFirstLine = false;
                        }
                        r.AppendChild(at);
                        p.Append(r);

                        // LINE BREAK -- if outer tag is div add line break
                        if (closingTags.Contains(item.Parent.Tag) && skipLineBreak == false)
                        {
                            p.Append(new A.Break());
                        }
                    }

                    // remove parsed html part
                    newText = newText.Substring(nodes.Html.Length);
                    if (newText.Trim() == "")
                    {
                        break;
                    }
                    hp    = new HtmlParser(newText);
                    nodes = hp.FindBodyOrFirstElement();
                }

                var run = p.Descendants <A.Run>();
                foreach (var item in run)
                {
                    if (fontName != null)
                    {
                        item.RunProperties.RemoveAllChildren <A.LatinFont>();
                        var latinFont = new A.LatinFont();
                        latinFont.Typeface = fontName;
                        item.RunProperties.AppendChild(latinFont);
                    }
                    if (fontSize > 0)
                    {
                        item.RunProperties.FontSize = (fontSize > 99) ? fontSize : fontSize * 100; // e.g. translate value 8 (Power Point UI font size) to 800 for API
                    }
                }

                replaced = true;
            }

            return(replaced);
        }
        private int InsertTitleSlide(PresentationDocument presentationDocument, int slideNumber, string slideTitle, string subTitle, bool firstSlide)
        {
            int thisSlideNumber = slideNumber;
            if (presentationDocument == null)
            {
                MessageBox.Show("Can't insert slide in the presentation.");
            }

            PresentationPart presentationPart = presentationDocument.PresentationPart;

            if (presentationPart == null)
            {
                MessageBox.Show("The presentation document is empty.");
            }

            Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
            SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
            slide.Save(slidePart);

            string layoutName = Properties.Settings.Default.TITLE_SLIDE;

            SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
            SlideLayoutPart slideLayoutPart = null;
            foreach (SlideMasterPart smp in presentationPart.SlideMasterParts)
            {
                foreach (SlideLayoutPart slp in smp.SlideLayoutParts)
                {
                    if (slp.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase))
                    {
                        slideLayoutPart = slp;
                    }
                }
            }

            if (slideLayoutPart == null)
            {
                MessageBox.Show("Slide Layout not found");
                return slideNumber;
            }

            slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
            slidePart.Slide.CommonSlideData = (CommonSlideData)slideLayoutPart.SlideLayout.CommonSlideData.Clone();
            using (Stream stream = slideLayoutPart.GetStream())
            {
                slidePart.SlideLayoutPart.FeedData(stream);
            }

            foreach (ImagePart iPart in slideLayoutPart.ImageParts)
            {
                ImagePart newImagePart = slidePart.AddImagePart(iPart.ContentType, slideLayoutPart.GetIdOfPart(iPart));
                newImagePart.FeedData(iPart.GetStream());
            }

            foreach (Shape shp in slidePart.Slide.CommonSlideData.ShapeTree.Elements<Shape>())
            {
                if (shp.InnerText.Contains(Properties.Settings.Default.TITLE_SLIDE_MAIN_TITLE_KEYWORD))
                {
                    foreach (Drawing.Paragraph p in shp.TextBody.Elements<Drawing.Paragraph>())
                    {
                        if (p.InnerText.Contains(Properties.Settings.Default.TITLE_SLIDE_MAIN_TITLE_KEYWORD))
                        {
                            int runCounter = 0;
                            foreach (Drawing.Run r in p.Elements<Drawing.Run>())
                            {
                                if (runCounter == 0)
                                {
                                    r.Text.Text = slideTitle;
                                }
                                else
                                {
                                    r.Text.Text = "";
                                }
                            }
                        }
                        else
                        {
                            p.RemoveAllChildren();
                        }
                    }
                }
                if (shp.InnerText.Contains(Properties.Settings.Default.TITLE_SLIDE_SUBTITLE_KEYWORD))
                {
                    foreach (Drawing.Paragraph p in shp.TextBody.Elements<Drawing.Paragraph>())
                    {
                        if (p.InnerText.Contains(Properties.Settings.Default.TITLE_SLIDE_SUBTITLE_KEYWORD))
                        {
                            int runCounter = 0;
                            foreach (Drawing.Run r in p.Elements<Drawing.Run>())
                            {
                                if (runCounter == 0)
                                {
                                    r.Text.Text = subTitle;
                                }
                                else
                                {
                                    r.Text.Text = "";
                                }
                            }
                        }
                        else
                        {
                            p.RemoveAllChildren();
                        }
                    }
                }

            }

            NotesSlidePart notesSlidePart = slidePart.AddNewPart<NotesSlidePart>();
            NotesSlide notesSlide = CreateDeafultNotesPart(string.Empty);

            string SlideNotesText = "";
            if (firstSlide)
            {
                SlideNotesText = Properties.Settings.Default.DEFAULT_TITLE_SLIDE_NOTES +
                    Environment.NewLine + Environment.NewLine +
                    Properties.Settings.Default.DEFAULT_NOTES_ENDING;
            }
            else
            {
                SlideNotesText = Properties.Settings.Default.HEADING1_MARKUP + subTitle + Properties.Settings.Default.HEADING1_MARKUP
                    + Environment.NewLine + Environment.NewLine +
                    Properties.Settings.Default.DEFAULT_NOTES_ENDING;
            }
            notesSlidePart.NotesSlide = notesSlide;
            Shape shpNotes = (Shape)notesSlide.CommonSlideData.ShapeTree.LastChild;
            Drawing.Run newRun = new Drawing.Run();
            Drawing.RunProperties runProp = new Drawing.RunProperties();
            runProp.Bold = DocumentFormat.OpenXml.BooleanValue.FromBoolean(true);
            Drawing.Text newText = new Drawing.Text(SlideNotesText);
            newRun.AppendChild<Drawing.Text>(newText);
            newRun.RunProperties = runProp;
            Drawing.Paragraph newP = new Drawing.Paragraph(newRun);
            shpNotes.TextBody.Append(newP);

            SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;

            // Find the highest slide ID in the current list.
            uint maxSlideId = 1;
            SlideId prevSlideId = null;

            foreach (SlideId slideId in slideIdList.ChildElements)
            {
                if (slideId.Id > maxSlideId)
                {
                    maxSlideId = slideId.Id;
                }

                slideNumber--;
                if (slideNumber == 0)
                {
                    prevSlideId = slideId;
                }

            }

            maxSlideId++;

            // Get the ID of the previous slide.
            SlidePart lastSlidePart;

            if (prevSlideId != null)
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
            }
            else
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
            }

            // Insert the new slide into the slide list after the previous slide.
            SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
            newSlideId.Id = maxSlideId;
            newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);

            // Save the modified presentation.
            presentationPart.Presentation.Save();

            thisSlideNumber++;
            return thisSlideNumber;
        }
        private int InsertQuestionsSlide(PresentationDocument presentationDocument, int slideNumber)
        {
            int thisSlideNumber = slideNumber;
            if (presentationDocument == null)
            {
                MessageBox.Show("Can't insert slide in the presentation.");
            }

            PresentationPart presentationPart = presentationDocument.PresentationPart;

            if (presentationPart == null)
            {
                MessageBox.Show("The presentation document is empty.");
            }

            Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
            SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
            slide.Save(slidePart);

            string layoutName = Properties.Settings.Default.QUESTIONS_SLIDE;

            SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
            SlideLayoutPart slideLayoutPart = null;
            foreach (SlideMasterPart smp in presentationPart.SlideMasterParts)
            {
                foreach (SlideLayoutPart slp in smp.SlideLayoutParts)
                {
                    if (slp.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase))
                    {
                        slideLayoutPart = slp;
                    }
                }
            }

            if (slideLayoutPart == null)
            {
                MessageBox.Show("Slide Layout not found");
                return slideNumber;
            }
            slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
            slidePart.Slide.CommonSlideData = (CommonSlideData)slideLayoutPart.SlideLayout.CommonSlideData.Clone();
            using (Stream stream = slideLayoutPart.GetStream())
            {
                slidePart.SlideLayoutPart.FeedData(stream);
            }

            foreach (ImagePart iPart in slideLayoutPart.ImageParts)
            {
                ImagePart newImagePart = slidePart.AddImagePart(iPart.ContentType, slideLayoutPart.GetIdOfPart(iPart));
                newImagePart.FeedData(iPart.GetStream());
            }

            NotesSlidePart notesSlidePart = slidePart.AddNewPart<NotesSlidePart>();
            NotesSlide notesSlide = CreateDeafultNotesPart(Properties.Settings.Default.FORCE_SLIDE_HANDBOOK_NO + Environment.NewLine);

            string notesText =
                Properties.Settings.Default.HEADING2_MARKUP +
                Properties.Settings.Default.QUESTIONS_SLIDE_TITLE +
                Properties.Settings.Default.HEADING2_MARKUP +
                Environment.NewLine + Environment.NewLine;

            notesSlidePart.NotesSlide = notesSlide;
            Shape shpNotes = (Shape)notesSlide.CommonSlideData.ShapeTree.LastChild;
            Drawing.Run newRun = new Drawing.Run();
            Drawing.RunProperties runProp = new Drawing.RunProperties();
            runProp.Bold = DocumentFormat.OpenXml.BooleanValue.FromBoolean(true);
            Drawing.Text newText = new Drawing.Text(notesText);
            newRun.AppendChild<Drawing.Text>(newText);
            newRun.RunProperties = runProp;
            Drawing.Paragraph newP = new Drawing.Paragraph(newRun);
            shpNotes.TextBody.Append(newP);

            shpNotes = (Shape)notesSlide.CommonSlideData.ShapeTree.LastChild;
            newRun = new Drawing.Run();
            runProp = new Drawing.RunProperties();
            runProp.Bold = DocumentFormat.OpenXml.BooleanValue.FromBoolean(true);
            newText = new Drawing.Text(Properties.Settings.Default.DEFAULT_NOTES_ENDING + Environment.NewLine);
            newRun.AppendChild<Drawing.Text>(newText);
            newRun.RunProperties = runProp;
            newP = new Drawing.Paragraph(newRun);
            shpNotes.TextBody.Append(newP);

            SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;

            uint maxSlideId = 1;
            SlideId prevSlideId = null;

            foreach (SlideId slideId in slideIdList.ChildElements)
            {
                if (slideId.Id > maxSlideId)
                {
                    maxSlideId = slideId.Id;
                }

                slideNumber--;
                if (slideNumber == 0)
                {
                    prevSlideId = slideId;
                }

            }
            maxSlideId++;
            SlidePart lastSlidePart;

            if (prevSlideId != null)
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
            }
            else
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
            }
            SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
            newSlideId.Id = maxSlideId;
            newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);

            // Save the modified presentation.
            presentationPart.Presentation.Save();

            thisSlideNumber++;
            return thisSlideNumber;
        }
        private int InsertTopicDividerSlide(PresentationDocument presentationDocument, int slideNumber, string topicTitle, List<string> topicDividerNotes)
        {
            int thisSlideNumber = slideNumber;
            if (presentationDocument == null)
            {
                MessageBox.Show("Can't insert slide in the presentation.");
            }

            PresentationPart presentationPart = presentationDocument.PresentationPart;

            if (presentationPart == null)
            {
                MessageBox.Show("The presentation document is empty.");
            }

            Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
            SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
            slide.Save(slidePart);

            string layoutName = Properties.Settings.Default.TOPIC_DIVIDER_SLIDE;

            SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
            SlideLayoutPart slideLayoutPart = null;
            foreach (SlideMasterPart smp in presentationPart.SlideMasterParts)
            {
                foreach (SlideLayoutPart slp in smp.SlideLayoutParts)
                {
                    if (slp.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase))
                    {
                        slideLayoutPart = slp;
                    }
                }
            }

            if (slideLayoutPart == null)
            {
                MessageBox.Show("Slide Layout not found");
                return slideNumber;
            }
            slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
            slidePart.Slide.CommonSlideData = (CommonSlideData)slideLayoutPart.SlideLayout.CommonSlideData.Clone();
            using (Stream stream = slideLayoutPart.GetStream())
            {
                slidePart.SlideLayoutPart.FeedData(stream);
            }

            foreach (ImagePart iPart in slideLayoutPart.ImageParts)
            {
                ImagePart newImagePart = slidePart.AddImagePart(iPart.ContentType, slideLayoutPart.GetIdOfPart(iPart));
                newImagePart.FeedData(iPart.GetStream());
            }

            foreach (Shape shp in slidePart.Slide.CommonSlideData.ShapeTree.Elements<Shape>())
            {
                if (shp.InnerText.Contains(Properties.Settings.Default.TOPIC_DIVIDER_SLIDE_CONTAINER_KEYWORD))
                {
                    foreach (Drawing.Paragraph p in shp.TextBody.Elements<Drawing.Paragraph>())
                    {
                        if (p.InnerText.Contains(Properties.Settings.Default.TOPIC_DIVIDER_SLIDE_CONTAINER_KEYWORD))
                        {
                            int runCounter = 0;
                            foreach (Drawing.Run r in p.Elements<Drawing.Run>())
                            {
                                if (runCounter == 0)
                                {
                                    r.Text.Text = topicTitle;
                                }
                                else
                                {
                                    r.Text.Text = "";
                                }
                            }
                        }
                        else
                        {
                            p.RemoveAllChildren();
                        }
                    }
                }
            }

            NotesSlidePart notesSlidePart = slidePart.AddNewPart<NotesSlidePart>();
            NotesSlide notesSlide = CreateDeafultNotesPart(string.Empty);

            string SlideNotesText = "";
            SlideNotesText = Properties.Settings.Default.HEADING1_MARKUP +
                topicTitle +
                Properties.Settings.Default.HEADING1_MARKUP +
                Environment.NewLine + Environment.NewLine +
                Properties.Settings.Default.DEFAULT_NOTES_ENDING;

            notesSlidePart.NotesSlide = notesSlide;
            Shape shpNotes = (Shape)notesSlide.CommonSlideData.ShapeTree.LastChild;
            Drawing.Run newRun = new Drawing.Run();
            Drawing.RunProperties runProp = new Drawing.RunProperties();
            runProp.Bold = DocumentFormat.OpenXml.BooleanValue.FromBoolean(true);
            Drawing.Text newText = new Drawing.Text(SlideNotesText);
            newRun.AppendChild<Drawing.Text>(newText);
            newRun.RunProperties = runProp;
            Drawing.Paragraph newP = new Drawing.Paragraph(newRun);
            shpNotes.TextBody.Append(newP);

            SlideNotesText = Properties.Settings.Default.INSTRUCTOR_NOTES_MARKUP;
            SlideNotesText += Properties.Settings.Default.TOPIC_DIVIDER_TOPIC_OBJECTIVE + topicDividerNotes[0] + Environment.NewLine;
            SlideNotesText += Properties.Settings.Default.TOPIC_DIVIDER_TOPIC_METHODS + topicDividerNotes[1] + Environment.NewLine;
            SlideNotesText += Properties.Settings.Default.TOPIC_DIVIDER_TOPIC_EVALUATION + topicDividerNotes[2] + Environment.NewLine;
            SlideNotesText += Properties.Settings.Default.TOPIC_DIVIDER_TOPIC_TIME + topicDividerNotes[3] + Environment.NewLine;
            SlideNotesText += Properties.Settings.Default.TOPIC_DIVIDER_TOPIC_MATERIALS + topicDividerNotes[4] + Environment.NewLine;
            SlideNotesText += Properties.Settings.Default.TOPIC_DIVIDER_TOPIC_NOTES + topicDividerNotes[5] + Environment.NewLine;
            SlideNotesText += Properties.Settings.Default.INSTRUCTOR_NOTES_MARKUP;

            shpNotes = (Shape)notesSlide.CommonSlideData.ShapeTree.LastChild;
            newRun = new Drawing.Run();
            runProp = new Drawing.RunProperties();
            runProp.Italic = DocumentFormat.OpenXml.BooleanValue.FromBoolean(true);
            newText = new Drawing.Text(SlideNotesText);
            newRun.AppendChild<Drawing.Text>(newText);
            newRun.RunProperties = runProp;
            newP = new Drawing.Paragraph(newRun);
            shpNotes.TextBody.Append(newP);

            SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;

            uint maxSlideId = 1;
            SlideId prevSlideId = null;

            foreach (SlideId slideId in slideIdList.ChildElements)
            {
                if (slideId.Id > maxSlideId)
                {
                    maxSlideId = slideId.Id;
                }

                slideNumber--;
                if (slideNumber == 0)
                {
                    prevSlideId = slideId;
                }

            }
            maxSlideId++;

            SlidePart lastSlidePart;

            if (prevSlideId != null)
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
            }
            else
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
            }

            SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
            newSlideId.Id = maxSlideId;
            newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);

            // Save the modified presentation.
            presentationPart.Presentation.Save();

            thisSlideNumber++;
            return thisSlideNumber;
        }