Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6852249
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T01:20:54+00:00 2026-05-27T01:20:54+00:00

I’m attempting to use C# as a scripting language using CSharpCodeProvider (using VS2010 and

  • 0

I’m attempting to use C# as a scripting language using CSharpCodeProvider (using VS2010 and .NET 4.0). I want the scripts to be run in a restricted AppDomain with minimal permissions. Currently, I’m getting an exception while trying to instantiate a class in the AppDomain (The call to CreateInstanceAndUnwrap()). Here is some simplified code that reproduces the exception:

using System;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Remoting;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // set permissions
            PermissionSet permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(new SecurityPermission( SecurityPermissionFlag.Execution));

            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;

            //Create a list of fully trusted assemblies
            Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
            List<StrongName> sns = new List<StrongName>();
            for (int x = 0; x < asms.Length; x++)
            {
                StrongName sn = asms[x].Evidence.GetHostEvidence<StrongName>();
                if (sn != null && sns.Contains(sn) == false)
                    sns.Add(sn);
            }
            //this includes: "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"            

            AppDomain domain = AppDomain.CreateDomain("NewAppDomain", AppDomain.CurrentDomain.Evidence, adSetup, permissions);//, sns);//, sn4, sn, sn2, sn3);
            try
            {
                String asmName = Assembly.GetExecutingAssembly().FullName;
                String typeName = typeof(ConsoleApp.ScriptRunner).FullName;
                //Throws exception here
                ScriptRunner scriptRunner = domain.CreateInstanceAndUnwrap(asmName, typeName) as ScriptRunner;
            }
            catch (SecurityException se)
            {
                System.Diagnostics.Debug.WriteLine(se.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
    }

    public class ScriptRunner : MarshalByRefObject
    {      
        public ScriptRunner()
        {
            //A breakpoint placed here is never reached.
            CompilerParameters param;
            param = new CompilerParameters();
            param.CompilerOptions = "";
            param.GenerateExecutable = false;
            param.GenerateInMemory = true;
            param.IncludeDebugInformation = false;

            // C# compiler
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();  

            CompilerResults results = codeProvider.CompileAssemblyFromFile(param, "Danger.cs");           
        }
    }
}

The exception is being thrown from mscorlib and it is a System.Reflection.TargetInvocationException that has an inner System.Security.SecurityException. Here is the exception:

System.Reflection.TargetInvocationException was unhandled
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
       at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
       at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
       at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
       at System.Activator.CreateInstance(Type type, Boolean nonPublic)
       at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
       at System.Activator.CreateInstance(String assemblyName, String typeName)
       at System.AppDomain.CreateInstance(String assemblyName, String typeName)
       at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
       at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
       at ConsoleApp.Program.Main(String[] args) in C:\Documents and Settings\NaultyCS\my documents\visual studio 2010\Projects\ConsoleApplication4\ConsoleApplication4\Program.cs:line 46
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Security.SecurityException
       Message=Request failed.
       Source=ConsoleApplication4
       GrantedSet=<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/>
</PermissionSet>

       PermissionState=<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>

       RefusedSet=""
       Url=file:///C:/Documents and Settings/NaultyCS/my documents/visual studio 2010/Projects/ConsoleApplication4/ConsoleApplication4/bin/Debug/ConsoleApplication4.EXE
       StackTrace:
            at ConsoleApp.ScriptRunner..ctor()
       InnerException: 

So it appears to me that mscorlib is demanding full trust. I’ve added it as a fully trusted assembly, but it has no effect. The above code works if I set the permissions to unrestricted:

PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);

But I want to restrict the AppDomain. What am I doing wrong here?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T01:20:55+00:00Added an answer on May 27, 2026 at 1:20 am

    Sorry for the late edit. Try the following. I got it up and running in Visual Studio with a test app. On a side note, I personally do not like “logic” in constructors because the true error tends to get a little hidden. The steps below have the Compile logic moved from the constructor to a new method.

    1. Ensure your Console App has a StrongName / Signed.
    2. Include the sns variable as the last parameter to call AppDomain.CreateDomain. The LinkDemand Permission requires your ConsoleApp to be fully trusted.

      AppDomain domain = AppDomain.CreateDomain("NewAppDomain", AppDomain.CurrentDomain.Evidence, adSetup, permissions, sns.ToArray());
      
    3. Change the asmName to use the Full File Path to your assembly.

      String asmName = Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
      
    4. Delete the CreateInstanceAndUnwrap call to the following 2 lines of code

      var handle = Activator.CreateInstanceFrom(domain, asmName, typeName);
      var scriptRunner = (ScriptRunner)handle.Unwrap();
      
    5. Move all your code from the Constructor to a new method such as “Start”.

    6. Add the line to call the Start method.

      scriptRunner.Start();
      
    7. Add the FileIOPermission to read your Danger.cs file.

      permissions.AddPermission(new FileIOPermission(PermissionState.None) { AllFiles = FileIOPermissionAccess.Read });
      
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I am trying to understand how to use SyndicationItem to display feed which is
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a French site that I want to parse, but am running into
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.