The issue is when creating the template file, I get an error that this
is not compatible with sandboxed solutions.
try
{
Stream docStream = new MemoryStream();
SPContentType contentType =
volunteersDocLib.ContentTypeOrder[int.Parse(lstContentTypes.SelectedValue)];
SPFile templateFile =
contentType.ResourceFolder.Files[contentType.DocumentTemplate];
Stream templateStream = templateFile.OpenBinaryStream();
BinaryReader reader = new BinaryReader(templateStream);
BinaryWriter writer = new BinaryWriter(docStream);
writer.Write(reader.ReadBytes((int)templateStream.Length));
writer.Flush();
reader.Close();
templateStream.Dispose();
//insert custom xml part into the document stream
SPListItem volunteerItem = null;
volunteerItem =
webObj.Lists[this.listId].GetItemById(this.itemId);
//open .docx file in memory stream as package file
docStream.Position = 0;
//Begin edits here for Open XML SDK
WordprocessingDocument wordDoc =
WordprocessingDocument.Open(docStream, true);
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
//retrieve package part with XML data
XmlDocument xDoc = null;
CustomXmlPart customPart = null;
foreach (CustomXmlPart cp in mainPart.CustomXmlParts)
{
xDoc = new XmlDocument();
xDoc.Load(cp.GetStream());
if (xDoc.DocumentElement.NamespaceURI ==
"http://www.sample.com/2011/schemas/volunteer/")
{
customPart = cp;
break;
}
}
//serialize the contact item into this customXml part
XmlNode rootNode = xDoc.DocumentElement;
rootNode.RemoveAll();
foreach (SPField field in contactItem.Fields)
{
XmlNode fieldNode = xDoc.CreateElement("sc",
XmlConvert.EncodeName(field.Title),
"http://www.sample.com/2011/schemas/volunteer/");
if (contactItem[field.Id] != null)
{
XmlNode fieldVal =
xDoc.CreateTextNode(contactItem[field.Id].ToString());
fieldNode.AppendChild(fieldVal);
}
rootNode.AppendChild(fieldNode);
}
xDoc.Save(customPart.GetStream(FileMode.Create,
FileAccess.Write));
//deliver file to library
volunteersDocLib.Files.Add(txtFileName.Text, docStream);
lblMessage.Visible = true;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}