title: .NET 4 method security exception when pinvoking
body: <p>I've got some code which pinvokes native win32. Since I upgraded to .NET 4, the code started throwing a MethodAccessException saying:</p>
  
  <blockquote>
    <p>Attempt by security transparent method 'Tek.Audio.Midi.MidiDevice.GetDevices()' to call native code through method 'Tek.Native.Windows.Multimedia.midiInGetNumDevs()' failed.  Methods must be security critical or security safe-critical to call native code.</p>
  </blockquote>
  
  <p>Here's what's going on:</p>
  
  <ul>
  <li>Executable assembly's <code>Program.Main</code> method calls library1 public static <code>Tek.Audio.Midi.MidiDevice.GetDevices()</code></li>
  <li>Library1's <code>GetDevices()</code> calls library2's public static pinvoke <code>Tek.Native.Windows.Multimedia.midiInGetNumDevs()</code> (yeah, bad practice, whatever)</li>
  </ul>
  
  <p>The only security-related attributes on classes, methods and assemblies involved are AllowPartiallyTrustedCallers on library1, and I don't even know why.</p>
  
  <p>It shames me to admit that I'm quite ignorant about security in .NET. What should I do to prevent this exception? And while I'm here, any good articles to get me started on .NET security?</p>