Code Metrics what do they mean?

 

Code metrics is a set of software measures that provide developers better insight into the code they are developing. By taking advantage of code metrics, developers can understand which types and/or methods should be reworked or more thoroughly tested.

What is the preferred score range for the code metrics calculation for the following

  • Maintainability Index
  • Cyclomatic Complexity
  • Depth of Inheritance
  • class Coupling

The theoretically optimal values are:

  • Maintainability index: 100. Higher values indicate better maintainability.
  • Cyclomatic complexity: 1. The number of different paths that code can take.
  • Depth of inheritance: 1. The number of class definitions above this one in the inheritance tree, not including interfaces.
  • Class coupling: 0. Number of other entities this entity is dependent on.

There are no hard and fast “good” ranges, though it’s possible to make some general statements.

  • Having high per-method cyclomatic complexity suggests a method is getting too complicated.
  • Having an inheritance depth more than about 3 or 4 (of your own classes, not the framework’s) is a trouble sign that you may be unnecessarily representing abstract relationships that aren’t really in your software’s domain.
  • Low class coupling is in general better, but sometimes it’s unavoidable. To the extent possible, you should definitely minimise the dependency between namespaces, since there’s much less reason for dependencies here.

A project could only reach all four values simultaneously by essentially doing nothing and being useless: software that does nothing and depends on nothing is certainly maintainable, but not a very good use of client dollars.

Therefore, all complexity is a trade-off: additional so-called inherent complexity encodes more sophistication into the program, allowing it to expand the feature set. What you would like to avoid is accidental complexity introduced by a poor or deficient implementation.

IoC Benchmark

So which is the fastest at different IoC Lifestyles.

In this benchmark we will be running, head to had, with Castle Windsor, Ninject, Spring.NET, Unity, Microsoft DI, AutoFac, and Structure Map.

Here is a working project, this uses NuGet to included the packages, so as time goes on you may find the packages go out of date, so you’ll need to refactor the code to work with the next packages.

I’m using a Parallel test as this represents a closer real life example of how the containers will be used.

ioc-benchmark

 

Differences between Scrum and Kanban

Scrum and Kanban are two terms that are often (incorrectly) used interchangeably or thought to be two sides of the same coin. In reality, there are significant differences between these two Agile methodologies. Understanding these differences is key to choosing the path that will work best for your environment. In a nutshell, what is Scrum? Without getting too detailed, Scrum is a tool used to organise work into small, manageable pieces that can be completed by a cross-functional team within a prescribed time period (called a sprint, generally 2-4 weeks long). To plan, organise, administer, and optimise this process, Scrum relies on at least three prescribed roles: the Product Owner (responsible for initial planning, prioritising, and communication with the rest of the company), the Scrum Master (responsible for overseeing the process during each sprint), and the Team Members (responsible to carry out the purpose of each sprint, such as producing software code.) Another common tool used by scrum teams is the Scrum Board – a visual representation of the work flow, broken down into manageable chunks called “stories”, with each story moved along the board from the “backlog” (the to-do list), into work-in-progress (WIP), and on to completion.

What is Kanban?

Again, scratching the surface, Kanban is also a tool used to organise work for the sake of efficiency. Like Scrum, Kanban encourages work to be broken down into manageable chunks and uses a Kanban Board (very similar to the Scrum Board) to visualise that work as it progresses through the work flow. Where Scrum limits the amount of time allowed to accomplish a particular amount of work (by means of sprints), Kanban limits the amount of work allowed in any one condition (only so many tasks can be ongoing, only so many can be on the to-do list.)

How are Scum and Kanban the same?

Both Scrum and Kanban allow for large and complex tasks to be broken down and completed efficiently. Both place a high value on continual improvement, optimisation of the work and the process. And both share the very similar focus on a highly visible work flow that keeps all team members in the loop on WIP and what’s to come.

How are Scrum and Kanban different?

As alluded to above, there are a number of differences in both the philosophy behind and the practical application of Scrum and Kanban. While the individual differences are many, they can be grouped into the following three buckets:

  • Scheduling
  • Iteration
  • Cadence

Scrum processes place heavy emphasis on schedule. The scrum team is provided with a prioritised list of story points that need to be completed to deliver a shippable product. The team must decide how many of the points they feel can be completed within one sprint. Anything outside the scope they commit to must wait for the next sprint. Optimally, an efficient scrum team will quickly learn their capabilities over the course of several sprints and their estimates will improve and be optimised as time goes on. Then, every two weeks (or however long their sprint is) the team produces a shippable product, carries out a retrospective to discuss optimising the process, and moves into the next sprint. This iterative process is designed to allow for accurate estimations of work flow and effective management of multiple projects. On a Kanban team, there are no required time boxes or iterations. While the Kanban method is iterative in nature, the continual improvement is expected to occur in an evolutionary fashion as work is continually completed. The limitations placed on various conditions in the work flow will be regulated early in a team’s (or organisation’s) use of Kanban until an optimal set of limits is arrived at to keep the flow steady and efficient.

Roles and Responsibilities

On scrum teams, there are at least three roles that must be assigned in order to effectively process the work: the Product Owner, Scrum Master, and Team Members. Each role has its own set of responsibilities, and they must work together to achieve an orderly and efficient balance. The scrum team itself also must be cross-functional, which is to say that one team must have all the resources necessary to complete the entire sprint’s work. Under Kanban, no set roles are prescribed. Practically speaking, it makes sense for someone to serve as a project manager or supervisor, especially for larger more complex Kanban projects, but the roles should theoretically evolve with the needs of the project and the organisation. A Kanban team is not required to be cross-functional since the Kanban work flow is intended to be used by any and all teams involved in the project. Therefore, a team of specialists and a separate team of generalists may be working on different aspects of the same Kanban project from the same board, and that’s okay.

The Board

While very similar, the Scrum Board and Kanban Board are different animals. On a Scrum board, the columns are labelled to reflect periods in the work flow beginning with the sprint backlog and ending with whatever fulfils the team’s definition of done. All the stories added to the board at the beginning of each sprint should be found in the final column at the end of that sprint or the sprint was unsuccessful. After the sprint retrospective, the board is cleared and prepped for the next sprint. On a Kanban board, the columns are likewise labelled to show work flow states, but with one vital difference: they also publish the maximum number of stories allowed in each column at any one time. This enforces the team-determined limitations Kanban prescribes for each condition. Since each column has a limited number of allowed stories and there are no required time boxes (such as sprint length), there is no reason to reset the Kanban board as work progresses. It will continue to flow for as long as the project continues, with new stories being added as the need arises, and completed stories being re-evaluated should it be necessary.

Which is better for your needs?

There’s really no way to answer that question for you in this article. Both Scrum and Kanban are powerful, proven process tools that can vastly improve your project management. The best option is to become familiar with both of them and experiment with various aspects of both in your production environment. Creating a hybrid of both is perfectly acceptable if that works best for you. For more information about Scrum and Kanban, take a peek inside this webinar and learn how to incorporate these approaches into your overall strategy.

Factory Support Facility

Factory Support Facility allows using factories to create components. This is beneficial when you want to make available as services components that do not have accessible constructor, or that you don’t instantiate, like HttpContext.

Prefer UsingFactoryMethod over this facility: while the facility provides programmatic API it is deprecated and its usage is discouraged and won’t be discussed here. Recommended approach is to use UsingFactoryMethod method of fluent registration API to create components. This limits the usefulness of the facility to XML-driven and legacy scenarios.

UsingFactoryMethod does not require this facility anymore: In older versions of Windsor (up to and including version 2.1) UsingFactoryMethod method in the fluent API discussed above required this facility to be active in the container. That was later changed and there’s no such dependency anymore.

Using factories from configuration

In addition to code, the facility uses XML configuration. You can register the facility in the standard facilities section of Windsor’s config:

Just install the facility and add the proper configuration.

<configuration>
 <facilities>
   <facility
     id="factory.support"
     type="Castle.Facilities.FactorySupport.FactorySupportFacility, 
           Castle.Facilities.FactorySupport" />
  </facilities>
</configuration>

Configuration Schema

Broadly speaking facility exposes the following scheme, with two kinds of supported factories: accessors and methods

<components>
 <component id="mycomp1" instance-accessor="Static accessor name" />
 <component id="factory1" />
 <component id="mycomp2" factoryId="factory1" factoryCreate="Create" />
</components>

Accessor example

Given the following singleton class:

public class SingletonWithAccessor
{
 private static readonly SingletonWithAccessor instance = new SingletonWithAccessor();

private SingletonWithAccessor()
 {
 }

public static SingletonWithAccessor Instance
 {
 get { return instance; }
 }
}

You may expose its instance to the container through the following configuration:

<components>
 <component id="mycomp1"
 type="Company.Components.SingletonWithAccessor, Company.Components"
 instance-accessor="Instance" />
</components>

Using it:

var comp = container.Resolve<SingletonWithAccessor>("mycomp1");

Factory example

Given the following component and factory classes:

public class MyComp
{
 internal MyComp()
 {
 }

...
}

public class MyCompFactory
{
 public MyComp Create()
 {
 return new MyComp();
 }
}

You may expose its instance to the container through the following configuration:

<components>
 <component id="mycompfactory"
 type="Company.Components.MyCompFactory, Company.Components"/>
 <component id="mycomp"
 type="Company.Components.MyComp, Company.Components"
 factoryId="mycompfactory" factoryCreate="Create" />
</components>

Using it:

var comp = container.Resolve<MyComp>("mycomp");

Factory with parameters example

Given the following component and factory classes:

public class MyComp
{
 internal MyComp(String storeName, IDictionary props)
 {
 }

...
}

public class MyCompFactory
{
 public MyComp Create(String storeName, IDictionary props)
 {
 return new MyComp(storeName, props);
 }
}

You may expose its instance to the container through the following configuration:

<components>
 <component id="mycompfactory"
 type="Company.Components.MyCompFactory, Company.Components"/>
 <component id="mycomp"
 type="Company.Components.MyComp, Company.Components"
 factoryId="mycompfactory" factoryCreate="Create">
 <parameters>
 <storeName>MyStore</storeName>
 <props>
 <dictionary>
 <entry key="key1">item1</entry>
 <entry key="key2">item2</entry>
 </dictionary>
 </props>
 </parameters>
 </component>
</components>

Using it:

var comp = container.Resolve<MyComp>("mycomp");

Factory using auto-wire example

If your factory request as parameter some other component instance, this facility will be able to resolve it without your aid:

public class MyComp
{
 internal MyComp(IMyService serv)
 {
 }

...
}

public class MyCompFactory
{
 public MyComp Create(IMyService service)
 {
 return new MyComp(service);
 }
}

You may expose its instance to the container through the following configuration:

<facilities>
 <facility
 id="factorysupport"
 type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Facilities.FactorySupport"/>
</facilities>

<components>
 <component id="myservice"
 service="SomethingElse.IMyService"
 type="Company.Components.MyServiceImpl, Company.Components" />
 <component id="mycompfactory"
 type="Company.Components.MyCompFactory, Company.Components" />
 <component id="mycomp"
 type="Company.Components.MyComp, Company.Components"
 factoryId="mycompfactory" factoryCreate="Create" />
</components>

Using it:

var comp = container.Resolve<MyComp>("mycomp");

 

Registering components for IoC

Inversion of Control (IoC) is quite a big step for some developers, but the benefits once implemented are huge.  With the applications performance, maintainability, unit testing and more importantly separation of concerns, just to name a few.

Due to the nature and the new concept of IoC to many of the developers, I would strongly recommend that you take some time to go over these two PluralSight course that go into IoC in a lot more detail that we can cover here.   There are other courses that also cover IoC available on PluralSights, but these are the two I would recommend.
Inversion of Control – by John Sonmez
A comprehensive look at inversion of control and how to use common IoC containers
Practical IoC With ASP.NET MVC 4 – by John Sonmez
In this course, we’ll learn how to use an IoC container, like Unity in an ASP.NET MVC 4 application and some of the basics of the practical application of IoC containers.

Basic Registration

The starting point for registering anything in the container is the container’s Register method, with has one or more IRegistration objects as parameter. The simplest way to create those objects is using the static Castle.MicroKernel.Registration.Component class. Its For method returns a ComponentRegistration that you can use to further configure the registration.

Isolate your registration code: It is a recommended practice to keep your registration code in a dedicated class(es) implementing IWindsorInstaller.

Install infrastructure components first: Some components may require a facility or other extension to the core container to be registered properly. As such it is recommended that you always register your facilities, custom subsystems, Component model creation contributors etc before you start registering your components.

To register a type in the container

container.Register(
	Component.For(MyServiceImpl) );

This will register type MyServiceImpl as service MyServiceImpl with default lifestyle (Singleton).

To register a type as non-default service

container.Register(
    Component.For(IMyService).ImplementedBy(MyServiceImpl));

Note that For and ImplementedBy also have non-generic overloads.

// Same result as example above.
container.Register(Component.For(typeof(IMyService))
    .ImplementedBy(typeof(MyServiceImpl))
);

Services and Components: You can find more information about services and components here.

To register a generic type

Suppose you have a IRepository<TEntity> interface, with NHRepository<TEntity> as the implementation.

You could register a repository for each entity class, but this is not needed.

// Registering a repository for each entity is not needed.
container.Register(
    Component.For<IRepository<Customer>>()
        .ImplementedBy<NHRepository<Customer>>(),
    Component.For<IRepository<Order>>()
        .ImplementedBy<NHRepository<Order>>(),
//    and so on...
);


One IRepository<> (so called open generic type) registration, without specifying the entity, is enough.

// Does not work (compiler won't allow it):
 container.Register(
     Component.For<IRepository<>>()
         .ImplementedBy<NHRepository<>>()
 );

Doing it like this however is not legal, and the above code would not compile. Instead you have to use typeof()

// Use typeof() and do not specify the entity:
container.Register(
     Component.For(typeof(IRepository<>))
         .ImplementedBy(typeof(NHRepository<>))
);

Configuring component’s lifestyle

container.Register(
 Component.For<IMyService>()
 .ImplementedBy<MyServiceImpl>()
 .LifeStyle.Transient
);

When the lifestyle is not set explicitly, the default Singleton lifestyle will be used.

Register more components for the same service

You can do this simply by having more registrations for the same service.

container.Register(
    Component.For<IMyService>().ImplementedBy<MyServiceImpl>(),
    Component.For<IMyService>().ImplementedBy<OtherServiceImpl>()
);

When a component has a dependency on IMyService, it will by default get the IMyService that was registered first (in this case MyServiceImpl).

In Windsor first one wins: In Castle, the default implementation for a service is the first registered implementation.

You can force the later-registered component to become the default instance via the method IsDefault.

container.Register(
    Component.For<IMyService>().ImplementedBy<MyServiceImpl>(),
    Component.For<IMyService>().Named("OtherServiceImpl")
        .ImplementedBy<OtherServiceImpl>().IsDefault()
);

In the above example, any component that has a dependency on IMyService, will by default get an instance of OtherServiceImpl, even though it was registered later.

Of course, you can override which implementation is used by a component that needs it. This is done with service overrides.

When you explicitly call container.Resolve<IMyService>() (without specifying the name), the container will also return the first registered component for IMyService (MyServiceImpl in the above example).

Provide unique names for duplicated components: If you want to register the same implementation more than once, be sure to provide different names for the registered components.

Using a delegate as component factory

You can use a delegate as a lightweight factory for a component:

container.Register(
    Component.For<IMyService>()
        .UsingFactoryMethod(
            () => MyLegacyServiceFactory.CreateMyService())
);

UsingFactoryMethod method has two more overloads, which can provide you with access to kernel, and creation context if needed.

Example of UsingFactoryMethod with kernel overload (Converter)

container.Register(
    Component.For<IMyFactory>().ImplementedBy<MyFactory>(),
        Component.For<IMyService>()
            .UsingFactoryMethod(kernel => kernel.Resolve<IMyFactory>().Create())
);

In addition to UsingFactoryMethod method, there’s a UsingFactory method. (without the “method” suffix 🙂 ). It can be regarded as a special version of UsingFactoryMethod method, which resolves an existing factory from the container, and lets you use it to create instance of your service.

container.Register(
    Component.For<User>().Instance(user),
         Component.For<AbstractCarProviderFactory>(),
         Component.For<ICarProvider>()
             .UsingFactory((AbstractCarProviderFactory f) =>
                f.Create(container.Resolve<User>()))
);

Avoid UsingFactory: It is advised to use UsingFactoryMethod, and to avoid UsingFactory when creating your services via factories. UsingFactory will be obsoleted/removed in future releases.

OnCreate

It is sometimes needed to either inspect or modify created instance, before it is used. You can use OnCreate method to do this

container.Register(
   Component.For<IService>()
       .ImplementedBy<MyService>()
       .OnCreate((kernel, instance) => instance.Name += "a")
);

The method has two overloads. One that works with a delegate to which an IKernel and newly created instance are passed. Another only takes the newly created instance.

OnCreate works only for components created by the container: This method is not called for components where instance is provided externally (like when using Instance method). It is called only for components created by the container. This also includes components created via certain facilities (Remoting Facility, Factory Support Facility)

A good source of reference is the Castle Windsor documentation, which can be found here:

https://github.com/castleproject/Windsor/tree/master/docs

Here is a sample project with examples and a MVC application showing how it all works

castle windsor

Introduction to IoC with Windsor

I do love dependency injection, but many developers still seem to miss the point and the reason for having it. If you’re only using it on a small scale, you don’t really need any tools to use the technique. But once you’re used to this design technique, you’ll quickly start using it in many places of your code. If you do, it quickly becomes cumbersome to deal with the real instances of your runtime dependencies manually. This is where tools like Inversion Of Control (IoC) containers come in to play. There are a few solid containers available for the .NET world, and even Microsoft has released their own container. Basically, what the IoC container does for you, is take care of providing dependencies to components in a flexible and customizable way. It allows clients to remain completely oblivious to the dependencies of components they use. This makes it easy to change components without having to modify client code. Not to mention the fact that your components are a lot easier to test, since you can simply inject fake dependencies during your tests.

Lets get do to looking at a sample. Suppose we have a class called OrderRepository which exposes methods such as GetById, GetAll, FindOne, FindMany and Store. Obviously, the OrderRepository has a dependency on a class that can actually communicate with some kind of physical datastore, either a database or an xml file or whatever. Either way, it needs another object to access the Order data. Suppose we have an OrderAccessor class which implements an IOrderAccessor interface. The interface declares all the methods we need to retrieve or store our Orders. So our OrderRepository would need to communicate with an object that implements the IOrderAccessor interface. Instead of letting the OrderRepository instantiate that object itself, it will receive it as a parameter in it’s constructor:

        private readonly IOrderDataAccessor _accessor;

        public OrderRepository(IOrderDataAccessor accessor)

        {

            _accessor = accessor;

        }

This makes it easy to test the OrderRepository class, and it’s also easy to make it use different implementations of IOrderDataAccessor later on, should we need to. Now obviously, you really don’t want to do this when you need to instantiate the OrderRepository in your production code:

OrderRepository repo = new OrderRepository(new OrderDataAccessor());

As a consumer of the OrderRepository, you shouldn’t need to know what its dependencies are and you most certainly shouldn’t need to pass the right dependencies into the constructor. Instead, you just want a valid instance of OrderRepository. You really don’t care how it was constructed, which dependencies it has and how they’re provided. You just need to be able to use it. That’s all. This is where the IoC container comes in to help you. Suppose we wrap the IoC container in a Container class that has a few static methods to help you with instantiating instances of types. We could then do this:

OrderRepository repository = Container.Resolve<OrderRepository>();

That would leave you with a valid OrderRepository instance… one that has a usable IOrderDataAccessor but you don’t even know about it, nor do you care how it got there. In other words, you can use the OrderRepository without knowing anything about its underlying implementation.

Let’s take a look at the implementation of the Container class:

    public static class Container

    {

        private static readonly IWindsorContainer _container;

        static Container()

        {

            _container = new WindsorContainer();

            _container.Register(Component.For<IOrderDataAccessor>).ImplementedBy<OrderDataAccessor>());

_container.Register(Component.For<OrderRepository>).ImplementedBy<OrderRepository>());

        }

        public static T Resolve<T>()

        {

            return _container.Resolve<T>();

        }

    }

It just uses a static instance of Windor’s Container and it registers the types we need… let’s examine the following line:

_container.Register(Component.For<IOrderDataAccessor>).ImplementedBy<OrderDataAccessor>());

this basically sets up the container to return a new instance of OrderDataAccessor whenever an instance of IOrderDataAcessor is requested.

We still have to make sure the Windsor container knows about the OrderRepository class by adding it as a known component like this:

_container.Register(Component.For<OrderRepository>).ImplementedBy<OrderRepository>());

By doing this, the Windsor container will inspect the type (in this case, OrderRepository) and it will see that its constructor requires an IOrderDataAccessor instance. We ‘registered’ the IOrderDataAccessor type with the container to return an instance of the OrderDataAccessor type. So basically, whenever someone asks the container to return an instance of an OrderRepository class, the container knows to instantiate an OrderDataAccessor instance to pass along as the required IOrderDataAccessor object to the OrderRepository constructor.

At this point, you may be wondering: “Why go through all this trouble to register the concrete implementation of IOrderDataAccessor to be used in code? We could just as well instantiate the type ourselves!”. That’s certainly true. The code would be slightly uglier, but you’d get the same behavior. Of course, the Windsor container supports XML configuration (either in the app.config or web.config or in a custom configuration file) as well as explicit configuration through code. So you can configure the container through code explicitly, but if there is a config file present, the container will use that configuration instead of the one provided through code. So you could define the defaults in code, and should you need to change it later on, you can just provide a config file.

You know what bothers me about our current implementation? We’re still communicating with an OrderRepository instance. If we wanna be really flexible, it would be better if we were communicating with an object that implemented an IOrderRepository interface. So let’s just define the following interface:

    public interface IOrderRepository

    {

        Order GetById(Guid id);

        IEnumerable<Order> GetAll();

        Order FindOne(Criteria criteria);

        IEnumerable<Order> FindMany(Criteria criteria);

        void Store(Order order);

    }

After all, that’s all we care about as consumers of a IOrderRepository type. We shouldn’t really care about the concrete implementation. We just need an interface to program to. So let’s change the OrderRepository definition to this:

    public class OrderRepository : IOrderRepository

And then when we configure our IoC container we do it like this:

        static Container()

        {

            _container = new WindsorContainer();

            _container.Register(Component.For<IOrderDataAccessor>).ImplementedBy<OrderDataAccessor>());

_container.Register(Component.For<IOrderRepository>).ImplementedBy<OrderRepository>());

        }

Now we can no longer ask the contianer for an OrderRepository interface. But we can ask for an instance that implements the IOrderRepository interface like this:

IOrderRepository repository = Container.Resolve<IOrderRepository>();

So now our client is completely decoupled from the implementation of IOrderRepository, as well as the dependencies it may or may not have.

Ok, lets suppose that this implementation makes it to the production environment. Everything’s working but for some reason, someone makes a decision to retrieve the orders from a specially prepared XML file instead of the database. Unfortunately, your OrderDataAccessor class communicates with a SQL server database. Luckily, the OrderRepository implementation doesn’t know which specific implementation of IOrderDataAccessor it’s using. We just need to make sure that every time someone needs an IOrderRepository instance, it uses the new xml-based IOrderDataAccessor implementation instead of the one we originally intended.

Because we’re using Dependency Injection and an IoC container, this only requires changing one line of code:

_container.Register(Component.For<IOrderDataAccessor>().ImplementedBy<XmlOrderDataAccessor>());

Actually, if we’d put the mapping between the IOrderDataAccessor type and the XmlOrderDataAccessor implementation in an xml file, we wouldn’t even have to change any code! Well, except for the XmlOrderDataAccessor implementation obviously.

We can even take this one step further… After the change to the xml-based OrderDataAccessor went successfully, they (the ‘business’) all of a sudden want to log who retrieves or saves each order for auditing purposes.

We create an implementation of IOrderRepository which keeps extensive auditing logs so they can be retrieved later on. We could just inherit from the default OrderRepository implementation and add auditing logic before each method is executed. Then we’d only have to configure our IoC container to return a different instance of the IOrderRepository type whenever someone requests it:

        static Container()

        {

            _container = new WindsorContainer();

            _container.Register(Component.For<IOrderDataAccessor>().ImplementedBy<XmlOrderDataAccessor>());

            _container.Register(Component.For<IOrderRepository>().ImplementedBy<OrderRepositoryWithAuditing>());

        }

Again, our client code does not need to be modified in any way, yet we did modify the runtime behavior of the application. Instead of retrieving the Orders from a SQL database, it’s now retrieving them from an XML file, and the repository is performing auditing as well, without having to change any client code.

And if we were using the xml-configuration features of Windsor, we could get all of this working without even having to recompile the client-assemblies.

This was just an introduction to using an IoC contianer (Castle’s Windsor specifically) and we briefly touched on benefits that you can achieve with this way of working. The Windsor container can do much more, but you’ll either have to figure that stuff out yourself, or wait for future posts about its other features/possibilities

Updated with new methods and calls for Castle Windsor

Object to CSV extension

Here is a nice little extension that will take an object and convert it into a CSV file.

Also has the option if you want to include a header on the CSV file.

public static class ObjectToCsv
 {
 public static string ToCsv<T>(this IEnumerable<T> items, bool includeHeading = true)
 where T : class
 {
 var csvBuilder = new StringBuilder();
 var properties = typeof(T).GetProperties();

 if (includeHeading)
 {
 csvBuilder.AppendLine(string.Join(",", properties.Select(p => p.Name.ToCsvValue()).ToArray()));
 }

 foreach (var item in items)
 {
 var line = string.Join(",", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
 csvBuilder.AppendLine(line);
 }
 return csvBuilder.ToString();
 }

 private static string ToCsvValue<T>(this T item)
 {
 if (item == null) return "\"\"";

 if (item is string)
 {
 return $"\"{item.ToString().Replace("\"", "\\\"")}\"";
 }
 double dummy;
 return double.TryParse(item.ToString(), out dummy) ? $"{item}" : $"\"{item}\"";
 }
 }

OWASP Testing Guide v3

Every vibrant technology marketplace needs an unbiased source of information on best practices as well as an active body advocating open standards. In the Application Security space, one of those groups is the Open Web Application Security Project (or OWASP for short).

The Open Web Application Security Project (OWASP) is a 501(c)(3) worldwide not-for-profit charitable organization focused on improving the security of software. Our mission is to make software security visible, so that individuals and organizations are able to make informed decisions. OWASP is in a unique position to provide impartial, practical information about AppSec to individuals, corporations, universities, government agencies and other organizations worldwide. Operating as a community of like-minded professionals, OWASP issues software tools and knowledge-based documentation on application security.

The entire Open Web Application Security Project (OWASP) Testing Guide v3 can be downloaded here

Testing for Vulnerable Remember Password and Password Reset

Brief Summary

Most web applications allow users to reset their password if they have forgotten it, usually by sending them a password reset email and/or by asking them to answer one or more “security questions.” In this test, we check that this function is properly implemented and that it does not introduce any flaw in the authentication scheme. We also check whether the application allows the user to store the password in the browser (“remember password” function).

Description of the Issue

A great majority of web applications provide a way for users to recover (or reset) their password in case they have forgotten it. The exact procedure varies heavily among different applications, also depending on the required level of security, but the approach is always to use an alternate way of verifying the identity of the user. One of the simplest (and most common) approaches is to have on file the user’s email address (e.g., this is obtained when the user first registers), and send the old password (or a new one) to that address. This scheme is based on the assumption that the user’s email has not been compromised and that is secure enough for this goal.
Alternatively (or in addition to that), the application could ask the user to answer one or more “secret questions”, which are usually chosen by the user among a set of possible ones. The security of this scheme lies in the ability to provide a way for someone to identify themselves to the system with answers to questions that are not easily answerable via personal information lookups. As an example, a very insecure question would be “your mother’s maiden name” since that is a piece of information that an attacker could find out without much effort. An example of a better question would be “favorite grade-school teacher” since this would be a much more difficult topic to research about a person whose identity may otherwise already be stolen.
Another common feature that applications use to provide users a convenience is to cache the password locally in the browser (on the client machine) and having it ‘pre-typed’ in all subsequent accesses. While this feature can be perceived as extremely friendly for the average user, at the same time, it introduces a flaw, as the user account becomes easily accessible to anyone that uses the same account on the client machine.

Black Box Testing and Examples

Password Reset
The first step is to check whether secret questions are used. Sending the password (or a password reset link) to the user email address without first asking for a secret question means relying 100% on the security of that email address, which is not suitable if the application needs a high level of security.
On the other hand, if secret questions are used, the next step is to assess their strength.
As a first point, how many questions need to be answered before the password can be reset? The majority of applications only need the user to answer to one question, but some critical applications require the user to answer correctly to two or even more questions.
As a second step, we need to analyze the questions themselves. Often a self-reset system offers the choice of multiple questions; this is a good sign for the would-be attacker as this presents him/her with options. Ask yourself whether you could obtain answers to any or all of these questions via a simple Google search on the Internet or with a social engineering attack. As a penetration tester, here is a step-by-step walk-through of assessing a password self-reset tool:

  • Are there multiple questions offered?
    • If so, try to pick a question which would have a “public” answer; for example, something Google would find with a simple query
    • Always pick questions which have a factual answer such as a “first school” or other facts which can be looked up
    • Look for questions which have few possible options, such as “what make was your first car”. These questions would present the attacker with a short-list of answers to guess at and based on statistics the attacker could rank answers from most to least likely
  • Determine how many guesses you have (if possible)
    • Does the password reset allow unlimited attempts?
    • Is there a lockout period after X incorrect answers? Keep in mind that a lockout system can be a security problem in itself, as it can be exploited by an attacker to launch a Denial of Service against legitimate users
  • Pick the appropriate question based on analysis from above point, and do research to determine the most likely answers
  • How does the password-reset tool (once a successful answer to a question is found) behave?
    • Does it allow immediate change of the password?
    • Does it display the old password?
    • Does it email the password to some pre-defined email address?
    • The most insecure scenario here is if the password reset tool shows you the password; this gives the attacker the ability to log into the account, and unless the application provides information about the last login the victim would not know that his/her account has been compromised.
    • A less insecure scenario is if the password reset tool forces the user to immediately change his/her password. While not as stealthy as the first case, it allows the attacker to gain access and locks the real user out.
    • The best security is achieved if the password reset is done via an email to the address the user initially registered with, or some other email address; this forces the attacker to not only guess at which email account the password reset was sent to (unless the application tells that) but also to compromise that account in order to take control of the victim’s access to the application.

The key to successfully exploiting and bypassing a password self-reset is to find a question or set of questions which give the possibility of easily acquiring the answers. Always look for questions which can give you the greatest statistical chance of guessing the correct answer, if you are completely unsure of any of the answers. In the end, a password self-reset tool is only as strong as the weakest question. As a side note, if the application sends/visualizes the old password in cleartext it means that passwords are not stored in a hashed form, which is a security issue in itself.

Password Remember

The “remember my password” mechanism can be implemented with one of the following methods:

  1. Allowing the “cache password” feature in web browsers. As of 2014 this is the preferred method as all major browsers have disabled the setting of autocomplete=”off” by default for password fields.
  2. Storing the password in a permanent cookie. The password must be hashed/encrypted and not sent in the clear.

To check the second implementation type, examine the cookies stored by the application. Verify that the credentials are not stored in cleartext, but are hashed. Examine the hashing mechanism: if it is a common, well-known algorithm, check for its strength; in homegrown hash functions, attempt several usernames to check whether the hash function is easily guessable. Additionally, verify that the credentials are only sent during the login phase, and not sent together with every request to the application.

Gray Box Testing and Examples

This test uses only functional features of the application and HTML code that is always available to the client, the graybox testing follows the same guidelines of the previous section. The only exception is for the password encoded in the cookie, where the same gray box analysis described in the Testing for Session Management Schema chapter can be applied.

Original Article