Ejemplo n.º 1
0
        /// <summary>
        /// Save the styl for worksheet headers.
        /// </summary>
        /// <param name="cellLocation">Cell location.</param>
        /// <param name="spreadSheet">Spreadsheet to change.</param>
        /// <param name="workSheetPart">Worksheet to change.</param>
        private static void SeatHeaderStyle(string cellLocation, SpreadsheetDocument spreadSheet, WorksheetPart workSheetPart)
        {
            Stylesheet styleSheet = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
            Cell       cell       = workSheetPart.Worksheet.Descendants <Cell>().Where(c => c.CellReference == cellLocation).FirstOrDefault();

            if (cell == null)
            {
                throw new ArgumentNullException("Cell not found");
            }

            cell.SetAttribute(new OpenXmlAttribute("", "s", "", "1"));
            OpenXmlAttribute cellStyleAttribute = cell.GetAttribute("s", "");
            CellFormats      cellFormats        = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats;

            // pick tthe first cell format.
            CellFormat cellFormat = (CellFormat)cellFormats.ElementAt(0);

            CellFormat cf = new CellFormat(cellFormat.OuterXml);

            cf.FontId = styleSheet.Fonts.Count;
            cf.FillId = styleSheet.Fills.Count;

            cellFormats.AppendChild(cf);

            int a = (int)styleSheet.CellFormats.Count.Value;

            cell.SetAttribute(cellStyleAttribute);

            cell.StyleIndex = styleSheet.CellFormats.Count;

            workSheetPart.Worksheet.Save();
        }
Ejemplo n.º 2
0
        private void writeTables(OpenXmlWriter writer, WorksheetPart part, ref int tableCount)
        {
            if (!_tables.Any())
            {
                return;
            }
            var countAtt = new OpenXmlAttribute("count", null, _tables.Count.ToString());

            writer.WriteStartElement(new TableParts(), new List <OpenXmlAttribute>()
            {
                countAtt
            });

            foreach (var table in _tables)
            {
                var tableId         = "table" + tableCount;
                var tableDefinition = part.AddNewPart <TableDefinitionPart>(tableId);
                tableDefinition.Table = table.Value.GetTableDefinition(tableCount, table.Key.ColumnIndex, table.Key.RowIndex);
                var idAtt = new OpenXmlAttribute("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", tableId);
                writer.WriteStartElement(new TablePart(), new List <OpenXmlAttribute>()
                {
                    idAtt
                });
                writer.WriteEndElement();
                tableCount++;
            }
            writer.WriteEndElement();
        }
Ejemplo n.º 3
0
        private static string GetFieldNameWithOptions(SimpleField field, out string[] switches, out string[] options)
        {
            OpenXmlAttribute a = field.GetAttribute("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

            switches = new string[0];
            options  = new string[3];
            string fieldName   = string.Empty;
            string instruction = a.Value;

            if (!string.IsNullOrEmpty(instruction))
            {
                Match m = InstructionRegEx.Match(instruction);

                if (m.Success)
                {
                    fieldName  = m.Groups["name"].ToString().Trim();
                    options[0] = m.Groups["Format"].Value.Trim();
                    options[1] = m.Groups["PreText"].Value.Trim();
                    options[2] = m.Groups["PostText"].Value.Trim();

                    int pos = fieldName.IndexOf('#');

                    if (pos > 0)
                    {
                        // process the switches, correct the fieldName
                        switches  = fieldName.Substring(pos + 1).ToLower().Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                        fieldName = fieldName.Substring(0, pos);
                    }
                }
            }

            return(fieldName);
        }
Ejemplo n.º 4
0
        public void GetAttributeTest()
        {
            FooterReference paragraph = new FooterReference();

            //OpenXmlAttribute target = paragraph.GetAttribute("type", null);
            //Assert.Null(target);
            OpenXmlAttribute target;

            //target = paragraph.GetAttribute("type", paragraph.NamespaceURI);
            //Assert.Null(target);

            //  2 predefined attributes
            paragraph.Type = HeaderFooterValues.Default;
            paragraph.Id   = "1";

            // 1 extended attribute
            OpenXmlAttribute openXmlAttribute = new OpenXmlAttribute("test", "attribute", "http://test", "true");

            paragraph.SetAttribute(openXmlAttribute);

            target = paragraph.GetAttribute(openXmlAttribute.LocalName, openXmlAttribute.NamespaceUri);

            Assert.NotSame(openXmlAttribute, target);
            Assert.Equal(openXmlAttribute.NamespaceUri, target.NamespaceUri);
            Assert.Equal(openXmlAttribute.LocalName, target.LocalName);
            Assert.Equal(openXmlAttribute.Prefix, target.Prefix);
            Assert.Equal(openXmlAttribute.Value, target.Value);

            target = paragraph.GetAttribute("type", paragraph.NamespaceUri);
            Assert.Equal(paragraph.NamespaceUri, target.NamespaceUri);
            Assert.Equal("type", target.LocalName);
            Assert.Equal("w", target.Prefix);
            Assert.Equal(paragraph.Type.InnerText, target.Value);
        }
Ejemplo n.º 5
0
        internal static string GetFieldNameWithOptions(SimpleField field, out string[] switches, out string[] options)
        {
            OpenXmlAttribute attribute = field.GetAttribute("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

            switches = new string[0];
            options  = new string[3];
            string str   = string.Empty;
            string input = attribute.Value;

            if (!string.IsNullOrEmpty(input))
            {
                Match match = DocumentMerge.instructionRegEx.Match(input);
                if (match.Success)
                {
                    str        = match.Groups["name"].ToString().Trim();
                    options[0] = match.Groups["Format"].Value.Trim();
                    options[1] = match.Groups["PreText"].Value.Trim();
                    options[2] = match.Groups["PostText"].Value.Trim();
                    int length = str.IndexOf('#');
                    if (length > 0)
                    {
                        switches = str.Substring(length + 1).ToLower().Split(new char[1]
                        {
                            '#'
                        }, StringSplitOptions.RemoveEmptyEntries);
                        str = str.Substring(0, length);
                    }
                }
            }
            return(str);
        }
Ejemplo n.º 6
0
        private void writeColumns(OpenXmlWriter writer)
        {
            writer.WriteStartElement(new Columns());
            for (var i = 1; i <= _maxColumnIndex; i++)
            {
                var width = 20d;
                if (_maxNumberOfCharsPerColumn.ContainsKey(i))
                {
                    width = _maxNumberOfCharsPerColumn[i] > 255 ? 255 : _maxNumberOfCharsPerColumn[i];
                    width = width * DBL_AutoWidthCharacterScalingNumber;
                }
                var minAtt = new OpenXmlAttribute("min", null, i.ToString());
                var maxAtt = new OpenXmlAttribute("max", null, i.ToString());

                if (MaxColumnWidth.HasValue && width > MaxColumnWidth)
                {
                    width = MaxColumnWidth.Value;
                }

                var widthAtt = new OpenXmlAttribute("width", null, width.ToString(CultureInfo.InvariantCulture));
                writer.WriteStartElement(new Column(), new List <OpenXmlAttribute>()
                {
                    minAtt, maxAtt, widthAtt
                });
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Ejemplo n.º 7
0
        private void writeFrozenFirstColumn(OpenXmlWriter writer)
        {
            if (!_forzenFirstColumn)
            {
                return;
            }
            writer.WriteStartElement(new SheetViews());

            var tabSelectedAtt    = new OpenXmlAttribute("tabSelected", null, 1.ToString());
            var workBookViewIdAtt = new OpenXmlAttribute("workbookViewId", null, 0.ToString());

            writer.WriteStartElement(new SheetView(), new List <OpenXmlAttribute>()
            {
                tabSelectedAtt, workBookViewIdAtt
            });

            var xSplitAtt      = new OpenXmlAttribute("xSplit", null, 1.ToString());
            var topLeftCellAtt = new OpenXmlAttribute("topLeftCell", null, "B1");
            var activePane     = new OpenXmlAttribute("activePane", null, "topRight");
            var state          = new OpenXmlAttribute("state", null, "frozen");

            writer.WriteStartElement(new Pane(), new List <OpenXmlAttribute>()
            {
                xSplitAtt, topLeftCellAtt, activePane, state
            });
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.WriteEndElement();
        }
Ejemplo n.º 8
0
        private IEnumerable <OpenXmlAttribute> EnumCellProxyAttributes(uint row, uint col, CellProxy cellProxy)
        {
            OpenXmlAttribute iteratorVariable0 = new OpenXmlAttribute {
                LocalName = "r",
                Value     = RowColumn.ToAddress(row, col)
            };

            yield return(iteratorVariable0);

            if (cellProxy.DataType.HasValue)
            {
                OpenXmlAttribute iteratorVariable1 = new OpenXmlAttribute {
                    LocalName = "t",
                    Value     = this.STCellType(cellProxy.DataType.Value)
                };
                yield return(iteratorVariable1);
            }
            if (cellProxy.StyleIndex.HasValue)
            {
                OpenXmlAttribute iteratorVariable2 = new OpenXmlAttribute {
                    LocalName = "s",
                    Value     = cellProxy.StyleIndex.Value.ToString()
                };
                yield return(iteratorVariable2);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Get name of attribute in <w:p> fashion.
        /// </summary>
        /// <param name="attribute">attribute in question</param>
        /// <returns>name of attribute in <w:p> format</returns>
        public static string GetFullName(this OpenXmlAttribute attribute)
        {
            if (string.IsNullOrEmpty(attribute.Prefix))
            {
                return(attribute.LocalName);
            }

            return($"{attribute.Prefix}:{attribute.LocalName}");
        }
Ejemplo n.º 10
0
        private static Cell WriteCell(OpenXmlWriter writer, object value, int rowIndex)
        {
            var cell = new Cell();
            //cell.CellReference = "";
            var attributeListCell = new OpenXmlAttribute[] { };

            if (default(object) == value)
            {
                cell.DataType = CellValues.String;
            }
            else if (typeof(bool).IsInstanceOfType(value))
            {
                cell.DataType = CellValues.Boolean;
            }
            else if (typeof(DateTime).IsInstanceOfType(value))
            {
                cell.DataType = CellValues.Date;
            }
            else if (typeof(double).IsAssignableFrom(value.GetType()))
            {
                cell.DataType = CellValues.Number;
            }
            else
            {
                cell.DataType = CellValues.String;
            }

            writer.WriteStartElement(cell);

            if (default(object) == value)
            {
                var cellValue = new CellValue("");
                writer.WriteElement(cellValue);
            }
            else if (typeof(CellReference).IsAssignableFrom(value.GetType()))
            {
                var cellRef = (CellReference)value;

                var formula = new DocumentFormat.OpenXml.Spreadsheet.CellFormula(cellRef.formula);
                writer.WriteElement(formula);
                var cellValue = new CellValue(cellRef.value);
                writer.WriteElement(cellValue);
                // <c r="H2" t="str">
                //  <f>Manufacturer!A15</f>
                //  <v>30</v>
                //</c>
            }
            else
            {
                var cellValue = new CellValue(value.ToString());
                writer.WriteElement(cellValue);
            }

            writer.WriteEndElement();

            return(cell);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get XName of pass-in OpenXmlAttribute.
        /// </summary>
        /// <param name="attribute">attribute in question</param>
        /// <returns>XName of pass-in OpenXmlAttribute</returns>
        public static XName GetXName(this OpenXmlAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            return(XName.Get(attribute.LocalName, attribute.NamespaceUri));
        }
Ejemplo n.º 12
0
        public void With_Attribute_Success()
        {
            OpenXmlAttribute attribute = GetParagraphId();

            Paragraph paragraph = new Paragraph().With(attribute);

            Assert.Equal(attribute.Value, paragraph.ParagraphId);
            Assert.Empty(paragraph.Elements <Run>());
        }
Ejemplo n.º 13
0
        public void LoadAttributeTest()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcdoc, file);


            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement actual;
                actual = target.RootElement;

                Assert.NotEqual(null, actual.MCAttributes.Ignorable);

                //get attribute, no exception thrown
                OpenXmlAttribute attr = actual.GetAttribute("Ignorable", AlternateContent.MarkupCompatibilityNamespace);
                Assert.Equal("w14 wp14", attr.Value);

                var list = actual.GetAttributes();
                Assert.True(list.Contains(attr));

                //set attribute
                actual.MCAttributes = null;

                actual.FirstChild.MCAttributes = new MarkupCompatibilityAttributes();
                actual.FirstChild.MCAttributes.PreserveAttributes = "w14:editId";
                actual.FirstChild.SetAttribute(new OpenXmlAttribute("mc:PreserveElements", AlternateContent.MarkupCompatibilityNamespace, "w14:para"));

                actual.FirstChild.FirstChild.MCAttributes           = new MarkupCompatibilityAttributes();
                actual.FirstChild.FirstChild.MCAttributes.Ignorable = "w14";
                actual.FirstChild.FirstChild.RemoveAllChildren();

                actual.Save();
            }

            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement actual;
                actual = target.RootElement;

                Assert.Equal(null, actual.MCAttributes);

                Assert.NotEqual(null, actual.FirstChild.MCAttributes.PreserveAttributes);

                Assert.True(actual.FirstChild.HasChildren);
                //get attribute, no exception thrown
                OpenXmlAttribute attr = actual.FirstChild.GetAttribute("PreserveAttributes", AlternateContent.MarkupCompatibilityNamespace);
                Assert.Equal("w14:editId", attr.Value);

                var list = actual.FirstChild.GetAttributes();
                Assert.True(list.Contains(attr));
            }
            System.IO.File.Delete(file);
        }
Ejemplo n.º 14
0
        private static int GetWidth(OpenXmlAttribute openXmlAttribute)
        {
            int back = 0;

            if (null != openXmlAttribute && !int.TryParse(openXmlAttribute.Value, out back))
            {
                back = 0;
            }
            return(back);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Test whether the attribute is "xml:space" or "xml:lang".
 /// </summary>
 /// <param name="attribute">The attribute to be tested.</param>
 /// <returns>True if the attribute is "xml:space" or "xml:lang".</returns>
 internal static bool IsXmlSpaceOrXmlLangAttribue(OpenXmlAttribute attribute)
 {
     if ("http://www.w3.org/XML/1998/namespace" == attribute.NamespaceUri)
     {
         if (attribute.LocalName == "space" || attribute.LocalName == "lang")
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 16
0
        public void LoadAttributeTest()
        {
            using (var stream = GetStream(TestFiles.Mcdoc, true))
            {
                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement actual;
                    actual = target.RootElement;

                    Assert.NotNull(actual.MCAttributes.Ignorable);

                    // get attribute, no exception thrown
                    OpenXmlAttribute attr = actual.GetAttribute("Ignorable", AlternateContent.MarkupCompatibilityNamespace);
                    Assert.Equal("w14 wp14", attr.Value);

                    var list = actual.GetAttributes();
                    Assert.True(list.Contains(attr));

                    // set attribute
                    actual.MCAttributes = null;

                    actual.FirstChild.MCAttributes = new MarkupCompatibilityAttributes();
                    actual.FirstChild.MCAttributes.PreserveAttributes = "w14:editId";
                    actual.FirstChild.SetAttribute(new OpenXmlAttribute("mc:PreserveElements", AlternateContent.MarkupCompatibilityNamespace, "w14:para"));

                    actual.FirstChild.FirstChild.MCAttributes           = new MarkupCompatibilityAttributes();
                    actual.FirstChild.FirstChild.MCAttributes.Ignorable = "w14";
                    actual.FirstChild.FirstChild.RemoveAllChildren();

                    actual.Save();
                }

                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement actual;
                    actual = target.RootElement;

                    Assert.Null(actual.MCAttributes);

                    Assert.NotNull(actual.FirstChild.MCAttributes.PreserveAttributes);

                    Assert.True(actual.FirstChild.HasChildren);

                    // get attribute, no exception thrown
                    OpenXmlAttribute attr = actual.FirstChild.GetAttribute("PreserveAttributes", AlternateContent.MarkupCompatibilityNamespace);
                    Assert.Equal("w14:editId", attr.Value);

                    var list = actual.FirstChild.GetAttributes();
                    Assert.True(list.Contains(attr));
                }
            }
        }
        public void OpenXmlAttributeTest()
        {
            OpenXmlAttribute target = new OpenXmlAttribute();
            OpenXmlAttribute other  = new OpenXmlAttribute();

            Assert.NotEqual(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(OpenXmlAttribute.Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            target = new OpenXmlAttribute("test", "http://test", "test", "value");
            other  = new OpenXmlAttribute("test", "http://test", "test", "value");

            Assert.NotEqual(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(OpenXmlAttribute.Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            other.Value = "other";

            Assert.NotEqual(target, other);
            Assert.False(target == other);
            Assert.True(target != other);
            Assert.False(target.Equals(other));
            Assert.False(target.Equals((object)other));
            Assert.False(OpenXmlAttribute.Equals(target, other));
            Assert.NotEqual(target.GetHashCode(), other.GetHashCode());

            other.Value = "value";

            Assert.NotEqual(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(OpenXmlAttribute.Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            other.Prefix = "t";

            Assert.NotEqual(target, other);
            Assert.False(target == other);
            Assert.True(target != other);
            Assert.False(target.Equals(other));
            Assert.False(target.Equals((object)other));
            Assert.False(OpenXmlAttribute.Equals(target, other));
            Assert.NotEqual(target.GetHashCode(), other.GetHashCode());
        }
Ejemplo n.º 18
0
        public void WriteDrawings(WorksheetPart worksheetPart, OpenXmlWriter writer)
        {
            if (!_images.Any() || !_imageDetails.Any())
            {
                return;
            }
            var          drawingPartId = "drawingPart1";
            DrawingsPart drawingsPart  = worksheetPart.AddNewPart <DrawingsPart>(drawingPartId);
            int          imgCounter    = 0;

            foreach (var image in _images)
            {
                var imagePart1 = drawingsPart.AddNewPart <ImagePart>("image/png", "image" + imgCounter);

                imgCounter++;
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Png);
                    ms.Position = 0;
                    imagePart1.FeedData(ms);
                }
            }
            using (var drawingsWriter = OpenXmlWriter.Create(drawingsPart))
            {
                drawingsWriter.WriteStartElement(new Xdr.WorksheetDrawing(), new List <OpenXmlAttribute>(), new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"),
                    new KeyValuePair <string, string>("a", "http://schemas.openxmlformats.org/drawingml/2006/main")
                });
                foreach (var imageDetails in _imageDetails)
                {
                    var twoCellAnchor1 = createImageAnchor(imageDetails);
                    drawingsWriter.WriteElement(twoCellAnchor1);
                }
                drawingsWriter.WriteEndElement();
            }

            var idAtt        = new OpenXmlAttribute("id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", drawingPartId);
            var pageMargins1 = new PageMargins()
            {
                Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D
            };

            //  PageSetup pageSetup1 = new PageSetup() { PaperSize = (UInt32Value)9U, Orientation = OrientationValues.Portrait};
            writer.WriteElement(pageMargins1);
            //writer.WriteElement(pageSetup1);
            writer.WriteStartElement(new Drawing(), new List <OpenXmlAttribute>()
            {
                idAtt
            });
            writer.WriteEndElement();
        }
Ejemplo n.º 19
0
        public void DefaultOpenXmlAttributeTest()
        {
            var target = new OpenXmlAttribute();
            var other  = new OpenXmlAttribute();

            Assert.Equal(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());
        }
Ejemplo n.º 20
0
        public void WriteRow(OpenXmlWriter writer, int columnIndex, int rowIndex, SpreadsheetStylesManager stylesManager, SpreadsheetHyperlinkManager hyperlinkManager, DrawingsManager drawingsManager)
        {
            var span          = string.Format("{0}:{1}", columnIndex, RowCells.Count + columnIndex);
            var attributeList = new List <OpenXmlAttribute>();

            var rowIndexAtt = new OpenXmlAttribute("r", null, rowIndex.ToString());
            var spanAtt     = new OpenXmlAttribute("spans", null, span);

            attributeList.Add(rowIndexAtt);
            attributeList.Add(spanAtt);
            if (this.RowHeight != null)
            {
                attributeList.Add(new OpenXmlAttribute("customHeight", null, "1"));
                attributeList.Add(new OpenXmlAttribute("ht", null, this.RowHeight.Value.ToString(CultureInfo.InvariantCulture)));
            }
            if (!IsVisible)
            {
                var hiddenAttribute = new OpenXmlAttribute("hidden", null, 1.ToString());
                attributeList.Add(hiddenAttribute);
            }
            if (!IsExpanded)
            {
                var hiddenAttribute = new OpenXmlAttribute("collapsed", null, 1.ToString());
                attributeList.Add(hiddenAttribute);
            }
            if (!IsMaster)
            {
                var hiddenAttribute = new OpenXmlAttribute("outlineLevel", null, 1.ToString());
                attributeList.Add(hiddenAttribute);
            }

            writer.WriteStartElement(new Row(), attributeList);
            foreach (var cell in RowCells)
            {
                if (cell.ImageIndex != -1)
                {
                    drawingsManager.SetImageForCell(new ImageDetails()
                    {
                        Column           = columnIndex,
                        ImageIndex       = cell.ImageIndex,
                        ImageScaleFactor = cell.ImageScaleFactor,
                        Indent           = cell.Indent,
                        Row = rowIndex
                    });
                }

                cell.WriteCell(writer, columnIndex, rowIndex, stylesManager, hyperlinkManager);
                columnIndex++;
            }
            writer.WriteEndElement();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Get name of attribute in <w:p> fashion.
        /// </summary>
        /// <param name="attribute">attribute in question</param>
        /// <returns>name of attribute in <w:p> format</returns>
        public static string GetFullName(this OpenXmlAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            if (string.IsNullOrEmpty(attribute.Prefix))
            {
                return(attribute.LocalName);
            }

            return($"{attribute.Prefix}:{attribute.LocalName}");
        }
Ejemplo n.º 22
0
        private void Bug514988(OpenXmlValidator validator)
        {
            var paragraph = new Paragraph();

            paragraph.RsidParagraphAddition = new HexBinaryValue();
            OpenXmlAttribute rsidR   = paragraph.GetAttribute("rsidR", paragraph.NamespaceUri);
            OpenXmlAttribute newattr = new OpenXmlAttribute(rsidR.LocalName, rsidR.NamespaceUri, "0102");

            paragraph.SetAttribute(newattr);
            var errors = new OpenXmlValidator().Validate(paragraph);

            Assert.Single(errors);
            Assert.Equal(ValidationErrorType.Schema, errors.First().ErrorType);
            Assert.Equal("Sch_AttributeValueDataTypeDetailed", errors.First().Id);
            Assert.Equal("The attribute 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:rsidR' has invalid value '0102'. The actual length according to data type 'hexBinary' is not equal to the specified length. The expected length is 4.", errors.First().Description);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Get default style by type, the possible types are Paragraph, Character, Table, and Numbering. Default styles are the styles have attribute w:default="1", not w:docDefaults.
        /// </summary>
        /// <param name="type">Target style type.</param>
        /// <returns></returns>
        public Word.Style GetDefaultStyle(DefaultStyleType type)
        {
            if (this.styles == null)
            {
                return(null);
            }

            String typeStr = defaultStyleName[type];

            return(this.styles.FirstOrDefault(c =>
            {
                try
                {
                    //// put "default" search in front has performance degradation because
                    //// it generates lots of KeyNotFoundException output to console, that
                    //// results in the terrible performance degradation
                    //OpenXmlAttribute attrDefault = c.GetAttribute("default", docDefaults.NamespaceUri);
                    //if (attrDefault.Value != null && attrDefault.Value == "1")
                    //{
                    //    OpenXmlAttribute attrType = c.GetAttribute("type", docDefaults.NamespaceUri);
                    //    if (attrType.Value != null)
                    //    {
                    //        if (attrType.Value.IndexOf(typeStr, 0, StringComparison.Ordinal) >= 0)
                    //            return true;
                    //    }
                    //}

                    OpenXmlAttribute attrType = c.GetAttribute("type", docDefaults.NamespaceUri);
                    if (attrType.Value != null)
                    {
                        if (attrType.Value.IndexOf(typeStr, 0, StringComparison.Ordinal) >= 0)
                        {
                            OpenXmlAttribute attrDefault = c.GetAttribute("default", docDefaults.NamespaceUri);
                            if (attrDefault.Value != null)
                            {
                                if (attrDefault.Value == "1")
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
                catch (Exception) { }
                return false;
            }));
        }
Ejemplo n.º 24
0
        public static uint GetMaxIdFromChild(OpenXmlElement el)
        {
            uint max = 2147483648;

            //Get max id value from set of children
            foreach (OpenXmlElement child in el.ChildElements)
            {
                OpenXmlAttribute attribute = child.GetAttribute("id", "");
                uint             id        = uint.Parse(attribute.Value);
                if (id > max)
                {
                    max = id;
                }
            }

            return(max);
        }
Ejemplo n.º 25
0
        private void WriteSharedString(XlsxSharedStringCell cell)
        {
            var style = !string.IsNullOrEmpty(cell.FormatName) ? Style.CellFormats[cell.FormatName] : "0";
            var attributes = new OpenXmlAttribute[] { new OpenXmlAttribute("s", null, style) }.ToList();

            attributes.Add(new OpenXmlAttribute("t", null, "s"));//shared string type
            Writer.WriteStartElement(new Cell(), attributes);
            if (!ShareStringDictionary.ContainsKey(cell.Value))
            {
                ShareStringDictionary.Add(cell.Value, ShareStringDictionary.Keys.Count());
            }

            //writing the index as the cell value
            Writer.WriteElement(new CellValue(ShareStringDictionary[cell.Value].ToString()));

            Writer.WriteEndElement();//cell
        }
Ejemplo n.º 26
0
        public TResult WriteSheetByRow <TResult>(Func <Action <object[]>, TResult> writeRowCallback, string sheetName = "Sheet1")
        {
            if (this.workbookPart.IsDefaultOrNull())
            {
                this.workbook.AddWorkbookPart();
                this.workbookPart = this.workbook.WorkbookPart;
            }

            var worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
            var writer        = OpenXmlWriter.Create(worksheetPart);

            writer.WriteStartElement(new Worksheet());
            writer.WriteStartElement(new SheetData());

            var rowIndex = 1;
            var result   = writeRowCallback(
                (rowCells) =>
            {
                var row        = new Row();
                var attributes = new OpenXmlAttribute[]
                {
                    // this is the row index
                    new OpenXmlAttribute("r", null, rowIndex.ToString())
                };
                writer.WriteStartElement(row, attributes);

                foreach (var rowCell in rowCells)
                {
                    WriteCell(writer, rowCell, rowIndex);
                }

                writer.WriteEndElement();
                rowIndex++;
            });

            // this is for SheetData
            writer.WriteEndElement();
            // this is for Worksheet
            writer.WriteEndElement();
            writer.Close();

            sheets.Add(sheetName, worksheetPart);

            return(result);
        }
Ejemplo n.º 27
0
        public void OpenXmlAttributeTest()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var target = new OpenXmlAttribute("test", "http://test", "test", "value");
            var other  = new OpenXmlAttribute("test", "http://test", "test", "value");

            Assert.Equal(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            other.Value = "other";

            Assert.NotEqual(target, other);
            Assert.False(target == other);
            Assert.True(target != other);
            Assert.False(target.Equals(other));
            Assert.False(target.Equals((object)other));
            Assert.False(Equals(target, other));
            Assert.NotEqual(target.GetHashCode(), other.GetHashCode());

            other.Value = "value";

            Assert.Equal(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            other.Prefix = "t";

            Assert.NotEqual(target, other);
            Assert.False(target == other);
            Assert.True(target != other);
            Assert.False(target.Equals(other));
            Assert.False(target.Equals((object)other));
            Assert.False(Equals(target, other));
            Assert.NotEqual(target.GetHashCode(), other.GetHashCode());
#pragma warning restore CS0618 // Type or member is obsolete
        }
Ejemplo n.º 28
0
        private IEnumerable <OpenXmlAttribute> EnumRowAttributes(uint thisRowIdx, SortedList <uint, CellProxy> cells)
        {
            Row  iteratorVariable0;
            bool iteratorVariable1 = false;

            if (this._cachedRows.TryGetValue(thisRowIdx, out iteratorVariable0))
            {
                IEnumerable <OpenXmlAttribute> iteratorVariable2 = from a in iteratorVariable0.GetAttributes()
                                                                   where (a.LocalName != "r") && (a.LocalName != "spans")
                                                                   select a;
                foreach (OpenXmlAttribute iteratorVariable3 in iteratorVariable2)
                {
                    yield return(iteratorVariable3);

                    iteratorVariable1 = true;
                }
            }
            if (iteratorVariable1 || (cells.Count != 0))
            {
                OpenXmlAttribute iteratorVariable7 = new OpenXmlAttribute {
                    LocalName = "r",
                    Value     = thisRowIdx.ToString()
                };
                yield return(iteratorVariable7);

                if (cells.Count > 0)
                {
                    uint             iteratorVariable4 = cells.Keys.First <uint>();
                    uint             iteratorVariable5 = cells.Keys.Last <uint>();
                    OpenXmlAttribute iteratorVariable6 = new OpenXmlAttribute {
                        LocalName = "spans",
                        Value     = iteratorVariable4 + ":" + iteratorVariable5
                    };
                    yield return(iteratorVariable6);
                }
            }
            else
            {
                yield break;
            }
        }
Ejemplo n.º 29
0
        private static void AddNewGridColumn(OpenXmlElement tableGrid, OpenXmlElement headerRow, OpenXmlElement contentRow)
        {
            var columns = tableGrid.Descendants <OXD.GridColumn>().ToList();

            if (columns.Count == 0 || !columns.Any())
            {
                return;
            }
            var    headerLastCell  = headerRow.Descendants <OXD.TableCell>().Last();
            var    contentLastCell = contentRow.Descendants <OXD.TableCell>().Last();
            double tableWidth      = columns.Sum(_ => Convert.ToInt32(_.Width.Value));
            var    newColWidth     = Math.Floor(tableWidth / columns.Count);

            foreach (var col in columns)
            {
                col.Width = col.Width > 0 ? Convert.ToInt64(Math.Floor((tableWidth - newColWidth) / (tableWidth / col.Width))) : 0;
            }

            OXD.GridColumn newcol = new OXD.GridColumn()
            {
                Width = Convert.ToInt64(newColWidth)
            };
            OXD.ExtensionList init_extlst = newcol.Descendants <OXD.ExtensionList>().FirstOrDefault();
            if (init_extlst != null)
            {
                OXD.Extension         init_ext   = init_extlst.Descendants <OXD.Extension>().FirstOrDefault();
                OpenXmlUnknownElement init_colId = init_ext?.GetFirstChild <OpenXmlUnknownElement>();
                OpenXmlUnknownElement new_colId  = init_colId?.CloneNode(true) as OpenXmlUnknownElement;
                if (new_colId != null)
                {
                    OpenXmlAttribute val = new_colId.GetAttributes().FirstOrDefault();
                    val.Value = new Random().Next().ToString();
                    new_colId.SetAttribute(val);
                    init_ext.ReplaceChild(new_colId, init_colId);
                }
            }
            tableGrid.InsertAfter(newcol, columns.Last());
            headerRow.InsertAfter((OXD.TableCell)headerLastCell.CloneNode(true), headerLastCell);
            contentRow.InsertAfter((OXD.TableCell)contentLastCell.CloneNode(true), contentLastCell);
        }
Ejemplo n.º 30
0
        private static void SetHeaderStyle(SpreadsheetDocument spreadSheet, Cell cell)
        {
            Stylesheet styleSheet = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;

            cell.SetAttribute(new OpenXmlAttribute("", "s", "", "1"));
            OpenXmlAttribute cellStyleAttribute = cell.GetAttribute("s", "");
            CellFormats      cellFormats        = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats;

            // pick the first cell format.
            CellFormat cellFormat = (CellFormat)cellFormats.ElementAt(0);

            CellFormat cf = new CellFormat(cellFormat.OuterXml);

            cf.FontId = styleSheet.Fonts.Count;
            cf.FillId = styleSheet.Fills.Count;

            cellFormats.AppendChild(cf);

            cell.SetAttribute(cellStyleAttribute);

            cell.StyleIndex = styleSheet.CellFormats.Count;
        }
 /// <summary>
 /// Test whether the attribute is "xml:space" or "xml:lang".
 /// </summary>
 /// <param name="attribute">The attribute to be tested.</param>
 /// <returns>True if the attribute is "xml:space" or "xml:lang".</returns>
 internal static bool IsXmlSpaceOrXmlLangAttribue(OpenXmlAttribute attribute)
 {
     if ("http://www.w3.org/XML/1998/namespace" == attribute.NamespaceUri)
     {
         if (attribute.LocalName == "space" || attribute.LocalName == "lang")
         {
             return true;
         }
     }
     return false;
 }
        public override void Textbox(Textbox tb, string t, Row row)
        {
            base.Textbox(tb, t, row);
            bool tableCell = IsTableCell(tb);
            if (!tableCell)
            {
                if (_currentRow == null || _currentRow != tb.Top.PixelsY)
                {
                        _currentRow = tb.Top.PixelsY;
                        _writer.WriteStartElement(new DocumentFormat.OpenXml.Spreadsheet.Row()); //new row
                }

            }

            int? idCellFormat = GetStyleIndex(tb.Style, row, ref t);

            if (idCellFormat != null)
            {

                var attributes = new OpenXmlAttribute[] { new OpenXmlAttribute("s", null, idCellFormat.ToString()) }.ToList();
              //  if (tb.Width!=null)
              //      attributes.Add(new OpenXmlAttribute("width", null, Measurement.PointsToExcelUnits(tb.Width.Points).ToString()));
                if ((IsNumeric(t) || IsNumeric(t, CultureInfo.CurrentCulture)))
                    _openXmlExportHelper.WriteCellValueSax(_writer, t, CellValues.Number, attributes);
                else
                    _openXmlExportHelper.WriteCellValueSax(_writer, t, CellValues.InlineString, attributes);
            }
            else
                _openXmlExportHelper.WriteCellValueSax(_writer, t, CellValues.InlineString);

            if (!tableCell)
            {
                _writer.WriteEndElement();
                _currentWorkSheet.NextRow();
            }
        }
Ejemplo n.º 33
0
        private void LoadAttributes()
        {
            Debug.Assert(this._xmlReader != null);

            this._attributeList.Clear();
            _nsDecls.Clear();

            // read attributes
            if (this._xmlReader.HasAttributes)
            {
                while (this._xmlReader.MoveToNextAttribute())
                {
                    if (this._xmlReader.Prefix == OpenXmlElementContext.xmlnsPrefix)
                    {
                        _nsDecls.Add(new KeyValuePair<string, string>(_xmlReader.LocalName, _xmlReader.Value));
                    }
                    else
                    {
                        OpenXmlAttribute attribute = new OpenXmlAttribute(this._xmlReader.Prefix, this._xmlReader.LocalName, this._xmlReader.NamespaceURI, this._xmlReader.Value);
                        this._attributeList.Add(attribute);
                    }
                }

                //  Moves the reader back to the element node.
                this._xmlReader.MoveToElement();
            }
   
        }
Ejemplo n.º 34
0
 private static int GetWidth(OpenXmlAttribute openXmlAttribute)
 {
     int back = 0;
     if (null != openXmlAttribute && !int.TryParse(openXmlAttribute.Value, out back))
     {
         back = 0;
     }
     return back;
 }
Ejemplo n.º 35
0
        public void RemoveAttributeTest()
        {
            // create an element to hold 3 attributes 
            FooterReference target = new FooterReference();

            Assert.False(target.HasAttributes);
            Assert.Equal(0, target.GetAttributes().Count);
            Assert.Equal(0, target.ExtendedAttributes.Count());

            Assert.Null(target.Type);
            Assert.Null(target.Id);

            //  2 predefined attributes
            target.Type = HeaderFooterValues.Default;
            target.Id = "1";

            // 1 extended attribute
            OpenXmlAttribute openXmlAttribute = new OpenXmlAttribute("test", "attribute", "http://test", "true");
            target.SetAttribute(openXmlAttribute);

            Assert.True(target.HasAttributes);
            Assert.Equal(3, target.GetAttributes().Count);
            Assert.Equal(1, target.ExtendedAttributes.Count());

            Assert.NotNull(target.Type);
            Assert.True(target.Type.HasValue);
            Assert.Equal(HeaderFooterValues.Default, target.Type.Value);
            Assert.Equal(HeaderFooterValues.Default, (HeaderFooterValues)(target.Type));

            Assert.NotNull(target.Id);
            Assert.Equal("1", (string)target.Id);

            // Remove the custom attribute
            target.RemoveAttribute(openXmlAttribute.LocalName, openXmlAttribute.NamespaceUri);
            Assert.True(target.HasAttributes);
            Assert.Equal(2, target.GetAttributes().Count);
            Assert.Equal(0, target.ExtendedAttributes.Count());

            Assert.NotNull(target.Type);
            Assert.True(target.Type.HasValue);
            Assert.Equal(HeaderFooterValues.Default, target.Type.Value);
            Assert.Equal(HeaderFooterValues.Default, (HeaderFooterValues)(target.Type));

            Assert.NotNull(target.Id);
            Assert.Equal("1", (string)target.Id);

            // remove the .Id
            openXmlAttribute = target.GetAttributes()[1];
            target.RemoveAttribute(openXmlAttribute.LocalName, openXmlAttribute.NamespaceUri);
            Assert.True(target.HasAttributes);
            Assert.Equal(1, target.GetAttributes().Count);
            Assert.Equal(0, target.ExtendedAttributes.Count());

            Assert.NotNull(target.Type);
            Assert.True(target.Type.HasValue);
            Assert.Equal(HeaderFooterValues.Default, target.Type.Value);
            Assert.Equal(HeaderFooterValues.Default, (HeaderFooterValues)(target.Type));

            Assert.Null(target.Id);

            // remove the .Type
            openXmlAttribute = target.GetAttributes()[0];
            target.RemoveAttribute(openXmlAttribute.LocalName, openXmlAttribute.NamespaceUri);
            Assert.False(target.HasAttributes);
            Assert.Equal(0, target.GetAttributes().Count);
            Assert.Equal(0, target.ExtendedAttributes.Count());

            Assert.Null(target.Type);
            Assert.Null(target.Id);
        }
Ejemplo n.º 36
0
        public void OpenXmlAttributeTest()
        {

            OpenXmlAttribute target = new OpenXmlAttribute();
            OpenXmlAttribute other = new OpenXmlAttribute();

            Assert.NotSame(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(OpenXmlAttribute.Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            target = new OpenXmlAttribute("test", "http://test", "test", "value");
            other = new OpenXmlAttribute("test", "http://test", "test", "value");

            Assert.NotSame(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(OpenXmlAttribute.Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            other.Value = "other";

            Assert.NotSame(target, other);
            Assert.False(target == other);
            Assert.True(target != other);
            Assert.False(target.Equals(other));
            Assert.False(target.Equals((object)other));
            Assert.False(OpenXmlAttribute.Equals(target, other));
            Assert.NotEqual(target.GetHashCode(), other.GetHashCode());

            other.Value = "value";

            Assert.NotSame(target, other);
            Assert.True(target == other);
            Assert.False(target != other);
            Assert.True(target.Equals(other));
            Assert.True(target.Equals((object)other));
            Assert.True(OpenXmlAttribute.Equals(target, other));
            Assert.Equal(target.GetHashCode(), other.GetHashCode());

            other.Prefix = "t";

            Assert.NotSame(target, other);
            Assert.False(target == other);
            Assert.True(target != other);
            Assert.False(target.Equals(other));
            Assert.False(target.Equals((object)other));
            Assert.False(OpenXmlAttribute.Equals(target, other));
            Assert.NotEqual(target.GetHashCode(), other.GetHashCode());

        }
Ejemplo n.º 37
0
        public void GetAttributeTest()
        {
            FooterReference paragraph = new FooterReference();

            //OpenXmlAttribute target = paragraph.GetAttribute("type", null);
            //Assert.Null(target);
            OpenXmlAttribute target;

            //target = paragraph.GetAttribute("type", paragraph.NamespaceURI);
            //Assert.Null(target);

            //  2 predefined attributes
            paragraph.Type = HeaderFooterValues.Default;
            paragraph.Id = "1";

            // 1 extended attribute
            OpenXmlAttribute openXmlAttribute = new OpenXmlAttribute("test", "attribute", "http://test", "true");
            paragraph.SetAttribute(openXmlAttribute);

            target = paragraph.GetAttribute(openXmlAttribute.LocalName, openXmlAttribute.NamespaceUri);

            Assert.NotSame(openXmlAttribute, target);
            Assert.Equal(openXmlAttribute.NamespaceUri, target.NamespaceUri);
            Assert.Equal(openXmlAttribute.LocalName, target.LocalName);
            Assert.Equal(openXmlAttribute.Prefix, target.Prefix);
            Assert.Equal(openXmlAttribute.Value, target.Value);

            target = paragraph.GetAttribute("type", paragraph.NamespaceUri);
            Assert.Equal(paragraph.NamespaceUri, target.NamespaceUri);
            Assert.Equal("type", target.LocalName);
            Assert.Equal("w", target.Prefix);
            Assert.Equal(paragraph.Type.InnerText, target.Value);

            //target = paragraph.GetAttribute("type", null);
            //Assert.Null(target);
            
            //target = paragraph.GetAttribute("type", "");
            //Assert.Null(target);
        }
Ejemplo n.º 38
0
        public void CompatibilityRuleAttributesValidationTest()
        {
            var validator = new SchemaValidator();
            var element = new Paragraph();
            var run = new Run();
            
            element.AppendChild(run);

            var result = validator.Validate(element);
            Assert.True(result.Valid);

            element.AddNamespaceDeclaration("o15", "http://o15.com");
            result = validator.Validate(element);
            Assert.True(result.Valid);

            run.MCAttributes = new MarkupCompatibilityAttributes();
            run.MCAttributes.Ignorable = "o15";
            result = validator.Validate(element);
            Assert.True(result.Valid);

            run.AddNamespaceDeclaration("w15", "http://w15.com");
            result = validator.Validate(element);
            Assert.True(result.Valid);

            run.MCAttributes.Ignorable = "o15 w15";
            result = validator.Validate(element);
            Assert.True(result.Valid);

            run.MCAttributes.PreserveAttributes = "  o15:id w15:*";
            run.MCAttributes.PreserveElements = "o15:*  w15:*  ";
            run.MCAttributes.ProcessContent = "  o15:newE   w15:newW  ";
            result = validator.Validate(element);
            Assert.True(result.Valid);

            run.MCAttributes.PreserveElements = "x15:* ";
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, result.Errors[0].ErrorType);
            Assert.Equal("MC_InvalidPreserveElementsAttribute", result.Errors[0].Id);

            run.MCAttributes.Ignorable = null;
            run.MCAttributes.PreserveAttributes = null;
            run.MCAttributes.PreserveElements = "w15:*";
            run.MCAttributes.ProcessContent = "";
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, result.Errors[0].ErrorType);
            Assert.Equal("MC_InvalidPreserveElementsAttribute", result.Errors[0].Id);

            run.MCAttributes.Ignorable = "o15";
            run.MCAttributes.PreserveAttributes = "";
            run.MCAttributes.PreserveElements = "w15:*";
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, result.Errors[0].ErrorType);
            Assert.Equal("MC_InvalidPreserveElementsAttribute", result.Errors[0].Id);
            run.MCAttributes.PreserveElements = null;

            run.MCAttributes.ProcessContent = "w14:newW";
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, result.Errors[0].ErrorType);
            Assert.Equal("MC_InvalidProcessContentAttribute", result.Errors[0].Id);
            run.MCAttributes.ProcessContent = null;

            var spaceAttribute = new OpenXmlAttribute("xml:space", "http://www.w3.org/XML/1998/namespace", "preserve");
            run.MCAttributes.ProcessContent = "o15:newP";
            run.SetAttribute(spaceAttribute);
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, result.Errors[0].ErrorType);
            Assert.Equal("MC_InvalidXmlAttributeWithProcessContent", result.Errors[0].Id);
            run.MCAttributes.ProcessContent = null;
            
            run.SetAttribute(new OpenXmlAttribute("o15:id", "http://o15.com", "1"));
            result = validator.Validate(element);
            Assert.True(result.Valid);

            run.MCAttributes.Ignorable = "o15 w15 x15";
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, result.Errors[0].ErrorType);
            Assert.Equal("MC_InvalidIgnorableAttribute", result.Errors[0].Id);

            run.MCAttributes.Ignorable = "o15 w15";
            run.SetAttribute(new OpenXmlAttribute("x15:id", "http://x15.com", "1"));
            result = validator.Validate(element);
            Assert.False(result.Valid);
            Assert.Equal(1, result.Errors.Count);
        }
Ejemplo n.º 39
0
        public void AcbSyntaxValidationTest()
        {
            var validator = new SchemaValidator();
            var element = new Run();
            var acFallback = new AlternateContentFallback();
            var ac = element.AppendChild(new AlternateContent());
            var errors = validator.Validate(ac).Errors;
            // Error case: must have one choice, can not have AlternateContent as di
            Assert.Equal(1, errors.Count());
            Assert.Equal("Sch_IncompleteContentExpectingComplex", errors[0].Id);

            ac.AddNamespaceDeclaration("o15", "http://o15.com");
            //ac.NamespaceDeclarations
            ac.AppendChild(new AlternateContentChoice() { Requires = "o15" });
            errors = validator.Validate(ac).Errors;
            Assert.Equal(0, errors.Count());

            ac.AddNamespaceDeclaration("o14", "http://o14.com");
            ac.PrependChild(new AlternateContentChoice() { Requires = "o14" });
            errors = validator.Validate(ac).Errors;
            Assert.Equal(0, errors.Count());

            ac.AppendChild(acFallback);
            errors = validator.Validate(ac).Errors;
            Assert.Equal(0, errors.Count());

            // Error case: should not contains AlternateContent directly as child.
            ac.AppendChild(new AlternateContent());
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal("Sch_InvalidElementContentExpectingComplex", errors.First().Id);
            ac.RemoveChild(ac.LastChild);

            // Error case: can only contains one Fallback.
            ac.AppendChild(new AlternateContentFallback());
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal("Sch_InvalidElementContentExpectingComplex", errors.First().Id);
            ac.RemoveChild(ac.LastChild);

            ac.RemoveChild(acFallback);
            // Error case: wrong sequence
            ac.PrependChild(acFallback);
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal("Sch_IncompleteContentExpectingComplex", errors.First().Id);
            ac.RemoveChild(acFallback);
            ac.Append(acFallback);

            var langAttribute = new OpenXmlAttribute("xml:lang", "http://www.w3.org/XML/1998/namespace", "en-us");
            ac.SetAttribute(langAttribute);
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal("MC_InvalidXmlAttribute", errors.First().Id);
            Assert.Equal( "The AlternateContent element should not have an xml:lang or xml:space attribute.", errors[0].Description);
            ac.RemoveAttribute(langAttribute.LocalName, langAttribute.NamespaceUri);

            ac.FirstChild.SetAttribute(langAttribute);
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Same(ac.FirstChild, errors[0].Node);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal("MC_InvalidXmlAttribute", errors.First().Id);
            Assert.Equal("The Choice element should not have an xml:lang or xml:space attribute.", errors[0].Description);
            ac.FirstChild.RemoveAttribute(langAttribute.LocalName, langAttribute.NamespaceUri);

            ac.LastChild.SetAttribute(langAttribute);
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Same(ac.LastChild, errors[0].Node);
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal("MC_InvalidXmlAttribute", errors.First().Id);
            Assert.Equal("The Fallback element should not have an xml:lang or xml:space attribute.", errors[0].Description);
            ac.LastChild.RemoveAttribute(langAttribute.LocalName, langAttribute.NamespaceUri);

            AlternateContentChoice choice1 = ac.FirstChild as AlternateContentChoice;
            choice1.Requires = "o17 o15";
            errors = validator.Validate(ac).Errors;
            Assert.Equal(1, errors.Count());
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Same(choice1, errors[0].Node);
            Assert.Equal("MC_InvalidRequiresAttribute", errors.First().Id);
            Assert.Equal("The Requires attribute is invalid - The value 'o17 o15' contains an invalid prefix that is not defined.", errors[0].Description);

            choice1.Requires = null;
            errors = validator.Validate(ac).Errors;
            Assert.Equal(ValidationErrorType.MarkupCompatibility, errors.First().ErrorType);
            Assert.Equal(1, errors.Count());
            Assert.Same(choice1, errors[0].Node);
            Assert.Equal("MC_MissedRequiresAttribute", errors.First().Id);
            Assert.Equal("All Choice elements must have a Requires attribute whose value contains a whitespace delimited list of namespace prefixes.", errors[0].Description);
        }
Ejemplo n.º 40
0
 private void Bug514988(OpenXmlValidator validator)
 {
     var paragraph = new Paragraph();
     paragraph.RsidParagraphAddition = new HexBinaryValue();
     OpenXmlAttribute rsidR = paragraph.GetAttribute("rsidR", paragraph.NamespaceUri);
     OpenXmlAttribute newattr = new OpenXmlAttribute(rsidR.LocalName, rsidR.NamespaceUri, "0102");
     paragraph.SetAttribute(newattr);
     var errors = new OpenXmlValidator().Validate(paragraph);
     Assert.Equal(1, errors.Count());
     Assert.Equal(ValidationErrorType.Schema, errors.First().ErrorType);
     Assert.Equal("Sch_AttributeValueDataTypeDetailed", errors.First().Id);
     Assert.Equal("The attribute 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:rsidR' has invalid value '0102'. The actual length according to datatype 'hexBinary' is not equal to the specified length. The expected length is 4.", errors.First().Description);
 }