Feed Icon  


  • Bryant Likes
  • Send mail to the author(s) E-mail
  • twitter
  • View Bryant Likes's profile on LinkedIn
  • del.icio.us
Get Microsoft Silverlight
by clicking "Install Microsoft Silverlight" you accept the
Silverlight license agreement

Hosting By

Hot Topics


Open Source Projects



Extending SharePoint using Global.asax

Posted in SharePoint at Tuesday, 11 May 2004 11:03 Pacific Daylight Time

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" %>
<SCRIPT language="C#" runat="server">
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    using (SqlConnection cn = new SqlConnection("[Your Connection String]"))
       SqlCommand cmd = new SqlCommand();
       cmd.Connection = cn;
       cmd.CommandText = "Hit_Add";
       cmd.CommandType = CommandType.StoredProcedure;
       HttpContext ctx = HttpContext.Current;
       cmd.Parameters.Add("@Url", SqlDbType.VarChar, 256).Value = ctx.Request.Url.ToString();
       cmd.Parameters.Add("@UserID", SqlDbType.VarChar, 50).Value = ctx.User.Identity.Name;
  catch (SqlException)
 // Eat the exception so that the site is still usable
 // even if the stats go down from some reason.

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 
create proc Hit_Add
 @Url varchar(256),
 @UserID varchar(50)
 insert into Hits values
 (@Url, @UserID, getdate())

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.

Thursday, 13 May 2004 16:10:00 (Pacific Daylight Time, UTC-07:00)
i'm place youre cod to my Global.asax file, create the table and procedure, but i have the Server Error in '/' Application. Runtime Error
Friday, 14 May 2004 00:25:00 (Pacific Daylight Time, UTC-07:00)
Make sure that your connection string is correct. You cannot use integrated security so you will need to set a username/password. When you do this make sure that SQL Server is setup to use mixed authentication.
Sunday, 23 May 2004 13:56:00 (Pacific Daylight Time, UTC-07:00)
can you show me example of the connection string ?
Friday, 04 June 2004 01:44:00 (Pacific Daylight Time, UTC-07:00)
I did everything the way you described but none of the events in my global.asax get triggered. Is there anything else I should do to make SharePoint use this global.asax?
Tuesday, 08 June 2004 11:14:00 (Pacific Daylight Time, UTC-07:00)
Mario: What kind of security do you have on the site? Also, I would try commenting out the try/catch section so that you can see if you're missing the SQL error.
<br>Denis: Here is the format I'm using:
<br>DATABASE=[DB Name];SERVER=[Server];UID=[User Name];Password=[Password];
Wednesday, 18 August 2004 06:03:00 (Pacific Daylight Time, UTC-07:00)
Everything ok, adds all in the DB.
<br>Also cab (signed and ok) with stsadm installed. All successfully.
<br>When in SharePoint dragging the webpart to the page (after dragging and auto refresh of the page) nothing is there :-(
<br>Can you help me out?
Monday, 27 September 2004 03:20:00 (Pacific Daylight Time, UTC-07:00)
This is a perfect example of how NOT to implement a Sharepoint Statistics tracking piece. Why not use some OOP techniques and implement the IHttpModule interface to accomplish this task. The resulting module would leave the original SPS global file intact, while delivering a truly elegant solution.
<br>You are an IDIOT!!
Monday, 27 September 2004 06:44:00 (Pacific Daylight Time, UTC-07:00)
I fail to see what advantages you would gain from using an OOP technique. Leaving the global file intact was not one of my prime concerns, nor was an elegant solution. I simply wanted to enable some logging into a database (which I accomplished in about ten minutes).
<br>If this means I'm an idiot, oh well.
Tuesday, 28 September 2004 01:10:00 (Pacific Daylight Time, UTC-07:00)
<br>They give the MVP status away to anybody.
Monday, 18 October 2004 02:32:00 (Pacific Daylight Time, UTC-07:00)
But you can analyze log of iis and get same info ;)
<br>Without creating gloabal.asax, base and other.
Monday, 18 October 2004 06:09:00 (Pacific Daylight Time, UTC-07:00)
True, you could analyze the log to get the stats. You wouldn't be able to show who's online though, unless you analyzed the log quite often. You also run into issues if you have multiple sites and/or if you have multiple front-end sites sinc e you have to analyze multiple logs on multiple machines.
Monday, 06 March 2006 22:13:18 (Pacific Standard Time, UTC-08:00)
Just came across this post and it implemented perfectly, when remembering that a stored procedure needs to have execute permissions granted to the user provided in the db connection.

On a separate note, people that call other people idiots for working implementations usually tend to be the bigger idiot. I'm pretty sure I, and probably every other developer out there, has worked with (at one time or another) the person who put that post up. Rude * 100.
Wednesday, 26 April 2006 02:30:40 (Pacific Daylight Time, UTC-07:00)
i agree with the other Ryan, it is very rude to call others idiots, especially if they are trying to benefit others, however i have a problem in sharepoint i need solving, is there a way to know the number of times a document in a document library has been opened (with/without modification, i.e used) by a specific person in an interval of time? if would prefer someone would could give hints about it without going to third party programs, i.e using sharepoint sdk if possible (i have already tried with event handlers but no luck ) :(
Any ideas?
Thursday, 18 May 2006 04:54:21 (Pacific Daylight Time, UTC-07:00)
could any of you help me? i don't know where i can find the global.asax of my site....
Friday, 19 May 2006 03:03:35 (Pacific Daylight Time, UTC-07:00)
You need to create one.
Tuesday, 24 October 2006 10:15:57 (Pacific Daylight Time, UTC-07:00)
Good post. I was looking around to see if you could run scripts in the Global.asax file in Sharepoint (since it's disabled in the ASPX pages).. guess this answered my question! ;)
Wednesday, 25 April 2007 20:26:52 (Pacific Daylight Time, UTC-07:00)
You have given a very good example of who's online web part Bryant..
Joydeep Banerjee
Wednesday, 23 May 2007 21:24:14 (Pacific Daylight Time, UTC-07:00)
How do i delete the users when they log out or close the browser? Can anybody help?

Thanks in advance
Joydeep banerjee
Monday, 06 August 2007 07:22:43 (Pacific Daylight Time, UTC-07:00)
Aside from using Application_AuthenticateRequest, is there another function or function that I can use so that it only triggers once per page. I am getting a lot of hits per page (i.e. .jpg's, .css's, etc.). I would prefer a single log entry per page per user.

Thanks a lot,
Kevin C
Wednesday, 16 January 2008 08:21:08 (Pacific Standard Time, UTC-08:00)
Hi I have implemented this on a sharepoint intranet/extranet (without webapart - data collection only at this stage). Works fine until i try to reload the extranet view. The site will not load and shows "An unexpected error has occurred. " I'm guessing this has something to do with the domain\user specified in the stored procedure? - as the extranet is forms authentication only. Any ideas would be appreciated.
Friday, 15 February 2008 04:41:18 (Pacific Standard Time, UTC-08:00)
I can not seem to get the connection to the Db to work. I setup the tables and stored prcedure and put the changes in to the global.asax file. But nothing gets put in to the DB. I have verified my sql connection string is correct. Is there anything special I have to do for SQL Express 2005. I am using Windows SharePoint services 3, and have applied all the patches.

Thanks in Advance
Friday, 29 February 2008 00:12:45 (Pacific Standard Time, UTC-08:00)
I had one heck of a time making the connection string work. So I am posting what I did here to hopefully help someone else. I admit I am new to this and still learning.
First if you use SQL2005 Express, remember it comes totally locked down. There instructions all over web about unlocking it.
Here is the connection string format I used:
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;User
ID=MyUsername;Password=MyPassword;Initial Catalog=Test;Integrated
Security=False;User Instance=False");
I really hope this helps someone.

Keith Davis
Tuesday, 29 April 2008 07:04:06 (Pacific Daylight Time, UTC-07:00)
Does anyone know if it is possible to accomplish this using a list/table on the sharepoint site?
Thanks for the post.
Wednesday, 11 June 2008 19:15:43 (Pacific Daylight Time, UTC-07:00)

I tried ur code, but I got the runtime error. P.S I have a correct Sql string.

Monday, 18 August 2008 17:02:55 (Pacific Daylight Time, UTC-07:00)
How do i delete the users when they log out or close the browser? Can anybody help?

Thanks in advance
satish (bflsrc@yahoo.com)
Saturday, 27 September 2008 02:38:16 (Pacific Daylight Time, UTC-07:00)
Be very careful doing this. Sharepoint (WSS 3.0 / MOSS 2007) overrides the Global.asax file to inherit from Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication rather than System.Web.HttpApplication.

If you use code behind (or code in the markup) you should make sure to perserve that inheritance. For example, the top of your markup should look like:

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" Language="C#" %>

or (if using code behind)

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Codebehind="Global.asax.cs" Inherits="MyAppName.Global" Language="C#" %>

if your using code behind, your class should be declared like:

public class Global : Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication {

//Code goes here


Friday, 27 February 2009 16:48:35 (Pacific Standard Time, UTC-08:00)
Thanks for your great solution,I implement this Code and now,every things are OK,But my problem is that I have a web application in Form Based Authenticatinon and an extended web application in Windows based.I just see the form based users,what can I do to view all users?
Comments are closed.