Tuesday, October 21, 2014

Logging error in event viewer

        void LogError(TraceSeverity Level, Exception exception)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string errorMessage = exception.Message + "--" + exception.StackTrace;
                SPDiagnosticsService.Local.WriteTrace(0,
                    new SPDiagnosticsCategory("Error Log", Level, EventSeverity.Error), TraceSeverity.Unexpected, errorMessage, null);
            });
        }

Friday, October 10, 2014

Change text in a word file using OpenXML

using (SPSite oSite = new SPSite("SP SITE URL"))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        SPFile oFile = oWeb.GetFile("FILE TEMPLATE URL");
        byte[] byteArray = oFile.OpenBinary();
        using (MemoryStream memStr = new MemoryStream())
        {
            memStr.Write(byteArray, 0, byteArray.Length);
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
            {
                Table table = wordDoc.MainDocumentPart.Document.Body.Elements<Table>().First();//find first table
                TableRow row = table.Elements<TableRow>().ElementAt(7);//get the 7th row
                TableCell cell = row.Elements<TableCell>().ElementAt(2);//get the 2nd cell
                Paragraph p = cell.Elements<Paragraph>().First();//1st paragraph
                Run r = p.Elements<Run>().First();//1st run
                Text t = r.Elements<Text>().First();//get the text
                t.Text = "TEXT TO BE UPDATED";//set the text
            }
        }
    }
}

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...