title: UnmanagedCode permission. What is it?
body: <p>The following code exists in LogEntry.cs in the Enterprise Library's Logging Application Block:</p>
  
  <pre><code>private bool UnmanagedCodePermissionAvailable
  {
    get
    {
      if (!unmanagedCodePermissionAvailableInitialized)
      {
        // check whether the unmanaged code permission is available to avoid three potential stack walks
        bool internalUnmanagedCodePermissionAvailable = false;
        SecurityPermission unmanagedCodePermission = 
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
        // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
        // stack walk modifiers before the call.
        if (SecurityManager.IsGranted(unmanagedCodePermission))
        {
          try
          {
            unmanagedCodePermission.Demand();
            internalUnmanagedCodePermissionAvailable = true;
          }
          catch (SecurityException)
          { }
        }
  
        this.UnmanagedCodePermissionAvailable = 
            internalUnmanagedCodePermissionAvailable;
      }
  
      return this.unmanagedCodePermissionAvailable;
    }
    set
    {
      this.unmanagedCodePermissionAvailable = value;
      unmanagedCodePermissionAvailableInitialized = true;
    }
  }
  </code></pre>
  
  <p>The function is called before any of several P/Invoke calls are made to retrieve various information to help fill in the LogEntry structure.  If "UnmanagedCodePermission" is not available, then the corresponding LogEntry property is set to a string indicating such ("XXX is not available").</p>
  
  <p>For example, LogEntry wants to get the Win32 thread id and it uses the Win32 function, GetCurrentThreadId, called by P/Invoke to get it.  Before calling GetCurrentThreadId, it checks to see if "unamanged code permission" is available.  If so, it makes the call, if not, it does not.  Something like this:</p>
  
  <pre><code>private void InitializeWin32ThreadId()
  {
    if (this.UnmanagedCodePermissionAvailable)
    {
      try
      {
        this.Win32ThreadId = LogEntryContext.GetCurrentThreadId();
      }
      catch (Exception e)
      {
        this.Win32ThreadId = string.Format(
                                    CultureInfo.CurrentCulture,
                                    Properties.Resources.IntrinsicPropertyError,
                                    e.Message);
      }
    }
    else
    {
      this.Win32ThreadId = string.Format(CultureInfo.CurrentCulture,
                  Properties.Resources.IntrinsicPropertyError,
                  Properties.Resources.
                  LogEntryIntrinsicPropertyNoUnmanagedCodePermissionError);
    }
  }
  </code></pre>
  
  <p>From what I understand, which, admittedly, is not much, making calls to unmanaged code (e.g. P/Invoke) is not always possible due to security/permissions/trust.  Having this check to see if unmanaged code calls are possible, makes it possible to protect all unmanaged calls in a uniform manner.</p>
  
  <p>When I compile this code, I get a warning on this line:</p>
  
  <pre><code>          if (SecurityManager.IsGranted(unmanagedCodePermission))
  </code></pre>
  
  <p>Here is the warning:</p>
  
  <p><strong>System.Security.SecurityManager.IsGranted(System.Security.IPermission)' is obsolete: 'IsGranted is obsolete and will be removed in a future release of the .NET Framework.  Please use the PermissionSet property of either AppDomain or Assembly instead.</strong></p>
  
  <p>(Note that I am building this on .Net 4.0 using VS2010).</p>
  
  <p>So, it looks IsGranted is obsolete.  I looked at the PermissionSet property for AppDomain and Assembly, and it wasn't obvious exactly how to make the same check.</p>
  
  <p>In the case of LogEntry, it looks like this information is not critical, so it is not considered a critical failure if unmanaged permission is not available.  Consider the following questions from the same point of view.  That is, if unmanaged code permission is not available, it is not a huge deal, I can live without the information.</p>
  
  <p>Finally, a couple of questions:</p>
  
  <ol>
  <li><p>Is it a good idea to try to protect calls to unmanaged code (e.g. P/Invoke)? Sometimes, always, never?</p></li>
  <li><p>If it is a good idea to protect these calls, is this a reasonable pattern for doing so? Is there a better way?</p></li>
  <li><p>What would be the correct (i.e. not obsolete) way to make the equivalent check in .Net 4.0?</p></li>
  </ol>