Custom SharePoint Page Counter
Posted by PANVEGA on September 7, 2009
In this post I show you how easy it is to develope a custom Page Counter Webpart in Visual Studio.
In one of my older post I explaid how to add Counter Web Component to your page by using the SP Designer. However this approach has some disadvantages.
http://panvega.wordpress.com/2009/06/22/how-to-add-a-hit-counter-to-a-page
Steps to do:
- Create a new Custom Field for instance PageCounter
- Add this custom field to your Page ContentTypes by using a FeatureReceiver Class
- Create a Webpart project
- Access the Pages List and parse all pages.
- increment the custom PageCounter filed
- Incremt just in Publish Level Mode
- do a item and list update
here is a code example from a custom webpart:
using (SPWeb web = site.OpenWeb())
{
string url = Page.Request.Url.ToString();
if (url.Contains(“Pages”))
{
string tmp = web.Url + “/Pages”;
SPList list = web.GetList(tmp);
web.AllowUnsafeUpdates = true;
SPListItem item = (SPListItem)web.GetObject(url);
//do not count when in design modus
if (item.Level == SPFileLevel.Checkout || item.Level == SPFileLevel.Draft)
{
counterlabel.CssClass = “WPCounter”;
counterlabel.Text = “<p>No Counter to show in this Webpart. Please publish Page for counting.<p>”;
}
else
{
if (!item.Fields.ContainsField(“ows_PageCounter”))
{
counterlabel.CssClass = “WPCounter”;
counterlabel.Text = “<p>Counter field does not exist. Please ensure that the feature ‘Page Counter for Page Templates’ is activated.<p>”;
}
if (item["ows_PageCounter"] == null)
{
item["ows_PageCounter"] = (double)0;
item.SystemUpdate(false);
list.Update();
counterlabel.Text = “Page Visits: 0″;
}
else
{
double field = (double)item["ows_PageCounter"];
field = field + 1;
item["ows_PageCounter"] = field;
item.SystemUpdate(false);
list.Update();
counterlabel.Text = “Page Visits: ” + field.ToString();
}
counterlabel.CssClass = “WPCounter”;
counterlabel.Visible = true;
}
this.Controls.Add(counterlabel);
}
}
create a custom field in your solution using column.xml file
<?xml version=”1.0″ encoding=”utf-8″ ?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/” >
<Field ID=”{xxxxxxxxxxxxxxxxxxxxxxxxxx}”
Name=”PageCounter”
StaticName=”PageCounter”
SourceID=”http://schemas.microsoft.com/sharepoint/v3″
Group=”Columns”
DisplayName=”Page Counter”
Type=”Number”
Format=”FALSE”
Required=”TRUE”
Sealed=”TRUE”
Min=”0″
Decimals=”0″>
<Default>0</Default>
</Field>
</Elements>
That´s it.