Move P/Invokes to NativeMethods class

Rule ND2401 .NET Framework Usage / System.Runtime.InteropServices

Platform Invocation methods (tagged DllImportAttribute or VB Declare) should be in one of these static internal classes with static internal methods:

- NativeMethods - no SuppressUnmanagedCodeSecurityAttribute: stack walks are performed, methods usable anywhere.

- SafeNativeMethods - SuppressUnmanagedCodeSecurityAttribute applied: harmless methods safe for anyone to call, no security review needed.

- UnsafeNativeMethods - SuppressUnmanagedCodeSecurityAttribute applied: potentially dangerous methods, callers must perform a full security review since no stack walk is performed.

Matches P/Invoke methods not declared in such classes.

How to fix

Move the method to the appropriate NativeMethods class; for most applications a new class named NativeMethods is enough.

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Move P/Invokes to NativeMethods class</Name>
// <Id>ND2401:MovePInvokesToNativeMethodsClass</Id>

warnif count > 0 from m in Application.Methods where
   m.HasAttribute ("System.Runtime.InteropServices.DllImportAttribute".AllowNoMatch()) &&
   m.ParentType.SimpleName != "NativeMethods"
select new {
   m,
   Debt = 5.ToMinutes().ToDebt(),
   Severity = Severity.Medium
}

//<Expl>
// The *P/Invoke {0}* should be moved to a dedicated class named *NativeMethods*.
//</Expl>

//<Desc>
// **Platform Invocation methods** (tagged **DllImportAttribute** or VB
// **Declare**) should be in one of these *static internal* classes with
// *static internal* methods:
//
// - **NativeMethods** - no *SuppressUnmanagedCodeSecurityAttribute*: stack
// walks are performed, methods usable anywhere.
//
// - **SafeNativeMethods** - *SuppressUnmanagedCodeSecurityAttribute*
// applied: harmless methods safe for anyone to call, no security review
// needed.
//
// - **UnsafeNativeMethods** - *SuppressUnmanagedCodeSecurityAttribute*
// applied: potentially dangerous methods, callers must perform a full
// security review since no stack walk is performed.
//
// Matches *P/Invoke* methods not declared in such classes.
//</Desc>

//<HowToFix>
// Move the method to the appropriate **NativeMethods** class; for most
// applications a new class named **NativeMethods** is enough.
//</HowToFix>

.NET Framework Usage / System.Runtime.InteropServices: all 3 items