NopCommerce提供的一项功能是操作日志记录,例如XX用户在后台管理进行了XX操作:我们先看一下和ActivityLog相关的界面以及表。
当我需要增加一个自己的操作记录的时候,我们需要哪些操作?接下来一一道来:
/****** Script forSelectTopNRows command from SSMS ******/
SELECT TOP 1000 [Id]
,[SystemKeyword]
,[Name]
,[Enabled]
FROM [nop].[dbo].[ActivityLogType]
文件:nopcommerce\Libraries\Nop.Services\Installation\InstallationService.cs
protected virtual void InstallActivityLogTypes()
{
var activityLogTypes = newList<ActivityLogType>()
{
new ActivityLogType
{
SystemKeyword = "AddNewCategory",
Enabled = true,
Name = "Add a new category"
},
增加:在安装过程:
new ActivityLogType
{
SystemKeyword = "AddSnatchItem",
Enabled = true,
Name = "Add a new snatch" },
在数据库层次: insert into [nop].[dbo].[ActivityLogType]values('AddSnatchItem','Add a new snatch',1)
由于我们并不需要修改数据表结构,在Core和Data两层可以忽略,在Service层Nop\Library\service中CustomerActivitySerivce的对应实现:
public virtual ActivityLogInsertActivity(string systemKeyword, string comment)
{
returnInsertActivity(systemKeyword, comment, new object[0]);
}
/// <summary>
/// Inserts an activity log item
/// </summary>
/// <paramname="systemKeyword">The systemkeyword</param>
/// <paramname="comment">The activitycomment</param>
/// <paramname="commentParams">The activitycomment parameters for string.Format() function.</param>
/// <returns>Activity log item</returns>
public virtual ActivityLogInsertActivity(string systemKeyword,
stringcomment, params object[]commentParams)
{
if(_workContext.CurrentCustomer == null)
returnnull;
varactivityTypes = GetAllActivityTypes();
varactivityType = activityTypes.ToList().Find(at => at.SystemKeyword ==systemKeyword);
if(activityType == null || !activityType.Enabled)
returnnull;
comment = CommonHelper.EnsureNotNull(comment);
comment = string.Format(comment,commentParams);
comment = CommonHelper.EnsureMaximumLength(comment,4000);
varactivity = new ActivityLog();
activity.ActivityLogType =activityType;
activity.Customer =_workContext.CurrentCustomer;
activity.Comment = comment;
activity.CreatedOnUtc = DateTime.UtcNow;
_activityLogRepository.Insert(activity);
returnactivity;
}
在Controller Action中使用ActivityLog功能:
基本不需要修改,首先注册SystemKeyWord,在表activityLogTypes中(通过安装方式的话,在InstallationService中)在Controller的构造函数中增加IcustomerActivityservice,在需要使用的地方调用InsertActivity即可,SystemKeyWord需要Match。
//activity log
_customerActivityService.InsertActivity("AddNewCategory",_localizationService.GetResource("ActivityLog.AddNewCategory"),category.Name);
函数定义: ActivityLogInsertActivity(string systemKeyword, string comment, paramsobject[] commentParams);