Monday, November 28, 2022

Hit Counter in ASP.NET C#

   protected void Page_Load(object sender, EventArgs e)

        {

            // Insert Hits

            try

            {

                if (Session["UserID"].ToString() == "")

                {

                    new UserLogs().HitsCounter(Session["UserID"].ToString(), "Hit");

                }

            }

            catch

            {

                new UserLogs().HitsCounter("0", "Anonymous Hit");

            }


        }


-----------------------------


  public void HitsCounter(string UserID, string Operation)

        {

            try

            {

                SqlParameter[] param = new SqlParameter[5]

                {

                    new SqlParameter("UserID", UserID),

                    new SqlParameter("IP", HttpContext.Current.Request.UserHostAddress.ToString()),

                    new SqlParameter("PageName", HttpContext.Current.Request.Url.ToString()),

                    new SqlParameter("RefererPage", RefererUrl()),

                    new SqlParameter("Operation", Operation)

                };

                new DataAccess().Write("InsertHits", param);

            }

            catch

            {

            }



-------------------


ALTER proc [dbo].[InsertHits]

@UserID bigint,

@IP varchar(130),

@PageName varchar(800),

@RefererPage varchar(800),

@Operation varchar(800)

as

begin

insert into HitssCounter(UserID,IP,PageName,RefererPage,Operation) values(@UserID,@IP,@PageName,@RefererPage,@Operation)

end


---------------


CREATE TABLE [dbo].[HitssCounter](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[UserID] [bigint] NULL,
[IP] [varchar](130) NULL,
[PageName] [varchar](800) NULL,
[RefererPage] [varchar](800) NULL,
[Operation] [varchar](800) NULL,
[CurrentTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[HitssCounter] ADD  CONSTRAINT [defaultDateHits]  DEFAULT (getdate()) FOR [CurrentTime]
GO

Note:- This can be used in master page.

No comments:

Post a Comment