CodeProject

Code Analyzing and NDepend

Posted on August 17, 2012. Filed under: .Net, Analyzing And Research, CodeProject, NDepend | Tags: , , |


In my childhood, my uncle has shown me how to see the cloud in a close look and I understand that one can draw some elements of the Earth in the sky-canvas if he/she wants to. After that the cloud becomes more close me and It teaches me one thing that, a deeper-look to something will give you some clues to draw your imagination. You can able to see that one which you have build-up in your mind.

Years past, after completing my graduation, I start my career as a software engineer but I have notice that I have not that much passion in my coding and development which I should be to enjoy my profession and I have started asking myself- am I doing any engineering here? Is my code becoming that thing which I have designed in my mind? So to find that answer I have tried that old solution here. I have decided to come closer to my code start analyzing them. And you know what, it is really working for me and at least it gives me the confidence that I can build something that I really want to. I can draw my thinking there through my code and can build-up my vision that I have designed in my mind. Yes, Code analyzing is an amazing thing. It helps you see your code quality, matrix, design, dependency, naming conversion, purity, visibility, architecture, layering and even the dead codes in your application.

I have started my first code analyzing tool for DOTNET with FXCOP which I have been introduced while I was reading a very nice book– Framework Design Guideline. After that I am hoping to more closer and freedom to go over my code analyzing. I got NDEPEND from Patrick Smacchia who has given me the opportunity to play with NDepend 4. Here I am picking the NDEPND to introduce a tool for analyzing you code.

I found some amazing things here in Ndepend :

Why Analyzing Code Structure, Design, Dependencies? It helps you

  • To avoid dependencies cycles between your components.
  • To know about layering and dependencies issues in your code base.
  • To prevent design erosion of your code base.
  • Care about fabricated complexity and how to reduce it effectively
  • Details the Level metric definition and usage.
  • Through Hints on how to componentize existing code
  • To Know Dependencies and Concerns
  • To Detect All Paths from A to B
  • To Re-factoring, Re-Structuring and the cost of Levelizing
  • Evolutionary Design and Acyclic componentization
  • Understanding Code: Static vs Dynamic Dependencies

Here is the dependency result for one of my Application:

all

Why Build Comparison? It will allow you –

  • To write rules that detects API breaking changes.
  • To focus code review on code that have been changed and added since the last release.
  • To Quality review on code that have been changed and added since a certain milestone.
  • To detect when new or refactored code is poorly covered by tests.

Ok now let me talk about the Code Metrics. In Ndepend I have found Code Metrics on:

– Application

– Assemblies (by measuring coupling between types of your application.)

– Namespaces

– Type

– Method

– Field

clip_image004

clip_image006

Metrics on Application gonna give you the following:

  • Lines of Code (NDepend computes this metric directly from the info provided in PDB files. The LOC for a method is equals to the number of sequence point found for this method in the PDB file. A sequence point is used to mark a spot in the IL code that corresponds to a specific location in the original source.)
  • Lines of Comments( Ndepend needs PDB files present and its corresponding source files)
  • Comment Percentage
  • Lines of code covered
  • Lines of code not covered
  • And all five things mention above ( Assemblies ,Namespaces, Type, methods and Fields)

Metrics on assemblies, Namespaces, Type, methods and Fields(only Afferent Coupling) allow you find two main coupling here on their respective level –

– Afferent Coupling
– Efferent coupling

Other things of Metrics on assemblies
– Relational Cohesion
– Instability
– Abstractness
– Distance from main sequence

Other things of Metrics on Namespaces
– Level(defined for assemblies, namespaces, types, methods)

Other things of Metrics on Type –
– Lack of Cohesion Of Methods
– Cyclomatic Complexity (defined for types, methods)
– IL Cyclomatic Complexity
– Size of instance (defined for instance fields and types)
– Interfaces Implemented
– Number of Children
– Depth of Inheritance Tree

Other things of Metrics on Methods
– IL Nesting Depth
– Parameters
– Variables
– Overloads
– Percentage Branch Coverage

Here is the Matrices result on one of current application:

clip_image008

What more:

Yes, It has lot more things like:

code quality, matrix, design, dependency, naming conversion, purity, visibility, architecture, layering and even the dead codes in your application.

Take a look into this result shot-

clip_image010

And Also thing like:

  • Warnings on Build Process Health
  • Harness Test Coverage Data
  • API and Power tools.

But the most exciting features that I like here is Code Rule and Code Query over LINQ. Its Amazing!!!!! Also it has the intelligence support.

clip_image012

Here are some examples that I have tried to my application

Here in first example I have tried to look into the type, found no of methods and field declared there-

clip_image013

And another example to search all fields which start with a certain string – say Jericho and also export the result into HTML –

Query Result

It seems pretty cool to me that allow me to deep drive into my application.

Hope it will help you to introduce with Ndepend and Code analyzing. Thanks guys for reading Smile.

Advertisements
Read Full Post | Make a Comment ( None so far )

Traversing an object Tree to the end in EF4

Posted on July 16, 2012. Filed under: C#, CodeProject, EF4, Entity Framework | Tags: , , |


Years ago, I read about Golden rule of Entity Framework from a blog post of Julia Lerman.As the Golden Rule says –

EF will not do anything that developer has not explicitly told you to do.

Some days ago I got an issue where I need to load a full object graph will all its relationship. It means I need to load the object with all children and also with grand children of the each child which means I need to traverse the full tree of the object through their relationship/navigation until I will reach to leaf.

For Example, The tree can be represent as:

<Customer>
    ...
    <Orders>
      <Order>
        ...
        <Order_Details>
          </Order_Detail>
          ... .. .. .. .. .. So on.. .. .. (continue)
          </Order_Detail>
          ...
        </Order_Details>
      </Order>
      ...
    </Orders>
  ...
  </Customer> 

Or can be represent as:

Customar

   |

   |

   -----Orders

          |

          |

          ------OrderDetails

|

|________.. .. .. .. So on .. ..(continue)

 

So I don’t know how much depth of the object-tree will be and that’s why I am going to avoid the LINQ way. You can also

do this by disabling the Lazy-loading but POCO entities do not have the same relationship requirements as objects that

inherit from EntityObject, a slightly different process is required to load related objects. Ok, it is a very simple matter

of Recursive solution by loading entity for the each navigation object. To load the navigation property I got

simple and useful method there-

 

ObjectContext.LoadProperty Method (Object, String)

public void LoadProperty(
    Object entity,
    string navigationProperty)
 

Before going into my recursive method, I would like to talk about my Entity. All of my entity is child of “BaseDataContract”

class. While traversing to the object you can set a list of data type also to ignore while traversing them. Here I check the

navigation property whether that is a one or many relationship with current entity. If it is one –then I simply call the

same method that it is currently in Recursive way; otherwise is call another Generic method which calls the Traverse method

for each entity in a collection for many relationship ends.

private ObjectContext _ctx;
private bool IsInheritFromType(Type childType, Type parentType)
        {
            var type = childType;
            while (type.BaseType != null)
            {
                if (type.BaseType.Equals(parentType))
                    return true;

                type = type.BaseType;
            }
            return false;
        }    
        /// <summary>
        /// Traverse to the end and load the related entity. 
        /// </summary>
        /// <param name="entity">Set the entity from which start traversing</param>
        /// <param name="parentType">Set the Parent to ignore the recurtion. For root entity, set it null</param>
        /// <param name="ignoreType">Some Type of entity I want to Ignore</param>
        /// <returns></returns>
        public void TraverseToTheEnd<T>(T entity, Type parentType =null ,Type[] ignoreType =null ) where T : BaseDataContract
        {
            if (null != entity)
            {
                var navigationProperties = _ctx.GetNavigationProperty<T>();
                if (null != navigationProperties)
                {
                    foreach (var navigationProperty in navigationProperties)
                    {
                        var info = entity.GetType().GetProperty(navigationProperty.Name);

                        if (null != info)
                        {
                            Type t = info.PropertyType;
                            if (null == ignoreType || !Array.Exists(ignoreType, i => i.Equals(t)))
                            {
                                if (((AssociationType) navigationProperty.RelationshipType).IsForeignKey)
                                {
                                    _ctx.LoadProperty(entity, navigationProperty.Name);

                                    var value = info.GetValue(entity, null);
                                    if (value != null)
                                    {
                                        Type baseType;
                                        if (!t.IsGenericType)
                                        {
                                            #region One to One or Zero

                                            baseType = t.BaseType;
                                            if (null != baseType && (parentType == null || !t.Equals(parentType))
                                                //avoid the recursion, dont back to parent 
                                                && baseType.BaseType != null
                                                && IsInheritFromType(baseType, typeof (BaseDataContract)))
                                            {
                                                //Traverse each child
                                                MethodInfo method = this.GetType().GetMethod("TraverseToTheEnd");
                                                MethodInfo generic = method.MakeGenericMethod(t);
                                                generic.Invoke(this, new object[] {value, typeof (T), ignoreType});
                                            }

                                            #endregion
                                        }
                                        else
                                        {
                                            #region One to Many

                                            Type[] genericBases = t.GetGenericArguments();
                                            // Q&D: pick the first one
                                            baseType = genericBases[0];
                                            if (null != baseType && (parentType == null || !baseType.Equals(parentType))
                                                //avoid the recursion, dont back to parent
                                                && baseType.BaseType != null &&
                                                IsInheritFromType(baseType, typeof (BaseDataContract)))
                                            {
                                                //Traverse each child
                                                MethodInfo method =
                                                    this.GetType().GetMethod("TraverseToTheEndForCollection");
                                                MethodInfo generic = method.MakeGenericMethod(baseType);
                                                generic.Invoke(this, new object[] {value, typeof (T), ignoreType});
                                            }

                                            #endregion
                                        }

                                    } //end if 
                                } //end if
                            }//end if                            
                        }
                    }//end foreach
                }//end if
            }//end if 
        }
        /// <summary>
        /// Traverse each entity of a collection to their end and load the related entity. 
        /// </summary>
        /// <param name="entities">Set the collection of entity for traversing each entity</param>
        /// <param name="parentType">Set the Parent to ignore the recurtion. For root entity, set it null</param>
        /// <param name="ignoreType">Some Type of entity I want to Ignore</param>
        /// <returns></returns>
        public void TraverseToTheEndForCollection<T>(FixupCollection<T> entities, Type parentType =null ,Type[] ignoreType =null )
           where T : BaseDataContract
        {
            if (null != entities)
            {
                for (int i = 0; i < entities.Count; i++)
                {
                    TraverseToTheEnd(entities[i], parentType, ignoreType);
                }
            }
        }

To load the navigation property value I just call the above method –loadProperty which is provided by the ObjectContext 

_ctx.LoadProperty(entity, navigationProperty.Name);

var value = info.GetValue(entity, null);

 

After that , Check the navigation property type whether that is generic type or not. in EF , Generic navigation type is

used for Collection of entity in case of Many End and on the other hand normal property type for One or Zero End.

Here, The method –IsInheritFromType is nothing but check for BaseType to some desired parent Type.This has been checked

to determine whether it is database object or not. To call a Generic method -

 

MethodInfo method = this.GetType().GetMethod("TraverseToTheEnd");

MethodInfo generic = method.MakeGenericMethod(t);

generic.Invoke(this, new object[] {value, typeof (T), ignoreType});

 

And TraverseToTheEndForCollection method has been called in the same way with the parameter of child/navigation property value

parent type and other paramters.

 

Here I need to create some extension of ObjectContext to get all navigation properties of an entity by manipulating

the metadata information. In GetNavigationProperty method we need to retrieve the entity set name (that’s why we need the

GetEntitySet method) and from its type members it check for nevigationProperty as BuiltInTypeKind.

 

public static EntitySetBase GetEntitySet(this ObjectContext context, Type entityType)
      {
          if (context == null)
          {
              throw new ArgumentNullException("context");
          }
          if (entityType == null)
          {
              throw new ArgumentNullException("entityType");
          }
          EntityContainer container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
          EntitySetBase entitySet = container.BaseEntitySets.Where(item => item.ElementType.Name.Equals(entityType.Name))
                                                            .FirstOrDefault();
          return entitySet;
      }

      public static List<NavigationProperty> GetNavigationProperty<T>(
      this ObjectContext context)
      {
          var containerName = context.DefaultContainerName;
          var model = DataSpace.CSpace;
          var workspace = context.MetadataWorkspace;
          var container = workspace.GetEntityContainer(containerName, model);
          EntitySetBase entitySet = context.GetEntitySet(typeof(T));

          if (entitySet == null)
              return null;

          //materialize nav props for testing
          var navigationProps = entitySet.ElementType.Members
              .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty
              )
              .Cast<NavigationProperty>()
              .ToList();

          return navigationProps;
      }

Ok that is it.

Yes you can ask me why I am going to such great length. Answer is-  because I want to backup the object tree into a backup file and later on it will be attached to database that might be the same database or another one with same schema. It will not override any entity if that any data of this object-tree already exist, if not then it will insert the object with related object as it is currently in its own. But that’s a different story. This method gives an object tree with all its related objects to the leaf and I can do whatever I want. For now I would like to serialize this object in a file and on the next post I will try to re-attach the object to database. Thanks for reading and Hope you like it Smile.

Read Full Post | Make a Comment ( None so far )

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: