Thursday, November 17, 2016

Retrieve Popular items Programmatically In SharePoint using SOM


In this article, we’ll see how to retrieve popular items based on view counts programmatically using SOM.


Make sure that you have enabled the reporting feature under site collection features in the site to see the popular documents.

The following lines of code retrieve the data and update the results in a Data table.

using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.Office.Server.Search.Query;
using System.Data;

namespace GetPopularItems
   class Program
       static void Main(string[] args)
           DataTable table = new DataTable();
table.Columns.Add("ItemID", typeof(Int32));
           table.Columns.Add("Name", typeof(String));
           table.Columns.Add("Recent", typeof(Int32));
           table.Columns.Add("Views", typeof(Int32));

           string siteurl = "http://SiteURL/";
           string docLibURL = "http://SiteURL/Shared%20Documents";

           using (SPSite siteCollection = new SPSite(siteurl))
               using (SPWeb rootWeb = siteCollection.OpenWeb())

                   KeywordQuery keywordQuery = new KeywordQuery(siteCollection);
var properties = keywordQuery.SelectProperties; properties.Add("ListItemID");
                   keywordQuery.QueryText = "Path:"+ docLibURL;
                   SearchExecutor searchExecutor = new SearchExecutor();
                   ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
                   var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);
                   ResultTable resultTable = resultTables.FirstOrDefault();
                   DataRowCollection dataTable = resultTable.Table.Rows;
                   for (var i = 1; i < dataTable.Count; i++)
                       DataRow datarowObj = table.NewRow();
datarowObj["ItemID"] = resultTable.Table.Rows[i][(resultTable.Table.Columns["ListItemID"]).Ordinal];
                       datarowObj["Name"] =  resultTable.Table.Rows[i][(resultTable.Table.Columns["Path"]).Ordinal];
                       datarowObj["Recent"] = resultTable.Table.Rows[i][(resultTable.Table.Columns["ViewsRecent"]).Ordinal];
                       datarowObj["Views"] = resultTable.Table.Rows[i][(resultTable.Table.Columns["ViewsLifeTime"]).Ordinal];

No comments:

Post a Comment