Tuesday, March 7, 2017

How to measure a time spent on a page ?

I have to assign a task in which I have to calculate  how much time he/she spend on page.
For example we have multiples pages and we have menu too that is assign  unique Ids that bind from our menu table.
So what first thing in my mind is come every time when i click the menu  it will go the Default.Master page on Page_Load method.
So what I did i make a simple function that call on Page_Load method and the function is just pass the login user name, page name ,Current time and IP that it :) rest of the thing i handle in SQL .
So my table structure is like .

CREATE TABLE [dbo].[log](
[id] [int] IDENTITY(1,1) NOT NULL,
[user_name] [varchar](100) NOT NULL,
[page_name] [varchar](500) NOT NULL,
[currenttime] [datetime] NULL,
[spendtime] [int] NULL,
[page_id] [int] NULL,
[parameter] [varchar](5000) NULL,
[ip] [varchar](100) NULL
) ON [PRIMARY]

@parameter is secret ;) i will tell you in next post that how to get all the user selected drop downs and text boxes values.

Ok when I make a function that will call this Store Procedure .

CREATE PROCEDURE [dbo].[sp_name]          
@user_name varchar(100),          
@page_name varchar(500),          
@currenttime DATETIME,        
@ip varchar(100),      
@parameter varchar(5000),  
@is_download int        
AS          
         
 declare @page_id int    
   SELECT   @page_id=page_id from page where page_name = '' + @page_name + ''  ;  
  BEGIN        
 
   INSERT INTO log          
     ( user_name ,page_name ,currenttime,ip,parameter,page_id)          
   VALUES  ( @user_name ,@page_name ,@currenttime,@ip,@parameter,@page_id)                
   END

   the magic is here :) I made a trigger that will calculate the time for that specific user

 CREATE TRIGGER [dbo].[LogOnInsert]
ON [dbo].[log]
FOR INSERT
AS

declare @InsertedUser as nvarchar(50)
declare @InsertedTime as datetime
declare @PreviousID as int
declare @PreviousTime as datetime
declare @ip as varchar(100)


select @inserteduser = i.user_name, @insertedTime = i.currenttime,@ip=i.ip
from Inserted i

SELECT @previousid = id, @previoustime = currenttime FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY ID desc) AS rownumber,
    id, currenttime
  FROM log
where user_name = @inserteduser and ip=@ip
) AS foo
WHERE rownumber = 2
declare @timediff as int
set @timediff = DATEDIFF(SECOND, CONVERT(DATETIME, CONVERT(VARCHAR, @PreviousTime, 120)), CONVERT(DATETIME, CONVERT(VARCHAR, @InsertedTime, 120)))

update log
set spendtime = @timediff -- value in second
where id = @PreviousID


and this is function that i used to get the user IP

private string GetUserIP()
{
string ipList = Request.ServerVariables("HTTP_X_FORWARDED_FOR");

if (!string.IsNullOrEmpty(ipList)) {
return ipList.Split(',')(0);
}

return Request.ServerVariables("REMOTE_ADDR");
}


No comments:

Post a Comment