Exemple #1
0
        static void Main()
        {
            // Register a channel.
            TcpChannel myChannel = new TcpChannel();

            ChannelServices.RegisterChannel(myChannel);
            RemotingConfiguration.RegisterActivatedClientType(
                typeof(HelloService), "tcp://localhost:8085/");

            // Get the remote object.
            HelloService myService = new HelloService();

            // Get a sponsor for renewal of time.
            ClientSponsor mySponsor = new ClientSponsor();

            // Register the service with sponsor.
            mySponsor.Register(myService);

            // Set renewaltime.
            mySponsor.RenewalTime = TimeSpan.FromMinutes(2);

            // Renew the lease.
            ILease   myLease = (ILease)mySponsor.InitializeLifetimeService();
            TimeSpan myTime  = mySponsor.Renewal(myLease);

            Console.WriteLine("Renewed time in minutes is " + myTime.Minutes.ToString());

            // Call the remote method.
            Console.WriteLine(myService.HelloMethod("World"));

            // Unregister the channel.
            mySponsor.Unregister(myService);
            mySponsor.Close();
        }
Exemple #2
0
        public void BuildDocument()
        {
            var sponsor = new ClientSponsor();

            if (_listener != null)
            {
                Logger.LogLevelThreshold = _logLevel;
                Logger.RegisterListener(_listener);
                sponsor.Register(_listener);
            }
            try
            {
                try
                {
                    BuildDocument(_config, _manager, _baseDirectory, _outputDirectory, _pluginDirectory);
                }
                catch (Exception e) when(e is DocfxException || e is DocumentException)
                {
                    throw new DocfxException(e.Message);
                }
                catch (Exception e)
                {
                    throw new DocfxException(e.ToString());
                }
            }
            finally
            {
                sponsor.Close();
            }
        }
Exemple #3
0
        public void BuildDocument()
        {
            var sponsor = new ClientSponsor();

            if (_listener != null)
            {
                Logger.LogLevelThreshold = _logLevel;
                Logger.RegisterListener(_listener);
                sponsor.Register(_listener);
            }
            try
            {
                try
                {
                    BuildDocument(_config, _manager, _baseDirectory, _outputDirectory, _pluginDirectory);
                }
                catch (Exception e)
                {
                    // For non-serializable exception, wrap it and throw docfx exception instead
                    throw new DocfxException(e.ToString());
                }
            }
            finally
            {
                sponsor.Close();
            }
        }
Exemple #4
0
        public void SetUp()
        {
            tempDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "protobuf-net-gh24-" + Convert.ToBase64String(BitConverter.GetBytes(DateTime.UtcNow.Ticks)).Replace('/', '-').Substring(0, 11)));
            tempDir.Create();

            var subdir = tempDir.CreateSubdirectory("temp");

            assemblyPath = new FileInfo(Path.Combine(subdir.FullName, ASSEMBLY_NAME + ".dll"));
            CopyAssembly(assemblyPath);

            var setup = new AppDomainSetup
            {
                ApplicationBase = tempDir.FullName,
                // setting this to true allows both tests to pass
                DisallowApplicationBaseProbing = false
            };

            domain = AppDomain.CreateDomain("Gh24", null, setup);

            sponsor = new ClientSponsor();

            remoteSide = (RemoteSide)domain.CreateInstanceFromAndUnwrap(typeof(RemoteSide).Assembly.Location, typeof(RemoteSide).FullName);
            sponsor.Register(remoteSide);

            var references    = new[] { typeof(Serializer).Assembly };
            var assemblyPaths = references.ToDictionary(a => a.GetName(), a => a.Location);

            assemblyPaths[new AssemblyName(ASSEMBLY_NAME)] = assemblyPath.FullName;
            remoteSide.Initialize(assemblyPaths);
        }
        public static void Sponsor(ServerObject obj)
        {
            ClientSponsor sponsor = new ClientSponsor();

            sponsor.RenewalTime = TimeSpan.FromMinutes(2);
            sponsor.Register(obj);
        }
Exemple #6
0
        /// <summary>
        /// Indicates to the TaskHost that it is no longer needed.
        /// Called by TaskBuilder when the task using the EngineProxy is done.
        /// </summary>
        internal void MarkAsInactive()
        {
            lock (_callbackMonitor)
            {
                VerifyActiveProxy();
                _activeProxy = false;

                // Since the task has a pointer to this class it may store it in a static field. Null out
                // internal data so the leak of this object doesn't lead to a major memory leak.
                _host         = null;
                _requestEntry = null;

                // Don't bother clearing the tiny task location
                _taskLoggingContext    = null;
                _targetBuilderCallback = null;

                // Clear out the sponsor (who is responsible for keeping the EngineProxy remoting lease alive until the task is done)
                // this will be null if the engine proxy was never sent across an AppDomain boundary.
                if (_sponsor != null)
                {
                    ILease lease = (ILease)RemotingServices.GetLifetimeService(this);

                    if (lease != null)
                    {
                        lease.Unregister(_sponsor);
                    }

                    _sponsor.Close();
                    _sponsor = null;
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Indicates to the EngineProxy that it is no longer needed.
        /// Called by TaskEngine when the task using the EngineProxy is done.
        /// </summary>
        internal void MarkAsInActive()
        {
            activeProxy = false;

            // Since the task has a pointer to this class it may store it in a static field. Null out
            // internal data so the leak of this object doesn't lead to a major memory leak.
            loggingServices   = null;
            parentModule      = null;
            buildEventContext = null;

            // Clear out the sponsor (who is responsible for keeping the EngineProxy remoting lease alive until the task is done)
            // this will be null if the engineproxy was never sent accross an appdomain boundry.
            if (sponsor != null)
            {
                ILease lease = (ILease)RemotingServices.GetLifetimeService(this);

                if (lease != null)
                {
                    lease.Unregister(sponsor);
                }

                sponsor.Close();
                sponsor = null;
            }
        }
        //--//

        protected void RegisterRemoteObject(ServerRemoteObject mbr)
        {
            UnregisterRemoteObject();

            m_mbr     = mbr;
            m_sponsor = new ClientSponsor();
            m_sponsor.Register(mbr);
        }
 protected virtual void Dispose(bool isDisposing)
 {
     if (isDisposing)
     {
         _clientSponsor?.Close();
         _clientSponsor = null;
     }
 }
        static void Main()
        {
// <Snippet3>
            // Register the channel.
            TcpChannel myChannel = new TcpChannel();

            ChannelServices.RegisterChannel(myChannel);
            RemotingConfiguration.RegisterActivatedClientType(
                typeof(HelloService), "Tcp://localhost:8085");

            TimeSpan myTimeSpan = TimeSpan.FromMinutes(10);

            // Create a remote object.
            HelloService myService = new HelloService();

            ILease myLease;

            myLease = (ILease)RemotingServices.GetLifetimeService(myService);
            if (myLease == null)
            {
                Console.WriteLine("Cannot lease.");
                return;
            }

            Console.WriteLine("Initial lease time is " + myLease.InitialLeaseTime);
            Console.WriteLine("Current lease time is " + myLease.CurrentLeaseTime);
            Console.WriteLine("Renew on call time is " + myLease.RenewOnCallTime);
            Console.WriteLine("Sponsorship timeout is " + myLease.SponsorshipTimeout);
            Console.WriteLine("Current lease state is " + myLease.CurrentState.ToString());
// </Snippet3>
            // Register with a sponser.
            ClientSponsor mySponsor = new ClientSponsor();

            myLease.Register(mySponsor);
            Console.WriteLine("Wait for lease to expire (approx. 15 seconds)...");
            System.Threading.Thread.Sleep(myLease.CurrentLeaseTime);
            Console.WriteLine("Current lease time before renewal is " + myLease.CurrentLeaseTime);

            // Renew the lease time.
            myLease.Renew(myTimeSpan);
            Console.WriteLine("Current lease time after renewal is " + myLease.CurrentLeaseTime);

            // Call the Remote method.
            Console.WriteLine("Remote method output is " + myService.HelloMethod("Microsoft"));

            myLease.Unregister(mySponsor);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // Register with lease time of 15 minutes.
            myLease.Register(mySponsor, TimeSpan.FromMinutes(15));
            Console.WriteLine("Registered client with lease time of 15 minutes.");
            Console.WriteLine("Current lease time is " + myLease.CurrentLeaseTime);

            // Call the Remote method.
            Console.WriteLine("Remote method output is " + myService.HelloMethod("Microsoft"));
            myLease.Unregister(mySponsor);
        }
Exemple #11
0
        /// <inheritdoc />
        /// <summary>
        /// InitializeLifetimeService is called when the remote object is activated.
        /// This method will determine how long the lifetime for the object will be.
        /// </summary>
        /// <returns>The lease object to control this object's lifetime.</returns>
        public override object InitializeLifetimeService()
        {
            lock (_callbackMonitor)
            {
                VerifyActiveProxy();

                // Each MarshalByRef object has a reference to the service which
                // controls how long the remote object will stay around
                ILease lease = (ILease)base.InitializeLifetimeService();

                // Set how long a lease should be initially. Once a lease expires
                // the remote object will be disconnected and it will be marked as being availiable
                // for garbage collection
                int initialLeaseTime = 1;

                string initialLeaseTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYINITIALLEASETIME");

                if (!String.IsNullOrEmpty(initialLeaseTimeFromEnvironment))
                {
                    int leaseTimeFromEnvironment;
                    if (int.TryParse(initialLeaseTimeFromEnvironment, out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0)
                    {
                        initialLeaseTime = leaseTimeFromEnvironment;
                    }
                }

                lease.InitialLeaseTime = TimeSpan.FromMinutes(initialLeaseTime);

                // Make a new client sponsor. A client sponsor is a class
                // which will respond to a lease renewal request and will
                // increase the lease time allowing the object to stay in memory
                _sponsor = new ClientSponsor();

                // When a new lease is requested lets make it last 1 minutes longer.
                int leaseExtensionTime = 1;

                string leaseExtensionTimeFromEnvironment = Environment.GetEnvironmentVariable("MSBUILDENGINEPROXYLEASEEXTENSIONTIME");
                if (!String.IsNullOrEmpty(leaseExtensionTimeFromEnvironment))
                {
                    int leaseExtensionFromEnvironment;
                    if (int.TryParse(leaseExtensionTimeFromEnvironment, out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0)
                    {
                        leaseExtensionTime = leaseExtensionFromEnvironment;
                    }
                }

                _sponsor.RenewalTime = TimeSpan.FromMinutes(leaseExtensionTime);

                // Register the sponsor which will increase lease timeouts when the lease expires
                lease.Register(_sponsor);

                return(lease);
            }
        }
        private void SetLeases()
        {
            _clientSponsor?.Close();
            _clientSponsor = new ClientSponsor(TimeSpan.MaxValue);
            _clientSponsor.Register((MarshalByRefObject)_missionPlannerInterfaces.CurrentState);
            //_clientSponsor.Register((MarshalByRefObject) _missionPlannerInterfaces.FlightComms);
            _clientSponsor.Register((MarshalByRefObject)_missionPlannerInterfaces.MissionPlanner);

            var lease = (ILease)_clientSponsor.InitializeLifetimeService();

            _clientSponsor.Renewal(lease);
        }
Exemple #13
0
 public static void UnloadToolboxItems()
 {
     if (_domain != null)
     {
         AppDomain domain = _domain;
         _domainObjectSponsor.Close();
         _domainObjectSponsor = null;
         _domainObject        = null;
         _domain = null;
         AppDomain.Unload(domain);
     }
 }
Exemple #14
0
            public void KeepRemoteObjectAlive()
            {
                sum = CSScript.Evaluator
                      .CreateDelegateRemotely(@"int Sum(int a, int b)
                                                        {
                                                            return a+b;
                                                        }");

                //Normally remote objects are disposed if they are not accessed withing a default timeout period.
                //It is not even enough to keep transparent proxies or their wrappers (e.g. 'sum') referenced.
                //To prevent GC collection in the remote domain use .NET ClientSponsor mechanism as below.
                sumSponsor = sum.ExtendLifeFromMinutes(30);
            }
Exemple #15
0
        /// <summary>
        /// 通过ClientSponsor来延长远程对象生命周期
        /// </summary>
        /// <param name="counter"></param>
        /// <returns></returns>
        static ISponsor ExtendLifetimeViaSponsor(object counter)
        {
            CounterService counterService = counter as CounterService;

            ILease lease = RemotingServices.GetLifetimeService(counterService) as ILease;

            //为Lease注册一个Sposnor,并把Renew时间设为4s
            ClientSponsor clientSponsor = new ClientSponsor(TimeSpan.FromSeconds(4));

            clientSponsor.Register(counterService);

            return(clientSponsor);
        }
Exemple #16
0
        public virtual void Dispose()
        {
            if (Sponsor != null) {
                if (Agent != null) {
                    //...
                    Sponsor.Unregister(Agent);
                }

                Sponsor.Close();
                Sponsor = null;
            }

            if (!isUnloaded) Unload(false).GetAwaiter().GetResult();
        }
Exemple #17
0
        public static ICollection GetToolboxItems(AssemblyName an, bool throwOnError)
        {
            if (_domainObject == null)
            {
                _domain              = AppDomain.CreateDomain("Assembly Enumeration Domain");
                _domainObject        = (DomainProxyObject)_domain.CreateInstanceAndUnwrap(typeof(DomainProxyObject).Assembly.FullName, typeof(DomainProxyObject).FullName);
                _domainObjectSponsor = new ClientSponsor(new TimeSpan(0, 5, 0));
                _domainObjectSponsor.Register(_domainObject);
            }
            byte[]          toolboxItems = _domainObject.GetToolboxItems(an, throwOnError);
            BinaryFormatter formatter    = new BinaryFormatter();

            return((ICollection)formatter.Deserialize(new MemoryStream(toolboxItems)));
        }
        public static async Task Run(Action <RemoteTaskCompletionSource, ISponsor> action, CancellationToken token)
        {
            var sponsor = new ClientSponsor();

            try {
                var taskHandle = new RemoteTaskCompletionSource(token);
                sponsor.Register(taskHandle);

                action(taskHandle, sponsor);
                await taskHandle.Task;
            }
            finally {
                sponsor.Close();
            }
        }
        protected void UnregisterRemoteObject()
        {
            try
            {
                if (m_sponsor != null)
                {
                    m_sponsor.Unregister(m_mbr);
                }
            }
            catch
            {
            }

            m_sponsor = null;
            m_mbr     = null;
        }
Exemple #20
0
        public void BuildDocument()
        {
            var sponsor = new ClientSponsor();

            EnvironmentContext.SetBaseDirectory(_baseDirectory);
            EnvironmentContext.SetGitFeaturesDisabled(_disableGitFeatures);
            EnvironmentContext.SetVersion(_version);
            if (_listener != null)
            {
                Logger.LogLevelThreshold = _logLevel;
                Logger.RegisterListener(_listener);
                sponsor.Register(_listener);
            }
            try
            {
                try
                {
                    BuildDocument(_config, _manager, _baseDirectory, _outputDirectory, _pluginDirectory, _templateDirectory);
                }
                catch (AggregateException agg) when(agg.InnerException is DocfxException)
                {
                    throw new DocfxException(agg.InnerException.Message);
                }
                catch (AggregateException agg) when(agg.InnerException is DocumentException)
                {
                    throw new DocumentException(agg.InnerException.Message);
                }
                catch (DocfxException e)
                {
                    throw new DocfxException(e.Message);
                }
                catch (DocumentException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw new DocfxException(e.ToString());
                }
            }
            finally
            {
                sponsor.Close();
            }
        }
Exemple #21
0
        private void btnSponsor_Click(object sender, System.EventArgs e)
        {
            mLease = (ILease)RemotingServices.GetLifetimeService(objCount);

            mSponsor             = new ClientSponsor();
            mSponsor.RenewalTime = TimeSpan.FromSeconds(15);

            try
            {
                mLease.Register(mSponsor);
            }
            catch
            {
                MessageBox.Show(this, "Lease has expired");
            }


            MessageBox.Show("Sponsor registered with object");
        }
Exemple #22
0
        public void Stop()
        {
            lock (_lock)
            {
                if (serverManager != null)
                {
                    try
                    {
                        clientSponsor.Unregister(serverManager as MarshalByRefObject);
                        Logging.Log.Info("Closing client sponsor");
                        clientSponsor.Close();
                        Logging.Log.Info("Stopping server manager");
                        serverManager.Stop();
                        Logging.Log.Info("Unloading AssemblyLoader from server app domain");
                        AssemblyLoader.Unload(serverDomain);
                    }
                    catch (Exception ex)
                    {
                        Logging.Log.Warn("Error during shutdown", ex);
                        throw;
                    }
                }
                else
                {
                    Logging.Log.Error("Tried unloading an already unloaded server manager.");
                }

                clientSponsor = null;
                serverManager = null;

                if (serverDomain != null)
                {
                    Logging.Log.Info("Unloading server app domain");
                    AppDomain.Unload(serverDomain);
                }
                else
                {
                    Logging.Log.Warn("Server app domain already vanished.");
                }

                serverDomain = null;
            }
        }
        /// <summary>
        /// Indicates to the TaskHost that it is no longer needed.
        /// Called by TaskBuilder when the task using the EngineProxy is done.
        /// </summary>
        internal void MarkAsInactive()
        {
            VerifyActiveProxy();
            _activeProxy = false;

            _loggingContext  = null;
            _elementLocation = null;

            // Clear out the sponsor (who is responsible for keeping the EngineProxy remoting lease alive until the task is done)
            // this will be null if the engineproxy was never sent across an appdomain boundry.
            if (_sponsor != null)
            {
                ILease lease = (ILease)RemotingServices.GetLifetimeService(this);

                lease?.Unregister(_sponsor);

                _sponsor.Close();
                _sponsor = null;
            }
        }
        protected DomainAgentSessionHostBase(IServerSession sessionBase, ServerAgent agent, CancellationToken token)
        {
            this.agent = agent;
            this.Token = token;

            Tasks = new TaskRunnerManager();

            SessionClient = new DomainAgentSessionClient();
            SessionClient.OnSessionBegin   += SessionClient_OnSessionBegin;
            SessionClient.OnSessionRelease += SessionClient_OnSessionRelease;
            SessionClient.OnSessionRunTask += SessionClient_OnSessionRunTask;

            sponsor = new ClientSponsor();
            sponsor.Register(SessionClient);

            MessageClient = new MessageClient(PhotonServer.Instance.MessageRegistry);
            MessageClient.Transceiver.Context = sessionBase;

            MessageClient.ThreadException += MessageClient_OnThreadException;
        }
        public void OnCompleted(Action action)
        {
            var sponsor = new ClientSponsor();

            Callback cb = null;

            cb = new Callback(() =>
            {
                try
                {
                    action();
                }
                finally
                {
                    sponsor.Unregister(cb);
                }
            });

            sponsor.Register(cb);

            OnCompletedCore(cb.Invoke);
        }
Exemple #26
0
        public void Initialize(string assemblyFilename)
        {
            var assemblyName = Path.GetFileName(assemblyFilename);
            var assemblyPath = Path.GetDirectoryName(assemblyFilename);

            if (string.IsNullOrEmpty(assemblyName))
                throw new ApplicationException("Assembly filename is empty!");

            var domainSetup = new AppDomainSetup {
                ApplicationBase = assemblyPath,
                ConfigurationFile = $"{assemblyFilename}.config",
            };

            Sponsor = new ClientSponsor();
            domain = AppDomain.CreateDomain(assemblyName, null, domainSetup);

            var agentType = typeof(T);
            Agent = (T)domain.CreateInstanceAndUnwrap(agentType.Assembly.FullName, agentType.FullName);
            Agent.LoadAssembly(assemblyFilename);

            Sponsor.Register(Agent);
        }
Exemple #27
0
        /// <summary>
        /// Stops the hosted ASP.NET application if one is running.
        /// </summary>
        public void Close()
        {
            lock (syncLock)
            {
                if (listener != null)
                {
                    try
                    {
                        var lease = (ILease)listener.GetLifetimeService();

                        lease.Unregister(sponser);
                        sponser = null;

                        listener.Stop();
                        listener = null;
                    }
                    catch (AppDomainUnloadedException)
                    {
                        // Ignore these
                    }
                }
            }
        }
Exemple #28
0
        public void Start(ZetboxConfig config)
        {
            using (Logging.Log.DebugTraceMethodCall("Start", "Starting AppDomain for Server"))
            {
                serverDomain = AppDomain.CreateDomain("ServerAppDomain",
                                                      AppDomain.CurrentDomain.Evidence,
                                                      AppDomain.CurrentDomain.SetupInformation);

                AssemblyLoader.Bootstrap(serverDomain, config);

                serverManager = (IZetboxAppDomain)serverDomain.CreateInstanceAndUnwrap(
                    "Zetbox.Server.Service",
                    "Zetbox.Server.Service.ServerManager");
                serverManager.Start(config);

                if (clientSponsor == null)
                {
                    clientSponsor             = new ClientSponsor();
                    clientSponsor.RenewalTime = TimeSpan.FromMinutes(2);
                }

                clientSponsor.Register(serverManager as MarshalByRefObject);
            }
        }
Exemple #29
0
        /// <summary>Initializes a new instance of the <see cref="RazorTemplater" /> class.</summary>
        /// <param name="templateAssemblyPath">The template assembly path. This is the path where the generated templates are stored/cached.
        /// If shadow copy is enabled this path will be ignored and the shadow copy path will be used.</param>
        /// <param name="renderTimeout">The render timeout. This is the time in ms a template is allowed to render itself.</param>
        /// <param name="templateNamespace">The template namespace.</param>
        /// <param name="allowedDirectories">The directories the templates are allowed to read from.</param>
        /// <param name="baseType">Type of the template base class. Defaults to <see cref="TemplateBase" />.</param>
        /// <param name="defaultNamespaces">The default namespaces. Defaults to "System", "System.Collections.Generic", "System.Linq" and "System.Text".</param>
        /// <param name="forbiddenTypes">The forbidden types (FQDN). Defaults to "Task", "Thread", "System.Activator" and "System.Reflection.Assembly".</param>
        /// <param name="language">The language. Defaults to C#.</param>
        /// <param name="sponsor">The sponsor to keep the object alive.</param>
        /// <param name="persistTemplates">If set to <c>true</c> the generated templates are persisted over multiple application runs. Otherwise they are deleted when disposing.</param>
        public RazorTemplater(string templateAssemblyPath, int renderTimeout = 5000, string templateNamespace = "IsolatedRazor.RazorTemplate", List <string> allowedDirectories = null,
                              Type baseType = null, List <string> defaultNamespaces = null, List <string> forbiddenTypes = null, RazorCodeLanguage language = null, ClientSponsor sponsor = null, bool persistTemplates = false)
        {
            RenderTimeout          = renderTimeout;
            this.templateNamespace = templateNamespace;
            this.persistTemplates  = persistTemplates;
            DefaultNamespaces      = defaultNamespaces ?? new List <string>()
            {
                "System", "System.Collections.Generic", "System.Net", "System.Linq", "System.Text", "IsolatedRazor"
            };
            ForbiddenTypes = forbiddenTypes ?? new List <string>()
            {
                "System.Threading.Tasks.Task", "System.Threading.Tasks.Task`1", "System.Threading.Thread", "System.Activator", "System.Reflection.Assembly"
            };
            clientSponsor = sponsor ?? new ClientSponsor(TimeSpan.FromMinutes(1));

            defaultBaseClass = (baseType ?? typeof(TemplateBase)).FullName;
            var host = new RazorEngineHost(language ?? new CSharpRazorCodeLanguage())
            {
                DefaultNamespace = templateNamespace
            };

            DefaultNamespaces.ForEach(n => host.NamespaceImports.Add(n));
            engine   = new RazorTemplateEngine(host);
            provider = host.CodeLanguage.LanguageName == "vb" ? (CodeDomProvider) new VBCodeProvider() : new CSharpCodeProvider();

            adSetup = new AppDomainSetup();
            if (AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles == "true")
            {
                isShadowCopied = true;
                templatePath   = Path.Combine(AppDomain.CurrentDomain.SetupInformation.CachePath, AppDomain.CurrentDomain.SetupInformation.ApplicationName);

                var shadowCopyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (shadowCopyDir.Contains("assembly"))
                {
                    shadowCopyDir = shadowCopyDir.Substring(0, shadowCopyDir.LastIndexOf("assembly"));
                }

                var privatePaths = new List <string>();
                foreach (var assemblyLocation in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.Location.StartsWith(shadowCopyDir)).Select(a => a.Location))
                {
                    privatePaths.Add(Path.GetDirectoryName(assemblyLocation));
                }

                adSetup.ApplicationBase = shadowCopyDir;
                adSetup.PrivateBinPath  = String.Join(";", privatePaths);
            }
            else
            {
                isShadowCopied          = false;
                templatePath            = templateAssemblyPath;
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                adSetup.PrivateBinPath  = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            }

            var resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(Path.GetDirectoryName(adSetup.ApplicationBase));
            readerParameters = new ReaderParameters()
            {
                AssemblyResolver = resolver
            };

            if (templateCache == null)
            {
                var path = Path.Combine(templatePath, TEMPLATE_CACHE_FILE);
                if (persistTemplates && File.Exists(path))
                {
                    using (var filestream = File.Open(path, FileMode.Open))
                    {
                        var formatter = new BinaryFormatter();
                        templateCache = (TemplateCache)formatter.Deserialize(filestream);
                    }
                }
                else
                {
                    templateCache = new TemplateCache();
                }
            }

            Directory.CreateDirectory(templatePath);

            permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));                              // run the code
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration));                  // remoting lifetime (sponsor)
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, templatePath));                       // read templates
            permissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));             // support dynamic

            if (allowedDirectories != null)
            {
                allowedDirectories.ForEach(dir => permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, dir)));
            }

            RecycleAppDomain();
        }
        internal LoaderAssemblyExtension(string path)
            : base(path)
        {
            var dd        = Loader.CreateAssemblyDescriber();
            var describer = dd.Item2;

            try
            {
                _assemblyName = describer.LoadFrom(path);

                TypeDescriptor[] assemblyTypes = null;

                if (GetAssemblyName() != null)
                {
                    foreach (var missing in describer.GetReferencedAssemblies(GetAssemblyName())
                             .Where(x => Loader.FindAssemblyPath(x) == null && !GAC.IsInGAC(x))
                             .ToList())
                    {
                        AddMissingDependency(missing);
                    }

                    if (MissingDependencies.Count > 0)
                    {
                        return;
                    }

                    assemblyTypes = describer.GetTypes(GetAssemblyName());
                }

                if (assemblyTypes == null || assemblyTypes.Length == 0)
                {
                    throw new NotAnExtensionException();
                }

                // TODO: check thumbprint of assembly instead of path
                if (Path.Contains("Test\\Extensions"))
                {
                    var permissions = new PermissionSet(PermissionState.Unrestricted);
                    //permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.RemotingConfiguration));
                    //permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.NoFlags));
                    //permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
                    //permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
                    //  Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));
                    //permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery,
                    //    Environment.GetFolderPath(Environment.SpecialFolder.MyComputer)));
                    //permissions.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE"));
                    //permissions.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CURRENT_USER"));
                    //permissions.AddPermission(new RegistryPermission(RegistryPermissionAccess.Write, "HKEY_CURRENT_USER\\Software\\twomindseye\\Commando\\extensions"));

                    var setup = new AppDomainSetup();
                    setup.ApplicationBase = Loader.EngineDirectory;
                    _domain        = AppDomain.CreateDomain("Extension: " + _assemblyName.FullName, null, setup, permissions);
                    _clientSponsor = new ClientSponsor();

                    Loader.InitDomainLoader(_domain);
                }

                Description = describer.GetAssemblyTitle(GetAssemblyName()) ?? System.IO.Path.GetFileName(Path);
                Initialize(describer, assemblyTypes);
            }
            finally
            {
                AppDomain.Unload(dd.Item1);
            }
        }