gud day... i just wanna ask if someone could give me a sample code of a user's activity log
..where it records the time of login and logout of the user
.. and also records the users deleted, created and updated data...
.tnx :D

and should i also create a table in the database for activity log?

Dani AI

Generated

For 's scenario (many forms, track login/logout and CRUD), a database-backed audit is usually the best choice. 's file-based approach can work for small single-user tools, but a DB gives concurrency, queryability and retention control as and suggested. A practical pattern is two related structures: a Sessions (login) record that creates a SessionID on authentication, and an ActivityLog that records every CRUD action with a timestamp and the SessionID for correlation.

A compact example schema and a simple VB.NET logging helper follow.

CREATE TABLE Sessions (
  SessionID UNIQUEIDENTIFIER PRIMARY KEY,
  UserID INT NOT NULL,
  LoginTime DATETIMEOFFSET NOT NULL,
  LogoutTime DATETIMEOFFSET NULL,
  ClientIP NVARCHAR(45) NULL,
  UserAgent NVARCHAR(200) NULL
);

CREATE TABLE ActivityLog (
  ActivityID BIGINT IDENTITY PRIMARY KEY,
  SessionID UNIQUEIDENTIFIER NULL,
  UserID INT NOT NULL,
  ActionType NVARCHAR(32) NOT NULL,
  ObjectType NVARCHAR(100) NULL,
  ObjectId NVARCHAR(100) NULL,
  Details NVARCHAR(MAX) NULL,
  TimeStamp DATETIMEOFFSET NOT NULL
);
Public Class ActivityLogger
  Private Shared ReadOnly Conn As String = ConfigurationManager.ConnectionStrings("MyConn").ConnectionString

  Public Shared Sub LogActivity(userId As Integer, actionType As String, objectType As String, objectId As String, details As String, Optional sessionId As Guid? = Nothing)
    Using cn As New SqlClient.SqlConnection(Conn)
      Using cmd As New SqlClient.SqlCommand("INSERT INTO ActivityLog (SessionID,UserID,ActionType,ObjectType,ObjectId,Details,TimeStamp) VALUES (@SessionID,@UserID,@ActionType,@ObjectType,@ObjectId,@Details,@TimeStamp)", cn)
        cmd.Parameters.AddWithValue("@SessionID", If(sessionId.HasValue, CType(sessionId.Value, Object), DBNull.Value))
        cmd.Parameters.AddWithValue("@UserID", userId)
        cmd.Parameters.AddWithValue("@ActionType", actionType)
        cmd.Parameters.AddWithValue("@ObjectType", objectType)
        cmd.Parameters.AddWithValue("@ObjectId", objectId)
        cmd.Parameters.AddWithValue("@Details", details)
        cmd.Parameters.AddWithValue("@TimeStamp", DateTimeOffset.UtcNow)
        cn.Open()
        cmd.ExecuteNonQuery()
      End Using
    End Using
  End Sub
End Class

Implementation notes: call the logger from each form's Create/Update/Delete handlers and create/update the Sessions row on login/logout. Use parameterized queries or stored procedures, consider asynchronous/batched inserts under load, index TimeStamp/UserID for reports, and apply retention/PII rules (mask or avoid sensitive data). For a simple login-flow demo see 's linked example and adapt the schema above for full auditing.

Recommended Answers

All 9 Replies

See if this helps to get you started.
1.Button

Imports System.IO
Public Class Form1

#Region "-----===-----===-----===-----===-----=== Log chopping crap xD ===-----===-----===-----===-----===-----"
    Public myFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\user.log activity\" '// Folder for File(s).
    Private myLogFile As String = myFolder & "myCoolLogFile.txt" '// your.File.
    '// easier to write and understand File.
    Private sLogIn As String = "Logged in: ", sLogOut As String = "Logged out: ", sUpdateData As String = "Updated Data: "

    Public Sub xSaveCoolLogFile(ByVal selCoolFile As String, ByVal selCoolContent As String)
        If File.Exists(selCoolFile) Then
            File.WriteAllText(selCoolFile, selCoolContent & vbNewLine & File.ReadAllText(selCoolFile))
        Else
            File.WriteAllText(selCoolFile, selCoolContent)
        End If
    End Sub
#End Region

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        xSaveCoolLogFile(myLogFile, sLogOut & DateTime.Now)
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Directory.Exists(myFolder) Then Directory.CreateDirectory(myFolder) '// create Folder if Not .Exists.
        xSaveCoolLogFile(myLogFile, sLogIn & DateTime.Now)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim sTemp As String = "some data to update to ""whatever/wherever"""
        MsgBox(sTemp) '// code here to update/edit/etc. data.
        xSaveCoolLogFile(myLogFile, sUpdateData & DateTime.Now & " - " & sTemp)
    End Sub
End Class

It uses a File, Not a db(database) and it's quite simple to get you on the road to success.:D

If you do end up using a File to save the user's activity, I would create a new file every week/month, depending on how often a user might use your app..

My advice is make a 2 tables, LogTables and UserActions, where logTables will record the log information (LogID, UserID, LogIn,LogOut) and in UserActions table record the users activity (ActivityId,logID,userAction,time). In the save, update or delete button you should have insert statement in userActions table. Just create an method and call it.

better have the logs in database table.

actually i have lots of forms, i want to record users activity
for example. user deleted a file from formA so, it should be in the activity like
user1 deleted citizenid 1000002 at 12/1/2012
what should i do to record all activity? should i put a eventlog?

My advice is make a 2 tables, LogTables and UserActions, where logTables will record the log information (LogID, UserID, LogIn,LogOut) and in UserActions table record the users activity (ActivityId,logID,userAction,time). In the save, update or delete button you should have insert statement in userActions table. Just create an method and call it.

sir could you please give me an example? im really new in vb.net

user will delete the files from system using ur Application? or if u just want to record the application events then write a class file with public function and use that function to log in all the events

user will delete the files from system using ur Application? or if u just want to record the application events then write a class file with public function and use that function to log in all the events

sir could you please give me a sample code? i really don't know how to start tnx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.