Count this page Hits


Hi,

Sometimes we require some webpart to calculate the number of hits on a particular page. I am sharing a Hit counter webpart which will count the number of hits on any page if added to any particular page.

Following are the steps to create this Webpart:

Step1: Create a SharePoint 2010 solution using default basic template.

Step2: Add a Simple webpart named “Hit Counter” to the project. The webpart class will contains following code:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace HitCounterWebPart.HitCounterWebPart
{
[ToolboxItemAttribute(false)]
public class HitCounterWebPart : WebPart
{
string cLoginName = string.Empty;
string cDate = string.Empty;
string cURL = string.Empty;
SPList myList;
private const string listName = "HitsList";
private const string fieldUrl = "Url";
private const string fieldDate = "Date";
private const string fieldUser = "UserName";
protected override void Render(HtmlTextWriter writer)
{
SPWeb myWeb = SPContext.Current.Web;
string cMonth = DateTime.Today.Month.ToString();
string cDay = DateTime.Today.Day.ToString();
string cYear = DateTime.Today.Year.ToString();
cLoginName = myWeb.CurrentUser.LoginName;
cDate = cMonth + "/" + cDay + "/" + cYear;
cURL = HttpContext.Current.Request.Url.AbsoluteUri;
if (cLoginName != "" && cDate != "" && cURL != "")
{
myList = myWeb.Lists[listName];
SPQuery myQuery = new SPQuery();
myQuery.Query = " <OrderBy>" +
"<FieldRef Name='ID' />" +
"<FieldRef Name=" + fieldUrl + " />" +
"<FieldRef Name=" + fieldUser + " />" +
"<FieldRef Name=" + fieldDate + " /></OrderBy><Where><And><And><Eq>" +
"<FieldRef Name=" + fieldUrl + " />" +
"<Value Type='Note'>" + cURL + "</Value></Eq>" +
"<Eq><FieldRef Name=" + fieldUser + " />" +
"<Value Type='Text'>" + cLoginName + "</Value></Eq></And>" +
"<Eq><FieldRef Name=" + fieldDate + " /><Value Type='Text'>" + cDate + "</Value>" +
"</Eq></And></Where>";
SPListItemCollection myItemcol = myList.GetItems(myQuery);
if (myItemcol.Count > 0)
{
writer.Write(myList.ItemCount.ToString());
return;
}
else
{
SPListItem myItem = myList.Items.Add();
myItem[fieldUrl] = cURL;
myItem[fieldDate] = cDate;
myItem[fieldUser] = cLoginName;
myWeb.AllowUnsafeUpdates = true;
myItem.Update();
myWeb.AllowUnsafeUpdates = false;
writer.Write(myList.ItemCount.ToString());
}
}
}
}
}

Step3: Create a feature event reciever. paste the code below:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace HitCounterWebPart.HitCounterWebPart
{
[ToolboxItemAttribute(false)]
public class HitCounterWebPart : WebPart
{
string cLoginName = string.Empty;
string cDate = string.Empty;
string cURL = string.Empty;
SPList myList;
private const string listName = "HitsList";
private const string fieldUrl = "Url";
private const string fieldDate = "Date";
private const string fieldUser = "UserName";
protected override void Render(HtmlTextWriter writer)
{
SPWeb myWeb = SPContext.Current.Web;
string cMonth = DateTime.Today.Month.ToString();
string cDay = DateTime.Today.Day.ToString();
string cYear = DateTime.Today.Year.ToString();
cLoginName = myWeb.CurrentUser.LoginName;
cDate = cMonth + "/" + cDay + "/" + cYear;
cURL = HttpContext.Current.Request.Url.AbsoluteUri;
if (cLoginName != "" && cDate != "" && cURL != "")
{
myList = myWeb.Lists[listName];
SPQuery myQuery = new SPQuery();
myQuery.Query = " " +
"" +
"" +
"" +
"" +
"" +
"" + cURL + "" +
"" +
"" + cLoginName + "" +
"" + cDate + "" +
"";
SPListItemCollection myItemcol = myList.GetItems(myQuery);
if (myItemcol.Count > 0)
{
writer.Write(myList.ItemCount.ToString());
return;
}
else
{
SPListItem myItem = myList.Items.Add();
myItem[fieldUrl] = cURL;
myItem[fieldDate] = cDate;
myItem[fieldUser] = cLoginName;
myWeb.AllowUnsafeUpdates = true;
myItem.Update();
myWeb.AllowUnsafeUpdates = false;
writer.Write(myList.ItemCount.ToString());
}
}
}
}
}

This will create a new list will be used to store the URL and their hitcounts. These are only the code files required to create the webpart. Now solution is ready for deployment.

After successfully deployment of this solution, add the hit counter web part to the page.

Thanks for time…

Advertisements

Powershell: Creating and updating profile property


Hi Friends,

I have recently create a user profile property using power shell commands. I am just sharing the code i used to create and then edit the properties like description, privacy settings, display settings etc of the property.

Code to add/edit:

if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin Microsoft.SharePoint.PowerShell
}


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("microsoft.sharepoint.portal")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("System.Web")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy.dll")
function CheckNull($obj, $name)
{
if ($obj -eq $null)
{
Write-Host $name "is null" -ForegroundColor Red
return $true
}
return $false
}
$siteurl = "http://sp2010server/"
$site = Get-SPSite -Identity $siteurl -ErrorAction Stop
$ctx = [Microsoft.Office.Server.ServerContext]::GetContext($site)
$upm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ctx)
$upcm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($ctx)
$comProp = $upm.Properties.Create($false)
$comProp.Name = "Company"
$comProp.DisplayName = "Company"
$comProp.Type = [Microsoft.Office.Server.UserProfiles.PropertyDataType]::StringSingleValue
$comProp.Length = 50
$comProp.PrivacyPolicy = [Microsoft.Office.Server.UserProfiles.PrivacyPolicy]::OptIn;
$comProp.DefaultPrivacy = [Microsoft.Office.Server.UserProfiles.Privacy]::Public;
$comProp.IsVisibleOnViewer = $true;
$upm.Properties.Add($comProp)

I want to share some of the basic properties which you can edit while updating the property using Power shell.

  • [string] $displayname : used if we want to change the display name under Property Settings.
  • [int] $length: used to edit “Length” of the property value again under Property Settings.
  • [string] $description: used to edit “Description” of the property value again under User Description.
  • PrivacyPolicy: used to edit “Policy Settings” of the property value under Policy Settings.
  • DefaultPrivacy: used to edit “Default Policy Settings”of the property value again under Policy Settings.
  • [bool] $userOverridePrivacy: used to edit “User can override” of the property value again under Policy Settings.
  • [bool] $isReplicable: used to edit “Replicable” of the property value again under Policy Settings.
  • [bool] $isUserEditable: used to edit “Edit Settings” of the property
  • [bool] $IsMultivalued: used to edit “Description” of the property value again under User Description.
  • [bool] $isColleagueEventLog: used to edit “Show updates to the property in newsfeed” of the property value again under User Description.
  • [bool] $isAlias: used to edit “Alias” of the property value under Search Settings.
  • [bool] $isSearchable: used to edit “Indexed” of the property value again under Search Settings.
  • [bool] $isVisibleOnEditor: used to edit “Show on the Editor Details Page” of the property value under Show Settings.
  • [bool] $isVisibleOnViewer: used to edit “Show in the profile properties section of the user’s profile page” of the property value again under Show Settings.
  • [int] $maximumShown: used to edit “Show updates to the property in newsfeed” of the property value again under Show Settings.

Hope this information will be helpful.

Thanks for Time 🙂

Building Customer Service Applications


Building Customer Service Applications

The purpose of this sample code is to provide the reader with an insight into how SharePoint 2010 Service Applications can be used to create truly distributed scalable architecture. The sample code acts as a framework for developers who want to start creating SharePoint Service Applications without worrying about the underlying plumbing required to create such applications.

The sample code demonstrates how service application can be used to create a service orientated application (SOA) within the realm of SharePoint 2010’s infrastructure. The sample provides a framework which can be used to create such applications without writing an extensive amount of boiler plate code.

The example code provided, allows system administrators to capture auditing events from a particular site collection. The custom timer job is responsible for writing the audit events from the site collections to the provisioned database.

A consumer (Web Part) is used to retrieve information from the provisioned database via the Service Application Proxies.

Step1: Create Visual Studio Solution

In Visual Studio 2010, create a new project using the “Empty SharePoint Project” and call it “ServiceApplication”.

You will be asked for the SharePoint site address for debugging. Since we are deploying this to the central administration site, enter the URL of Central Administration site and check the “Deploy as a farm solution” radio button. Click “Finish” to continue.

Step 2: Create Basic WCF application

We will change the assembly name and default namespace to “ServiceApplication”. Right click the “ServiceApplication” and select “Properties”. Under the “Application” tab, change both the “Assembly name” and “Default namespace” to “ServiceApplication”. Save the settings.

Add a reference to the following assembly:

  • System.ServiceModel
  • Microsoft.SharePoint
  • Microsoft.Office.Server
  • Microsoft.SharePoint.ApplicationPages.Administration(C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14CONFIGADMINBINMicrosoft.SharePoint.ApplicationPages.Administration.dll)
  • Microsoft.SharePoint.Security
  • System.Data.DataSetExtentions
Create WCF Contract and Service Host Declaration

We start this by adding a mapped folder to the WebServices folder in {SharePointRoot}. To do this, right click the ServiceApplication > Add > SharePoint Mapped Folder…, then select the “WebServices” folder and click “OK”. A new WebService folder “ServiceApplication” will be added to the project.

Let’s add a contract file that has a single signature “Service”. Right click the Project and add a new item. Select the “WCF Service” project template and give it a name called Service.

Open IService.cs and declare a signature “Service”. Replace all the code with “IService_cs” file code.

Next we will add a service host declaration. Add a text file type in the WebServicesServiceApplication folder and rename it to “ServiceApplication_svc”. Click the link to get the code and paste it to the newly added file.

Note that you need to enter your own public key token.

We will add a configuration file to our WCF service that contains the information such as the behaviour. Right click WebServicesServiceApplication folder again and this time we will add an application configuration file called “web_config”.

Delete Service.cs as we don’t need it. Also delete the app.config added to the base project.

We have successfully completed a simple WCF service that is ready to deploy to a SharePoint farm.

Step 3: Create service application framework

Next we will create a number of classes for the service application. Each of these classes represents a key component for a service application, such as:

  • Service
  • Service Proxy
  • Service Application
  • Service Application Proxy
  • Service Instance
  • Service Factory
  • Service DataBase

Service: Next create a new class called “WebService_cs“.

Service Proxy:Next create a new class called “WebServiceProxy_cs”. Note that it has a SupportedServiceApplication decorative and it is referencing the WebServiceApplicationProxy by its Guid.

Service Application : Next create a new class called “WebServiceApplication_cs“. This class will implements IService and contains the actual implementation of our functional methods.

Service Application Proxy: Next create a new class called “WebServiceApplicationProxy_cs“.

Service Instance: Create a new class in the root folder of the project and call it “ServiceInstance_cs”.

Service Factory: Next create a “ServiceFactory_cs” class

Service Database: Next we create a custom database class “WebServiceDatabase_cs” which inherits SPDataBase class.

Once database class has been created next is to create some basic entity classes which interact with the database to update and retrieve data. First we will create a folder to the “Entities” folder and this is the folder where the database entity classes will deploy. To do this, right click the ServiceApplication > Add > New Folder…, then rename that folder to “Entities” folder. Now add a class “ListEntries_cs“.

Another Entity Class “AuditEntries_cs

Few helper classes are required to implement the logic. To add new classes creat a new folder at root project with name “Helpers”. Add two classes “Common_cs” and “Database_cs”.

Now in order to create a custom database we require custom script file which contains SQL command to create and configure database. Create a mapped folder “SQL” it must be mapped to ..14TEMPLATESQL. Create a new folder called “Service Application”. Now create a sql script with name “ServiceApplication_sql”.

Next is to create a timer job in order to get the initial data. Create a new folder called “Timer” and add a new class called “GatherEvents_cs

Next we need to define the client configuration file. Map a another folder “WebClients” which directly resides under 14 hive. Create a new project folder and add a new application configuration file and renamed it to “client_config”.

And we have completed our custom service application implementation. But we are not there yet. We will need to create administration pages for service creation and management. And we also need to register the service application to the farm so that we can create an instance of it. More to come next:

We will need to create two administration pages for our service application. One will be used for service application instance creation, and the other one for managing existing application instance. As a reference we will use the pages for Excel Service, which can be located in the ADMIN folder (C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATEADMIN).

First we will create a mapped folder to the ADMIN folder and this is the folder where the administration pages will deploy. To do this, right click the ServiceApplication > Add > SharePoint Mapped Folder…, then expand the “TEMPLATE” node and select the “ADMIN” folder. A new ADMIN folder “ServiceApplication” will be added to the project.

We will first create the service creation page. Right click the newly created “ServiceApplication” folder under “ADMIN” and add a new item. Select the “Application Page” template and give the page a name “Create_aspx”.

I am using Visual Studio 2010 Beta 2 and notice a funny thing. VS2010 will create the Create.aspx in “Layouts/ServiceAplication”. If you have this problem, just drag the aspx file to ADMINServiceApplication, as this is the location where we referencing in out Service Application implementation (Service.cs).

Replace the code behind file with “Create_aspx_aspx_cs

Now Create new aspx page with name “CustomizeAuditSettings_aspx” and place following code in it:

Now next we have to create a new aspx page “AuditSettings_aspx”.

Replace the code behind file with “AuditSettings_aspx_cs”

The project structure will looks like :

Step 4: Creating consumer webpart for the application

Create a new sharepoint project named “ServiceApplicationConsumer”. Add a new visual webpart to the project.

The ascx file should looks like “VisualWebPart1UserControl_ascx”

Code behind for the webpart should contains code as given in “VisualWebPart1UserControl_ascx_cs” file.

This finishes the implementation part of the service application. This is very basic service application which just retrives sharepoint webapplication list and save them to the database.

Step 5: Deployment

Install the solution/s on a SharePoint server:

  • ServiceApplication.wsp  – Farm Feature (Various Service Application Components)
  • ServiceApplicationConsumer.wsp – Site Feature (Web Part Consumer)

Navigate to Central Admin (CA) –> System Settings –> Manage Farm Solutions.

Start the newly create instance by navigating to CA –> System Settings –> Manage Services on Server

Navigate to CA –> Manage Service Applications and create a new instance of the sample Service Application ‘Service Application’

Enter the relevant information required to create the Service Application

This will create a new instance of the Service Application

Clicking on the newly create Service Application will open the following, the page enables system administrators to configure which events from which site collection are written into the newly provisioned database

Clicking on the URL (highlighted above) will open the following dialog which can be used to configure the audit settings for that particular site collection

Ensure that the Service Application Gather timer instance is running, after generating events within the site collection. Run the timer instance, this will persist the event data within the provisioned database

Navigate to a Site collection that you have configured to capture the audit logs from. Edit the page and add the ‘Service Application Consumer’ web part to the page. Save the page.

The audit logs are displayed in the following grid format

Service Instance:

Microsoft.SharePoint.ApplicationPages.dll


Hi,

I was exploring some SP stuff related to the application pages, I need to refer applicatio pages dll and oops its not there in ISAPI. After exploring I wondered its located at:

C:\Inetpub\wwwroot\wss\VirtualDirectories\<Your Virtual Server >\_app_bin\Microsoft.SharePoint.ApplicationPages.dll

Here is the full list of assemblies at _app_bin folder:

  1. Microsoft.Office.DocumentManagement.Pages.dll
  2. Microsoft.Office.officialfileSoap.dll
  3. Microsoft.Office.Policy.Pages.dll
  4. Microsoft.Office.SlideLibrarySoap.dll
  5. Microsoft.Office.Workflow.Pages.dll
  6. Microsoft.Office.WorkflowSoap.dll
  7. Microsoft.SharePoint.ApplicationPages.dll
  8. STSSOAP.DLL

Why SP is always so tough!!!!

Haapy Sharepointing 🙂