Friday, March 11, 2011

Technologies as Girls

ASP.NET


She is quite easy to please. At her age it's no wonder. If you aren’t looking for anything special – she’s totally yours. A bit of dressing-up and tuning and voilà, you have a girlfriend! But if you're not the kind of guy who loves endless repetitive conversations, you ran into trouble… You’ve got to be a real genius to tell her what you really want to do or to understand what she is saying or can do every now and then. She won’t dance to your tune and she most often likes the things that her parents taught her – there are no ifs ands or buts about it, she affords something new with deep breath. And if, on top of that, you happen to be a man of fashion, then dressing her up will be a great strain on your nerves. So you’d better think before you mess up with her.

ASP.NET MVC

She is young and beautiful. Her mind is not burdened with conventionalities and complex rules, and she doesn’t expect her boyfriend to know all the social graces. She is willing to make all sorts of connections and she can maintain them so that her reputation is impeccable. She changes her opinion and behaviour to be a match for capable partners that stick around. Oh, and by the way, you can keep total control over her wardrobe :-)

WinForms


Sometimes you can look at her and take her for some other girl. They all look the same as if they were from incubator. And they bring an air of old times, of something long forgotten. People hardly ever call them beautiful. All right! She might become beautiful… but then she needs a celebrity make-up artist. But such high-flying professionals would rather court the next girl…

WPF


Wow! She would stop a running horse, and rush in a burning house. She can do nearly anything. More than that: she looks stunning… and wait till you see the way she moves… Yes, she may be weird or naughty at times, but if you manage and tame her, the effect will be astonishing. And the only thing you will have to fight with is the temptation to show your friends all you can do with her.

Silverlight


Rejoice, ye nymphet lovers! WPF's little sister has grown up and even come of age in some way, but she has retained her freshness and tiny frame together with the beauty and smoothness of her movements. Yet unlike WPF, she is far less fussy about rendezvous points, less demanding about your financial well-being and sometimes even willing to change her name. So if you have to leave her for ASP.NET (uh-oh! :-( ), you will keep thinking of that air of freedom you relished in communication with her every time you were unbuttoning her blouse and pondering over what you want her to be like this time.


P.S. Couldn't find photo copyrights. Tried to pick out the copiable ones. Offers welcome!
P.P.S. Huge thanks to Kate Melnikova who did a major work of the translation of this text from Russian.

Thursday, February 17, 2011

Forums are evil?

Don't understand me wrong - I'm not against forums, blogs and other community related activities. I just want to consider one usual situation.
Junior developer faced with a problem. And of course as usual this problem has appeared out of the blue where none could expect and caused by not knowing basics of used technology. What does junior do? Start learning the elements - no! Start trying to dig the technology - no! Today everyone knows the magic word "google", "bing" (etc - insert your favourite search engine). Junior quickly hammer the question into the search box and voilà  - they could get answer on some forums!

And now let's look at forums' contingent and even assume that there are some expers in necessary sophere.

An expert open forum, sees junior's question and moaning "ohh, lamers have completely cowed me" and skips it.
Another junior opens forum, sees the complex (from their point of view) querstion and starts reasoning.

Results usually are regrettable. Answer could be obtained, but there is no guarantee that it would be right. And I repeat - it's not always! And yes, sometimes you can get an answer from the man who thinks in right direction. And sometimes questions are not lame. But all my many years experience of juniors upbringing cries: "Learn the basics!!!"

P.S. There are some communities like experts-exchange, in which it's much easier to find right answers and where much more experts. I was registered there and obtained the status of expert, but it's a pity, to support this status you need time but not all seniors have it :(

So, forums are not evil if you are ready and if it's a right forum :)

RUS: http://asliborsky-ru.blogspot.com/2011/02/blog-post.html

Thursday, December 17, 2009

All Validation Techniques in ASP.NET MVC

Authors and editors: Sergey Khalipsky, Aleksandr Sliborsky
In the first article (Validation Techniques Comparison) we just considered the most useful and the best techniques that could be used for validation implementation in ASP.NET MVC.
We don’t want to deprive you of a pleasure of doing all this by yourself, so we will just give you a direction and some samples of implementation and let you dig deeper .
So, today’s agenda is:
  1. Manual validation in Model Binder and Controllers (client validation type 1 and server validation type 1)
  2. DataAnnotations (client validation type 2, server validation type 2);
  3. Custom Validation engine implementation (client validation type 1, server validation type 2);
  4. Spring Validation Framework usage on a server, manual validation on a client (client validation type 1, server validation type 3)
  5. Spring Validation Framework usage on a server, DataAnnotations + manual validation on a client (it’s a mix from several points from previous review);
  6. xVal Validation Framework
Let’s start fingerscrossed

Tuesday, December 15, 2009

Advanced validation techniques in ASP.NET MVC


Authors and editors: Khalipsky Sergey, Sliborsky Aleksandr

Introduction

When you start development using new technology or framework several questions are arisen: how does it support work with RDBS, how to implement UI better etc.
And, of course, – Validation.
There are several solutions on how to implement validation in the projects based on ASP.NET MVC. When our company first time faced with the ability to implement a solution based on this technology we made an analysis of all viable possibilities. This article and some upcoming articles are the results of those investigations. In this, first article we will consider more theoretical questions and just consider why we have chosen this or that approach in validation. In the next article we will consider implementation of different approaches.

Monday, December 14, 2009

SharePoint Security. Part 1. Introduction


When our company involved into SharePoint development as Security consultants or when we asked to improve legacy system we very often shocked by the level of security of that systems and by the implementation efforts applied to it. Sometimes it seems that all we are working in trust environment where everyone is a saint and there is no thefts, corruptions and other sins.
We prepared the series of articles which should help in security implementation and design in SharePoint portals. This is only the first one from this series.

Monday, December 7, 2009

ASP.NET MVC WebForms vs Spark View Engines. Part 2. Markup

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…

Friday, December 4, 2009

ASP.NET WebForms vs Spark View Engine. Part 1


Preamble

There is no "the best", "one fits all" engine, framework or something else. I didn't try to choose the best, I just tried to investigate the possibilities to have them in mind for line of the upcoming projects and to have a possibility to choose between them depending on the requirements.
Also, I’m not a guru in both engines, I had just made a surface comparison and appreciate any comments, fixes and additions!

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:


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 properties
    foreach (PropertyInfo property in type.GetProperties(bindingFlags))
    {
        ImplementProperty(typeBuilder, type, property, methodMap);
    }
    // override virtual events
    foreach (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 properties
            foreach (PropertyInfo property in type.GetProperties(bindingFlags))
            {
                ImplementProperty(typeBuilder, type, property, methodMap);
            }
            // override virtual events
            foreach (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.

kick it on DotNetKicks.com
Share this Post:

Facebook
Digg DelIcioUs

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:

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 DEBUG
        return 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... :)

kick it on DotNetKicks.com




Share this Post:

Facebook


Digg


DelIcioUs

How to be with config files

Often (more precisely - always) we meet the situation where we should store information in configuration files. But when we commit this files to our Version Control System other developers obtain our settings and try to connect to our DB, web service etc.

How to avoid such situation?

Just use templates.

Instead of commiting Web.config, for example, you create Web.config.template that is the copy of Web.config and commit it.

Then every developer during first obtaining of sources renames template file into necessary one and change configuration parameters.

It also helps with build automation - you store config file with the settings that are good for automation server. During every commit (or by schedule - it depends on how you configure you Continuous Integration server) scripts rename files and compilation and unit testing passed successfully.

One tip: templates should contain such default values that allow to build and run tests successfully without changing them in standard environment.

How to implement a task

Here is I tried to describe what I require from my subordinaries for task implementation.

During obtaining the task it's necessary to do the following:
1. Listen attentively.
2. Think
3. Write a letter in which you should indicate the following:
a) Task description
b) Splitting task to subtasks with short description of solution (if non trivial)
c) Estimation of the task with division to subtasks
4. Send e-mail and start implementation (but only after you fix remarks and bugs or write tests)
5. Approve the task (by receiving comments and approval of estimation)

Task is considered as completed if:
1. Unit tests are written
2. Task is implemented completely.
3. Whats New information file is filled
4. Files are commited to Version Control System.
5. If necessary, correspondent paragraph is added to project knowledge base.

Before starting implementation of the task (after writing task description letter to manager), following steps should be performed:
1. Fix all Critical and Major errors.
2. Fix all remarks that are not marked as POSTPONED

I hope this will help you to organize your work.

Please, advice me what could be improved here.

Thanks.

Tuesday, February 12, 2008

One more Debug.Fail

I wrote about Debug.Fail usage earlier (Debug.Fail). One more usage - in the exception handling routine. You can't throw an exception there because this exception will go to the client and client will be confused. So I recommend not to throw an exception (if e.g. HandleException method obtains null as one of the mandatory arguments) but do something like this:

Debug.Assert (exc == null, "Exception passed to the ExceptionHanlder.HandleException can not be null");
 
or 

if (exc == null)
{
    Debug.Fail("Exception passed to the ExceptionHanlder.HandleException can not be null");
    throw new MeaningfulException();
}

This prevents system from sending wrong confusing exception. Instead of this we can for example send SoapException with the message that operation couldn't be completed.