Add Rule - Regions are must for all the code blocks

Aug 2, 2012 at 1:31 PM

Our organization has it own coding standards and it states that all the code blocks should be enclosed in "Regions"

I have written the following code , but it raises a runtime exception that "TokenNode cannot be converted to type Region"

Below is the code:

public override void AnalyzeDocument(CodeDocumentdocument)

{

 

 

 C sDocument document2 = (CsDocument)document;

 

{

document2.WalkDocument(

new CodeWalkerElementVisitor<object>(VisitElement), null, null);

}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

private

 

bool VisitElement(CsElement element, CsElement parentElement, object

context)

{

 

if (element.ElementType == ElementType.Method && element.ElementType == ElementType

.Event && !element.Generated)

{

 

var method = (Method

)element;

 

bool isErrorHandled = false

;

 

foreach (var token in

method.Tokens)

{

 

if (token.CsTokenType == CsTokenType

.Try)

{

isErrorHandled =

true

;

 

//return true;

}

}

 

if (isErrorHandled == false

)

{

 

base.AddViolation(element, "TryCatchBlockIsNecessaryForAllCodeBlocks", new object

[0]);

 

//return true;

}

}

 

this

.CheckForRegions(element, context);

 

return true

;

}

private

 bool CheckForRegions(CsElement element, object context)

{

 

//Raise violation rule if regions are not found

 

 

if (element.ElementType == ElementType.Method && !element.Generated)

{

 

Node<CsToken> tokenNode = element.Tokens.First;

 

// If this token is not having an opening region directive, this is a violation.
 

 

if (tokenNode.Value.CsTokenClass != CsTokenClass.RegionDirective)

{

 

Region region = (Region)tokenNode.Value;

 

if (!region.Beginning && !region.Generated && !region.IsGeneratedCodeRegion)

{

 

this.AddViolation(element, tokenNode.Value.LineNumber, "UseRegionsForAllTheCodeBlocks", new object[0]);

}

}

}

 

return true;

}

private

bool CheckForRegions(CsElement element, object context)

{

 

//Raise violation rule if regions are not found

 

 

 

 

 

 

 

 

 

if (element.ElementType == ElementType

.Method && !element.Generated)

{

 

Node<CsToken

> tokenNode = element.Tokens.First;

 

// If this token is not having an opening region directive, this is a violation.

 

if (tokenNode.Value.CsTokenClass != CsTokenClass

.RegionDirective)

{

 

Region region = (Region

)tokenNode.Value;

 

if

(!region.Beginning && !region.Generated && !region.IsGeneratedCodeRegion)

{

 

this.AddViolation(element, tokenNode.Value.LineNumber, "UseRegionsForAllTheCodeBlocks", new object

[0]);

}

}

}

 

return true

;

}

if ((document2.RootElement != null) && !document2.RootElement.Generated)

 

 Param.RequireNotNull(document, "document");