Question

Can any one help me in knowing what's wrong in my code Because I want all the columns from Audit entries should get create in my Data Row dynamically

using (SPSite mysiteCollection = new SPSite(SPContext.Current.Site.ID))
        {
            using (SPWeb web = mysiteCollection.OpenWeb())
            {
                web.AllowUnsafeUpdates = true;
                SPAuditQuery query = new SPAuditQuery(mysiteCollection);
                query.SetRangeStart(DateTime.Now.AddDays(-1));
                query.SetRangeEnd(DateTime.Now);
                SPAuditEntryCollection auditCol = mysiteCollection.Audit.GetEntries(query);

              DataTable dtAudit = new DataTable();
         dtAudit.Columns.Add("NewColumn", typeof(System.String));

         foreach (SPAuditEntry entry in auditCol)
         {
              if (entry.Event == SPAuditEventType.Update)
              {
                  DataRow dRow = dtAudit.Rows.Add();
                  dRow["NewColumn"] = entry.MachineName;
                  dtAudit.Rows.Add(dRow);
              }
          }

                GridView1.DataSource = dtAudit;
                GridView1.DataBind();
            }
        }
Was it helpful?

Solution

The issue is related to this line dRow["NewColumn"] = entry.MachineName; where the entry.MachineName returns as NULL. (Debugged on my side)

Unfortunately, By Design the returned values of the MachineName and MachineIP are always NULL for Privacy concerns.

Besides the above issue, There is a bit syntax issue related to this line

DataRow dRow = dtAudit.Rows.Add(); it should be dtAudit.NewRow();


So in your code, you should exclude both MachineIP and MachineName columns when you tried to show the SPAuditEntryCollection data.

Also, Make sure that the value of retrieved column is not NULL before adding a new row in dtAudit datatable to avoid the null value exception and fix dtAudit.Rows.Add(); to be dtAudit.NewRow(); as the following:

if (entry.MachineName != null)
 {
   DataRow dRow = dtAudit.NewRow();       
   dRow["NewColumn"] = entry.MachineName;
   dtAudit.Rows.Add(dRow);
 }

Output

Empty value for MachineName

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top