public override void OnException(PostSharp.Aspects.MethodExecutionArgs args)
        {
            log4net.ILog log = _logger;

            if(log==null)
                log = InternalFieldFinder.Instance.GetInstance<log4net.ILog>(args.Method, args.Instance);
            if (log == null)
                log = FallBackLogger;
            log.Error(Msg, args.Exception);
            args.FlowBehavior = _suppressException ? FlowBehavior.Continue : FlowBehavior.RethrowException;
            if (TraceParameters && args.Arguments != null && args.Arguments.Count>0)
            {
                var sb = new StringBuilder();
                for (int i = 0; i < args.Arguments.Count; i++)
                {
                    object arg = args.Arguments[i];
                    sb.Append(i).Append(". - ");
                    if (arg == null)
                        sb.AppendLine("<NULL>");
                    else
                        sb.AppendLine(arg.ToString());
                }
                log.Error(sb.ToString());
            }
            if (WrapExceptionType != null)
            {
                args.Exception = (Exception)Activator.CreateInstance(WrapExceptionType, Msg, args.Exception);
                args.FlowBehavior = FlowBehavior.ThrowException;
            }
            log = null;
        }
 public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
 {
     string exContext = string.Format(System.Globalization.CultureInfo.InvariantCulture, _context, args.Arguments.ToArray());
     using (log4net.ThreadContext.Stacks[Zieschang.Net.Projects.PostsharpAspects.Utilities.LogHelper.DefaultLoggerContextStack].Push(exContext))
     {
         args.Proceed();
     }
 }
 public override void OnSuccess(PostSharp.Laos.MethodExecutionEventArgs eventArgs)
 {
     base.OnSuccess(eventArgs);
     var instance = (ICairoNotifyPropertyChanged)eventArgs.Instance;
     if (instance != null)
     {
         instance.OnPropertyChanged(this.PropertyName);
     }
 }
        public void ProvideAdvices(PostSharp.CodeWeaver.Weaver codeWeaver)
        {
            // Gets the dictionary of custom attributes.
            CustomAttributeDictionaryTask customAttributeDictionary =
                CustomAttributeDictionaryTask.GetTask(this.Project);

            // Requests an enumerator of all instances of our Singleton.
            IEnumerator<ICustomAttributeInstance> customAttributeEnumerator =
                            customAttributeDictionary.GetCustomAttributesEnumerator(typeof(SingletonAttribute), true);

            ICollection<TypeDefDeclaration> singletons = new HashSet<TypeDefDeclaration>();
            // For each instance of our Singleton.
            while (customAttributeEnumerator.MoveNext())
            {
                // Gets the type to which it applies.
                TypeDefDeclaration typeDef = customAttributeEnumerator.Current.TargetElement
                                                as TypeDefDeclaration;

                if (typeDef != null && !singletons.Contains(typeDef))
                {
                    singletons.Add(typeDef);

                    codeWeaver.AddTypeLevelAdvice(new SingletonAccessorAdvice(typeDef), JoinPointKinds.BeforeStaticConstructor, new Singleton<TypeDefDeclaration>(typeDef));
                    codeWeaver.AddMethodLevelAdvice(new SingletonAdvice(typeDef),
                        null,
                        JoinPointKinds.InsteadOfNewObject,
                        new Singleton<MetadataDeclaration>(typeDef.Methods.GetOneByName(".ctor")));
                }
            }
            singletons.Clear();

            foreach(AssemblyRefDeclaration assembly in this.Project.Module.AssemblyRefs)
            {
                foreach (TypeRefDeclaration type in assembly.TypeRefs)
                {
                    TypeDefDeclaration def = type.GetTypeDefinition();
                    foreach(CustomAttributeDeclaration att in def.CustomAttributes)
                    {
                        if (Object.Equals(att.Constructor.DeclaringType.GetSystemType(new Type[]{},new Type[]{}), typeof(SingletonAttribute)))
                        {
                            singletons.Add(def);
                        }
                    }
                }
            }

            foreach(TypeDefDeclaration type in singletons)
            {
                codeWeaver.AddMethodLevelAdvice(new SingletonAdvice(type),
                        null,
                        JoinPointKinds.InsteadOfNewObject,
                        new Singleton<MetadataDeclaration>(type.Methods.GetOneByName(".ctor")));
            }
        }
예제 #5
0
파일: AOP.cs 프로젝트: NickQi/TianheDemo
 public override void OnException(PostSharp.Aspects.MethodExecutionArgs args)
 {
     StringBuilder sb = new StringBuilder();
     sb.Append("*********************************************************************************************\r\n");
     sb.Append("ErrorTime:" + System.DateTime.Now + "\r\n");
     sb.Append("ErrorFun:" + args.Exception.Source + "\r\n");
     sb.Append("ErrorDetail:" + args.Exception.StackTrace.ToString() + "," + args.Exception.Message + "\r\n");
     sb.Append("*********************************************************************************************\r\n\r\n\r\n");
     WriteFile(AppDomain.CurrentDomain.BaseDirectory + "\\SystemError.txt", sb.ToString());
     base.OnException(args);
     //args.FlowBehavior = PostSharp.Aspects.FlowBehavior.Return;
 }
예제 #6
0
        public override void OnExit(PostSharp.Aspects.MethodExecutionArgs args)
        {
            base.OnExit(args);
            bool isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
            if (!(args.ReturnValue is IQueryable) || !isAuthenticated)
            {
                
                return;
            }
            SessionStorage sessionStorage = new SessionStorage(HttpContext.Current.User.Identity.Name);
            string serviceName = args.Instance.GetType().FullName + "." + args.Method.Name;
            if (sessionStorage.DataPermission==null)
                return;
            if (sessionStorage.DataPermission.ContainsKey(serviceName))
            {
                IQueryable query = (IQueryable)args.ReturnValue;
                string queryTxt = sessionStorage.DataPermission[serviceName];
                foreach (string token in sessionStorage.UserSpecificValues.Keys)
                    if (queryTxt.Contains(token))
                        queryTxt.Replace(token, sessionStorage.UserSpecificValues[token]);

                args.ReturnValue = query.Where(queryTxt);
            }
        }
 public override void CompileTimeInitialize(PostSharp.Reflection.LocationInfo targetLocation, AspectInfo aspectInfo)
 {
     propname = targetLocation.Name;
 }
        public void Weave(WeavingContext context, PostSharp.CodeModel.InstructionBlock block)
        {
            TypeDefDeclaration typeDef = m_type;
            // Declare the static field
            FieldDefDeclaration fieldDef = new FieldDefDeclaration();
            fieldDef.Attributes = FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.NotSerialized | FieldAttributes.InitOnly;
            fieldDef.Name = "s_instance";
            fieldDef.FieldType = typeDef;

            typeDef.Fields.Add(fieldDef);

            // Declare the static accessor.
            PropertyDeclaration propDef = new PropertyDeclaration();
            propDef.Name = "Instance";

            typeDef.Properties.Add(propDef);

            MethodSemanticDeclaration sematic = new MethodSemanticDeclaration();
            sematic.Semantic = MethodSemantics.Getter;

            MethodDefDeclaration methodDef = new MethodDefDeclaration();
            methodDef.Name = "get_Instance";
            methodDef.Attributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.SpecialName;
            methodDef.CallingConvention = CallingConvention.Default;

            typeDef.Methods.Add(methodDef);

            ParameterDeclaration retVal = new ParameterDeclaration();
            retVal.ParameterType = typeDef;
            retVal.Attributes = ParameterAttributes.Retval;
            methodDef.ReturnParameter = retVal;

            sematic.Method = methodDef;

            propDef.Members.Add(sematic);
            propDef.PropertyType = typeDef;

            methodDef.MethodBody = new MethodBodyDeclaration();
            methodDef.MethodBody.MaxStack = 1;
            methodDef.MethodBody.RootInstructionBlock = methodDef.MethodBody.CreateInstructionBlock();

            //throw new NotFiniteNumberException();
            InstructionSequence sequence = methodDef.MethodBody.CreateInstructionSequence();
            methodDef.MethodBody.RootInstructionBlock.AddInstructionSequence(sequence, NodePosition.After , null);
            context.InstructionWriter.AttachInstructionSequence(sequence);

            context.InstructionWriter.EmitInstructionField(OpCodeNumber.Ldsfld, typeDef.Fields.GetByName("s_instance"));
            context.InstructionWriter.EmitInstruction(OpCodeNumber.Ret);

            context.InstructionWriter.DetachInstructionSequence();

            // code for the static constructor
            sequence = context.Method.MethodBody.CreateInstructionSequence();
            block.AddInstructionSequence(sequence, NodePosition.Before, null);
            context.InstructionWriter.AttachInstructionSequence(sequence);
            context.InstructionWriter.EmitInstructionMethod(OpCodeNumber.Newobj, typeDef.Methods.GetOneByName(".ctor"));
            context.InstructionWriter.EmitInstructionField(OpCodeNumber.Stsfld, typeDef.Fields.GetByName("s_instance"));
            context.InstructionWriter.DetachInstructionSequence();

            // Change visibility to the constructor
            typeDef.Methods.GetOneByName(".ctor").Attributes = MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
        }
        public override void OnExit(PostSharp.Aspects.MethodExecutionArgs args)
        {
            if (args.Arguments.Any())
            {
                args.Arguments
                    .ToList().ForEach(
                        argument =>
                        {
                            var locator = new HasSpecLocator();
                            var specs = typeof(HasSpecLocator)
                                .GetMethod("Locate")
                                .MakeGenericMethod(argument.GetType())
                                .Invoke(locator, BindingFlags.Public, null, null, null);

                            foreach (var iHasSpec in ((IEnumerable)specs))
                            {
                                var spec = typeof(IHasSpec<>)
                                    .MakeGenericType(argument.GetType())
                                    .GetMethod("GetSpec")
                                    .Invoke(iHasSpec, new object[] { });

                                var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(argument.GetType()));
                                typeof(List<>).MakeGenericType(argument.GetType())
                                    .GetMethod("Add")
                                    .Invoke(list, new object[] { argument });

                                var arr = typeof(List<>).MakeGenericType(argument.GetType())
                                    .GetMethod("ToArray")
                                    .Invoke(list, new object[] { });

                                typeof(Spec<>)
                                    .MakeGenericType(argument.GetType())
                                    .GetMethod("Run")
                                    .Invoke(spec, new object[] { arr });
                            }
                        });
            }
            else
            {
                var locator = new HasSpecLocator();
                var specs = typeof(HasSpecLocator)
                    .GetMethod("Locate")
                    .MakeGenericMethod(args.Instance.GetType())
                    .Invoke(locator, BindingFlags.Public, null, null, null);

                foreach (var iHasSpec in ((IEnumerable)specs))
                {
                    var spec = typeof(IHasSpec<>)
                        .MakeGenericType(args.Instance.GetType())
                        .GetMethod("GetSpec")
                        .Invoke(iHasSpec, new object[] { });

                    var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(args.Instance.GetType()));
                    typeof(List<>).MakeGenericType(args.Instance.GetType())
                        .GetMethod("Add")
                        .Invoke(list, new object[] { args.Instance });

                    var arr = typeof(List<>).MakeGenericType(args.Instance.GetType())
                        .GetMethod("ToArray")
                        .Invoke(list, new object[] { });

                    typeof(Spec<>)
                        .MakeGenericType(args.Instance.GetType())
                        .GetMethod("Run")
                        .Invoke(spec, new object[] { arr });
                }
            }
        }
 public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
 {
     int counter = 0;
     object instance = args.Instance;
     log4net.ILog lg = null;
     if (_staticInstanceField == null)
     {
         lg = InternalFieldFinder.Instance.GetInstance<log4net.ILog>(args.Method, instance);
     }
     else
     {
         lg = _staticInstanceField;
     }
     do
     {
         //delay on each cycle before continue
         //in future use a strategy 
         if (counter > 0 && RetryDelay > 0)
             System.Threading.Thread.Sleep(RetryDelay);
         counter++;
         try
         {
             args.Proceed();
             counter = Int32.MaxValue;
         }
         catch (Exception ex)
         {
             if (ExceptionFilterType == null || ExceptionFilterType.IsAssignableFrom(ex.GetType()))
             {
                 if (counter < _maxRetries)
                 {
                     lg.Info(string.Format(System.Globalization.CultureInfo.InvariantCulture, _retryMessage, counter), ex);
                 }
                 else
                 {
                     string msg = string.Format(System.Globalization.CultureInfo.InvariantCulture, _failureMessage, counter);
                     if (!string.IsNullOrEmpty(_message))
                         msg = Message + " " + msg;
                     lg.Error(msg, ex);
                     if (_raiseAfterRetries)
                         throw;
                 }
             }
         }
     } while (counter < _maxRetries);
 }
 ///
 public override void OnExecution(PostSharp.Laos.MethodExecutionEventArgs eventArgs)
 {
     GetQueryString();
     base.OnExecution(eventArgs);
 }
 /// <summary>
 /// </summary>
 /// <param name="args"></param>
 public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
 {
     string msg = string.Format(Message, args.Arguments);
     using(new Profiler(msg, _typeName,Level, EnableHirachy))
         args.Proceed();
 }
 /// <summary>
 /// </summary>
 /// <param name="method"></param>
 /// <param name="aspectInfo"></param>
 public override void CompileTimeInitialize(System.Reflection.MethodBase method, PostSharp.Aspects.AspectInfo aspectInfo)
 {
     _typeName = string.Intern(method.ReflectedType.Name);
 }
        public void ProvideAdvices(PostSharp.Sdk.CodeWeaver.Weaver codeWeaver)
        {
            LogInitializeAdvice.InitializeLoggerPolicies(this);

              // Gets the dictionary of custom attributes.
              var customAttributeDictionaryTask = AnnotationRepositoryTask.GetTask(this.Project);

              // Requests an enumerator of all instances of the LogAttribute.
              var customAttributeEnumerator = customAttributeDictionaryTask.GetAnnotationsOfType(typeof(LogAttribute), false);

              // For each instance of the LogAttribute.
              while (customAttributeEnumerator.MoveNext())
              {
            // Gets the method to which it applies.
            MethodDefDeclaration methodDef = customAttributeEnumerator.Current.TargetElement as MethodDefDeclaration;
            if (methodDef != null)
            {
              // Type whose constructor is being woven.
              TypeDefDeclaration wovenType = methodDef.DeclaringType;

              // Do not weave interface.
              if ((wovenType.Attributes & TypeAttributes.Interface) != TypeAttributes.Interface)
              {
            // Constructs a custom attribute instance.
            LogAttribute attribute = (LogAttribute)CustomAttributeHelper.ConstructRuntimeObject(customAttributeEnumerator.Current.Value);

            bool isMethodEligibleForInjection;

            if (attribute.IncludeCompilerGeneratedCode)
            {
              // Logging code can be injected even if the method is compiler generated.
              // Method processing can safely continue.
              isMethodEligibleForInjection = true;
            }
            else
            {
              // Proceed with the method only when it is not compiler generated and
              // its declaring type is not generated.
              isMethodEligibleForInjection = !(methodDef.CustomAttributes.Contains(this.compilerGeneratedAttributeType) || methodDef.DeclaringType.CustomAttributes.Contains(this.compilerGeneratedAttributeType));
            }

            if (isMethodEligibleForInjection)
            {
              // Build an advice based on this custom attribute.
              LogAdvice advice = new LogAdvice(this, attribute);

              // Join point kinds that are used by respective logging code.
              JoinPointKinds enterKinds = (attribute.EntryLevel != LogLevel.None) ? JoinPointKinds.BeforeMethodBody : 0;
              JoinPointKinds exitKinds = (attribute.ExitLevel != LogLevel.None) ? JoinPointKinds.AfterMethodBodySuccess : 0;
              JoinPointKinds exceptionKinds = (attribute.ExceptionLevel != LogLevel.None) ? JoinPointKinds.AfterMethodBodyException : 0;
              // Sum of all required join point kinds;
              JoinPointKinds effectiveKinds = enterKinds | exitKinds | exceptionKinds;

              // Ensure there is at least one join point the logging advice applies to.
              if (effectiveKinds != 0)
              {
                if (!this.perTypeLoggingDatas.ContainsKey(wovenType))
                {

                  AddTypeLogginData(wovenType);
                  codeWeaver.AddTypeLevelAdvice(new LogInitializeAdvice(this),
                                                JoinPointKinds.BeforeStaticConstructor,
                                                new Singleton<TypeDefDeclaration>(wovenType));

                }

                codeWeaver.AddMethodLevelAdvice(advice,
                                                new Singleton<MethodDefDeclaration>(methodDef),
                                                effectiveKinds,
                                                null);
              }
            }
              }
            }
              }

              //Check for types having LoggerAttribute and have no LogAttribute.
              customAttributeEnumerator = customAttributeDictionaryTask.GetAnnotationsOfType(typeof(LoggerAttribute), false);
              while (customAttributeEnumerator.MoveNext())
              {
            // Gets the method to which it applies.
            TypeDefDeclaration wovenType = customAttributeEnumerator.Current.TargetElement as TypeDefDeclaration;
            if (wovenType != null && !perTypeLoggingDatas.ContainsKey(wovenType))
            {
              //Weave
              AddTypeLogginData(wovenType);
              codeWeaver.AddTypeLevelAdvice(new LogInitializeAdvice(this),
                              JoinPointKinds.BeforeStaticConstructor,
                              new Singleton<TypeDefDeclaration>(wovenType));
            }
              }

              //Check for types compatible to LoggerPolicyAttribute and have no LogAttribute.
              customAttributeEnumerator = customAttributeDictionaryTask.GetAnnotationsOfType(typeof(LoggerPolicyAttribute), false);
              while (customAttributeEnumerator.MoveNext())
              {
            // Gets the method to which it applies.
            TypeDefDeclaration wovenType = customAttributeEnumerator.Current.TargetElement as TypeDefDeclaration;
            if (wovenType != null && !wovenType.IsModuleSpecialType && !perTypeLoggingDatas.ContainsKey(wovenType))
            {
              //Weave
              AddTypeLogginData(wovenType);
              codeWeaver.AddTypeLevelAdvice(new LogInitializeAdvice(this),
                    JoinPointKinds.BeforeStaticConstructor,
                    new Singleton<TypeDefDeclaration>(wovenType));
            }
              }
        }
        public void ProvideAdvices(PostSharp.CodeWeaver.Weaver codeWeaver)
        {
            // Gets the dictionary of custom attributes.
            CustomAttributeDictionaryTask customAttributeDictionaryTask = CustomAttributeDictionaryTask.GetTask(this.Project);

            // Requests an enumerator of all instances of the LogAttribute.
            IEnumerator<ICustomAttributeInstance> customAttributeEnumerator = customAttributeDictionaryTask.GetCustomAttributesEnumerator(typeof (LogAttribute), false);

            // For each instance of the LogAttribute.
            while (customAttributeEnumerator.MoveNext()) {
                // Gets the method to which it applies.
                MethodDefDeclaration methodDef = customAttributeEnumerator.Current.TargetElement as MethodDefDeclaration;
                if (methodDef != null) {
                    // Type whose constructor is being woven.
                    TypeDefDeclaration wovenType = methodDef.DeclaringType;

                    // Do not weave interface.
                    if ((wovenType.Attributes & TypeAttributes.Interface) != TypeAttributes.Interface) {
                        // Constructs a custom attribute instance.
                        LogAttribute attribute = (LogAttribute) CustomAttributeHelper.ConstructRuntimeObject(customAttributeEnumerator.Current.Value, this.Project.Module);

                        bool isMethodEligibleForInjection;

                        if (attribute.IncludeCompilerGeneratedCode) {
                            // Logging code can be injected even if the method is compiler generated.
                            // Method processing can safely continue.
                            isMethodEligibleForInjection = true;
                        } else {
                            // Proceed with the method only when it is not compiler generated and
                            // its declaring type is not generated.
                            isMethodEligibleForInjection = ! (methodDef.CustomAttributes.Contains(this.compilerGeneratedAttributeType) || methodDef.DeclaringType.CustomAttributes.Contains(this.compilerGeneratedAttributeType));
                        }

                        if (isMethodEligibleForInjection) {
                            // Build an advice based on this custom attribute.
                            LogAdvice advice = new LogAdvice(this, attribute);

                            // Join point kinds that are used by respective logging code.
                            JoinPointKinds enterKinds = (attribute.EntryLevel != LogLevel.None) ? JoinPointKinds.BeforeMethodBody : 0;
                            JoinPointKinds exitKinds = (attribute.ExitLevel != LogLevel.None) ? JoinPointKinds.AfterMethodBodySuccess : 0;
                            JoinPointKinds exceptionKinds = (attribute.ExceptionLevel != LogLevel.None) ? JoinPointKinds.AfterMethodBodyException : 0;
                            // Sum of all required join point kinds;
                            JoinPointKinds effectiveKinds = enterKinds | exitKinds | exceptionKinds;

                            // Ensure there is at least one join point the logging advice applies to.
                            if (effectiveKinds != 0) {
                                if (!this.perTypeLoggingDatas.ContainsKey(wovenType)) {
                                    this.perTypeLoggingDatas.Add(wovenType, new PerTypeLoggingData());

                                    // Logging data for the woven type.
                                    PerTypeLoggingData perTypeLoggingData = this.perTypeLoggingDatas[wovenType];

                                    // Field where ILog instance is stored.
                                    FieldDefDeclaration logField = CreateField("~log4PostSharp~log", this.ilogType);
                                    wovenType.Fields.Add(logField);
                                    perTypeLoggingData.Log = logField;

                                    codeWeaver.AddTypeLevelAdvice(new LogInitializeAdvice(this),
                                                                  JoinPointKinds.BeforeStaticConstructor,
                                                                  new Singleton<TypeDefDeclaration>(wovenType));
                                }

                                codeWeaver.AddMethodLevelAdvice(advice,
                                                                new Singleton<MethodDefDeclaration>(methodDef),
                                                                effectiveKinds,
                                                                null);
                            }
                        }
                    }
                }
            }
        }