Wednesday, July 30, 2014

Handling SharePoint exception in ULS log and SharePoint List

Adding log to ULS and also adding to sharepoint list

// adding log to ULS log
public class ULSLogService : SPDiagnosticsServiceBase
    {
        private static string PRODUCT_NAME = "Biraj_Blog";

        private ULSLogService() : base("Biraj Logging Service", SPFarm.Local) { }
        private static ULSLogService logSerivce;
        public static ULSLogService LogSerivce
        {
            get
            {
                if (logSerivce == null)
                {
                    logSerivce = new ULSLogService();
                }
                return logSerivce;
            }
        }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>{
             new SPDiagnosticsArea(PRODUCT_NAME, new List<SPDiagnosticsCategory>{
                 new SPDiagnosticsCategory("Biraj_Info", TraceSeverity.Verbose, EventSeverity.Information),
                 new SPDiagnosticsCategory("Biraj_Error", TraceSeverity.Unexpected, EventSeverity.Warning),
             })
             };
            return areas;
        }

        public static void DisplayInfo(string ClassMethodName, Exception ex)
        {
            SPDiagnosticsCategory category = ULSLogService.LogSerivce.Areas[PRODUCT_NAME].Categories["Biraj_Info"];
            ULSLogService.LogSerivce.WriteTrace(0, category, TraceSeverity.Verbose, ClassMethodName + " \n-- " + ex.TargetSite + " \n-- " + ex.Message + " \n-- " + ex.StackTrace + " \n-- " + ex.Source + " \n-- " + ex.Data);
            Logs.AddIntoList("Info", ClassMethodName, ex);
        }

        public static void DisplayError(string ClassMethodName, Exception ex)
        {
            SPDiagnosticsCategory category = ULSLogService.LogSerivce.Areas[PRODUCT_NAME].Categories["Biraj_Error"];
            ULSLogService.LogSerivce.WriteTrace(0, category, TraceSeverity.Unexpected, ClassMethodName + " \n-- " + ex.TargetSite + " \n-- " + ex.Message + " \n-- " + ex.StackTrace + " \n-- " + ex.Source + " \n-- " + ex.Data);
            Logs.AddIntoList("Error", ClassMethodName, ex);
        }

    }


// adding log to SharePoint List
public static void AddIntoList(string Title, string ClassMethodName, Exception exception)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {                           
                            try
                            {
                                spWeb.AllowUnsafeUpdates = true;
                                SPList logsList = spWeb.Lists.TryGetList("Logs");
                                SPListItem newItem = logsList.Items.Add();
                                newItem["Title"] = Title;
                                newItem["MethodName"] = ClassMethodName;
                                newItem["TargetSite"] = exception.TargetSite;
                                newItem["Message"] = exception.Message;
                                newItem["Source"] = exception.Source;
                                newItem["StackTrace"] = exception.StackTrace;
                                newItem["Data"] = exception.Data;   
                                
                                newItem.Update();
                                spWeb.AllowUnsafeUpdates = false;
                            }
                            catch(Exception ex)
                            {
                                
                            }                           
                        }
                    }
                });
            }
            catch (Exception ex)
            {
               
               
            }
        }

Read table row and perform total in Word document using Open Xml

Read Table row and perform total of row cells and append table cell at end for total


                                    #region HORIZONTAL TOTAL
                                    // append last Column to total
                                    GridColumn gc1 = new GridColumn();
                                    tg.AppendChild(gc1);

                                    Hashtable hashTable1 = new Hashtable();
                                    IEnumerable<TableRow> trs1 = t.Descendants<TableRow>();
                                    int iRowsCount1 = 0;
                                    // storing values in hashtable
                                    while (iRowsCount1 < trs1.Count())
                                    {
                                        hashTable1.Add(iRowsCount1, 0);
                                        IEnumerable<TableCell> tcc = t.Descendants<TableRow>().ElementAt(iRowsCount1).Descendants<TableCell>();
                                        TableCell tcClone = (TableCell)t.Descendants<TableRow>().ElementAt(iRowsCount1).Descendants<TableCell>().Last().CloneNode(true);

                                        foreach (TableCell tc in tcc)
                                        {
                                            int value;
                                            if (int.TryParse(tc.InnerText, out value))
                                            {
                                                hashTable1[iRowsCount1] = hashTable1[iRowsCount1] + "+" + tc.InnerText;
                                            }
                                        }
                                        // values are stored in hashtable
                                        if (tcClone.InnerText != "")
                                        {
                                            // Gel all text elements of TableCell
                                            IEnumerable<Text> texts = tcClone.Descendants<Text>();
                                            ////Clear all text elements' inner text
                                            foreach (Text text in texts)
                                            {
                                                text.Text = "";
                                            }
                                            // Find the first paragraph in the table cell.
                                            Paragraph p = tcClone.Elements<Paragraph>().First();
                                            // Find the first run in the paragraph.
                                            Run r = p.Elements<Run>().First();
                                            // Set the text for the run.
                                            Text t1 = r.Elements<Text>().First();
                                            if (hashTable1[iRowsCount1].ToString() == "0")
                                            {
                                                t1.Text = "";
                                            }
                                            else
                                            {
                                                RunProperties rp = new RunProperties();
                                                Bold bold = new Bold();
                                                rp.Append(bold);
                                                r.Append(rp);
                                                t1.Text = "Formula(" + hashTable1[iRowsCount1].ToString() + ")";
                                            }
                                            t.Descendants<TableRow>().ElementAt(iRowsCount1).AppendChild(tcClone);
                                        }
                                        iRowsCount1++;


                                    }

                                    #endregion
                                }
                            }

                        }

Table with totals in a Word document using Open Xml


Table with totals in a Word document using Open Xml 
Assuming you have table object in word document

#region Append Last TOTAL Row
                            IEnumerable<GridColumn> gcc = t.Descendants<GridColumn>();
                            Hashtable hashTable = new Hashtable();
                            int iTmpColumns = 0;
                            while (iTmpColumns < gcc.Count())
                            {
                                hashTable.Add(iTmpColumns, 0);
                                iTmpColumns++;
                            }

                            int iTmpTableRows = 0;
                            if (initialTableRowCounts == 2)
                            {
                                iTmpTableRows = 1;
                            }
                            while (iTmpTableRows < t.Descendants<TableRow>().Count())
                            {
                                // process hash table and inset values
                                int tmp = 0;
                                while (tmp < hashTable.Count)
                                {
                                    TableCell tc = t.Descendants<TableRow>().ElementAt(iTmpTableRows).Descendants<TableCell>().ElementAt(tmp);
                                    int value;
                                    if (int.TryParse(tc.InnerText, out value))
                                    {
                                        hashTable[tmp] = hashTable[tmp] + "+" + tc.InnerText;
                                    }
                                    tmp++;
                                }
                                //                              
                                iTmpTableRows++;
                            }

                            // Clone last row for repetition
                            TableRow rowCopy1 = (TableRow)lastRow.CloneNode(true);
                            // Get all cells of last row
                            IEnumerable<TableCell> tcc2 = rowCopy1.Descendants<TableCell>();
                            // iterate through all cells of last row
                            int iTmpCellCount = 0;
                            while (iTmpCellCount < tcc2.Count())
                            {
                                TableCell tc = tcc2.ElementAt(iTmpCellCount);
                                // Gel all text elements of TableCell
                                IEnumerable<Text> texts = tc.Descendants<Text>();
                                //Clear all text elements' inner text
                                foreach (Text text in texts)
                                {
                                    text.Text = "";
                                }
                                //// Find the first paragraph in the table cell.
                                Paragraph p = tc.Elements<Paragraph>().First();
                                //// Find the first run in the paragraph.
                                Run r = p.Elements<Run>().First();
                                //// Set the text for the run.
                                Text t1 = r.Elements<Text>().First();
                                // Set first text element
                                t1.Text = "Formula(" + hashTable[iTmpCellCount].ToString() + ")";
                                iTmpCellCount++;
                            }
                            t.AppendChild(rowCopy1);

                            #endregion