Wednesday, May 30, 2012

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:

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



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

16 comments :

  1. Thanks. Works like a charm...

    ReplyDelete
  2. 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

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

      Delete
    2. Hardly any content inside newly created site and site is not locked.

      Do you see any other force issue?

      Thanks,
      Sudarshan

      Delete
    3. 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.

      Delete
    4. 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

      Delete
  3. How do you enable this report?

    ReplyDelete
    Replies
    1. Make a console application with this code in visual studio and run it in your SharePoint WFE.

      Delete
  4. 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 :)

    ReplyDelete
  5. How can we get user hit for a Page or clicking on link of a Blog site?

    ReplyDelete
  6. can we get the user name as well??

    ReplyDelete
    Replies
    1. Sure! Line#23 is passing "User" as report type, which returns a "Data Table". You can iterate through that to get user data.

      Delete
  7. your blog is awesome man !! Good work
    thanks !
    this is the first place where I look for all my issues :)

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

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

    ReplyDelete

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...