public void TestInitialize() { this.testFieldObject = new SimpleField { boolField = true, floatField = 1.2f, integerField = 5, stringField = "test" }; this.testPropertyObject = new SimpleProperty(true, "test", 1.2f) { StringProperty = "test", IntegerProperty = 5, FloatProperty = 1.2f, BoolProperty = true, ActualNameInJsonAttribute = 5 }; this.testComplexObject = new ComplexObject() { TestBoolean = true, testField = 1.2f, NestedObject = new NestedObject() { testfield = "test", TestProperty = 5 } }; this.changer = new UntypedObjectChanger(); }
public void UntypedCollection_Removed_RemovesObject() { var objectToAdd = new SimpleField() { integerField = 10 }; var collection = new UntypedCollection(collName); collection.Added("1", JObject.FromObject(objectToAdd)); collection.Removed("1"); Assert.AreEqual(0, collection.Objects.Count); }
public void UntypedCollection_Added_AddsValue() { var objectToAdd = new SimpleField() {integerField = 10}; var collection = new UntypedCollection(collName); collection.Added("1", JObject.FromObject(objectToAdd)); Assert.AreEqual(1, collection.Objects.Count); var objectAdded = collection.Objects["1"].ToObject<SimpleField>(); Assert.AreEqual(10, objectAdded.integerField); }
public void UntypedCollection_Changed_InvalidObjectDoesNothing() { var objectToAdd = new SimpleField() { integerField = 10 }; var collection = new UntypedCollection(collName); collection.Added("1", JObject.FromObject(objectToAdd)); var change = new Dictionary<string, JToken>() { {"integerField", JToken.FromObject(999)} }; collection.Changed("2", change, null); var objectAdded = collection.Objects["1"].ToObject<SimpleField>(); Assert.AreEqual(10, objectAdded.integerField); }
/// <summary> /// Creates a new NodePointer representing the SimpleField /// </summary> /// <param name="pointerParent"></param> /// <param name="field"></param> /// <returns></returns> public static INodePointer Create( SifElementPointer pointerParent, SimpleField field) { SifVersion version = pointerParent.Version; if (pointerParent.IsLegacyVersion) { IElementDef fieldDef = field.ElementDef; IRenderSurrogate rs = fieldDef.GetVersionInfo(version).GetSurrogate(); if (rs != null) { return(rs.CreateNodePointer(pointerParent, field, version)); } } if (field.ElementDef.IsAttribute(version)) { return(new SimpleFieldAttributePointer(pointerParent, field, version)); } else { return(new SimpleFieldElementPointer(pointerParent, field, version)); } }
/// <summary> /// Creates a new NodePointer representing the SimpleField /// </summary> /// <param name="pointerParent"></param> /// <param name="field"></param> /// <returns></returns> public static INodePointer Create( SifElementPointer pointerParent, SimpleField field ) { SifVersion version = pointerParent.Version; if ( pointerParent.IsLegacyVersion ) { IElementDef fieldDef = field.ElementDef; IRenderSurrogate rs = fieldDef.GetVersionInfo( version ).GetSurrogate(); if ( rs != null ) { return rs.CreateNodePointer( pointerParent, field, version ); } } if ( field.ElementDef.IsAttribute( version ) ) { return new SimpleFieldAttributePointer( pointerParent, field, version ); } else { return new SimpleFieldElementPointer( pointerParent, field, version ); } }
/// <summary> /// separte all words for handle rtl (when english has than disable rtl) l.g /// Returns a <see cref="Run"/>-openxml element for the given text. /// Specific about this run-element is that it can describe multiple-line and tabbed-text. /// The <see cref="SimpleField"/> placeholder can be provided too, to allow duplicating the formatting. /// </summary> /// <param name="text">The text to be inserted.</param> /// <param name="placeHolder">The placeholder where the text will be inserted.</param> /// <param name="defaultHebFont">The default Hebrew Font where the text will be inserted 1.0.0.6.</param> /// <returns>A new <see cref="Run"/>-openxml element containing the specified text.</returns> internal static Run GetRunElementForTextRtlHandle(string text, SimpleField placeHolder, string defaultHebFont = "") { string rpr = null; if (placeHolder != null) { var xdoc = XDocument.Parse((placeHolder.Parent).OuterXml.Replace(placeHolder.OuterXml, string.Empty)); if (xdoc.Root != null) { var xrpr = xdoc.Root.Elements().FirstOrDefault(x => x.Name.LocalName == "rPr"); if (xrpr != null) { rpr = xrpr.ToString(); } } } var r = new Run(); if (!string.IsNullOrEmpty(rpr)) { r.AppendChild(new RunProperties(rpr)); } if (!string.IsNullOrEmpty(text)) { string[] split = text.Split(new string[] { "\n" }, StringSplitOptions.None); bool first = true; foreach (string s in split) { if (!first) { r.Append(new Break()); } first = false; // then process tabs bool firsttab = true; string[] tabsplit = s.Split(new[] { "\t" }, StringSplitOptions.None); foreach (string tabtext in tabsplit) { if (!firsttab) { r.Append(new TabChar()); } // separte all words for handle rtl (when english has than disable rtl) // string[] wordSpl = Regex.Split(tabtext, @"(?<=[\s+])"); string[] wordSpl = Regex.Split(tabtext, splitWhiteSpaceIncludeRegFormater); foreach (var w in wordSpl) { Run rWord = new Run(); var txtTemp = new Text(w); txtTemp.Space = SpaceProcessingModeValues.Preserve; rWord.AppendChild(new RunProperties(rpr)); rWord.AppendChild <Text>(txtTemp); r.AppendChild <Run>(rWord); bool isHasEngChar = Regex.IsMatch(w, isEngCharcter);// @"[A-Za-z]+"); //l.g var rprLtr = rWord.GetFirstChild <RunProperties>(); //1.0.0.7 remove rtl (false) on english chracters //if (isHasEngChar && r.GetFirstChild<RunProperties>() != null) //{ // //if (rprLtr.RightToLeftText == null) // // rprLtr.RightToLeftText = new RightToLeftText(); // //rprLtr.RightToLeftText.Val = false; //} //else\ if (!isHasEngChar) { //1.0.0.5 save font hebrew //set font hebrew (if not english) rprLtr.AppendChild(GetHebrew()); //1.0.0.6 if (rprLtr.RunFonts == null && !String.IsNullOrEmpty(defaultHebFont)) { rprLtr.RunFonts = new RunFonts(); // rprLtr.RunFonts.Hint = FontTypeHintValues.EastAsia; rprLtr.RunFonts.Ascii = defaultHebFont; } } } } } } return(r); }
private void Write( SimpleField f, bool isLegacy ) { if ( !Include( f ) ) { return; } if ( isLegacy ) { IRenderSurrogate surrogate = f.ElementDef.GetVersionInfo( fVersion ).GetSurrogate(); if ( surrogate != null ) { surrogate.RenderRaw( fWriter, fVersion, f, fFormatter ); return; } } // "<tag [attr...]>[text]" or "<tag [attr...]/>" String fieldValue = null; SifSimpleType simpleValue = f.SifValue; if ( simpleValue != null ) { fieldValue = simpleValue.ToString( fFormatter ); } if ( fieldValue == null ) { if ( !isLegacy ) { fWriter.WriteStartElement( f.ElementDef.Tag( fVersion ) ); fWriter.WriteAttributeString(NIL, XmlSchema.InstanceNamespace, "true"); //fWriter.WriteElementString( f.ElementDef.Tag( fVersion ), null ); fWriter.WriteFullEndElement(); } else { // The specified version of SIF doesn't support // the xsi:nil attribute. Set the value to an empty // string fWriter.WriteStartElement( f.ElementDef.Tag( fVersion ) ); fWriter.WriteFullEndElement(); } } else { fWriter.WriteStartElement( f.ElementDef.Tag( fVersion ) ); if ( f.DoNotEncode ) { fWriter.WriteRaw( fieldValue ); } else { fWriter.WriteString( fieldValue ); } fWriter.WriteEndElement(); } }
internal static string GetFieldName(SimpleField pField) { var attr = pField.GetAttribute("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); string strFieldname = string.Empty; string instruction = attr.Value; if (!string.IsNullOrEmpty(instruction)) { Match m = instructionRegEx.Match(instruction); if (m.Success) { strFieldname = m.Groups["name"].ToString().Trim(); } } return strFieldname; }
private void ConvertFieldCodes(OpenXmlElement mainElement) { // search for all the Run elements Run[] runs = mainElement.Descendants <Run>().ToArray(); if (runs.Length == 0) { return; } Dictionary <Run, Run[]> newfields = new Dictionary <Run, Run[]>(); int cursor = 0; do { Run run = runs[cursor]; if (run.HasChildren && run.Descendants <FieldChar>().Count() > 0 && (run.Descendants <FieldChar>().First().FieldCharType & FieldCharValues.Begin) == FieldCharValues.Begin) { List <Run> innerRuns = new List <Run>(); innerRuns.Add(run); // loop until we find the 'end' FieldChar bool found = false; string instruction = null; RunProperties runprop = null; do { cursor++; run = runs[cursor]; innerRuns.Add(run); if (run.HasChildren && run.Descendants <FieldCode>().Count() > 0) { instruction += run.GetFirstChild <FieldCode>().Text; } if (run.HasChildren && run.Descendants <FieldChar>().Count() > 0 && (run.Descendants <FieldChar>().First().FieldCharType & FieldCharValues.End) == FieldCharValues.End) { found = true; } if (run.HasChildren && run.Descendants <RunProperties>().Count() > 0) { runprop = run.GetFirstChild <RunProperties>(); } } while (found == false && cursor < runs.Length); // something went wrong : found Begin but no End. Throw exception if (!found) { throw new Exception("Found a Begin FieldChar but no End !"); } if (!string.IsNullOrEmpty(instruction)) { // build new Run containing a SimpleField Run newrun = new Run(); if (runprop != null) { newrun.AppendChild(runprop.CloneNode(true)); } SimpleField simplefield = new SimpleField(); simplefield.Instruction = instruction; newrun.AppendChild(simplefield); newfields.Add(newrun, innerRuns.ToArray()); } } cursor++; } while (cursor < runs.Length); // replace all FieldCodes by old-style SimpleFields foreach (KeyValuePair <Run, Run[]> kvp in newfields) { kvp.Value[0].Parent.ReplaceChild(kvp.Key, kvp.Value[0]); for (int i = 1; i < kvp.Value.Length; i++) { kvp.Value[i].Remove(); } } }
/// <summary> /// Checks if the given field is equal to the field. /// </summary> /// <param name="obj">The field</param> /// <returns>True if the fields are equal</returns> public virtual bool Equals(SimpleField <T> obj) { return(obj != null && EqualityComparer <T> .Default.Equals(Value, obj.Value)); }
public void TestxsiNill_SIFMessagePayload() { LearnerPersonal lp = new LearnerPersonal(); // Add a null UPN SifString str = new SifString(null); lp.SetField(LearnerDTD.LEARNERPERSONAL_UPN, str); // Add a null AlertMsg AlertMsg msg = new AlertMsg(AlertMsgType.DISCIPLINE, null); lp.AlertMsgList = new AlertMsgList(msg); msg.SetField(CommonDTD.ALERTMSG, new SifString(null)); SIF_Response sifMessage = new SIF_Response(); sifMessage.AddChild(lp); // Write the object to a file Console.WriteLine("Writing to file..."); using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write)) { SifWriter writer = new SifWriter(fos); sifMessage.SetChanged(true); writer.Write(sifMessage); writer.Flush(); fos.Close(); } // Parse the object from the file Console.WriteLine("Parsing from file..."); SifParser p = SifParser.NewInstance(); using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml")) { sifMessage = (SIF_Response)p.Parse(fis, null); } lp = (LearnerPersonal)sifMessage.GetChildList()[0]; SimpleField upn = lp.GetField(LearnerDTD.LEARNERPERSONAL_UPN); Assert.IsNotNull(upn); SifString rawValue = (SifString)upn.SifValue; Assert.IsNotNull(rawValue); Assert.IsNull(rawValue.Value); Assert.IsNull(upn.Value); AlertMsgList alertMsgs = lp.AlertMsgList; Assert.IsNotNull(alertMsgs); Assert.IsTrue(alertMsgs.Count == 1); msg = (AlertMsg)alertMsgs.GetChildList()[0]; Assert.IsNull(msg.Value); SifSimpleType msgValue = msg.SifValue; Assert.IsNotNull(msgValue); Assert.IsNull(msgValue.RawValue); }
private void AssertSimpleFieldEqual(SimpleField expectedValues, SimpleField actualValues) { Assert.AreNotEqual(expectedValues, actualValues); Assert.AreEqual(expectedValues.boolField, actualValues.boolField); Assert.AreEqual(expectedValues.floatField, actualValues.floatField); Assert.AreEqual(expectedValues.integerField, actualValues.integerField); Assert.AreEqual(expectedValues.stringField, actualValues.stringField); }
/// <summary> /// Returns a <see cref="Run"/>-openxml element for the given text. /// Specific about this run-element is that it can describe multiple-line and tabbed-text. /// The <see cref="SimpleField"/> placeholder can be provided too, to allow duplicating the formatting. /// </summary> /// <param name="text">The text to be inserted.</param> /// <param name="placeHolder">The placeholder where the text will be inserted.</param> /// <returns>A new <see cref="Run"/>-openxml element containing the specified text.</returns> internal static Run GetRunElementForText(string text, SimpleField placeHolder, bool preserveWhiteSpace = false) { string rpr = null; if (placeHolder != null) { var xdoc = XDocument.Parse((placeHolder.Parent).OuterXml.Replace(placeHolder.OuterXml, string.Empty)); if (xdoc.Root != null) { var xrpr = xdoc.Root.Elements().FirstOrDefault(x => x.Name.LocalName == "rPr"); if (xrpr != null) { rpr = xrpr.ToString(); } } } var r = new Run(); if (!string.IsNullOrEmpty(rpr)) { r.AppendChild(new RunProperties(rpr)); } if (!string.IsNullOrEmpty(text)) { var rprLtr = r.GetFirstChild <RunProperties>(); // l.g fixed ltr in latin language bool isHasEngChar = Regex.IsMatch(text, isEngCharcter);//, @"[A-Za-z]+"); //l.g if (isHasEngChar && r.GetFirstChild <RunProperties>() != null) { if (rprLtr.RightToLeftText == null) { rprLtr.RightToLeftText = new RightToLeftText(); } rprLtr.RightToLeftText.Val = false; } // var rRunProperties = r.GetFirstChild<RunProperties>(); string[] split = text.Split(new string[] { "\n" }, StringSplitOptions.None); bool first = true; foreach (string s in split) { if (!first) { r.Append(new Break()); } first = false; // then process tabs bool firsttab = true; string[] tabsplit = s.Split(new[] { "\t" }, StringSplitOptions.None); foreach (string tabtext in tabsplit) { if (!firsttab) { r.Append(new TabChar()); } var txt = new Text(tabtext); txt.Space = SpaceProcessingModeValues.Preserve; r.AppendChild <Text>(txt); firsttab = false; } } } return(r); }
/// <summary> /// Since MS Word 2010 the SimpleField element is not longer used. It has been replaced by a combination of /// Run elements and a FieldCode element. This method will convert the new format to the old SimpleField-compliant /// format. /// </summary> /// <param name="mainElement"></param> static void ConvertFieldCodes(OpenXmlElement mainElement) { // search for all the Run elements Run[] runs = mainElement.Descendants <Run>().ToArray(); if (runs.Length == 0) { return; } string[] allDateFormats = DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d'); List <string> datesFormat = new List <string>(); // Print out july28 in all DateTime formats using the default culture. foreach (string format in allDateFormats) { datesFormat.Add(format); } var newfields = new Dictionary <Run, Run[]>(); int cursor = 0; do { Run run = runs[cursor]; if (run.HasChildren && run.Descendants <FieldChar>().Count() > 0 && (run.Descendants <FieldChar>().First().FieldCharType & FieldCharValues.Begin) == FieldCharValues.Begin) { List <Run> innerRuns = new List <Run>(); innerRuns.Add(run); // loop until we find the 'end' FieldChar bool found = false; string instruction = null; RunProperties runprop = null; do { cursor++; run = runs[cursor]; innerRuns.Add(run); if (run.HasChildren && run.Descendants <FieldCode>().Count() > 0) { instruction += run.GetFirstChild <FieldCode>().Text; } if (run.HasChildren && run.Descendants <FieldChar>().Count() > 0 && (run.Descendants <FieldChar>().First().FieldCharType & FieldCharValues.End) == FieldCharValues.End) { found = true; } if (run.HasChildren && run.Descendants <RunProperties>().Count() > 0) { runprop = run.GetFirstChild <RunProperties>(); } // Fixed by lior G if (runprop != null && runprop.RightToLeftText != null) { // runprop.RightToLeftText.Val = false; } } while (found == false && cursor < runs.Length); // something went wrong : found Begin but no End. Throw exception if (!found) { throw new Exception("Found a Begin FieldChar but no End !"); } if (!string.IsNullOrEmpty(instruction)) { Run newrun = new Run(); // Jewish Calander Handle when is dynamic update // lior grossman // if (instruction.Contains("DATE \\@ \"dd/MM/yyyy\" \\h ")) bool isFoundFormatDate = false; foreach (var format in datesFormat) { if (instruction.Contains(format)) { isFoundFormatDate = true; break; } } if (isFoundFormatDate) { // Fixed jewish calander --lior // build new Run containing a SimpleField Paragraph paragraphDate = null; if (runprop != null && runprop.Parent != null && runprop.Parent.Parent != null) { paragraphDate = runprop.Parent.Parent as Paragraph; } else if (innerRuns.Any() && (innerRuns[0] != null && innerRuns[0].Parent != null)) { paragraphDate = runprop.Parent.Parent as Paragraph; } if (paragraphDate != null) { var texts = paragraphDate.Descendants <Text>(); // start: handle datetime number sticky to month l.g foreach (var text in texts) { if (text == null) { continue; } Run rWord = new Run(); var txtTemp = new Text(text.InnerText); txtTemp.Space = SpaceProcessingModeValues.Preserve; if (runprop != null) { rWord.AppendChild(runprop.CloneNode(true)); } rWord.AppendChild <Text>(txtTemp); newrun.AppendChild <Run>(rWord); } // end: handle datetime number sticky to month l.g // must be after text set all properties if (runprop != null) { var propCalder = runprop.CloneNode(true); newrun.AppendChild(propCalder); } } else { // must be befor simplefield set all properties if (runprop != null) { newrun.AppendChild(runprop.CloneNode(true)); } SimpleField simplefield = new SimpleField(); simplefield.Instruction = instruction; newrun.AppendChild(simplefield); } } //end is field date fromat else { // must be befor simplefield set all properties if (runprop != null) { newrun.AppendChild(runprop.CloneNode(true)); } // no field date format SimpleField simplefield = new SimpleField(); simplefield.Instruction = instruction; newrun.AppendChild(simplefield); } newfields.Add(newrun, innerRuns.ToArray()); } } cursor++; } while (cursor < runs.Length); // replace all FieldCodes by old-style SimpleFields foreach (KeyValuePair <Run, Run[]> kvp in newfields) { kvp.Value[0].Parent.ReplaceChild(kvp.Key, kvp.Value[0]); for (int i = 1; i < kvp.Value.Length; i++) { kvp.Value[i].Remove(); } } }
/// <summary> /// Fills in a .docx file with the provided data. /// </summary> /// <returns>The filled-in document.</returns> private byte[] GetWordReport() { var dataset = new DataSet(); // first read document in as stream byte[] original = File.ReadAllBytes(FileName); using (var stream = new MemoryStream()) { stream.Write(original, 0, original.Length); // Create a Wordprocessing document object. using (var docx = WordprocessingDocument.Open(stream, true)) { // 2010/08/01: addition ConvertFieldCodes(docx.MainDocumentPart.Document); // first: process all tables string[] switches; foreach (var field in docx.MainDocumentPart.Document.Descendants <SimpleField>()) { string fieldname = GetFieldName(field, out switches); if (!string.IsNullOrEmpty(fieldname) && fieldname.StartsWith("tbl_")) { var wrow = GetFirstParent <TableRow>(field); if (wrow == null) { continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted } var wtable = GetFirstParent <Table>(wrow); if (wtable == null) { continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted } string tablename = GetTableNameFromFieldName(fieldname); if (dataset == null || !dataset.Tables.Contains(tablename) || dataset.Tables[tablename].Rows.Count == 0) { continue; // don't remove table here: will be done in next pass } var table = dataset.Tables[tablename]; var props = new List <TableCellProperties>(); var cellcolumnnames = new List <string>(); var paragraphInfo = new List <string>(); var cellfields = new List <SimpleField>(); foreach (TableCell cell in wrow.Descendants <TableCell>()) { props.Add(cell.GetFirstChild <TableCellProperties>()); var p = cell.GetFirstChild <Paragraph>(); if (p != null) { var pp = p.GetFirstChild <ParagraphProperties>(); paragraphInfo.Add(pp != null ? pp.OuterXml : null); } else { paragraphInfo.Add(null); } var colname = string.Empty; SimpleField colfield = null; foreach (SimpleField cellfield in cell.Descendants <SimpleField>()) { colfield = cellfield; colname = GetColumnNameFromFieldName(GetFieldName(cellfield, out switches)); break; // supports only 1 cellfield per table } cellcolumnnames.Add(colname); cellfields.Add(colfield); } // keep reference to row properties var rprops = wrow.GetFirstChild <TableRowProperties>(); foreach (DataRow row in table.Rows) { var nrow = new TableRow(); if (rprops != null) { nrow.Append(new TableRowProperties(rprops.OuterXml)); } for (int i = 0; i < props.Count; i++) { var cellproperties = new TableCellProperties(props[i].OuterXml); var cell = new TableCell(); cell.Append(cellproperties); var p = new Paragraph(new ParagraphProperties(paragraphInfo[i])); cell.Append(p); // cell must contain at minimum a paragraph ! if (!string.IsNullOrEmpty(cellcolumnnames[i])) { if (!table.Columns.Contains(cellcolumnnames[i])) { throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", cellcolumnnames[i])); } if (!row.IsNull(cellcolumnnames[i])) { string val = row[cellcolumnnames[i]].ToString(); p.Append(GetRunElementForText(val, cellfields[i])); } } nrow.Append(cell); } wtable.Append(nrow); } // finally : delete template-row (and thus also the mergefields in the table) wrow.Remove(); } } // clean empty tables foreach (var field in docx.MainDocumentPart.Document.Descendants <SimpleField>()) { string fieldname = GetFieldName(field, out switches); if (!string.IsNullOrEmpty(fieldname) && fieldname.StartsWith("tbl_")) { var wrow = GetFirstParent <TableRow>(field); if (wrow == null) { continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted } var wtable = GetFirstParent <Table>(wrow); if (wtable == null) { continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted } var tablename = GetTableNameFromFieldName(fieldname); if (dataset == null || !dataset.Tables.Contains(tablename) || dataset.Tables[tablename].Rows.Count == 0) { // if there's a 'dt' switch: delete Word-table if (switches.Contains("dt")) { wtable.Remove(); } } } } // next : process all remaining fields in the main document FillWordFieldsInElement(MergeColsValues, docx.MainDocumentPart.Document); docx.MainDocumentPart.Document.Save(); // save main document back in package // process header(s) foreach (HeaderPart hpart in docx.MainDocumentPart.HeaderParts) { // 2010/08/01: addition ConvertFieldCodes(hpart.Header); FillWordFieldsInElement(MergeColsValues, hpart.Header); hpart.Header.Save(); // save header back in package } // process footer(s) foreach (FooterPart fpart in docx.MainDocumentPart.FooterParts) { // 2010/08/01: addition ConvertFieldCodes(fpart.Footer); FillWordFieldsInElement(MergeColsValues, fpart.Footer); fpart.Footer.Save(); // save footer back in package } } // get package bytes stream.Seek(0, SeekOrigin.Begin); byte[] data = stream.ToArray(); // WdRetrieveToc(FileName); return(data); } }
static string CreateRequest() { Console.WriteLine("\nIn CreateRequest"); //Convert request bean to the client stub Request request = new Request(); request.requestType = "Bug"; //Set Required Fields SimpleField[] fields = new SimpleField[6]; //Description fields[0] = new SimpleField(); fields[0].token = "REQ.DESCRIPTION"; fields[0].stringValue = new String[] { "WebService Test" }; //Department fields[1] = new SimpleField(); fields[1].token = "REQ.DEPARTMENT_NAME"; fields[1].stringValue = new String[] { "Finance" }; //Module fields[2] = new SimpleField(); fields[2].token = "REQD.VP.MODULE"; fields[2].stringValue = new String[] { "Module A" }; //Platform fields[3] = new SimpleField(); fields[3].token = "REQD.VP.PLATFORM"; fields[3].stringValue = new String[] { "Unix" }; //Impact fields[4] = new SimpleField(); fields[4].token = "REQD.VP.IMPACT"; fields[4].stringValue = new String[] { "Warning" }; //Reproducible fields[5] = new SimpleField(); fields[5].token = "REQD.VP.REPRO"; fields[5].stringValue = new String[] { "Y" }; //Add fields to request request.simpleFields = fields; //Set Notes Note[] notes = new Note[1]; notes[0] = new Note(); notes[0].author = "admin"; notes[0].content = "WebService Test Note"; notes[0].creationDate = DateTime.Now; //Add notes to request request.notes = notes; //Call Webservice createRequest cr = new createRequest(); cr.requestObj = request; createRequestResponse response = serviceProxy.createRequest(cr); Console.WriteLine("createRequest Succeeded"); Console.WriteLine("Request: " + [email protected] + " Status: " + [email protected]); return([email protected]); }
public static void Process(WordprocessingDocument docx, DataColumnInfo dcInfo, DataTable dataTable, SimpleField field, string fieldName) { string[] switches; if (string.IsNullOrEmpty(fieldName) || dcInfo.FieldType != FieldType.Table) { return; } var wordRow = GetFirstParent <TableRow>(field); if (wordRow == null) { return; } var wordTable = GetFirstParent <Table>(wordRow); if (!dcInfo.HasRows || wordTable == null) { return; } var props = new List <TableCellProperties>(); var cellcolumnnames = new List <string>(); var paragraphInfo = new List <string>(); var cellfields = new List <SimpleField>(); foreach (var cell in wordRow.Descendants <TableCell>()) { props.Add(cell.GetFirstChild <TableCellProperties>()); Paragraph p = cell.GetFirstChild <Paragraph>(); if (p != null) { var pp = p.GetFirstChild <ParagraphProperties>(); paragraphInfo.Add(pp?.OuterXml); } else { paragraphInfo.Add(null); } var colname = string.Empty; SimpleField colfield = null; foreach (var cellfield in cell.Descendants <SimpleField>()) { colfield = cellfield; colname = GetColumnInfo(GetFieldName(cellfield, out switches)).FieldName; break; } cellcolumnnames.Add(colname); cellfields.Add(colfield); } // keep reference to row properties var rprops = wordRow.GetFirstChild <TableRowProperties>(); foreach (DataRow row in dataTable.Rows) { TableRow nrow = new TableRow(); if (rprops != null) { nrow.Append(new TableRowProperties(rprops.OuterXml)); } for (var i = 0; i < props.Count; i++) { TableCellProperties cellproperties = new TableCellProperties(props[i].OuterXml); TableCell cell = new TableCell(); cell.Append(cellproperties); Paragraph p = new Paragraph(new ParagraphProperties(paragraphInfo[i])); cell.Append(p); // cell must contain at minimum a paragraph ! if (!string.IsNullOrEmpty(cellcolumnnames[i])) { if (!dataTable.Columns.Contains(cellcolumnnames[i])) { throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", cellcolumnnames[i])); } if (!row.IsNull(cellcolumnnames[i])) { string val = row[cellcolumnnames[i]].ToString(); p.Append(GetRunElementForText(val, cellfields[i])); } } nrow.Append(cell); } wordTable.Append(nrow); } }
/// <summary> /// Sets the value of this field /// </summary> /// <param name="field"></param> public override void SetField(SimpleField field) { if( field.SifValue.DataType != SifDataType.String ){ field.SifValue = new SifString( field.SifValue.ToString() ); } base.SetField(field); parseTextValue(); }
public void TestXsiNill_AllChildrenNilMultiple() { SIF_Data data = new SIF_Data(); for (int a = 0; a < 3; a++) { SchoolInfo si = new SchoolInfo(); AddressableObjectName paon = new AddressableObjectName(); paon.Description = "The little white school house"; paon.StartNumber = "321"; Address addr = new Address(AddressType.CURRENT, paon); GridLocation gl = new GridLocation(); gl.SetField(CommonDTD.GRIDLOCATION_PROPERTYEASTING, new SifDecimal(null)); gl.SetField(CommonDTD.GRIDLOCATION_PROPERTYNORTHING, new SifDecimal(null)); addr.GridLocation = gl; si.AddressList = new AddressList(addr); data.AddChild(si); } // Write the object to a file Console.WriteLine("Writing to file..."); using (Stream fos = File.Open("SifWriterTest.Temp.xml", FileMode.Create, FileAccess.Write)) { SifWriter writer = new SifWriter(fos); data.SetChanged(true); writer.Write(data); writer.Flush(); fos.Close(); } // Parse the object from the file Console.WriteLine("Parsing from file..."); SifParser p = SifParser.NewInstance(); using (Stream fis = File.OpenRead("SifWriterTest.Temp.xml")) { data = (SIF_Data)p.Parse(fis, null); } foreach (SchoolInfo si in data.GetChildList()) { AddressList al = si.AddressList; Assert.IsNotNull(al); Address addr = al.ItemAt(0); Assert.IsNotNull(addr); GridLocation gl = addr.GridLocation; Assert.IsNotNull(gl); Assert.IsNull(gl.PropertyEasting); Assert.IsNull(gl.PropertyNorthing); SimpleField sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYEASTING); Assert.IsNotNull(sf); Assert.IsNull(sf.Value); sf = gl.GetField(CommonDTD.GRIDLOCATION_PROPERTYNORTHING); Assert.IsNotNull(sf); Assert.IsNull(sf.Value); } }
/// <summary> /// Fills in the body element with the provided data. /// </summary> /// <param name="dataSet">Dataset with the datatables to use to fill the document tables with. Table names in the dataset should match the table names in the document.</param> /// <param name="values">Values to fill the document. Keys should match the MERGEFIELD names.</param> /// <returns>The filled-in document.</returns> public static void ProcessBody(WordOpenXmlDocument document, Body body, DataSet dataSet, IDictionary <string, string> values) { ConvertComplexFieldsToSimpleFields(body); #region Process All Tables string[] switches = null; foreach (var field in body.Descendants <SimpleField>()) { string fieldName = GetFieldName(field, out switches); if (!string.IsNullOrEmpty(fieldName) && fieldName.StartsWith("TBL_")) { var tableRow = GetFirstParent <TableRow>(field); if (tableRow == null) { // can happen because table contains multiple fields, and after 1 pass, the initial row is already deleted continue; } var table = GetFirstParent <Table>(tableRow); if (table == null) { // can happen because table contains multiple fields, and after 1 pass, the initial row is already deleted continue; } string tableName = GetTableNameFromFieldName(fieldName); if (dataSet == null || !dataSet.Tables.Contains(tableName) || dataSet.Tables[tableName].Rows.Count == 0) { // don't remove table here: will be done in next pass continue; } var dataTable = dataSet.Tables[tableName]; var cellPropertiesList = new List <TableCellProperties>(); var cellColumnNamesList = new List <string>(); var paragraphPropertiesList = new List <string>(); var cellFieldsList = new List <SimpleField>(); foreach (var tableCell in tableRow.Descendants <TableCell>()) { cellPropertiesList.Add(tableCell.GetFirstChild <TableCellProperties>()); var paragraph = tableCell.GetFirstChild <Paragraph>(); if (paragraph != null) { var pp = paragraph.GetFirstChild <ParagraphProperties>(); if (pp != null) { paragraphPropertiesList.Add(pp.OuterXml); } else { paragraphPropertiesList.Add(null); } } else { paragraphPropertiesList.Add(null); } string columnName = string.Empty; SimpleField columnField = null; foreach (var cellField in tableCell.Descendants <SimpleField>()) { columnField = cellField; columnName = GetColumnNameFromFieldName(GetFieldName(cellField, out switches)); break; // supports only 1 cellfield per table } cellColumnNamesList.Add(columnName); cellFieldsList.Add(columnField); } // keep reference to row properties var rowProperties = tableRow.GetFirstChild <TableRowProperties>(); foreach (DataRow dataRow in dataTable.Rows) { var row = new TableRow(); if (rowProperties != null) { row.Append(new TableRowProperties(rowProperties.OuterXml)); } for (int i = 0; i < cellPropertiesList.Count; i++) { var cellProperties = new TableCellProperties(cellPropertiesList[i].OuterXml); var cell = new TableCell(); cell.Append(cellProperties); var p = new Paragraph(new ParagraphProperties(paragraphPropertiesList[i])); cell.Append(p); // cell must contain at minimum a paragraph ! if (!string.IsNullOrEmpty(cellColumnNamesList[i])) { if (!dataTable.Columns.Contains(cellColumnNamesList[i])) { throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", cellColumnNamesList[i])); } if (!dataRow.IsNull(cellColumnNamesList[i])) { string val = dataRow[cellColumnNamesList[i]].ToString(); p.Append(GetRunElementForText(val, cellFieldsList[i])); } } row.Append(cell); } table.Append(row); } // finally : delete template-row (and thus also the mergefields in the table) tableRow.Remove(); } } #endregion Process All Tables #region Clean Empty Tables foreach (var field in body.Descendants <SimpleField>()) { string fieldName = GetFieldName(field, out switches); if (!string.IsNullOrEmpty(fieldName) && fieldName.StartsWith("TBL_")) { var tableRow = GetFirstParent <TableRow>(field); if (tableRow == null) { continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted } var table = GetFirstParent <Table>(tableRow); if (table == null) { continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted } string tableName = GetTableNameFromFieldName(fieldName); if (dataSet == null || !dataSet.Tables.Contains(tableName) || dataSet.Tables[tableName].Rows.Count == 0) { // if there's a 'dt' switch: delete Word-table if (switches.Contains("dt")) { table.Remove(); } } } } #endregion Clean Empty Tables #region Process Remaining Fields In Main Document & Save FillWordFieldsInElement(values, body); document.Save(); // save main document back in package #endregion Process Remaining Fields In Main Document & Save }
/// <summary> /// Perform processing on a token. Note that this is not called for discarded tokens. /// Figure out what to do with a token. Check if it is a field, etc. /// </summary> /// <remarks> /// XML Word fields can either be simple, or complex. Complex are spread over multiple elements, and can also be nested. /// </remarks> /// <param name="token"></param> void ProcessToken(Token token) { OpenXmlElement element = token.SourceNode; // Handle complex-token delimiters if (token.IsOpen && element is FieldChar) { FieldChar fc = (FieldChar)element; if (fc.FieldCharType.HasValue) { switch (fc.FieldCharType.Value) { // Start-marker a complex field case FieldCharValues.Begin: if (CurrentField != null) { CurrentField.ContainsNestedFields = true; } FieldData fieldData = new FieldData { FieldType = FieldType.Complex, FieldState = FieldState.InFieldCode, Instruction = "", SourceStart = new Token(element.Parent, false) }; // Push onto complex field stack _fieldDataStack.Push(fieldData); break; // Partition of a complex field (switches from detecting instruction, to detecting field text) case FieldCharValues.Separate: if (CurrentField == null) { throw new Exception("Unexpected fldChar:separate"); } CurrentField.FieldState = FieldState.InFieldText; break; // End-marker for a complex field case FieldCharValues.End: if (CurrentField == null) { throw new Exception("Unexpected fldChar:end"); } CurrentField.FieldState = FieldState.Done; CurrentField.SourceEnd = new Token(element.Parent, true); // Process the field ProcessField(CurrentField); // Pop off complex field stack _fieldDataStack.Pop(); break; } } } // Handle a field code (instrText) element within a complex field // That is, content that may be part of the instruction. if (token.IsOpen && element is FieldCode) { if (CurrentField != null && CurrentField.FieldState == FieldState.InFieldCode) { FieldCode fieldCode = (FieldCode)element; CurrentField.Instruction += fieldCode.InnerText; } } // Handle an entire simplefield if (token.IsOpen && element is SimpleField) { // E.g: // <fldSimple> <r> <t/> </r> </fldSimple> SimpleField sf = (SimpleField)element; FieldData fieldData = new FieldData { Instruction = sf.Instruction, FieldState = FieldState.Done, SourceStart = new Token(element, false), SourceEnd = new Token(element, true), FieldType = FieldType.Simple }; ProcessField(fieldData); } }
public static byte[] WordDokumanOlustur(string sablon, DataSet dataset, Dictionary <string, string> degerler) { byte[] buffer = File.ReadAllBytes(sablon); string[] switches = (string[])null; using (MemoryStream memoryStream = new MemoryStream()) { memoryStream.Write(buffer, 0, buffer.Length); using (WordprocessingDocument docx = WordprocessingDocument.Open((Stream)memoryStream, true)) { DocumentMerge.ConvertFieldCodes((OpenXmlElement)docx.MainDocumentPart.Document); foreach (SimpleField field in docx.MainDocumentPart.Document.Descendants <SimpleField>()) { string fieldName = DocumentMerge.GetFieldName(field, out switches); if (!string.IsNullOrEmpty(fieldName) && fieldName.StartsWith("TBL_")) { TableRow firstParent1 = DocumentMerge.GetFirstParent <TableRow>((OpenXmlElement)field); if (firstParent1 != null) { Table firstParent2 = DocumentMerge.GetFirstParent <Table>((OpenXmlElement)firstParent1); if (firstParent2 != null) { string nameFromFieldName = DocumentMerge.GetTableNameFromFieldName(fieldName); if (dataset != null && dataset.Tables.Contains(nameFromFieldName) && dataset.Tables[nameFromFieldName].Rows.Count != 0) { DataTable dataTable = dataset.Tables[nameFromFieldName]; List <TableCellProperties> list1 = new List <TableCellProperties>(); List <string> list2 = new List <string>(); List <string> list3 = new List <string>(); List <SimpleField> list4 = new List <SimpleField>(); foreach (TableCell tableCell in firstParent1.Descendants <TableCell>()) { list1.Add(tableCell.GetFirstChild <TableCellProperties>()); Paragraph firstChild1 = tableCell.GetFirstChild <Paragraph>(); if (firstChild1 != null) { ParagraphProperties firstChild2 = firstChild1.GetFirstChild <ParagraphProperties>(); if (firstChild2 != null) { list3.Add(firstChild2.OuterXml); } else { list3.Add((string)null); } } else { list3.Add((string)null); } string str = string.Empty; SimpleField simpleField = (SimpleField)null; using (IEnumerator <SimpleField> enumerator = tableCell.Descendants <SimpleField>().GetEnumerator()) { if (enumerator.MoveNext()) { SimpleField current = enumerator.Current; simpleField = current; str = DocumentMerge.GetColumnNameFromFieldName(DocumentMerge.GetFieldName(current, out switches)); } } list2.Add(str); if (str != "") { list4.Add(simpleField); } } TableRowProperties firstChild = firstParent1.GetFirstChild <TableRowProperties>(); foreach (DataRow dataRow in (InternalDataCollectionBase)dataTable.Rows) { TableRow tableRow = new TableRow(); if (firstChild != null) { tableRow.Append(new OpenXmlElement[1] { (OpenXmlElement) new TableRowProperties(firstChild.OuterXml) }); } for (int index = 0; index < list1.Count; ++index) { TableCellProperties tableCellProperties = new TableCellProperties(list1[index].OuterXml); TableCell tableCell = new TableCell(); tableCell.Append(new OpenXmlElement[1] { (OpenXmlElement)tableCellProperties }); Paragraph paragraph = new Paragraph(new OpenXmlElement[1] { (OpenXmlElement) new ParagraphProperties(list3[index]) }); tableCell.Append(new OpenXmlElement[1] { (OpenXmlElement)paragraph }); try { if (!string.IsNullOrEmpty(list2[index])) { if (!dataTable.Columns.Contains(list2[index])) { throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", (object)list2[index])); } if (!dataRow.IsNull(list2[index])) { string text = dataRow[list2[index]].ToString(); paragraph.Append(new OpenXmlElement[1] { (OpenXmlElement)DocumentMerge.GetRunElementForText(text, list4[index]) }); } } } catch { } tableRow.Append(new OpenXmlElement[1] { (OpenXmlElement)tableCell }); } firstParent2.Append(new OpenXmlElement[1] { (OpenXmlElement)tableRow }); } firstParent1.Remove(); } } } } } foreach (SimpleField field in docx.MainDocumentPart.Document.Descendants <SimpleField>()) { string fieldName = DocumentMerge.GetFieldName(field, out switches); if (!string.IsNullOrEmpty(fieldName) && fieldName.StartsWith("TBL_")) { TableRow firstParent1 = DocumentMerge.GetFirstParent <TableRow>((OpenXmlElement)field); if (firstParent1 != null) { Table firstParent2 = DocumentMerge.GetFirstParent <Table>((OpenXmlElement)firstParent1); if (firstParent2 != null) { string nameFromFieldName = DocumentMerge.GetTableNameFromFieldName(fieldName); if ((dataset == null || !dataset.Tables.Contains(nameFromFieldName) || dataset.Tables[nameFromFieldName].Rows.Count == 0) && Enumerable.Contains <string>((IEnumerable <string>)switches, "dt")) { firstParent2.Remove(); } } } } } DocumentMerge.FillWordFieldsInElement(docx, degerler, (OpenXmlElement)docx.MainDocumentPart.Document); ((OpenXmlPartRootElement)docx.MainDocumentPart.Document).Save(); foreach (HeaderPart headerPart in docx.MainDocumentPart.HeaderParts) { DocumentMerge.ConvertFieldCodes((OpenXmlElement)headerPart.Header); DocumentMerge.FillWordFieldsInElement(docx, degerler, (OpenXmlElement)headerPart.Header); ((OpenXmlPartRootElement)headerPart.Header).Save(); } foreach (FooterPart footerPart in docx.MainDocumentPart.FooterParts) { DocumentMerge.ConvertFieldCodes((OpenXmlElement)footerPart.Footer); DocumentMerge.FillWordFieldsInElement(docx, degerler, (OpenXmlElement)footerPart.Footer); ((OpenXmlPartRootElement)footerPart.Footer).Save(); } } memoryStream.Seek(0L, SeekOrigin.Begin); return(memoryStream.ToArray()); } }
internal static Run GetRunElementForText(string text, SimpleField placeHolder) { string outerXml = (string)null; if (placeHolder != null) { using (IEnumerator <RunProperties> enumerator = placeHolder.Descendants <RunProperties>().GetEnumerator()) { if (enumerator.MoveNext()) { outerXml = enumerator.Current.OuterXml; } } } Run run = new Run(); if (!string.IsNullOrEmpty(outerXml)) { run.Append(new OpenXmlElement[1] { (OpenXmlElement) new RunProperties(outerXml) }); } if (!string.IsNullOrEmpty(text)) { string[] strArray = ((object)text).ToString().Split(new string[1] { "\n" }, StringSplitOptions.None); bool flag1 = true; foreach (string str1 in strArray) { if (!flag1) { run.Append(new OpenXmlElement[1] { (OpenXmlElement) new Break() }); } flag1 = false; bool flag2 = true; string str2 = str1; string[] separator = new string[1] { "\t" }; int num = 0; foreach (string text1 in str2.Split(separator, (StringSplitOptions)num)) { if (!flag2) { run.Append(new OpenXmlElement[1] { (OpenXmlElement) new TabChar() }); } run.Append(new OpenXmlElement[1] { (OpenXmlElement) new Text(text1) }); flag2 = false; } } } return(run); }
public void RenderRaw( XmlWriter writer, SifVersion version, Element o, SifFormatter formatter) { SifSimpleType value; // Read the value out of the source object if (fValueXpath.StartsWith(".")) { value = o.SifValue; } else { IElementDef valueDef = null; if (o is SifElement) { valueDef = Adk.Dtd.LookupElementDefBySQP(o.ElementDef, fValueXpath); } if (valueDef == null) { throw new InvalidOperationException ("Support for value path {" + fValueXpath + "} is not supported by XPathSurrogate."); } SimpleField field = ((SifElement)o).GetField(valueDef); if (field == null) { return; } value = field.SifValue; } if (value == null) { return; } String[] xPathParts = fLegacyXpath.Split('/'); int currentSegment = 0; // Build the path while (currentSegment < xPathParts.Length - 1) { writer.WriteStartElement(xPathParts[currentSegment]); currentSegment++; } String finalSegment = xPathParts[currentSegment]; if (finalSegment.StartsWith("@")) { writer.WriteAttributeString( finalSegment.Substring(1), value.ToString(formatter)); } else { // Note: finalSegment can be equal to ".", which // signals to render the text only if (finalSegment.Length > 1) { writer.WriteStartElement(finalSegment); currentSegment++; } writer.WriteValue(value.ToString(formatter)); } currentSegment--; // unwind the path while (currentSegment > -1) { writer.WriteEndElement(); currentSegment--; } }