In my previous article (ASP.NET MVC WebForms vs Spark View Engine. Part 1) I had started to describe the differences between standard ASP.NET MVC View Engine and spark. In this short article I will just show the differences between implementation of 3 equal pages.
So, less words, more code…
This blog is about my development experience, my ideas and any things that are related to the development process.
Showing posts with label code. Show all posts
Showing posts with label code. Show all posts
Monday, December 7, 2009
Monday, September 22, 2008
What's wrong with Spring.Net Interceptors?
When I began using of Spring.Net interceptors part of my code stopped working! For example such code:
Before I added interceptor all were OK. I could save entity and no exception was occurred.
After some investigation I've found the problem: intercepted target object has right value of this property but proxy object does not expose it!
Finally I opened Spring.Net sources and found the Spring.Proxy.AbstractProxyTypeBuilder's InheritType method the proxies my class:
As you can see, Spring's default implementation creates proxy just for publicly published interfaces of the class. So first obvious solution is to mark all properties "public" instead of "protected". But this is unacceptable because of different reasons: huge reworking and (what is more important) encapsulation violation.
So I've decided to just reimplement this solution. This is quite easy with DI and Spring.Net. Simply follow the steps:
1. Create custom ProxyTypeBuilder.
2. Create custom ProxyFactory
3. Register ProxyFactory in configs.
As you can see I've added extra BindingFlags. This will allow to find and proxy not only public properties and methods.
Just inherit from one of the implemented Proxy factories and reimplement CreateAopProxy method:
Here we just replace creation of ProxyTypeBuilder with our own CustomInheritanceProxyTypeBuilder. Of course, you can parametrize you ProxyFaxtory to accept type of the ProxyTypeBuilder. I do not implement this functionality for simplicity.
As last step we need to define what IAopProxyFactory implementation will be used. For this purpose write in the configuration file the following:
That's it. Now we just need to define the reference to our ProxyFactory implementation. For example:
I hope this will help you. And you will help me to find easier and more clearer solution.

Share this Post:

public class POBlo
{private IDataProvider _dataProvider = null;
// Yes, I know about auto property :)protected virtual IDataProvider DataProvider
{get { return _dataProvider; }
set { _dataProvider = value; }
}
public virtual void Save (Entity entity)
{ // Here we have NullReferenceException :(DataProvider.Save (entity);
}
}
Before I added interceptor all were OK. I could save entity and no exception was occurred.
After some investigation I've found the problem: intercepted target object has right value of this property but proxy object does not expose it!
Finally I opened Spring.Net sources and found the Spring.Proxy.AbstractProxyTypeBuilder's InheritType method the proxies my class:
protected virtual void InheritType(TypeBuilder typeBuilder,
IProxyMethodBuilder proxyMethodBuilder, Type type, bool declaredMembersOnly)
{IDictionary methodMap = new Hashtable();
IList finalMethods = new ArrayList();
BindingFlags bindingFlags = BindingFlags.Public BindingFlags.Instance;
if (declaredMembersOnly) { bindingFlags = BindingFlags.DeclaredOnly;}
// override virtual methods MethodInfo[] methods = type.GetMethods(bindingFlags);foreach (MethodInfo method in methods)
{ if (method.IsVirtual && !method.IsFinal) {MethodBuilder methodBuilder = proxyMethodBuilder.BuildProxyMethod(method, null);
ApplyMethodAttributes(methodBuilder, method);
methodMap[method.Name] = methodBuilder;
}
}
// override virtual propertiesforeach (PropertyInfo property in type.GetProperties(bindingFlags))
{ImplementProperty(typeBuilder, type, property, methodMap);
}
// override virtual eventsforeach (EventInfo evt in type.GetEvents(bindingFlags))
{ImplementEvent(typeBuilder, type, evt, methodMap);
}
}
As you can see, Spring's default implementation creates proxy just for publicly published interfaces of the class. So first obvious solution is to mark all properties "public" instead of "protected". But this is unacceptable because of different reasons: huge reworking and (what is more important) encapsulation violation.
So I've decided to just reimplement this solution. This is quite easy with DI and Spring.Net. Simply follow the steps:
1. Create custom ProxyTypeBuilder.
2. Create custom ProxyFactory
3. Register ProxyFactory in configs.
Create custom ProxyTypeBuilder
Create custom proxy type builder where we define necessary binding flags.using System;using System.Collections;using System.Reflection;using System.Reflection.Emit;using Spring.Aop;using Spring.Aop.Framework;using Spring.Aop.Framework.DynamicProxy;using Spring.Proxy;namespace Qulix.Spring.Aop{///
/// Implements proxy type builder that uses inheritance and exposes not only public methods
///
[CLSCompliant(false)]
public class CustomInheritanceProxyTypeBuilder : DecoratorAopProxyTypeBuilder
{ #region IProxyTypeBuilder Members[CLSCompliant(false)]
protected override void InheritType(TypeBuilder typeBuilder,
IProxyMethodBuilder proxyMethodBuilder, Type type, bool declaredMembersOnly)
{IDictionary methodMap = new Hashtable();
BindingFlags bindingFlags = BindingFlags.NonPublic BindingFlags.Public BindingFlags.Instance;
if (declaredMembersOnly) { bindingFlags = BindingFlags.DeclaredOnly;}
// override virtual methods MethodInfo[] methods = type.GetMethods(bindingFlags);foreach (MethodInfo method in methods)
{ if (method.IsVirtual && !method.IsFinal) {MethodBuilder methodBuilder = proxyMethodBuilder.BuildProxyMethod(method, null);
ApplyMethodAttributes(methodBuilder, method);
methodMap[method.Name] = methodBuilder;
}
}
// override virtual propertiesforeach (PropertyInfo property in type.GetProperties(bindingFlags))
{ImplementProperty(typeBuilder, type, property, methodMap);
}
// override virtual eventsforeach (EventInfo evt in type.GetEvents(bindingFlags))
{ImplementEvent(typeBuilder, type, evt, methodMap);
}
}
#endregion}
}
As you can see I've added extra BindingFlags. This will allow to find and proxy not only public properties and methods.
Create custom proxy factory
Just inherit from one of the implemented Proxy factories and reimplement CreateAopProxy method:
[Serializable][CLSCompliant(false)]
public class InheritanceAopProxyFactory : DefaultAopProxyFactory
{[CLSCompliant(false)]
public override IAopProxy CreateAopProxy(AdvisedSupport advisedSupport)
{if (advisedSupport == null)
{throw new AopConfigException("Cannot create IAopProxy with null ProxyConfig");
}
if (advisedSupport.Advisors.Length == 0 && advisedSupport.TargetSource == EmptyTargetSource.Empty)
{throw new AopConfigException("Cannot create IAopProxy with no advisors and no target source");
}
IProxyTypeBuilder typeBuilder = new CustomInheritanceProxyTypeBuilder(advisedSupport);
Type aopProxy = BuildProxyType(typeBuilder);ConstructorInfo constructor = aopProxy.GetConstructor(new Type[] { typeof(IAdvised) });
return (IAopProxy)constructor.Invoke(new object[] { advisedSupport });
}
}
Here we just replace creation of ProxyTypeBuilder with our own CustomInheritanceProxyTypeBuilder. Of course, you can parametrize you ProxyFaxtory to accept type of the ProxyTypeBuilder. I do not implement this functionality for simplicity.
Register ProxyFactory in cofig
As last step we need to define what IAopProxyFactory implementation will be used. For this purpose write in the configuration file the following:
<object id="IAopProxyFactory" type="Qulix.Spring.Aop.InheritanceAopProxyFactory, Qulix.Spring" />
That's it. Now we just need to define the reference to our ProxyFactory implementation. For example:
<object id="POBloProxier" type="Spring.Aop.Framework.AutoProxy.ObjectNameAutoProxyCreator, Spring.Aop">
<property name="AopProxyFactory" ref="IAopProxyFactory" />
...
I hope this will help you. And you will help me to find easier and more clearer solution.
Share this Post:
Wednesday, September 17, 2008
Security implementation tips
How do you implement security in your ASP.NET application?
I propose to use AOP and interceptors. Short sample.
You have business logic methods like:
And you don't care about security there. You just do your job: create list of all supported actions and return it in GetActions and execute any supported actions in ExecuteAction. Smart, clear and straightforward.
But where is security? In interceptors.
You create interceptor that wraps these two methods. These interceptor knows about allowed actions and has access to such list of actions.
On every execute of GetActions it intersects List of returned actions with list of allowed actions and returns the result of intersection.
On every execute of ExecuteAction it checks whether action is allowed or not.
So you:
1. Have separate security mechanism that works independently.
2. Do not care about security during business logic development.
3. Can split these tasks and divide them between different people.
4. Can use other tips mentioned below :)
And few more tips with security:
1. Always try to separate logic from security as much as possible. This allows you to separate concerns, divide work and allows developers to concentrate on their narrow task.
2. Add possibility to switch off the security. Sometimes it's necessary to test if error occurred because of business logic failure or security failure. It's hard to do if there is no possibility to switch off security. It's not a hard task but it could save time during testing and stabilization.
3. Remove possibility to switch off security from production version. There is a risk that somebody could change your configuration parameter directly or indirectly and in such way perform leverage privileges attack. To avoid this, remove security switch off from production code. But do not delete code! Just use the following:
4. Avoid possibility to delete last administrator. To prevent system from being "unadministrable" add code that will check all delete operation on subject of is there any administrators in the system or last one is deleted. Or select one "Super Administrator" that could be removed from the system.
5. Make security as fast as possible. Create User permissions tickets to save all user allowed actions, cache actions etc. Security should be quick because may be used often.
6. Check security on business logic level. Do not rely on GUI. On UI level you should concentrate on UI as much as possible and do not make security checks where allowed. Or GUI could be even compromised, or UI developer could forget to exclude operation from UI. Moreover, later customer could ask you to write another client based on current application logic level.
To be continued... :)

I propose to use AOP and interceptors. Short sample.
You have business logic methods like:
public List<Action> GetActions();
public void ExecuteAction(Action action, object data);
And you don't care about security there. You just do your job: create list of all supported actions and return it in GetActions and execute any supported actions in ExecuteAction. Smart, clear and straightforward.
But where is security? In interceptors.
You create interceptor that wraps these two methods. These interceptor knows about allowed actions and has access to such list of actions.
On every execute of GetActions it intersects List of returned actions with list of allowed actions and returns the result of intersection.
On every execute of ExecuteAction it checks whether action is allowed or not.
So you:
1. Have separate security mechanism that works independently.
2. Do not care about security during business logic development.
3. Can split these tasks and divide them between different people.
4. Can use other tips mentioned below :)
And few more tips with security:
1. Always try to separate logic from security as much as possible. This allows you to separate concerns, divide work and allows developers to concentrate on their narrow task.
2. Add possibility to switch off the security. Sometimes it's necessary to test if error occurred because of business logic failure or security failure. It's hard to do if there is no possibility to switch off security. It's not a hard task but it could save time during testing and stabilization.
3. Remove possibility to switch off security from production version. There is a risk that somebody could change your configuration parameter directly or indirectly and in such way perform leverage privileges attack. To avoid this, remove security switch off from production code. But do not delete code! Just use the following:
private bool IsSecurityEnabled
{ get {#if DEBUGreturn Configuration.IsSecurityEnabled;
#else return true;#endif}
}
4. Avoid possibility to delete last administrator. To prevent system from being "unadministrable" add code that will check all delete operation on subject of is there any administrators in the system or last one is deleted. Or select one "Super Administrator" that could be removed from the system.
5. Make security as fast as possible. Create User permissions tickets to save all user allowed actions, cache actions etc. Security should be quick because may be used often.
6. Check security on business logic level. Do not rely on GUI. On UI level you should concentrate on UI as much as possible and do not make security checks where allowed. Or GUI could be even compromised, or UI developer could forget to exclude operation from UI. Moreover, later customer could ask you to write another client based on current application logic level.
To be continued... :)
Friday, January 18, 2008
Debug.Fail
Formerly I thought why should we use Debug.Fail and not to use exception throwing? About a year ago I thought out the case where Debug.Fail will be better than exception throwing. But... I didn't write it down so I've forgotten it :(
But now I want to note an another case:
If we use, for example Abstract Factory of Factory Method we could use Debug.Fail.
Consider the code (it's just a sample to demonstrate one practice not all!):
Than you add some others entities, quantity of them grows quickly. One day (usually it happens right before the build :) ) you add one more entity type and forget to define strategy for it. Oh, damn! Exception is generated. Not good solutions, especially if the function was missed by tester and client will see the exception message.
So, let's rewrite the code:
Now we get an exception only during Debug time no runtime on the customer's side. We just return a strategy that can perform only the minimum set of functionality. May be it's even will be good enough to customer and won't turn into the fatal error that should be fixed ASAP (e.g. minimal menu will contain "Open" and "Delete" items, but won't contain "Call this person" which absence is not critical for customer for a time).
Yes, it's a fake code and a little far-fetched solution. But it works and I think works better in the second case than in first one. And general rule: call Debug.Fail where the developer's mistake that you should cover with some solution, and throw exception in other cases.
But now I want to note an another case:
If we use, for example Abstract Factory of Factory Method we could use Debug.Fail.
Consider the code (it's just a sample to demonstrate one practice not all!):
public IReporter GetStrategy(Type entityType)
{if (entityType == typeof (DictionaryEntity))
{ return SimpleMenuStrategy();}
else if (entityType == typeof (ProgramEntity))
{ return ExtendedMenuStrategy();}
else {throw new ArgumentException("Unknown type of entity" + entityType, "entityType");
}
}
Than you add some others entities, quantity of them grows quickly. One day (usually it happens right before the build :) ) you add one more entity type and forget to define strategy for it. Oh, damn! Exception is generated. Not good solutions, especially if the function was missed by tester and client will see the exception message.
So, let's rewrite the code:
public IReporter GetStrategy(Type entityType)
{if (entityType == typeof (DictionaryEntity))
{ return SimpleMenuStrategy();}
else if (entityType == typeof (ProgramEntity))
{ return ExtendedMenuStrategy();}
else {Debug.Fail("Unknown type of entity" + entityType);
return SimpleMenuStrategy();}
}
Now we get an exception only during Debug time no runtime on the customer's side. We just return a strategy that can perform only the minimum set of functionality. May be it's even will be good enough to customer and won't turn into the fatal error that should be fixed ASAP (e.g. minimal menu will contain "Open" and "Delete" items, but won't contain "Call this person" which absence is not critical for customer for a time).
Yes, it's a fake code and a little far-fetched solution. But it works and I think works better in the second case than in first one. And general rule: call Debug.Fail where the developer's mistake that you should cover with some solution, and throw exception in other cases.
Subscribe to:
Posts (Atom)