Sunday, December 27, 2009

向SharePoint 延伸 Global.asax - Extending SharePoint using Global.asax

Have you ever wanted to do stuff with SharePoint sites that webparts just won't let you do? Here are a few things that I wanted to do in SharePoint that I knew I couldn't really do with WebParts or custom pages.

  • Better stats - the built-in stats are ok, but I want some better stats.
  • Register Users - I want everyone to have access to the site, but I would like to collect a little information about them before I give them access.

For this article I will just tackle the task of getting better stats about SharePoint usage, but you can easily apply the methods I use to do all kinds of things in your SharePoint application.

First off, you will need to do a little background reading on Global.asax (if you aren't already familiar with it). The Global.asax file allows you to write code against events that happen within an ASP.Net application. SharePoint is no different so you can write custom code and stick it in the Global.asax file and gain more control over your application.

Below is a quick and dirty solution for capturing information about how people are using your SharePoint site (or portal). Of course you can use the built in stats, however, I personally find those stats to be somewhat limited. The method below captures the URL the person went to, the timestamp of the request, and the UserID. What you can do is to add this code to a file called Global.asax and place it in the root directory of your site.

<%@ Application ClassName="Globals" language="c#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web" %>

Before you can use the script you will also need to create a table and a stored procedure to populate the table. Below is the SQL script to create both. You will need to put them in a custom database (I would not recommend putting them in one of the SharePoint databases).

create table [Hits]
(
Url varchar(256) NOT NULL,
UserID varchar(50) NOT NULL,
Timestamp datetime NOT NULL
)
go
create proc Hit_Add
(
@Url varchar(256),
@UserID varchar(50)
)
as
insert into Hits values
(@Url, @UserID, getdate())

go

That's all there is to it. The AuthenticateRequest Event gets fired each time the user makes a request to the site. You make the call to the database here because in the BeginRequest event the user hasn't been authenticated yet. I'm not sure but I believe this is different from normal ASP.Net applications due to the way SharePoint handles the request.

I'm sure you can think of many other ways that this will be useful. I'll be looking forward to your comments and suggestions.

No comments: