Bryant Likes's Blog

It's all about WebData

Recent Posts

Tags

News


  • Windows Live Alerts
    View Bryant Likes's profile on LinkedIn

    Me

    The posts on this weblog are provided "as is" with no warranties and confer no rights. The opinions expressed herin are the personal opinions of the individual authors and do not represent the views of Avanade in any way.

Community

Email Notifications

Archives

Extending SharePoint using Global.asax - Who's Online

In my last article on this subject I explained how to add some basic page tracking to SharePoint. In this article I will expand on this by adding a Who's Online WebPart. This WebPart will show who is currently online.

First we need to create the ActiveUsers table which will keep track of the users that are currently online. We also need to modify the Hit_Add stored procedure to update the ActiveUsers table. Finally, we need to create a very simple stored procedure to get the list of users that are currently online. Below is the SQL script for these tasks.

create table ActiveUsers (
 UserID varchar(50) not null,
 LastHit datetime not null,
 LastUrl varchar(256) not null,
 constraint PK_ActiveSessions primary key clustered
 (
  UserID
 )
)
go
alter proc Hit_Add
(
 @Url varchar(256),
 @UserID varchar(50)
)
as
 -- this needs to be changed to the userID
 -- that your site runs as
 if (@UserID = 'DOMAIN\PROCESSID') return
 insert into Hits values
 (@Url, @UserID, getdate())
 delete ActiveUsers
 where UserID = @UserID
  or datediff(mi, LastHit, getdate()) > 30 -- minutes
 insert into ActiveUsers values
 (@UserID, getdate(), @Url)
go
create proc ActiveUsers_Get
as
 select UserID, LastHit, LastUrl, datediff(mi, LastHit, getdate()) Age
 from ActiveUsers

go

That is all there is to tracking the users that are currently online. You can adjust the time by changing the minutes in the delete statement. Next we need to create our WebPart. The WebPart I'm going to show you is somewhat simple and just displays a list of users. You can easily add more functionality to it if you want. Below is the code for the Who's Online WebPart.

using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace Bml.Stats.WebParts
{
 /// 
 /// Description for ActiveUsers.
 /// 
 [ToolboxData("<{0}:ActiveUsers runat=server>"),
  XmlRoot(Namespace="SPSStats")]
 public class ActiveUsers : Microsoft.SharePoint.WebPartPages.WebPart
 {
  
  protected override void RenderWebPart(HtmlTextWriter output)
  {
   output.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
   output.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
   output.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
   output.RenderBeginTag(HtmlTextWriterTag.Table);
   output.RenderBeginTag(HtmlTextWriterTag.Tr);
   output.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
   output.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
   output.RenderBeginTag(HtmlTextWriterTag.Td);
   output.AddAttribute(HtmlTextWriterAttribute.Class, "ms-ls");
   output.RenderBeginTag(HtmlTextWriterTag.Table);
   AddUserRows(output);
   output.RenderEndTag(); // table
   output.RenderEndTag(); // td
   output.RenderEndTag(); // tr
   output.RenderEndTag(); // table
  }
  
  private void AddUserRows(HtmlTextWriter output)
  {
   try
   {
    SPWeb web = SPControl.GetContextWeb(Context);
    using (SqlConnection cn = new SqlConnection("[Your Connection]"))
    {
     cn.Open();
   
     SqlCommand cmd = new SqlCommand();
     cmd.Connection = cn;
     cmd.CommandText = "ActiveUsers_Get";
     cmd.CommandType = CommandType.StoredProcedure;
     
     SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
     while (dr.Read())
     {
      string userName = (string)dr["UserID"];
      
      output.RenderBeginTag(HtmlTextWriterTag.Tr);
      output.AddAttribute(HtmlTextWriterAttribute.Class, "ms-lsmin ms-vb");
      output.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
      output.RenderBeginTag(HtmlTextWriterTag.Td);
      output.AddAttribute(HtmlTextWriterAttribute.Align, "absbottom");
      output.AddAttribute(HtmlTextWriterAttribute.Src, "/_layouts/images/perusr.gif");
      output.RenderBeginTag(HtmlTextWriterTag.Img);
      output.RenderEndTag(); // img
      output.Write(" {0}", SPUtility.GetFullNameFromLogin(web.Site, userName));
      output.RenderEndTag(); // td
      output.RenderEndTag(); // tr
     }
     
     dr.Close();
     cn.Close();
    }
   }
   catch (Exception exc)
   {
    output.Write(exc.Message);
   }
  }
 }
}

Once you've compiled the WebPart and added it to the server you will need to make one change to your web.config file before the part will work. You will need to change the trust level from WSS_Minimal to WSS_Medium. This will allow the part to use the SQL Connection which isn't allowed in the minimal trust scheme. After you add it to a page you should see something very much like the following image.

As I wrote this WebPart I thought of a lot of other uses for the hits data such as a Favorites list (based on urls with the most hits), recently viewed pages, and others. There seems to be a lot you can do once you start collecting this data.

Comments

TrackBack said:

# May 13, 2004 2:31 PM

TrackBack said:

# July 7, 2004 3:01 AM

TrackBack said:

# July 7, 2004 3:03 AM

bryantlikes said:

Thank you, in advance, and I know this is not necessarily the appropriate place for this question, but can you point me to a chat room that would tell me how to set up Visual Basic 6.0 so it sees objects on my SharePoint server?

Thanks,

Ken
kstephan@csc.com
# July 7, 2004 12:31 PM

bryantlikes said:

When I do this, I get the following error message:

Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection

Any idea?
# July 21, 2004 10:38 AM

bryantlikes said:

You can't use a trusted connection to connect to the database. So you need to change your connection string to something like this:

http://blogs.sqlxml.org/bryantlikes/articles/583.aspx#675
# July 21, 2004 11:24 AM

bryantlikes said:

I've tried changing my connect string. I have searched far and wide through the net for the answer to this.

My connectstring is this:
strConn = "Server=MySERVER;Database=MYDEV;integrated security=SSPI";

SqlConnection cn = new SqlConnection(strConn);

cn.Open();

I have also tried:
strConn = "server=MYSERVER;Trusted_Connection=True;Database=MYDEV;uid=me;password=********"

Neither of them work. they both work from a standard winform.
# July 22, 2004 12:04 PM

bryantlikes said:

You can't use "Trusted_Connection=true". See the example connection string that I posted here:

http://blogs.sqlxml.org/bryantlikes/articles/583.aspx#675
# July 26, 2004 7:24 AM

bryantlikes said:

Why can't you use Trusted Connection?
# August 3, 2004 8:17 AM

bryantlikes said:

Yes!? Why can't we use Trusted Connection? My company's administrator is allways boring me with this issue...
# August 3, 2004 9:41 AM

bryantlikes said:

You can't use it here unless the user id that executes the global.asax has access to the database.
# August 9, 2004 12:36 PM

bryantlikes said:

If the Account that your App Pool is configured to run under (in W2k3) can access the SQL Server then you can use Trusted_Connection=true.. otherwise, you will have to specify the userid and password in the connection string without the trusted_connection part.
# October 5, 2004 9:19 AM

TrackBack said:

Found these on a SharePoint blog.&nbsp; There appears to be lots of useful web parts here as well as...
# August 17, 2005 8:08 AM

TrackBack said:

SharePoint Web Parts (free)

ActiveX Scripting Web Part (Simon Mourier)
Alert Manager, Subweb Viewer...
# October 14, 2005 3:13 PM

bryantlikes said:

When I upload the .dwp file and add it to a page I get the control is not registered as safe error
# December 18, 2005 7:26 AM

TrackBack said:

# January 27, 2006 2:28 PM

TrackBack said:

# February 14, 2006 2:01 AM

TrackBack said:

# February 14, 2006 2:04 AM

Luis Du Solier G said:

Really nice one!
# April 20, 2006 1:25 PM

wssproject said:

I'd like to know where i need to create the global.asax
and also where i create table??
# May 30, 2006 1:00 AM

Niranjan Ameta said:

that is Pretty one
# August 4, 2006 4:30 AM

Levan Kiladze said:

Hello,

Excuse me, I think here is small error:

insert into Hits values..

Perhaps, there should be insert into ActiveUsers values...

# October 23, 2006 12:36 AM

John said:

You can use a trusted connection in WebParts _if_ you implement impersonation.  NTLM v2 will hand off your credentials to Sharepoint, but NTLM will then not hand off your credentials to SQL.  I had this problem because SQL Server Analysis Services 2005 requires a trusted connection.  The two solutions are to 1.)  Use Basic authentication which will pass off your credentials again.  Unless you're running a secure site this probably isn't a great option.  The other is to impersonate via code instead of the web.config a proxy Active Directory user that has access to the account for the sections that access the database.  This will allow you to establish the connection.  Here's a link that explains more:

http://blakepell.spaces.live.com/blog/cns!808E32F75B9CF425!117.entry

# October 24, 2006 5:27 PM

John said:

Well, the link got cut off, copy and paste it. ;)
# October 24, 2006 5:28 PM

Cam said:

Can someone post a link to a compiled version?

# November 17, 2006 9:16 AM

Joydeep Banerjee said:

How does the ActiveUser table gets populated?

# April 26, 2007 1:33 AM

Josh Dunigan said:

Is there a compiled version already available for download?  Please email me at josh.dunigan@thetravelauthority.com if so.  Thanks.

# June 27, 2007 9:21 AM

jtrober said:

I am a bit new at sharepoint in general, so couple questions. I have a SBS 2003 server, I have sharepoing 2007 installed along side the 2003 site.

How would i go about creating that table? and What do I need to compile the web part?

Is there a compiled version out there I can download? Please email me if there is, jtrober@hotmail.com

# April 1, 2008 6:40 AM

Gaurav Saxena said:

When iam using this code, iam not getting anything(data value) in webpart. The webpart just displays the title and rest is just blank.

I have used SQL Authentication, and just changed the namespace and class name to 'WhoIsOnline'. Rest everything is same.

Any clue why this webpart is blank...:(

# May 5, 2008 9:47 PM

Gaurav Saxena said:

How to integrate communicator functionality with this application.

# May 12, 2008 9:17 PM

TheSniper said:

plss...is there a compiled version of this!

really want this "WhosOnline" on our Sharepoint site, with the Chat box already on it.

if there is, pls email the compiled version to:

dasniperz at gmail dot com

thanks!

# July 29, 2008 10:32 AM

Propecia. said:

Side effects from taking propecia. Propecia. Propecia generic. Buy propecia. Fertility restored after ending propecia.

# July 30, 2008 6:37 AM

buy clomid said:

<a href=" www.nola.com/.../profile.ssf "> buy clomid<a/>

# August 20, 2008 4:35 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)