lxl 2 年之前
父节点
当前提交
1a804a17d1

+ 3 - 3
.gitignore

@@ -30,8 +30,6 @@ bld/
 [Bb]in/
 [Oo]bj/
 [Oo]ut/
-[Ll]og/
-[Ll]ogs/
 
 # Visual Studio 2015/2017 cache/options directory
 .vs/
@@ -360,4 +358,6 @@ MigrationBackup/
 .ionide/
 
 # Fody - auto-generated XML schema
-FodyWeavers.xsd
+FodyWeavers.xsd
+/EMIS.Web/Logs
+/EMIS.Web/Content/DownFile/2022-09-19

+ 42 - 0
EMIS.CommonLogic/Log/OperateLogServices.cs

@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using EMIS.ViewModel.Log;
+using Bowin.Common.Linq.Entity;
+using EMIS.ViewModel;
+using EMIS.DataLogic.Log;
+using System.Linq.Expressions;
+using EMIS.Entities.Log;
+
+namespace EMIS.CommonLogic.Log
+{
+    public class OperateLogServices : BaseServices, IOperateLogServices
+    {
+        public OperateLogDAL OperateLogDAL { get; set; }
+
+        public IGridResultSet<OperateLogView> GetOperateLogViewList(ConfiguretView searchCondition, DateTime startTime, DateTime endTime
+            , int pageIndex, int pageSize)
+        {
+            var q = OperateLogDAL.GetOperateLogView(x => (x.OperateTime >= startTime && x.OperateTime <= endTime), x => true);
+            if (!string.IsNullOrEmpty(searchCondition.ConditionValue) && !string.IsNullOrEmpty(searchCondition.Attribute))
+                q = q.DynamicWhere(searchCondition.Attribute, searchCondition.Condition, searchCondition.ConditionValue);
+
+            return q.OrderByDescending(x => x.OperateTime).ToGridResultSet<OperateLogView>(pageIndex, pageSize);
+        }
+
+        public IList<OperateLogView> GetOperateLogViewList(ConfiguretView searchCondition, DateTime startTime, DateTime endTime)
+        {
+            var q = OperateLogDAL.GetOperateLogView(x => (x.OperateTime >= startTime && x.OperateTime <= endTime), x => true);
+            if (!string.IsNullOrEmpty(searchCondition.ConditionValue) && !string.IsNullOrEmpty(searchCondition.Attribute))
+                q = q.DynamicWhere(searchCondition.Attribute, searchCondition.Condition, searchCondition.ConditionValue);
+
+            return q.OrderByDescending(x => x.OperateTime).ToList();
+        }
+
+        public void Delete(IList<Guid?> logIDList)
+        {
+            this.LogUnitOfWork.RemoveLogs(logIDList);
+        }
+    }
+}

+ 34 - 0
EMIS.ICommonLogic/Log/IOperateLogServices.cs

@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Bowin.Common.Linq.Entity;
+using EMIS.ViewModel.Log;
+using EMIS.ViewModel;
+
+namespace EMIS.CommonLogic.Log
+{
+    public interface IOperateLogServices
+    {
+        /// <summary>
+        /// 获取日志列表
+        /// </summary>
+        /// <param name="searchCondition">动态查询条件</param>
+        /// <param name="startTime">开始时间(必填)</param>
+        /// <param name="endTime">结束时间(必填)</param>
+        /// <param name="pageIndex">页码</param>
+        /// <param name="pageSize">每页行数</param>
+        /// <returns>数据库分页后的单页结果,以及总记录数</returns>
+        IGridResultSet<OperateLogView> GetOperateLogViewList(ConfiguretView searchCondition, DateTime startTime, DateTime endTime, int pageIndex, int pageSize);
+        /// <summary>
+        /// 获取日志列表
+        /// </summary>
+        /// <param name="searchCondition">动态查询条件</param>
+        /// <param name="startTime">开始时间(必填)</param>
+        /// <param name="endTime">结束时间(必填)</param>
+        /// <returns>获取全部结果</returns>
+        IList<OperateLogView> GetOperateLogViewList(ConfiguretView searchCondition, DateTime startTime, DateTime endTime);
+
+        void Delete(IList<Guid?> logIDList);
+    }
+}

+ 12 - 0
EMIS.Utility/Log/BatchModifyDbLog.cs

@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace EMIS.Utility.Log
+{
+    public class BatchModifyDbLog
+    {
+
+    }
+}

+ 317 - 0
EMIS.Utility/Log/DbLog.cs

@@ -0,0 +1,317 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Data.Entity.Infrastructure;
+using EMIS.Entities.Log;
+using EMIS.Utility.FormValidate;
+using Bowin.Common.Data;
+using System.Web;
+using System.Data;
+using System.Linq.Expressions;
+
+namespace EMIS.Utility.Log
+{
+    public class DbLog
+    {
+        public static List<Log_Operate> GetBatchUpdateLog<T>(IList<T> entities, System.Data.Entity.DbContext ctx) where T : class
+        {
+            var result = new List<Log_Operate>();
+            var principal = CustomPrincipal.Current;
+            var operateUserID = (principal != null) ? (Guid?)principal.UserID : null;
+
+            var tableKey = EMIS.Entities.TableKeyDictionary.GetKeyName<T>();
+            ParameterExpression keyParamter = Expression.Parameter(typeof(DbEntityEntry<T>), "w");
+            MemberExpression keyEntryExpression = Expression.Property(keyParamter, "Entity");
+            MemberExpression keyExpression = Expression.Property(keyEntryExpression, tableKey);
+            var entryList = ctx.ChangeTracker.Entries<T>().ToList();
+            var originalValues = entities.Select(x => new {
+                OriginalValues = entryList.FirstOrDefault(
+                    Expression.Lambda<Func<DbEntityEntry<T>, bool>>(
+                        Expression.Equal(keyExpression, Expression.Constant((Guid)typeof(T).GetProperty(tableKey).GetValue(x, null)))
+                    , keyParamter).Compile()).OriginalValues,
+                CurrentValues = x
+            }).ToList();
+
+            foreach (var updateChange in originalValues)
+            {
+                var log = new Log_Operate
+                {
+                    OperateID = Guid.NewGuid(),
+                    UserID = operateUserID,
+                    IP = ApplicationClientHelper.GetIP(),
+                    TableName = updateChange.CurrentValues.GetType().Name,
+                    SourceUrl = (HttpContext.Current == null) ? null : HttpContext.Current.Request.UrlReferrer.OriginalString,
+                    OperateTime = DateTime.Now
+                };
+                log.Operate = "修改";
+                log.Detail = "修改前内容(" + GatherValues(updateChange.OriginalValues) + "),";
+                log.Detail += "修改后内容(" + GatherValues(updateChange.CurrentValues) + ")";
+
+                result.Add(log);
+            }
+
+            return result;
+        }
+
+        public static List<Log_Operate> GetBulkInsertLog<T>(IList<T> entities)
+        {
+            var table = entities.ToTable();
+            return GetBulkInsertLog(table, typeof(T).Name);
+        }
+        public static List<Log_Operate> GetBulkInsertLog(DataTable table, string tableName)
+        {
+            var result = new List<Log_Operate>();
+            var principal = CustomPrincipal.Current;
+            var operateUserID = (principal != null) ? (Guid?)principal.UserID : null;
+            var myIP = ApplicationClientHelper.GetIP();
+
+            foreach (DataRow row in table.Rows)
+            {
+                var value = "详细内容(";
+                for (int i = 0; i < table.Columns.Count; i++)
+                {
+                    string columnName = table.Columns[i].ColumnName;
+                    value += columnName + ":";
+                    value += row[columnName].ToString() + "|";
+                }
+                if (value.EndsWith("|"))
+                {
+                    value = value.TrimEnd('|');
+                }
+                value += ")";
+
+                Log_Operate operate = new Log_Operate()
+                {
+                    OperateID = Guid.NewGuid(),
+                    UserID = operateUserID,
+                    IP = myIP,
+                    TableName = tableName,
+                    SourceUrl = (HttpContext.Current == null) ? null : HttpContext.Current.Request.UrlReferrer.OriginalString,
+                    OperateTime = DateTime.Now,
+                    Operate = "新增",
+                    Detail = value
+                };
+
+                result.Add(operate);
+            }
+
+            return result;
+        }
+
+        public static List<Log_Operate> GetDeleteLog<T>(IList<T> entities)
+        {
+            var table = entities.ToTable();
+            return GetDeleteLog(table, typeof(T).Name);
+        }
+        public static List<Log_Operate> GetDeleteLog(DataTable table, string tableName)
+        {
+            var result = new List<Log_Operate>();
+            var principal = CustomPrincipal.Current;
+            var operateUserID = (principal != null) ? (Guid?)principal.UserID : null;
+            var myIP = ApplicationClientHelper.GetIP();
+
+            foreach (DataRow row in table.Rows)
+            {
+                var value = "删除内容(";
+                for (int i = 0; i < table.Columns.Count; i++)
+                {
+                    string columnName = table.Columns[i].ColumnName;
+                    value += columnName + ":";
+                    value += row[columnName].ToString() + "|";
+                }
+                if (value.EndsWith("|"))
+                {
+                    value = value.TrimEnd('|');
+                }
+                value += ")";
+
+                Log_Operate operate = new Log_Operate()
+                {
+                    OperateID = Guid.NewGuid(),
+                    UserID = operateUserID,
+                    IP = myIP,
+                    TableName = tableName,
+                    SourceUrl = (HttpContext.Current == null) ? null : HttpContext.Current.Request.UrlReferrer.OriginalString,
+                    OperateTime = DateTime.Now,
+                    Operate = "删除",
+                    Detail = value
+                };
+
+                result.Add(operate);
+            }
+
+            return result;
+        }
+
+        public static List<Log_Operate> GetLog(DbChangeTracker changeTracker)
+        {
+            var result = new List<Log_Operate>();
+            var entryList = changeTracker.Entries().ToList();
+            var principal = CustomPrincipal.Current;
+
+            entryList.ForEach(x => AddLog(x, result, principal));
+
+            return result;
+        }
+
+        public static List<Log_Operate> GetRelationshipLog(System.Data.Entity.DbContext ctx)
+        {
+            var result = new List<Log_Operate>();
+            var principal = CustomPrincipal.Current;
+            var operateUserID = (principal != null) ? (Guid?)principal.UserID : null;
+            var objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
+            var deleteChanges = objectContext.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Deleted);
+            var addChanges = objectContext.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added);
+            var myIP = ApplicationClientHelper.GetIP();
+
+            foreach(var deleteChange in deleteChanges)
+            {
+                if (deleteChange.IsRelationship)
+                {
+                    var log = new Log_Operate
+                    {
+                        OperateID = Guid.NewGuid(),
+                        UserID = operateUserID,
+                        IP = myIP,
+                        TableName = deleteChange.EntitySet.Name,
+                        SourceUrl = (HttpContext.Current == null) ? null : HttpContext.Current.Request.UrlReferrer.OriginalString,
+                        OperateTime = DateTime.Now,
+                        Operate = "删除",
+                        Detail = "删除内容(" + GatherValues(deleteChange.OriginalValues) + ")"
+                    };
+                    result.Add(log);
+                }
+            }
+            foreach (var addChange in addChanges)
+            {
+                if (addChange.IsRelationship)
+                {
+                    var log = new Log_Operate
+                    {
+                        OperateID = Guid.NewGuid(),
+                        UserID = operateUserID,
+                        IP = myIP,
+                        TableName = addChange.EntitySet.Name,
+                        SourceUrl = (HttpContext.Current == null) ? null : HttpContext.Current.Request.UrlReferrer.OriginalString,
+                        OperateTime = DateTime.Now,
+                        Operate = "新增",
+                        Detail = "详细内容(" + GatherRelationValues(addChange.CurrentValues, objectContext) + ")"
+                    };
+                    result.Add(log);
+                }
+            }
+
+            return result;
+        }
+
+        private static void AddLog(DbEntityEntry entry, IList<Log_Operate> logList, CustomPrincipal principal)
+        {
+            var operateUserID = (principal != null) ? (Guid?)principal.UserID : null;
+            var log = new Log_Operate { 
+                    OperateID = Guid.NewGuid(),
+                    UserID = operateUserID,
+                    IP = ApplicationClientHelper.GetIP(),
+                    TableName = entry.Entity.GetType().Name,
+                    SourceUrl = (HttpContext.Current == null) ? null : (HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.OriginalString : HttpContext.Current.Request.RawUrl),
+                    OperateTime = DateTime.Now
+                };
+            switch (entry.State)
+            {
+                case System.Data.Entity.EntityState.Added:
+                    log.Operate = "新增";
+                    log.Detail = "详细内容(" + GatherValues(entry.CurrentValues) + ")";
+                    break;
+                case System.Data.Entity.EntityState.Modified:
+                    log.Operate = "修改";
+                    log.Detail = "修改前内容(" + GatherValues(entry.OriginalValues) + "),";
+                    log.Detail += "修改后内容(" + GatherValues(entry.CurrentValues) + ")";
+                    break;
+                case System.Data.Entity.EntityState.Deleted:
+                    log.Operate = "删除";
+                    log.Detail = "删除内容(" + GatherValues(entry.OriginalValues) + ")";
+                    break;
+                default:
+                    return;
+            }
+
+            logList.Add(log);
+        }
+
+        private static string GatherRelationValues(System.Data.Common.DbDataRecord values, 
+            System.Data.Entity.Core.Objects.ObjectContext context)
+        {
+            var result = "";
+            for (int i = 0; i < values.FieldCount; i ++ )
+            {
+                var entry = (System.Data.Entity.Core.EntityKey)values.GetValue(i);
+                result += entry.EntitySetName + ":";
+                var entity = context.GetObjectByKey(entry);
+                var entityType = entity.GetType();
+                var propertyName = entry.GetEntitySet(context.MetadataWorkspace).ElementType.KeyMembers[0].Name;
+                var property = entityType.GetProperty(propertyName);
+                result += property.GetValue(entity, null) + "|";
+                //foreach (var property in entityType.GetProperties())
+                //{
+                //    result += property.Name + ":" + property.GetValue(entity, null) + "|";
+                //}
+            }
+            if (result.EndsWith("|"))
+            {
+                result = result.TrimEnd('|');
+            }
+
+            return result;
+        }
+
+        private static string GatherValues(System.Data.Common.DbDataRecord values)
+        {
+            var result = "";
+            for (int i = 0; i < values.FieldCount; i ++ )
+            {
+                var entry = (System.Data.Entity.Core.EntityKey)values.GetValue(i);
+                result += entry.EntitySetName + ":" + entry.EntityKeyValues[0].Value.ToString() + "|";
+            }
+            if (result.EndsWith("|"))
+            {
+                result = result.TrimEnd('|');
+            }
+
+            return result;
+        }
+
+        private static string GatherValues(DbPropertyValues values)
+        {
+            var result = "";
+            foreach (var propertyName in values.PropertyNames)
+            {
+                result += propertyName + ":" + values[propertyName] + "|";
+            }
+            if (result.EndsWith("|"))
+            {
+                result = result.TrimEnd('|');
+            }
+
+            return result;
+        }
+
+        private static string GatherValues<T>(T entity)
+        {
+            var result = "";
+            var properties = typeof(T).GetProperties();
+            foreach (var property in properties)
+            {
+                if (property.PropertyType.IsPrimitive || property.PropertyType.IsValueType || property.PropertyType.Name.StartsWith("String"))
+                {
+                    result += property.Name + ":" + (property.GetValue(entity, null) ?? "").ToString() + "|";
+                }
+            }
+            if (result.EndsWith("|"))
+            {
+                result = result.TrimEnd('|');
+            }
+
+            return result;
+        }
+    }
+}

+ 52 - 0
EMIS.ViewModel/Log/OperateLogView.cs

@@ -0,0 +1,52 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace EMIS.ViewModel.Log
+{
+    public class OperateLogView
+    {
+        /// <summary>
+        /// OperateID
+        /// </summary>
+        public System.Guid OperateID { get; set; }
+        /// <summary>
+        /// UserID
+        /// </summary>
+        public Nullable<System.Guid> UserID { get; set; }
+
+        public string LoginID { get; set; }
+        public string UserName { get; set; }
+        /// <summary>
+        /// IP
+        /// </summary>
+        public string IP { get; set; }
+        /// <summary>
+        /// TableName
+        /// </summary>
+        public string TableName { get; set; }
+        /// <summary>
+        /// SourceUrl
+        /// </summary>
+        public string SourceUrl { get; set; }
+        /// <summary>
+        /// Operate
+        /// </summary>
+        public string Operate { get; set; }
+        /// <summary>
+        /// Detail
+        /// </summary>
+        public string Detail { get; set; }
+        /// <summary>
+        /// IsSuccess
+        /// </summary>
+        public Nullable<bool> IsSuccess { get; set; }
+
+        public string IsSuccessDesc { get; set; }
+        /// <summary>
+        /// OperateTime
+        /// </summary>
+        public Nullable<System.DateTime> OperateTime { get; set; }
+    }
+}

+ 40 - 0
EMiS.DataLogic/Log/OperateLogDAL.cs

@@ -0,0 +1,40 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using EMIS.DataLogic.Repositories.Log;
+using EMIS.ViewModel.Log;
+using EMIS.Entities.Log;
+using System.Linq.Expressions;
+
+namespace EMIS.DataLogic.Log
+{
+    public class OperateLogDAL
+    {
+        public OperateRepository OperateRepository { get; set; }
+        public VWUserRepository VWUserRepository { get; set; }
+
+        public IQueryable<OperateLogView> GetOperateLogView(Expression<Func<Log_Operate, bool>> exp, Expression<Func<VW_Sys_User, bool>> userExp)
+        {
+            var q = (from o in OperateRepository.GetList(exp) 
+                     join vu in VWUserRepository.GetList(userExp) on o.UserID equals vu.UserID 
+                     orderby o.OperateTime descending 
+                     select new OperateLogView {
+                        OperateID = o.OperateID,
+                        UserID = vu.UserID,
+                        LoginID = vu.LoginID,
+                        UserName = vu.Name,
+                        IP = o.IP,
+                        TableName = o.TableName,
+                        SourceUrl = o.SourceUrl,
+                        Operate = o.Operate,
+                        Detail = o.Detail,
+                        IsSuccess = o.IsSuccess,
+                        IsSuccessDesc = ((o.IsSuccess == true) ? "是" : "否"),
+                        OperateTime = o.OperateTime
+                     });
+
+            return q;
+        }
+    }
+}

+ 116 - 0
EMiS.DataLogic/Repositories/Log/LogRepository.cs

@@ -0,0 +1,116 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Linq.Expressions;
+using System.Data.Entity;
+using System.Data.Entity.Infrastructure;
+using Bowin.Common.Data;
+using Bowin.Common.Linq.Entity;
+
+namespace EMIS.DataLogic.Repositories.Log
+{
+    public class LogRepository<TEntity> where TEntity : class
+    {
+        private LogUnitOfWork _unitOfWork;
+
+        private LogRepository()
+        {
+        }
+
+        public LogRepository(LogUnitOfWork unitOfWork)
+        {
+            this._unitOfWork = unitOfWork;
+        }
+
+        public TEntity GetSingle(Expression<Func<TEntity, bool>> expression)
+        {
+            return this.Entities.Where<TEntity>(expression).FirstOrDefault<TEntity>();
+        }
+
+        public TEntity GetSingle(Expression<Func<TEntity, bool>> expression, params string[] paths)
+        {
+            IQueryable<TEntity> source = this.Entities;//.Include(path)
+            foreach (var path in paths)
+            {
+                source = source.Include(path);
+            }
+            return source.Where<TEntity>(expression).FirstOrDefault<TEntity>();
+        }
+
+        public TEntity GetSingle(Expression<Func<TEntity, bool>> expression, params Expression<Func<TEntity, object>>[] paths)
+        {
+            IQueryable<TEntity> source = this.Entities;//.Include(path)
+            foreach (var path in paths)
+            {
+                source = source.Include(path);
+            }
+            return source.Where<TEntity>(expression).FirstOrDefault<TEntity>();
+        }
+
+        public IQueryable<TEntity> Entities
+        {
+            get
+            {
+                return this._unitOfWork.Set<TEntity>();
+            }
+        }
+
+        public LogUnitOfWork UnitOfWork
+        {
+            get
+            {
+                return this._unitOfWork;
+            }
+        }
+
+        public GridResultSet<TEntity> GetPagedList<S>(Expression<Func<TEntity, bool>> expression, int pageIndex, int pageSize, Expression<Func<TEntity, S>> orderBy, bool descending, params Expression<Func<TEntity, object>>[] paths)
+        {
+            IQueryable<TEntity> source = this.Entities;//.Include(path)
+            foreach (var path in paths)
+            {
+                source = source.Include(path);
+            }
+            source = source.Where<TEntity>(expression);
+            source = descending ? source.OrderByDescending<TEntity, S>(orderBy) : source.OrderBy<TEntity, S>(orderBy);
+
+            GridResultSet<TEntity> gridResult = new GridResultSet<TEntity>();
+
+            gridResult.rows = source.Skip<TEntity>((pageIndex) * pageSize).Take<TEntity>(pageSize).ToList();
+            gridResult.total = source.Count();
+            return gridResult;
+        }
+
+        public GridResultSet<TEntity> GetPagedList<S>(Expression<Func<TEntity, bool>> expression, int pageIndex, int pageSize, Expression<Func<TEntity, S>> orderBy, bool descending)
+        {
+            try
+            {
+                IQueryable<TEntity> source = this.Entities.Where<TEntity>(expression);
+                source = descending ? source.OrderByDescending<TEntity, S>(orderBy) : source.OrderBy<TEntity, S>(orderBy);
+
+                GridResultSet<TEntity> gridResult = new GridResultSet<TEntity>();
+
+                gridResult.rows = source.Skip<TEntity>((pageIndex) * pageSize).Take<TEntity>(pageSize).ToList();
+                gridResult.total = source.Count();
+
+                return gridResult;
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
+
+
+        public IQueryable<TEntity> GetList<S>(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, S>> orderBy, bool descending)
+        {
+            var source = GetList(expression);
+            return descending ? source.OrderByDescending<TEntity, S>(orderBy) : source.OrderBy<TEntity, S>(orderBy);
+        }
+
+        public IQueryable<TEntity> GetList(Expression<Func<TEntity, bool>> expression)
+        {
+            return this.Entities.Where<TEntity>(expression);
+        }
+    }
+}

+ 15 - 0
EMiS.DataLogic/Repositories/Log/OperateRepository.cs

@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using EMIS.Entities.Log;
+
+namespace EMIS.DataLogic.Repositories.Log
+{
+    public class OperateRepository : LogRepository<Log_Operate>
+    {
+        public OperateRepository(LogUnitOfWork unitOfWork)
+            : base(unitOfWork)
+        { }
+    }
+}

+ 232 - 0
EMiS.DataLogic/Repositories/Log/RepositoryGenerator.tt

@@ -0,0 +1,232 @@
+<#@ template debug="true" hostspecific="true" language="C#" #>
+<#@ assembly name="System.Core"#>
+<#@ assembly name="System.Data.Linq"#>
+<#@ assembly name="EnvDTE"#>
+<#@ assembly name="System.Xml"#>
+<#@ assembly name="System.Xml.Linq"#>
+<#@ import namespace="System.Diagnostics" #>
+<#@ import namespace="System"#>
+<#@ import namespace="System.CodeDom"#>
+<#@ import namespace="System.CodeDom.Compiler"#>
+<#@ import namespace="System.Collections.Generic"#>
+<#@ import namespace="System.Data.Linq"#>
+<#@ import namespace="System.Data.Linq.Mapping"#>
+<#@ import namespace="System.IO"#>
+<#@ import namespace="System.Linq"#>
+<#@ import namespace="System.Reflection"#>
+<#@ import namespace="System.Text"#>
+<#@ import namespace="System.Xml.Linq"#>
+<#@ output extension="/" #>
+<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
+<#@ assembly name="$(SolutionDir)\packages\EntityFramework.6.1.3\lib\net40\EntityFramework.dll" #>
+<#@ assembly name="$(SolutionDir)\EMIS.Entities.Log\bin\Debug\EMIS.Entities.Log.dll" #>
+
+<#
+var manager = Manager.Create(Host, GenerationEnvironment); 
+var blAssembly = Assembly.GetAssembly(typeof(EMIS.Entities.Log.EMISNewLogContext));
+var types = blAssembly.GetTypes().Where(x => 
+				x.FullName.StartsWith("EMIS.Entities.Log") && 
+                !x.Name.EndsWith("Mapping") && x.Name != "TableKeyDictionary" && !x.Name.EndsWith("Context"));
+
+foreach(var type in types)
+{
+	int startIndex = type.Name.IndexOf("_") + 1;
+	int length = type.Name.Length - startIndex;
+	string classShortName = type.Name.Substring(startIndex, length);
+	string className = classShortName + "Repository";
+
+	if (type.Name.StartsWith("VW"))
+	{
+		int secondStartIndex = classShortName.IndexOf("_") + 1;
+		classShortName = "VW" + classShortName.Substring(secondStartIndex, classShortName.Length - secondStartIndex);
+		className = classShortName + "Repository";
+	}
+
+	if (classShortName.StartsWith("SS_"))
+	{
+		continue;
+	}
+
+	manager.StartNewFile(className + ".cs");
+#>
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using EMIS.Entities.Log;
+
+namespace EMIS.DataLogic.Repositories.Log
+{
+    public class <#=className#> : LogRepository<<#=type.Name#>>
+    {
+        public <#=className#>(LogUnitOfWork unitOfWork)
+            : base(unitOfWork)
+        { }
+    }
+}
+<#	
+	manager.EndBlock();
+}
+manager.Process(true);
+#>
+<#+
+// Manager class records the various blocks so it can split them up
+class Manager {
+    private class Block {
+        public String Name;
+        public int Start, Length;
+    }
+
+    private Block currentBlock;
+    private List<Block> files = new List<Block>();
+    private Block footer = new Block();
+    private Block header = new Block();
+    private ITextTemplatingEngineHost host;
+    private StringBuilder template;
+    protected List<String> generatedFileNames = new List<String>();
+
+    public static Manager Create(ITextTemplatingEngineHost host, StringBuilder template) {
+        return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template);
+    }
+
+    public void StartNewFile(String name) {
+        if (name == null)
+            throw new ArgumentNullException("name");
+        CurrentBlock = new Block { Name = name };
+    }
+
+    public void StartFooter() {
+        CurrentBlock = footer;
+    }
+
+    public void StartHeader() {
+        CurrentBlock = header;
+    }
+
+    public void EndBlock() {
+        if (CurrentBlock == null)
+            return;
+        CurrentBlock.Length = template.Length - CurrentBlock.Start;
+        if (CurrentBlock != header && CurrentBlock != footer)
+            files.Add(CurrentBlock);
+        currentBlock = null;
+    }
+
+    public virtual void Process(bool split) {
+        if (split) {
+            EndBlock();
+            String headerText = template.ToString(header.Start, header.Length);
+            String footerText = template.ToString(footer.Start, footer.Length);
+            String outputPath = Path.GetDirectoryName(host.TemplateFile);
+            files.Reverse();
+            foreach(Block block in files) {
+                String fileName = Path.Combine(outputPath, block.Name);
+                String content = headerText + template.ToString(block.Start, block.Length) + footerText;
+                generatedFileNames.Add(fileName);
+                CreateFile(fileName, content);
+                template.Remove(block.Start, block.Length);
+            }
+        }
+    }
+
+    protected virtual void CreateFile(String fileName, String content) {
+        if (IsFileContentDifferent(fileName, content))
+            File.WriteAllText(fileName, content);
+    }
+
+    public virtual String GetCustomToolNamespace(String fileName) {
+        return null;
+    }
+
+    public virtual String DefaultProjectNamespace {
+        get { return null; }
+    }
+
+    protected bool IsFileContentDifferent(String fileName, String newContent) {
+        return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent);
+    }
+
+    private Manager(ITextTemplatingEngineHost host, StringBuilder template) {
+        this.host = host;
+        this.template = template;
+    }
+
+    private Block CurrentBlock {
+        get { return currentBlock; }
+        set {
+            if (CurrentBlock != null)
+                EndBlock();
+            if (value != null)
+                value.Start = template.Length;
+            currentBlock = value;
+        }
+    }
+
+    private class VSManager: Manager {
+        private EnvDTE.ProjectItem templateProjectItem;
+        private EnvDTE.DTE dte;
+        private Action<String> checkOutAction;
+        private Action<IEnumerable<String>> projectSyncAction;
+
+        public override String DefaultProjectNamespace {
+            get {
+                return templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString();
+            }
+        }
+
+        public override String GetCustomToolNamespace(string fileName) {
+            return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
+        }
+
+        public override void Process(bool split) {
+            if (templateProjectItem.ProjectItems == null)
+                return;
+            base.Process(split);
+            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null));
+        }
+
+        protected override void CreateFile(String fileName, String content) {
+            if (IsFileContentDifferent(fileName, content)) {
+                CheckoutFileIfRequired(fileName);
+                File.WriteAllText(fileName, content);
+            }
+        }
+
+        internal VSManager(ITextTemplatingEngineHost host, StringBuilder template)
+            : base(host, template) {
+            var hostServiceProvider = (IServiceProvider) host;
+            if (hostServiceProvider == null)
+                throw new ArgumentNullException("Could not obtain IServiceProvider");
+            dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));
+            if (dte == null)
+                throw new ArgumentNullException("Could not obtain DTE from host");
+            templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
+            checkOutAction = (String fileName) => dte.SourceControl.CheckOutItem(fileName);
+            projectSyncAction = (IEnumerable<String> keepFileNames) => ProjectSync(templateProjectItem, keepFileNames);
+        }
+
+        private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable<String> keepFileNames) {
+            var keepFileNameSet = new HashSet<String>(keepFileNames);
+            var projectFiles = new Dictionary<String, EnvDTE.ProjectItem>();
+            var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.get_FileNames(0)) + ".";
+            foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
+                projectFiles.Add(projectItem.get_FileNames(0), projectItem);
+
+            // Remove unused items from the project
+            foreach(var pair in projectFiles)
+                if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix))
+                    pair.Value.Delete();
+
+            // Add missing files to the project
+            foreach(String fileName in keepFileNameSet)
+                if (!projectFiles.ContainsKey(fileName))
+                    templateProjectItem.ProjectItems.AddFromFile(fileName);
+        }
+
+        private void CheckoutFileIfRequired(String fileName) {
+            var sc = dte.SourceControl;
+            if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName))
+                checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null));
+        }
+    }
+} #>

+ 15 - 0
EMiS.DataLogic/Repositories/Log/VWUserRepository.cs

@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using EMIS.Entities.Log;
+
+namespace EMIS.DataLogic.Repositories.Log
+{
+    public class VWUserRepository : LogRepository<VW_Sys_User>
+    {
+        public VWUserRepository(LogUnitOfWork unitOfWork)
+            : base(unitOfWork)
+        { }
+    }
+}

+ 46 - 0
Framework/Bowin.Common/Log/LogHelper.cs

@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NLog;
+
+namespace Bowin.Common.Log
+{
+    public enum LogType
+    {
+        CommmLog, //通用日志
+        ServiceLog
+    }
+
+    public class LogHelper
+    {
+        /// <summary>
+        /// 直接使用这个的话,类型就是Info(信息)
+        /// </summary>
+        /// <param name="logType"></param>
+        /// <param name="message"></param>
+        public static void WriteLog(LogType logType, string message)
+        {
+            //不要重载
+            LogManager.GetLogger(logType.ToString()).Log(LogLevel.Info, message.Replace("'", "''"));
+        }
+
+        public static void WriteErrorLog(LogType logType, string message)
+        {
+            //不要重载
+            LogManager.GetLogger(logType.ToString()).Log(LogLevel.Error, message.Replace("'", "''"));
+        }
+
+        public static void WriteLog(LogType logType, string message, LogLevel logLevel)
+        {
+            //不要重载
+            LogManager.GetLogger(logType.ToString()).Log(logLevel, message.Replace("'", "''"));
+        }
+
+        public static void WriteDebugLog(LogType logType, string message)
+        {
+            //不要重载
+            LogManager.GetLogger(logType.ToString()).Log(LogLevel.Debug, message.Replace("'", "''"));
+        }
+    }
+}