SharePoint Site Users & Hits Count Report for the past 30 days

Another SharePoint Report Requirement: 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!

No worries! My code goes here:

Find Hits Count for the Past 30 Days:

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: and my report output: Raw data

sharepoint site hits report

After adding a Pivot Table: SharePoint site usage report total hits and users:

sharepoint site usage report total hits and users

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

18 thoughts on “SharePoint Site Users & Hits Count Report for the past 30 days

  • Salladunin, Can I get script for Sharepoint2013 , ? It would be very helpful

    Reply
  • Hi
    How to capture user login and logout details along with time for a particular site in O365.

    Thanks

    Reply
  • hi
    how i implement this code in sharepoint 2013 site, please help me i am fresher in SP.

    Reply
  • Hi,
    I want to get top pages for site collection, How can I achieve this programmatically.

    Reply
  • your blog is awesome man !! Good work
    thanks !
    this is the first place where I look for all my issues 🙂

    Reply
  • can we get the user name as well??

    Reply
    • Sure! Line#23 is passing “User” as report type, which returns a “Data Table”. You can iterate through that to get user data.

      Reply
  • How can we get user hit for a Page or clicking on link of a Blog site?

    Reply
  • Hi Salaudeen,

    Thanks for this post.
    I am purely a SharePoint Administrator, So could you have power shell script to get the same result.

    Thanks In advance 🙂

    Reply
  • How do you enable this report?

    Reply
    • Make a console application with this code in visual studio and run it in your SharePoint WFE.

      Reply
  • Hi,
    I am trying to retrieve few site collection and sub site level counters for reporting purpose:
    e.g.
    1. Non Active Site Collections and Sites based custom threshold value
    2. Non Active Users Per Site or Site Collections

    Do any one have idea from where I can get above counters either direct (OOB) or indirect way (using custom code). I had tried with SP.GetUsageData / RPC GetUsageBlob is not working for me. Like to understand why these methods or call failed.

    Thanks,
    Sudarshan

    Reply
    • I see GetUsageData returns NULL when Site is locked/quota exceeded. Make sure Usage data collection is in place.

      Reply
    • If Usage Data collection is enabled, Check these timer jobs:

      Central Administration >> Monitoring >> Review Job definitions under Timer Jobs

      Make sure that the timer jobs are enabled:

      Microsoft SharePoint Foundation Usage Data Import
      Microsoft SharePoint Foundation Usage Data Processing

      Run them atleast once. Sometimes it takes a few hours for the data to populate.

      Reply
    • Hardly any content inside newly created site and site is not locked.

      Do you see any other force issue?

      Thanks,
      Sudarshan

      Reply
    • Hi

      Everything is enabled in my server but still the GetUsagedata returns nothing in powershell can you please help me to know who are the people accessesd my site

      Reply
  • Thanks. Works like a charm…

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *