using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Castle.DynamicProxy;//Castle.Core namespace MyAttribute.AOPWay { ////// 使用Castle\DynamicProxy 实现动态代理 /// public class CastleProxy { public static void Show() { User user = new User() { Name = "Eleven", Password = "123123123123" }; ProxyGenerator generator = new ProxyGenerator(); MyInterceptor interceptor = new MyInterceptor(); UserProcessor userprocessor = generator.CreateClassProxy (interceptor); userprocessor.RegUser(user); } public class MyInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { PreProceed(invocation); invocation.Proceed(); PostProceed(invocation); } public void PreProceed(IInvocation invocation) { Console.WriteLine("方法执行前"); } public void PostProceed(IInvocation invocation) { Console.WriteLine("方法执行后"); } } public interface IUserProcessor { void RegUser(User user); } public class UserProcessor : IUserProcessor { public virtual void RegUser(User user) { Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.Password); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AOPWay { ////// 装饰器模式实现静态代理 /// AOP 在方法前后增加自定义的方法 /// public class Decorator { public static void Show() { User user = new User() { Name = "Eleven", Password = "123123123123" }; IUserProcessor processor = new UserProcessor(); processor = new UserProcessorDecorator(processor); processor.RegUser(user); } public interface IUserProcessor { void RegUser(User user); } public class UserProcessor : IUserProcessor { public void RegUser(User user) { Console.WriteLine("用户已注册。Name:{0},PassWord:{1}", user.Name, user.Password); } } /// /// 装饰器的模式去提供一个AOP功能 /// public class UserProcessorDecorator : IUserProcessor { private IUserProcessor UserProcessor { get; set; } public UserProcessorDecorator(IUserProcessor userprocessor) { UserProcessor = userprocessor; } public void RegUser(User user) { PreProceed(user); try { this.UserProcessor.RegUser(user); } catch (Exception) { throw; } PostProceed(user); } public void PreProceed(User user) { Console.WriteLine("方法执行前"); } public void PostProceed(User user) { Console.WriteLine("方法执行后"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AOPWay { public class User { public int Id { get; set; } public string Name { get; set; } public string Password { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AOPWay { ////// 使用.Net Remoting/RealProxy 实现动态代理 /// public class Proxy { public static void Show() { User user = new User() { Name = "Eleven", Password = "123123123123" }; //UserProcessor processor = new UserProcessor(); UserProcessor userprocessor = TransparentProxy.Create (); userprocessor.RegUser(user); } public class MyRealProxy : RealProxy { private T tTarget; public MyRealProxy(T target) : base(typeof(T)) { this.tTarget = target; } public override IMessage Invoke(IMessage msg) { PreProceede(msg); IMethodCallMessage callMessage = (IMethodCallMessage)msg; object returnValue = callMessage.MethodBase.Invoke(this.tTarget, callMessage.Args); PostProceede(msg); return new ReturnMessage(returnValue, new object[0], 0, null, callMessage); } public void PreProceede(IMessage msg) { Console.WriteLine("方法执行前"); } public void PostProceede(IMessage msg) { Console.WriteLine("方法执行后"); } } //TransparentProxy public static class TransparentProxy { public static T Create () { T instance = Activator.CreateInstance (); MyRealProxy realProxy = new MyRealProxy (instance); T transparentProxy = (T)realProxy.GetTransparentProxy(); return transparentProxy; } } public interface IUserProcessor { void RegUser(User user); } public class UserProcessor : MarshalByRefObject, IUserProcessor { public void RegUser(User user) { Console.WriteLine("用户已注册。用户名称{0} Password{1}", user.Name, user.Password); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity.InterceptionExtension;//InterceptionExtension扩展 using Microsoft.Practices.Unity; namespace MyAttribute.AOPWay { ////// 使用EntLib\PIAB Unity 实现动态代理 /// public class UnityAOP { public static void Show() { User user = new User() { Name = "Eleven", Password = "123123123123" }; IUnityContainer container = new UnityContainer();//声明一个容器 container.RegisterType ();//声明UnityContainer并注册IUserProcessor IUserProcessor processor = container.Resolve (); processor.RegUser(user);//调用 container.AddNewExtension ().Configure () .SetInterceptorFor (new InterfaceInterceptor()); //IUserProcessor userprocessor = new UserProcessor(); IUserProcessor userprocessor = container.Resolve (); Console.WriteLine("********************"); userprocessor.RegUser(user);//调用 //userprocessor.GetUser(user);//调用 } #region 特性对应的行为 public class UserHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { User user = input.Inputs[0] as User; if (user.Password.Length < 10) { return input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位")); } Console.WriteLine("参数检测无误"); IMethodReturn methodReturn = getNext.Invoke().Invoke(input, getNext); //Console.WriteLine("已完成操作"); return methodReturn; } } public class LogHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { User user = input.Inputs[0] as User; string message = string.Format("RegUser:Username:{0},Password:{1}", user.Name, user.Password); Console.WriteLine("日志已记录,Message:{0},Ctime:{1}", message, DateTime.Now); return getNext()(input, getNext); } } public class ExceptionHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn methodReturn = getNext()(input, getNext); if (methodReturn.Exception == null) { Console.WriteLine("无异常"); } else { Console.WriteLine("异常:{0}", methodReturn.Exception.Message); } return methodReturn; } } public class AfterLogHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { IMethodReturn methodReturn = getNext()(input, getNext); User user = input.Inputs[0] as User; string message = string.Format("RegUser:Username:{0},Password:{1}", user.Name, user.Password); Console.WriteLine("完成日志,Message:{0},Ctime:{1},计算结果{2}", message, DateTime.Now, methodReturn.ReturnValue); return methodReturn; } } #endregion 特性对应的行为 #region 特性 public class UserHandlerAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { ICallHandler handler = new UserHandler() { Order = this.Order }; return handler; } } public class LogHandlerAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new LogHandler() { Order = this.Order }; } } public class ExceptionHandlerAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new ExceptionHandler() { Order = this.Order }; } } public class AfterLogHandlerAttribute : HandlerAttribute { public override ICallHandler CreateHandler(IUnityContainer container) { return new AfterLogHandler() { Order = this.Order }; } } #endregion 特性 #region 业务 [UserHandlerAttribute(Order = 1)] [ExceptionHandlerAttribute(Order = 3)] [LogHandlerAttribute(Order = 2)] [AfterLogHandlerAttribute(Order = 5)] public interface IUserProcessor { void RegUser(User user); User GetUser(User user); } public class UserProcessor : IUserProcessor//MarshalByRefObject, { public void RegUser(User user) { Console.WriteLine("用户已注册。"); //throw new Exception("11"); } public User GetUser(User user) { return user; } } #endregion 业务 /* TransparentProxyInterceptor:直接在类的方法上进行标记,但是这个类必须继承MarshalByRefObject...不建议用 VirtualMethod:直接在类的方法上进行标记,但这个方法必须是虚方法(就是方法要带virtual关键字) InterfaceInterceptor:在接口的方法上进行标记,这样继承这个接口的类里实现这个接口方法的方法就能被拦截 */ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AttributeExtend { public class BaseDAL { ////// 校验而且保存 /// /// /// public static void Save (T t) { bool isSafe = true; Type type = t.GetType(); foreach (var property in type.GetProperties()) { object[] oAttributeList = property.GetCustomAttributes(true); foreach (var item in oAttributeList) { if (item is IntValidateAttribute) { IntValidateAttribute attribute = item as IntValidateAttribute; isSafe = attribute.Validate((int)property.GetValue(t)); } } if (!isSafe) break; } if (isSafe) Console.WriteLine("保存到数据库"); else Console.WriteLine("数据不合法"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AttributeExtend { public enum UserState { ////// 正常 /// [Remark("正常")] Normal = 0, /// /// 冻结 /// [Remark("冻结")] Frozen = 1, /// /// 删除 /// [Remark("删除")] Delete = 2 } //public enum UserState1 //{ // /// // /// 正常 // /// // [Remark("正常")] // 正常 = 0, // /// // /// 冻结 // /// // [Remark("冻结")] // 冻结 = 1, // /// // /// 删除 // /// // [Remark("删除")] // 删除 = 2 //} }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AttributeExtend { public class RemarkAttribute : Attribute { public RemarkAttribute(string remark) { _Remark = remark; } private string _Remark; public string Remark { get { return _Remark; } } } public static class RemarkExtend { public static string GetRemark(this Enum eValue) { Type type = eValue.GetType(); FieldInfo field = type.GetField(eValue.ToString()); RemarkAttribute remarkAttribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute)); return remarkAttribute.Remark; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute.AttributeExtend { [AttributeUsage(AttributeTargets.Property)] public class IntValidateAttribute : Attribute { private int _Min = 0; private int _Max = 0; public IntValidateAttribute(int min, int max) { this._Min = min; this._Max = max; } public bool Validate(int num) { return num > this._Min && num < this._Max; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute { ////// 特性是一个继承或者间接继承Attribute的类 /// 通常用attribute结尾,那么在使用的时候,可以去掉这个结尾 /// /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class CustomAttribute : Attribute { public CustomAttribute() { } public CustomAttribute(int id) { } public CustomAttribute(int id, string name) { } public string Remark { get; set; } public string Description = null; public void Show() { } } public class TableAttribute : Attribute { private string _TableName = null; public TableAttribute(string tableName) { this._TableName = tableName; } public string GetTableName() { return this._TableName; } } public class CustomChildAttribute : CustomAttribute { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute { public static class Extend { ////// 根据类型获取表名称 /// /// /// /// public static string GetTableName (this T t) where T : new() { Type type = t.GetType(); object[] oAttributeList = type.GetCustomAttributes(true); foreach (var item in oAttributeList) { if (item is TableAttribute) { TableAttribute attribute = item as TableAttribute; return attribute.GetTableName(); } } return type.Name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute { ////// 这里是注释,除了让人看懂这里写的是什么,对运行没有任何影响 /// //[Obsolete("请不要使用这个了,请使用什么来代替", true)] [Serializable] public class People { //[Obsolete("请不要使用这个了1")] public int Id { get; set; } public string Name { get; set; } } }
using MyAttribute.AOPWay; using MyAttribute.AttributeExtend; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAttribute { ////// 1 特性attribute,和注释有什么区别 /// 特性可以影响编译 /// 特性可以影响运行 /// 2 声明和使用attribute /// 3 应用attribute /// 特性就是在不影响类型封装的前提下,额外的添加一些信息 /// 如果你用这个信息,那特性就有用, /// 如果你不管这个信息,那特性就没用 /// /// 4 AOP面向切面编程 /// Aspect Oriented Programming /// OOP 面向对象编程 /// /// 5 多种方式实现AOP /// class Program { static void Main(string[] args) { try { Console.WriteLine("今天的内容是特性和AOP==================================="); People people = new People(); UserModel user = new UserModel(); user.Id = 1; string name = user.GetTableName (); string remark = UserState.Normal.GetRemark(); BaseDAL.Save (user); #region AOP show Console.WriteLine("***********************"); Decorator.Show(); Console.WriteLine("***********************"); Proxy.Show(); Console.WriteLine("***********************"); CastleProxy.Show(); Console.WriteLine("***********************"); UnityAOP.Show(); #endregion } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); } } }
using MyAttribute.AttributeExtend; using System; namespace MyAttribute { ////// User:实体类(业务信息) /// //[CustomAttribute] //[Custom] //[CustomAttribute()] //[Custom()] //[Custom(123)] //[CustomAttribute(123)] //[Custom(123,"456")] //[CustomAttribute(123, "456")] //[Custom(Remark="这里是特性")] //[Custom(123, Remark = "这里是特性")] //[CustomAttribute(123, Remark = "这里是特性")] //[Custom(123, "456",Remark="这里是特性")] //[CustomAttribute(123, "456", Remark = "这里是特性", Description = "Description")] [Table("User")] public class UserModel { //public string TableName = "User"; [IntValidateAttribute(0, 10000)] //[IntValidateAttribute(2, 5000)] public int Id { get; set; } #region Model /// /// /// public string Account { set; get; } /// /// 密码 /// public string Password { set; get; } /// /// EMaill /// public string Email { set; get; } /// /// 手提 /// public string Mobile { set; get; } /// /// 企业ID /// public int? CompanyId { set; get; } /// /// 企业名称 /// public string CompanyName { set; get; } /// /// 用户状态 0正常 1冻结 2删除 /// public int? State { set; get; } /// /// 用户类型 1 普通用户 2管理员 4超级管理员 /// public int? UserType { set; get; } /// /// 最后一次登陆时间 /// public DateTime? LastLoginTime { set; get; } /// /// 最后一次修改人 /// public int? LastModifierId { set; get; } /// /// 最后一次修改时间 /// public DateTime? LastModifyTime { set; get; } #endregion Model } }