How to use WebAnalytics API – FrontEndDataRetriever.QueryData

This post is a contribution from Jaishree Thiyagarajan, an engineer with the SharePoint Developer Support team.

To use WebAnalytics API, first we need to add reference to Microsoft.Office.Server.WebAnalytics.dll and Microsoft.Office.Server.WebAnalytics.UI.dll.  These DLLs can be located in GAC (C:\Windows\Assembly\GAC_MSIL\).

The WebAnalytics DB (Report DB) has many Table-Valued-functions, which we can leverage programmatically through FrontEndDataRetriever.QueryData.

Check out the example given below.  I’ve used “fn_WA_GetNumberOfClickthroughs”, this function will retrieve the number of hits per URL.

List of available functions can be found in this article.

Sample below.

 try
 {
     using (SPSite site = new SPSite("https://siteURL/"))
     {
         AggregationContext aggregationContext = AggregationContext.GetContext(site);
         if (aggregationContext != null)
         {
             List<ViewParameterValue> viewParamsList = new List<ViewParameterValue>();
             viewParamsList.Add(new ViewParameterValue("StartDateId", DateTimeToDateId(DateTime.UtcNow.AddMonths(-6))));
             viewParamsList.Add(new ViewParameterValue("EndDateId", DateTimeToDateId(DateTime.UtcNow)));
             viewParamsList.Add(new ViewParameterValue("GroupByPageId", true));
             DataPacket dataPacket = FrontEndDataRetriever.QueryData(aggregationContext, null, "fn_WA_GetNumberOfClickthroughs", viewParamsList, null, GetSortOrder("Frequency", OrderType.Descending), 1, 25000, false);
             if (dataPacket.DataTable != null)
             {
                 //Datatable manipulation
             }
             else
             {
                 //No datatable available
             }
             Console.ReadLine();
         }
     }
 }
 catch (Exception ex)
 {
     Console.WriteLine(ex.Message);
 }