Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Problem using CSharpCodeProvider to add types at runtime

$
0
0

I am having an intermittent problem adding C# types from Powershell.  (If this isn't the right forum, please advise me on where to post my question).

I originally encountered this issue using the built-in Add-Type cmdlet, but in order to get at the root of the issue I have actually written my own variation of the cmdlet:

function New-Type {
  param(
    [Parameter(Mandatory=$True,Position=1)][string]$TypeDefinition=$(throw "Mandatory parameter -TypeDefinition missing.")
  )

  $Params = New-Object System.CodeDom.Compiler.CompilerParameters
  $Params.ReferencedAssemblies.AddRange($(@("System.dll", $([PSObject].Assembly.Location))))
  $Params.GenerateInMemory = $True
  $Temp = $(Get-Item ENV:TEMP).Value
  $Params.TempFiles = New-Object System.CodeDom.Compiler.TempFileCollection $Temp, $False

  $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
  Try {
    $CompilerResults = $Provider.CompileAssemblyFromSource($Params, $TypeDefinition)
    if ($CompilerResults.Errors.Count -gt 0) {
      $CodeLines = $TypeDefinition -Split '[\n]';
      $ErrorMessage = "Compilation Errors:"
      foreach ($CompileError in $CompilerResults.Errors) {
        $ErrorMessage = [String]::Concat($ErrorMessage, "`n", $CompileError.ToString())
      }
      Write-Error $ErrorMessage
    }
  } Catch [system.exception] {
    if ($_.GetType().ToString() -eq "System.Management.Automation.ErrorRecord") {
      Write-Error $_.Exception.ToString()
    } else {
      Write-Error $_.ToString()
    }
  }
}

This new function works great, but unfortunately it is no more reliable than Add-Type.  However I have been able to get a stack trace out of it:

System.IO.FileNotFoundException: Could not find file 'C:\Users\[name]\AppData\Local\Temp\abd4anxc.dll'.

File name: 'C:\Users\[name]\AppData\Local\Temp\abd4anxc.dll'

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

   at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)

   at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)

   at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)

   at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)

   at CompileAssemblyFromSource(Object , Object[] )

   at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments)

A few other folks seem to have observed similar issues before, but they were actually experiencing compiler errors.  I am not -- I appear to be running into an error wherein the compiler fails to serialize the assembly to a temp file (which is the little"trick" it performs to pretend that the compilation is happening in memory).

Unfortunately, this seems to be the worst kind of error, one that happens "sometimes" but not always.  I once actually put the code in a loop, and it failed 20k times in a row.  So when it's broken, it stays broken (for a little while anyway).  Sometimes re-starting Powershell will clear the problem, but not always.  So what's going on??

I would really like to avoid having to ship DLLs with my Powershell modules, so adding types dynamically is extremely appealing.  How can I determine what's causing this intermittent error?

Thanks!


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>