Posts

Showing posts with the label Interception

AOP through Unity interceptors - Conclusion

We have seen how pleasant could be the programmation with Unity and interceptors. Of course, you can use another IoC framework to achieve what we have done in this series. A good advice would be to use Autofac . This framework has more capabilities than Unity. An other point of attention is performance. Enabling interception is not cost free. You should take care of it: I would advice to measure the impact of enabling/disabling interception.

AOP through Unity interceptors - Cryptography

Today, in our AOP serie, we will use Unity to encrypt/decrypt our data. Let's imagine that you have a repo that stores personal information about users. You may want some of this data to be encrypted, in case your database is stolen, or accessed illegaly. Once again, AOP helps us in this situation. Let's build our sample. We will need an interface & an implementation representing the user repository. public interface IUserRepo     {         bool IsUserAuthenticated(string login, [Encrypt] string password);          [Decrypt]         string GetPasswordForUser(string login);     } public class UserRepoImpl : IUserRepo     {         public bool IsUserAuthenticated(string login, string password)         {             if (password == "1234")                 return false;             return true;         }         public string GetPasswordForUser(string login)         {             return "wOSHX/n2NyWWn53YXVvJIg==";         }     } Using t

AOP through Unity interceptors - Compression

Today we are going to compress our data. We will still use AOP through Unity. The scenario is the following: we have a class generating a huge set of data (in our example, data structure is string). we don't want it to be kept in memory, because we will use it later, or not often. So one solution could be to compress this data & uncompress it once we will really need it. public interface IBigDataRepo     {         string GetData();     }  public class BigDataRepo : IBigDataRepo     {         public string GetData()         {             return new string('X', 100000);         }     } We are going to use is this way: static void Main(string[] args)         {             using (var container = new UnityContainer())             {                 container.AddNewExtension<Interception>();                 // Register                 container.RegisterType<IBigDataRepo, BigDataRepo>(                     new Interceptor<InterfaceInterceptor>(),       

AOP through Unity interceptors - Performance monitoring

Today we continue the serie on AOP with Performance monitoring. The principle is very simple: we want to monitor the time a method took to execute. Here is the code of the class. public class PerformanceMonitoringInterceptionBehavior : IInterceptionBehavior     {         public IEnumerable<Type> GetRequiredInterfaces()         {             return Type.EmptyTypes;         }         public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)         {             Stopwatch sw = Stopwatch.StartNew();             var result = getNext()(input, getNext);             sw.Stop();              WriteLog(String.Format("Method {0} took {1} ms", input.MethodBase, sw.ElapsedMilliseconds));             return result;         }         public bool WillExecute         {             get { return true; }         }         private void WriteLog(string message, string args = null)         {             var utcNow = DateTime.UtcNow;            

AOP through Unity interceptors - Caching

Image
Let's continue our serie on AOP with another popular usage of interception: caching. Let's use the previously created project and add this class: public class CachingInterceptionBehavior : IInterceptionBehavior     {         private static IDictionary<string, MemoryCache> Cache = new Dictionary<string, MemoryCache>();         private static IList<string> SyncLock = new List<string>();         private static object SyncRoot = new object();         public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)         {             if (input.MethodBase.GetCustomAttribute<IgnoreCacheAttribute>() != null)             {                 return getNext()(input, getNext);             }             var arguments = JsonConvert.SerializeObject(input.Arguments);             string key = string.Concat(input.MethodBase.DeclaringType.FullName, "|", input.MethodBase.ToString(), "|", arguments); if (IsInCa

AOP through Unity interceptors - Logging

The first thing we think when talking about interception is logging. Let's see an implementation of a Logger. But before introducing the Logger implementation, let us scaffold a console sample project. public interface IFoo { FooItem GetItem(string name); } public interface IStore { StoreItem Get(int id); IEnumerable<StoreItem> GetAll(); void Save(StoreItem item); void ThrowException(); } public class FooImpl : IFoo { public FooItem GetItem(string name) { return new FooItem { Name = name }; } } public class StoreImpl : IStore { public StoreItem Get(int id) { Thread.Sleep(1000); return new StoreItem { Id = id, Name = "Fake name" }; } public IEnumerables<StoreItem> GetAll() { Thread.Sleep(2000); return new List&ltStoreItem>()

AOP through Unity interceptors - Introduction

Image
Hello, Today we will start a serie of blog posts concerning Aspect Oriented Programming (formely AOP ). This technic is used to have a better separation of concerns in the application you write. Let's take a basic example. When you are writing the implementation of a class that is specialized on a task, you could write someting like this: public class Calculator { public decimal Add(decimal num1, decimal num2) { Console.WriteLine("Entering Add Method"); var result = num1 + num2; Console.WriteLine("Exiting Add Method"); return result; } } The issue with this code is that the logging is part of the method. What will happen if you have a huge quantity of code? You will probably duplicate the logging code across te different class & methods you will write. Moreover, the Add method we wrote is not specialized on a single task: it has two different purpose: it effectly performs an adds operation and it lo