SharePoint Site Users & Hits Count Report For The Past 30 Days
I am sharing here code to get SharePoint Site User & Hits Count report.
Need count of users & hits on each site (not for site collection - site collection has OOTB report! but at site level) for a particular web application for past 30 days!
Use below code to get the Report:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Data;
using System.IO;
namespace AdminReports
{
class GetSiteUsageReport
{
//Method to Get Usage Data
public static int GetUserCount(SPWeb oSPWeb)
{
try
{
//Get the Usage Details
object userCount = null;
//DataTable for users set - Because GetUsageData returns DataTable!
DataTable dtUsers = new DataTable();
dtUsers = oSPWeb.GetUsageData(SPUsageReportType.user, SPUsagePeriodType.lastMonth);
if (dtUsers != null)
{
userCount = dtUsers.Compute("Count(user)", string.Empty);
return (Convert.ToInt32(userCount));
}
else
{
return (0);
}
}
catch (Exception Ex1)
{
return (0);
}
}
//Method to Get Hits Data
public static int GetHitsCount(SPWeb oSPWeb)
{
try
{
//DataTable for Hits set - Because GetUsageData returns DataTable!
object totalHits = null;
DataTable dtHits = new DataTable();
dtHits = oSPWeb.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.lastMonth);
if (dtHits != null)
{
totalHits = dtHits.Compute("Sum([Total Hits])", string.Empty);
return (Convert.ToInt32(totalHits));
}
else
{
return (0);
}
}
catch (Exception Ex2)
{
return (0);
}
}
static void Main(string[] args)
{
string site;
try
{
if (args.Length == 0)
{
Console.WriteLine("Enter the Web Application URL:");
site = Console.ReadLine();
}
else
{
site = args[0];
}
SPSite tmpRoot = new SPSite(site);
SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;
//objects for the CSV file generation
StreamWriter SW;
SW = File.AppendText("c:\\SiteUsageReport.csv");
//Write the CSV Header
SW.WriteLine("Site Name, URL, No. of Users, Hits Count");
//Enumerate through each site collection
foreach (SPSite tmpSite in tmpRootColl)
{
//Enumerate through each sub-site
foreach (SPWeb tmpWeb in tmpSite.AllWebs)
{
//Get the Site Name
string siteName;
if (tmpWeb.IsRootWeb)
{
siteName = tmpWeb.Title + " - Root";
}
else
{
siteName = tmpSite.RootWeb.Title + " - " + tmpWeb.Title;
}
//Log the retrieved details to a CSV file
SW.WriteLine(siteName.Replace(",", " ") + "," + tmpWeb.Url + "," + GetUserCount(tmpWeb) + "," + GetHitsCount(tmpWeb) );
}
}
//Dispose of the Root Site Object
SW.Close();
tmpRoot.Dispose();
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("Site Usage Report Report", ex.Message);
}
}
}
}
SharePoint Site Hits Report: after running above code you will get raw data in Excel form as below.
After adding a Pivot Table you will get SharePoint site usage report total hits and users report shown as below:
Drop your feedback
Note : You are required to be logged-in as a user to leave a feedback.