using Microsoft.SharePoint;
using
Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace
SiteUseageAndHitCount
{
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;
// object lastAccess = null;
DataTable dtHits = new DataTable();
dtHits = oSPWeb.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.lastMonth);
if (dtHits != null)
{
totalHits = dtHits.Compute("Sum([Total
Hits])", string.Empty);
//lastAccess = dtHits.Compute("Most Recent Day",
string.Empty);
return (Convert.ToInt32(totalHits));//, Convert.ToDateTime(lastAccess));
}
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;
if (File.Exists(@"C:\\UserHitsReport.csv"))
{
Console.WriteLine("Deleting old file.");
File.Delete(@"C:\\UserHitsReport.csv");
Console.WriteLine("Old file has been deleted successfully");
}
//objects for the CSV file generation
StreamWriter SW;
SW =
File.AppendText("C:\\UserHitsReport.csv");
//Write the CSV Header
SW.WriteLine("Site Name, URL, No.
of Users, Hits Count, Most Recent Day");
//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();
Console.WriteLine("Complete report sotred at- C:\\UserHitsReport.csv");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("Site
Usage Report Report", ex.Message);
}
}
}
}
No comments:
Post a Comment