Saturday 25 April 2015

Insert Master-Detail Data using Transact-SQL

Introduction
Many applications have components that connect, manage, and consume data from a database. If you are designing/building an application that connects to a database to continuously insert, update or delete data, you should keep in mind that each operation will need a round-trip to the database and will consume valuable resources (e.g., network traffic, memory, CPU, etc.). Microsoft SQL Server 2000 SQLXML allows among other things to manage batch operations in a database, which reduces significantly the need of more than one round-trip to a database. OpenXML is a Transact-SQL statement that allows to represent data in XML format and can be used to insert, update, and delete more than one row (represented by an element) in a table or group of tables.
Note: The samples provided in this document use the PUBS database shipped with Microsoft SQL Server 2000.
To create a stored procedure using SQLXML - OPENXML
  1. Open Microsoft SQL Server 2000 Query Analyzer.
  2. In the text panel, define the affected database.
    [TSQL] USE MYDATABASE
  3. Create the procedure and assign a owner and name.
    CREATE PROCEDURE dbo.dspSample
  4. Receive an XML string.
    @doc varchar(8000)AS
  5. Declare a XML document handle.
    DECLARE @hdoc int
  6. Generate the document in memory.
    EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc
  7. Create a new transaction.
    BEGIN TRANSACTION
  8. If you need to insert rows to a table, use the following sample code and replace the table and field names with the ones you need:
    INSERT INTO MYTABLESELECT *FROM OPENXML(@hdoc, 'XPath query')WITH MYTABLE
  9. If you need to update rows to a table, use the following sample code and replace the table and field names with the ones you need:
    UPDATE MYTABLE SETMYTABLE.fieldX = XMLTABLE.fieldX,
    MYTABLE.fieldY = XMLTABLE.fieldY
    FROM OPENXML
    (@hDoc, 'XPath query')WITH MYTABLE XMLTABLEWHERE MYTABLE.fieldID = XMLTABLE.fieldID
  10. If you need to delete rows to a table, use the following sample code and replace the table and field names with the ones you need:
    DELETE MYTABLEFROM OPENXML(@hDoc, 'XPath query')WITH MYTABLE XMLTABLEWHERE MYTABLE.fieldID = XMLTABLE.fieldID
  11. Commit the transaction.
    COMMIT
  12. Remove the XML document from memory.
    EXEC sp_xml_removedocument @hdoc
    Note Skipping this step avoids freeing memory and will result in poor performance. 
  13. Finish and run the procedure.
    RETURNGO
The following sample code shows how to create a stored procedure to insert a publisher and its corresponding titles (master-detail relationship) to the PUBS database:
[TSQL] CREATE PROCEDURE dbo.dspInsertPublisher_and_Titles
@doc 
varchar
(8000)AS
DECLARE 
@hdoc 
int
EXEC 
sp_xml_preparedocument @hdoc OUTPUT
, @docBEGIN TRANSACTION
INSERT INTO 
PUBLISHERSSELECT FROM OPENXML(@hdoc, '//publisher')WITH PUBLISHERSINSERT INTO TITLESSELECT FROM OPENXML(@hdoc, '//title')WITH TITLESCOMMIT
EXEC 
sp_xml_removedocument @hdocRETURNGO
To generate an XML document from your .NET application.
Create an XML document with an element for each row you need to insert and the corresponding attribute values. The following example shows how to create an XML document from a .NET application.
[C#]
XmlDocument xmldoc = new XmlDocument();
XmlElement doc = xmldoc.CreateElement("doc");
xmldoc.AppendChild(doc);
XmlElement publisher = xmldoc.CreateElement("publisher");
doc.AppendChild(publisher);
string
 pub_id = "9919";
publisher.SetAttribute("pub_id", pub_id);
publisher.SetAttribute("pub_name", "DotNetTreats Books");
publisher.SetAttribute("city", "Redmond");
publisher.SetAttribute("state", "WA");
publisher.SetAttribute("country", "USA");
for (int
 i = 1; i < 4; i++)
{
XmlElement title = xmldoc.CreateElement("title");
doc.AppendChild(title);
StringBuilder titleID = 
new
 StringBuilder("DT100");
StringBuilder titleName = 
new
 StringBuilder("OOP Concepts and .NET Part ");
title.SetAttribute("title_id", titleID.Append(i).ToString());
title.SetAttribute("title", titleName.Append(i).ToString());
title.SetAttribute("type", "Technical Article");
title.SetAttribute("pub_id", pub_id);
title.SetAttribute("price", "19.9900");
title.SetAttribute("advance", "9000.0000");
title.SetAttribute("royalty", "10");
title.SetAttribute("ytd_sales", "1000");
title.SetAttribute("notes", "Object-Oriented Programming concepts and samples.");
title.SetAttribute("pubdate", "2005-01-30");
}
[Visual Basic]
Dim xmldoc As XmlDocument = New XmlDocumentDim doc As XmlElement = xmldoc.CreateElement("doc")
xmldoc.AppendChild(doc)
Dim publisher As
 XmlElement = xmldoc.CreateElement("publisher")
doc.AppendChild(publisher)
Dim pub_id As String
 = "9919"
publisher.SetAttribute("pub_id", pub_id)
publisher.SetAttribute("pub_name", "DotNetTreats Books")
publisher.SetAttribute("city", "Redmond")
publisher.SetAttribute("state", "WA")
publisher.SetAttribute("country", "USA")
Dim i As Integer
 = 1Do While (i < 4)Dim title As XmlElement = xmldoc.CreateElement("title")
doc.AppendChild(title)
Dim titleID As StringBuilder = New
 StringBuilder("DT100")Dim titleName As StringBuilder = New StringBuilder("OOP Concepts and .NET Part ")
title.SetAttribute("title_id", titleID.Append(i).ToString)
title.SetAttribute("title", titleName.Append(i).ToString)
title.SetAttribute("type", "Technical Article")
title.SetAttribute("pub_id", pub_id)
title.SetAttribute("price", "19.9900")
title.SetAttribute("advance", "9000.0000")
title.SetAttribute("royalty", "10")
title.SetAttribute("ytd_sales", "1000")
title.SetAttribute("notes", "Object-Oriented Programming concepts and samples.")title.SetAttribute("pubdate", "2005-01-30")
i = (i + 1)
Loop
To insert data to the corresponding database using ADO.NET
Create a connection and a command that will call the stored procedure and send the XML document as a parameter.
[C#]
string connS = "data source=(local);database=pubs;integrated security=SSPI;persist security info=false";
SqlConnection sqlConn = 
new
 SqlConnection(connS);
sqlConn.Open();
SqlCommand cmd = 
new
 SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dspInsertPublisher_and_Titles";
cmd.Parameters.AddWithValue("@doc", xmldoc.OuterXml);
cmd.ExecuteNonQuery();
sqlConn.Close();
[Visual Basic]
Dim connS As String = "data source=(local);database=pubs;integrated security=SSPI;persist security info=false"Dim sqlConn As SqlConnection = New SqlConnection(connS)
sqlConn.Open()
Dim cmd As SqlCommand = New
 SqlCommand
cmd.Connection = sqlConn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "dspInsertPublisher_and_Titles"
cmd.Parameters.Add("@doc", xmldoc.OuterXml)
cmd.ExecuteNonQuery()
sqlConn.Close()

Note: The sample source code* for this document works only in Visual Studio 2005

From:
http://www.c-sharpcorner.com/UploadFile/ecabral/InsertMaster-DetailData06252005004031AM/InsertMaster-DetailData.aspx

Thursday 23 April 2015

Merge multiple word documents into one Open Xml

Using openXML SDK only, you can use AltChunk element to merge the multiple document into one.

using (WordprocessingDocument document = WordprocessingDocument.Open(@"C:\Temp\c.docx", true))
            {
                string altChunkId = "AltChunkID" + DateTime.Now.Ticks.ToString().Substring(0, 2);
                var mainPart = document.MainDocumentPart;
                var chunk = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = File.Open(@"C:\Temp\c1.docx", FileMode.Open))
                {
                    chunk.FeedData(fileStream);
                }
                var altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document.Body.InsertAfter(altChunk,mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                mainPart.Document.Save();

            }

Replace Multiple Image In Word OPENXML

I get the worked sample Code from:

http://openxmldeveloper.org/cfs-file.ashx/__key/communityserver-components-postattachments/00-00-15-84-97/ReplaceMultipleImages.rar

But it cannot make the image remain original size. the code below, it explained clearly how to calculate the image size.

Adding Images to Documents in Word 2007 by Using the Open XML SDK 2.0 for Microsoft Office

Code It

This visual how-to article presents a solution that creates a Word 2007 document that contains two images. The first image is formatted as an inline image by setting its Text Wrapping format to In Line with Text.
Figure 1. Inline image in a Word document

Inline image in a Word document

The second image is formatted as a floating image by setting its Text Wrapping format to Tight.
Figure 2. Floating image in a Word document

Floating image in a Word document

To illustrate how to create a Word 2007 document that contains inline and floating images programmatically, this section walks through the following steps:
  1. Creating a Windows console application solution in Visual Studio 2008.
  2. Adding references to the DocumentFormat.OpenXml, WindowsBase, and System.Drawing assemblies.
  3. Adding the sample code to the solution.

Creating a Windows Console Application in Visual Studio 2008

This visual how-to article uses a Windows console application to provide the framework for the sample code. However, you could use the same approach that is illustrated here with other application types as well.

To create a Windows Console Application in Visual Studio 2008

  1. Start Microsoft Visual Studio 2008.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box select the Visual C# Windows type in the Project types pane.
  4. Select Console Application in the Templates pane, and then name the project AddImage.
    Figure 3. Create new solution in the New Project dialog box

    Create new solution in the New Project dialog box

  5. Click OK to create the solution.

Adding References to the DocumentFormat.OpenXml, WindowsBase, and System.Drawing Assemblies

The sample code uses the classes and enumerations that are in the DocumentFormat.OpenXml.dll assembly that is installed with the Open XML SDK 2.0 for Microsoft Office. To add the reference to the assembly in the following steps or to build the sample code that accompanies this visual how-to, you must first download and install the Open XML SDK 2.0 for Microsoft Office so that the assembly is available.

To add References to the DocumentFormat.OpenXml, WindowsBase, and System.Drawing Assemblies

  1. Add a reference to the DocumentFormat.OpenXml assembly by doing the following:
    1. On the Project menu in Visual Studio, click Add Reference to open the Add Reference dialog box.
    2. Select the .NET tab, scroll down to DocumenFormat.OpenXml, select it, and then click OK.
      Figure 4. Add Reference to DocumentFormat.OpenXML

      Add Reference to DocumentFormat.OpenXML

  2. The classes in the DocumentFormat.OpenXml assembly use the System.IO.Packaging.Package class that is defined in the WindowsBase assembly. Add a reference to the WindowsBase assembly by doing the following:
    1. On the Project menu in Visual Studio, click Add Reference to open the Add Reference dialog box.
    2. Select the .NET tab, scroll down to WindowsBase, select it, and then click OK.
      Figure 5. Add Reference to WindowsBase

      Add Reference to WindowsBase

  3. The sample code uses the Bitmap class that is defined in the System.Drawing assembly. Add a reference to the System.Drawing assembly by doing the following:
    1. On the Project menu in Visual Studio, click Add Reference to open the Add Reference dialog box.
    2. Select the .NET tab, scroll down to System.Drawing, select it, and then click OK.
      Figure 6. Add Reference to System.Drawing

      Add Reference to System.Drawing

Adding the Sample Code to the Solution

Replace the entire contents of the Program.cs source file with the following code.
using System;
using System.IO;
using System.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using DocumentFormat.OpenXml;
using a = DocumentFormat.OpenXml.Drawing;
using pic = DocumentFormat.OpenXml.Drawing.Pictures;

class Program
{
  static void Main(string[] args)
  {
    string imageDocumentPath = @"C:\Temp\ImageDocument.docx";
    string imageFileFolder = @"C:\Temp\";
    string imageFileName = "Image.jpg";

    using (WordprocessingDocument package =
      WordprocessingDocument.Create(imageDocumentPath,
      WordprocessingDocumentType.Document))
    {
      AddParts(package, imageFileFolder, imageFileName);
    }
  }

  private static void AddParts(WordprocessingDocument parent,
      string imageFileFolder, string imageFileName)
  {
    long imageWidthEMU = 0;
    long imageHeightEMU = 0;

    var mainDocumentPart = parent.AddMainDocumentPart();

    var imagePart =
      mainDocumentPart.AddNewPart<ImagePart>("image/jpeg", "rId1");

    GenerateImagePart(imagePart, imageFileFolder + imageFileName,
      ref imageWidthEMU, ref imageHeightEMU);

    GenerateMainDocumentPart(imageFileName, imageWidthEMU,
      imageHeightEMU).Save(mainDocumentPart);
  }

  private static Document GenerateMainDocumentPart(
    string imageFileName, long imageWidthEMU, long imageHeightEMU)
  {
    string fillText = "0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 ";
    string GraphicDataUri =
      "http://schemas.openxmlformats.org/drawingml/2006/picture";
    
    // Image wrapping polygons in Microsoft Word use a fixed
    // coordinate space that is 21600 units x 21600 units.
    // Coordinate (0,0) is the upper left corner of the image and
    // coordinate (21600,21600) is the lower right corner of the
    // image. This is the case regardless of the original size of
    // the image. The 21600 value is a legacy artifact from the
    // drawing layer of early versions of the Microsoft Office.
    // 
    // In order to specify a triangular wrapping polygon with
    // specific margins for a floating image the code shown below
    // needs to know how many wrapping polygon units there are per
    // inch in both the horizontal and vertical directions since
    // they will not be the same for non-square images.

    double imageWidthInInches = imageWidthEMU / 914400.0;
    double imageHeightInInches = imageHeightEMU / 914400.0;

    long horizontalWrapPolygonUnitsPerInch =
      (long)(21600L / imageWidthInInches);

    long verticalWrapPolygonUnitsPerInch =
      (long)(21600L / imageHeightInInches); 

    var element =
      new Document(
        new Body(
          new Paragraph(

            new ParagraphProperties(
              new Justification() { Val = JustificationValues.Both }),

            new Run(
              new Text(fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText +
                       fillText + fillText + fillText)),

            new Run(
              new Drawing(
                new wp.Inline(

                  new wp.Extent()
                  {
                    Cx = imageWidthEMU,
                    Cy = imageHeightEMU
                  },

                  new wp.EffectExtent()
                  {
                    LeftEdge = 19050L,
                    TopEdge = 0L,
                    RightEdge = 9525L,
                    BottomEdge = 0L
                  },

                  new wp.DocProperties()
                  {
                    Id = (UInt32Value)1U,
                    Name = "Inline Text Wrapping Picture",
                    Description = imageFileName
                  },

                  new wp.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 = imageFileName
                          },
                          new pic.NonVisualPictureDrawingProperties()),

                        new pic.BlipFill(
                          new a.Blip() { Embed = "rId1" },
                          new a.Stretch(
                            new a.FillRectangle())),

                        new pic.ShapeProperties(
                          new a.Transform2D(
                            new a.Offset() { X = 0L, Y = 0L },
                            new a.Extents()
                            {
                                Cx = imageWidthEMU,
                                Cy = imageHeightEMU
                            }),

                          new a.PresetGeometry(
                            new a.AdjustValueList()
                          ) { Preset = a.ShapeTypeValues.Rectangle }))
                    )
                    { Uri = GraphicDataUri })
                )
                {
                    DistanceFromTop = (UInt32Value)0U,
                    DistanceFromBottom = (UInt32Value)0U,
                    DistanceFromLeft = (UInt32Value)0U,
                    DistanceFromRight = (UInt32Value)0U
                })),

              new Run(
                  new Text(fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText))
          ),

          new Paragraph(

            new ParagraphProperties(
              new Justification() { Val = JustificationValues.Both },

            new Run(

              new Drawing(

                new wp.Anchor(

                  new wp.SimplePosition() { X = 0L, Y = 0L },

                  // Center the image horizontally on the page.
                  new wp.HorizontalPosition(
                    new wp.HorizontalAlignement("center")
                  )
                  { RelativeFrom =
                    wp.HorizontalRelativePositionValues.Margin },

                  // Position the image 1.5" from the top of the
                  // paragraph.
                  new wp.VerticalPosition(
                    new wp.PositionOffset("1371600")
                  )
                  { RelativeFrom =
                    wp.VerticalRelativePositionValues.Paragraph },

                  new wp.Extent()
                  { Cx = imageWidthEMU,
                    Cy = imageHeightEMU },

                  new wp.EffectExtent()
                  { LeftEdge = 0L,
                    TopEdge = 0L,
                    RightEdge = 0L,
                    BottomEdge = 0L },

                  new wp.WrapTight(
                    new wp.WrapPolygon(
                      // Create a wrapping polygon that is a triangle.
                      // Start point is 1" to the left and .5" above
                      // the upper left corner of the image.
                      new wp.StartPoint()
                      { X = -horizontalWrapPolygonUnitsPerInch,
                        Y = -verticalWrapPolygonUnitsPerInch / 2
                      },
                      // Next point is centered horizontally and 1"
                      // below the bottom of the image.
                      new wp.LineTo()
                      { X = 10800,
                        Y = 21600L + verticalWrapPolygonUnitsPerInch
                      },
                      // Next point is 1" to the right and .5" above
                      // the upper right corner of the image.
                      new wp.LineTo() 
                      { X = 21600L + horizontalWrapPolygonUnitsPerInch,
                        Y = -verticalWrapPolygonUnitsPerInch / 2 }
                    ) { Edited = false }
                  ){ WrapText = wp.WrapTextValues.BothSides },
                  
                  new wp.DocProperties()
                  { Id = (UInt32Value)2U,
                    Name = "Tight Text Wrapping Picture",
                    Description = "imageFileName" },

                  new wp.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 = "imageFileName" },
                          new pic.NonVisualPictureDrawingProperties()),

                        new pic.BlipFill(
                          new a.Blip() { Embed = "rId1" },
                          new a.Stretch(
                            new a.FillRectangle())),

                        new pic.ShapeProperties(

                          new a.Transform2D(
                            new a.Offset() { X = 0L, Y = 0L },

                            new a.Extents()
                            { Cx = imageWidthEMU,
                              Cy = imageHeightEMU }),
                          
                          new a.PresetGeometry(
                            new a.AdjustValueList()
                          )
                          { Preset = a.ShapeTypeValues.Rectangle }
                        )
                      )
                )
                { Uri = GraphicDataUri })
              )
              { DistanceFromTop = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft = (UInt32Value)114300U,
                DistanceFromRight = (UInt32Value)114300U,
                SimplePos = false,
                RelativeHeight = (UInt32Value)251658240U,
                BehindDoc = true,
                Locked = false,
                LayoutInCell = true,
                AllowOverlap = true })),

                new Run(
                  new Text(fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText +
                           fillText + fillText + fillText))
          )
        )
      )
    );

    return element;
  }

  public static void GenerateImagePart(OpenXmlPart part,
    string imageFilePath, ref long imageWidthEMU,
    ref long imageHeightEMU)
  {
    byte[] imageFileBytes;
    Bitmap imageFile;

    // Open a stream on the image file and read it's contents.
    using (FileStream fsImageFile = File.OpenRead(imageFilePath))
    {
      imageFileBytes = new byte[fsImageFile.Length];
      fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

      imageFile = new Bitmap(fsImageFile);
    }

    // Get the dimensions of the image in English Metric Units (EMU)
    // for use when adding the markup for the image to the document.
    imageWidthEMU =
      (long)(
      (imageFile.Width / imageFile.HorizontalResolution) * 914400L);
    imageHeightEMU =
      (long)(
      (imageFile.Height / imageFile.VerticalResolution) * 914400L);

    // Write the contents of the image to the ImagePart.
    using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
    {
      writer.Write(imageFileBytes);
      writer.Flush();
    }
  }
}
Build and run the solution in Visual Studio by pressing CTRL+F5. When you build and run the sample code, it creates a document named ImageDocument.docx in the C:\Temp folder. To change the name or location of the document modify the sample code and change the value of the imageDocumentPath variable defined in the Main method.
The document that the sample code creates contains inline and floating images. The sample code specifies that the image file to insert into the document is named Image.jpg and is located in the C:\Temp folder. To change the name or the location of the image file, modify the sample code and change the values of the imageFileFolder orimageFileName variables defined in the Main method.

Read It

The sample code in this visual how-to article illustrates how to create a Word 2007 document that contains inline and floating images. This section uses code snippets from the Code It section to describe the approach to the solution.
The code first creates a WordprocessingDocument package via the WordprocessingDocument.Create method. It then calls the AddParts helper method to add the document parts needed to support the images.
using (WordprocessingDocument package =
    WordprocessingDocument.Create(imageDocumentPath,
    WordprocessingDocumentType.Document))
{
    AddParts(package, imageFileFolder, imageFileName);
}
The AddParts method calls helper methods to add the main document and image parts to the package.
var mainDocumentPart = parent.AddMainDocumentPart();

var imagePart =
    mainDocumentPart.AddNewPart<ImagePart>("image/jpeg", "rId1");

GenerateImagePart(imagePart, imageFileFolder + imageFileName,
    ref imageWidthEMU, ref imageHeightEMU);

GenerateMainDocumentPart(imageFileName, imageWidthEMU,
    imageHeightEMU).Save(mainDocumentPart);
The main document part created by the GenerateMainDocumentPart method contains two paragraphs. The first paragraph contains the inline image that is preceeded and followed by text to illustrate it's inline placement. The code adds a Run to the paragraph that contains a Drawing element with a child Inline element that specifies the details of the inline image. The relationship to the image part that contains the image bytes is specified with a Blip element that has it's Embed attribute set to the relationship ID of the image part.
new Paragraph(

  new ParagraphProperties(
    new Justification() { Val = JustificationValues.Both }),

  new Run(
    new Text(fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText +
             fillText + fillText + fillText)),

  new Run(
    new Drawing(
      new wp.Inline(

        new wp.Extent()
        {
          Cx = imageWidthEMU,
          Cy = imageHeightEMU
        },

        new wp.EffectExtent()
        {
          LeftEdge = 19050L,
          TopEdge = 0L,
          RightEdge = 9525L,
          BottomEdge = 0L
        },

        new wp.DocProperties()
        {
          Id = (UInt32Value)1U,
          Name = "Inline Text Wrapping Picture",
          Description = imageFileName
        },

        new wp.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 = imageFileName
                },
                new pic.NonVisualPictureDrawingProperties()),

              new pic.BlipFill(
                new a.Blip() { Embed = "rId1" },
                new a.Stretch(
                  new a.FillRectangle())),

              new pic.ShapeProperties(
                new a.Transform2D(
                  new a.Offset() { X = 0L, Y = 0L },
                  new a.Extents()
                  {
                      Cx = imageWidthEMU,
                      Cy = imageHeightEMU
                  }),

                new a.PresetGeometry(
                  new a.AdjustValueList()
                ) { Preset = a.ShapeTypeValues.Rectangle }))
          )
          { Uri = GraphicDataUri })
      )
      {
          DistanceFromTop = (UInt32Value)0U,
          DistanceFromBottom = (UInt32Value)0U,
          DistanceFromLeft = (UInt32Value)0U,
          DistanceFromRight = (UInt32Value)0U
      })),

    new Run(
        new Text(fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText))
)
The second paragraph contains the floating image. The code adds a Run to the paragraph that contains a Drawing element with a child Anchor element that specifies the details of the floating image. The floating image is positioned centered horizontally relative to the margins and vertically 1.5 inches from the top of the paragraph. Just as with the inline image the relationship to the image part that contains the image bytes is specified with a Blip element that has it's Embed attribute set to the relationship ID of the image part.
Floating images use a wrapping polygon to specify how text should flow around the image. Image wrapping polygons in Microsoft Word use a fixed coordinate space that is 21600 units x 21600 units. Coordinate (0,0) is the upper left corner of the image and coordinate (21600,21600) is the lower right corner of the image. Microsoft Word scales the size of the wrapping polygon units to fit the size of the image. The 21600 value is a legacy artifact from the drawing layer of early versions of Microsoft Office.
The following floating-image code snippet specifies a triangular wrapping polygon. To generically calculate the end points of the wrapping polygon for different sized images the code calculates how many wrapping polygon units there are per inch. This is done in both the horizontal and vertical directions since they will not be the same for non-square images. It then uses these values to specify the coordinates of the wrapping polygon end points. The 914400 value used in the calculations is the number of English Metric Units (EMU) in one inch.
double imageWidthInInches = imageWidthEMU / 914400.0;
double imageHeightInInches = imageHeightEMU / 914400.0;

long horizontalWrapPolygonUnitsPerInch =
  (long)(21600L / imageWidthInInches);

long verticalWrapPolygonUnitsPerInch =
  (long)(21600L / imageHeightInInches);
new Paragraph(

  new ParagraphProperties(
    new Justification() { Val = JustificationValues.Both },

  new Run(

    new Drawing(

      new wp.Anchor(

        new wp.SimplePosition() { X = 0L, Y = 0L },

        // Center the image horizontally on the page.
        new wp.HorizontalPosition(
          new wp.HorizontalAlignement("center")
        )
        { RelativeFrom =
          wp.HorizontalRelativePositionValues.Margin },

        // Position the image 1.5" from the top of the
        // paragraph.
        new wp.VerticalPosition(
          new wp.PositionOffset("1371600")
        )
        { RelativeFrom =
          wp.VerticalRelativePositionValues.Paragraph },

        new wp.Extent()
        { Cx = imageWidthEMU,
          Cy = imageHeightEMU },

        new wp.EffectExtent()
        { LeftEdge = 0L,
          TopEdge = 0L,
          RightEdge = 0L,
          BottomEdge = 0L },

        new wp.WrapTight(
          new wp.WrapPolygon(
            // Create a wrapping polygon that is a triangle.
            // Start point is 1" to the left and .5" above
            // the upper left corner of the image.
            new wp.StartPoint()
            { X = -horizontalWrapPolygonUnitsPerInch,
              Y = -verticalWrapPolygonUnitsPerInch / 2
            },
            // Next point is centered horizontally on the image
            // and 1" below the bottom of the image.
            new wp.LineTo()
            { X = 10800,
              Y = 21600L + verticalWrapPolygonUnitsPerInch
            },
            // Next point is 1" to the right and .5" above
            // the upper right corner of the image.
            new wp.LineTo() 
            { X = 21600L + horizontalWrapPolygonUnitsPerInch,
              Y = -verticalWrapPolygonUnitsPerInch / 2 }
          ) { Edited = false }
        ){ WrapText = wp.WrapTextValues.BothSides },
        
        new wp.DocProperties()
        { Id = (UInt32Value)2U,
          Name = "Tight Text Wrapping Picture",
          Description = "imageFileName" },

        new wp.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 = "imageFileName" },
                new pic.NonVisualPictureDrawingProperties()),

              new pic.BlipFill(
                new a.Blip() { Embed = "rId1" },
                new a.Stretch(
                  new a.FillRectangle())),

              new pic.ShapeProperties(

                new a.Transform2D(
                  new a.Offset() { X = 0L, Y = 0L },

                  new a.Extents()
                  { Cx = imageWidthEMU,
                    Cy = imageHeightEMU }),
                
                new a.PresetGeometry(
                  new a.AdjustValueList()
                )
                { Preset = a.ShapeTypeValues.Rectangle }
              )
            )
      )
      { Uri = GraphicDataUri })
    )
    { DistanceFromTop = (UInt32Value)0U,
      DistanceFromBottom = (UInt32Value)0U,
      DistanceFromLeft = (UInt32Value)114300U,
      DistanceFromRight = (UInt32Value)114300U,
      SimplePos = false,
      RelativeHeight = (UInt32Value)251658240U,
      BehindDoc = true,
      Locked = false,
      LayoutInCell = true,
      AllowOverlap = true })),

      new Run(
        new Text(fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText +
                 fillText + fillText + fillText))
  )
)
The Image part that contains the embedded image and is referenced by the Blip elements is generated by the GenerateImagePart method. The method opens a FileStream on the image file and reads the file contents into a byte array. It then opens the content data stream on the image part created by the AddParts method and uses a BinaryWriter to write the image file contents to the stream. The method also calculates the horizontal and vertical extents of the image in EMU. You can use those measurements to set the attributes related to those extents in the drawing elements of the inline and floating images.
public static void GenerateImagePart(OpenXmlPart part,
  string imageFilePath, ref long imageWidthEMU,
  ref long imageHeightEMU)
{
  byte[] imageFileBytes;
  Bitmap imageFile;

  // Open a stream on the image file and read it's contents. The
  // following code will generate an exception if an invalid file
  // name is passed.
  using (FileStream fsImageFile = File.OpenRead(imageFilePath))
  {
    imageFileBytes = new byte[fsImageFile.Length];
    fsImageFile.Read(imageFileBytes, 0, imageFileBytes.Length);

    imageFile = new Bitmap(fsImageFile);
  }

  // Get the dimensions of the image in English Metric Units (EMU)
  // for use when adding the markup for the image to the document.
  imageWidthEMU =
    (long)(
    (imageFile.Width / imageFile.HorizontalResolution) * 914400L);
  imageHeightEMU =
    (long)(
    (imageFile.Height / imageFile.VerticalResolution) * 914400L);

  // Write the contents of the image to the ImagePart.
  using (BinaryWriter writer = new BinaryWriter(part.GetStream()))
  {
    writer.Write(imageFileBytes);
    writer.Flush();
  }
}