예제 #1
0
        public void PopulateFeature_ThrowsIfSingleAssemblyContainsMultipleAttributesWithTheSamePath()
        {
            // Arrange
            var path1    = "/Views/test/Index.cshtml";
            var path2    = "/views/test/index.cshtml";
            var expected = string.Join(
                Environment.NewLine,
                "The following precompiled view paths differ only in case, which is not supported:",
                path1,
                path2);
            var part            = new AssemblyPart(typeof(object).GetTypeInfo().Assembly);
            var featureProvider = new TestableViewsFeatureProvider(new Dictionary <AssemblyPart, IEnumerable <RazorViewAttribute> >
            {
                {
                    part,
                    new[]
                    {
                        new RazorViewAttribute(path1, typeof(object)),
                        new RazorViewAttribute(path2, typeof(object)),
                    }
                },
            });

            var applicationPartManager = new ApplicationPartManager();

            applicationPartManager.ApplicationParts.Add(part);
            applicationPartManager.FeatureProviders.Add(featureProvider);
            var feature = new ViewsFeature();

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(() => applicationPartManager.PopulateFeature(feature));

            Assert.Equal(expected, ex.Message);
        }
        public SharedCompilerCacheProvider(
            ApplicationPartManager applicationPartManager,
            IRazorViewEngineFileProviderAccessor fileProviderAccessor,
            IEnumerable <IApplicationFeatureProvider <ViewsFeature> > viewsFeatureProviders,
            IHostingEnvironment env)
        {
            lock (_synLock)
            {
                if (_cache == null)
                {
                    var feature = new ViewsFeature();

                    var featureProviders = applicationPartManager.FeatureProviders
                                           .OfType <IApplicationFeatureProvider <ViewsFeature> >()
                                           .ToList();

                    featureProviders.AddRange(viewsFeatureProviders);

                    var assemblyParts =
                        new AssemblyPart[]
                    {
                        new AssemblyPart(Assembly.Load(new AssemblyName(env.ApplicationName)))
                    };

                    foreach (var provider in featureProviders)
                    {
                        provider.PopulateFeature(assemblyParts, feature);
                    }

                    _cache = new CompilerCache(fileProviderAccessor.FileProvider, feature.Views);
                }
            }
        }
        private IViewCompiler CreateCompiler()
        {
            var feature = new ViewsFeature();

            var featureProviders = _applicationPartManager.FeatureProviders
                                   .OfType <IApplicationFeatureProvider <ViewsFeature> >()
                                   .ToList();

            featureProviders.AddRange(_viewsFeatureProviders);

            var assemblyParts =
                new AssemblyPart[]
            {
                new AssemblyPart(Assembly.Load(new AssemblyName(_hostingEnvironment.ApplicationName)))
            };

            foreach (var provider in featureProviders)
            {
                provider.PopulateFeature(assemblyParts, feature);
            }

            return(new SharedRazorViewCompiler(
                       _fileProviderAccessor.FileProvider,
                       _razorTemplateEngine,
                       _csharpCompiler,
                       _viewEngineOptions.CompilationCallback,
                       feature.ViewDescriptors,
                       _logger));
        }
예제 #4
0
 /// <summary>
 /// Carrega o assembly guardado.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="exception">Exception caso ocorra.</param>
 /// <returns></returns>
 public System.Reflection.Assembly LoadAssemblyGuarded(AssemblyPart name, out Exception exception)
 {
     try
     {
         exception = null;
         return(LoadAssembly(name));
     }
     catch (System.IO.FileNotFoundException exception2)
     {
         exception = exception2;
     }
     catch (System.IO.FileLoadException exception3)
     {
         exception = exception3;
     }
     catch (BadImageFormatException exception4)
     {
         exception = exception4;
     }
     catch (System.Reflection.ReflectionTypeLoadException exception5)
     {
         exception = exception5;
     }
     catch (Exception ex)
     {
         exception = ex;
     }
     return(null);
 }
예제 #5
0
        public static IMvcBuilder AddPlugableMvc(this IMvcBuilder mvc)
        {
            var intermediateProvider = mvc.Services.BuildServiceProvider();
            var locator = intermediateProvider.GetRequiredService <IPluginLocator>();

            locator.Load();
            var plugins = locator.Locate();

            // mvc.Services.ConfigureOptions<PluginAssetConfigureOptions>();

            //add application parts
            mvc.ConfigureApplicationPartManager(manager =>
            {
                foreach (var p in plugins)
                {
                    var part = new AssemblyPart(p.Value);
                    manager.ApplicationParts.Add(part);
                }
            });

            //add MVC services
            foreach (var pluginAction in plugins.SelectMany(x => x.Key.ConfigureServiceActions).OrderByDescending(x => x.Priority))
            {
                pluginAction.ConfigureServices(mvc.Services);
            }

            return(mvc);
        }
예제 #6
0
        public static ApplicationPartManager EnableItvExtensionViews(this ApplicationPartManager manager)
        {
            ApplicationPart part = new AssemblyPart(typeof(ApplicationPartExtensions).Assembly);

            manager.ApplicationParts.Add(part);
            return(manager);
        }
예제 #7
0
        public void PopulateFeature_PrefersViewsFromPartsWithHigherPrecedence()
        {
            // Arrange
            var part1 = new AssemblyPart(typeof(ViewsFeatureProvider).Assembly);
            var item1 = new TestRazorCompiledItem(typeof(StringBuilder), "mvc.1.0.view", "/Areas/Admin/Views/Shared/_Layout.cshtml", new object[] { });

            var part2 = new AssemblyPart(GetType().Assembly);
            var item2 = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", "/Areas/Admin/Views/Shared/_Layout.cshtml", new object[] { });
            var item3 = new TestRazorCompiledItem(typeof(string), "mvc.1.0.view", "/Areas/Admin/Views/Shared/_Partial.cshtml", new object[] { });

            var items = new Dictionary <AssemblyPart, IReadOnlyList <RazorCompiledItem> >
            {
                { part1, new[] { item1 } },
                { part2, new[] { item2, item3, } },
            };

            var featureProvider = new TestableViewsFeatureProvider(items, attributes: new Dictionary <AssemblyPart, IEnumerable <RazorViewAttribute> >());
            var partManager     = new ApplicationPartManager();

            partManager.ApplicationParts.Add(part1);
            partManager.ApplicationParts.Add(part2);
            partManager.FeatureProviders.Add(featureProvider);
            var feature = new ViewsFeature();

            // Act
            partManager.PopulateFeature(feature);

            // Assert
            Assert.Collection(feature.ViewDescriptors.OrderBy(f => f.RelativePath, StringComparer.Ordinal),
                              view => Assert.Same(item1, view.Item),
                              view => Assert.Same(item3, view.Item));
        }
예제 #8
0
        private static Assembly AssemblyFromPart(AssemblyPart assemblyPart)
        {
            var assemblyName = assemblyPart.Source.Replace(".dll", "");
            var assembly     = Assembly.Load(assemblyName);

            return(assembly);
        }
예제 #9
0
        /// <summary>
        /// Gets the type of <see cref="ViewInfoContainer"/> for the specified <paramref name="assemblyPart"/>.
        /// </summary>
        /// <param name="assemblyPart">The <see cref="AssemblyPart"/>.</param>
        /// <returns>The <see cref="ViewInfoContainer"/> <see cref="Type"/>.</returns>
        protected virtual Type GetViewInfoContainerType(AssemblyPart assemblyPart)
        {
#if NETSTANDARD1_6
            if (!assemblyPart.Assembly.IsDynamic && assemblyPart.Assembly.Location != null)
            {
                var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name
                                                  + PrecompiledViewsAssemblySuffix
                                                  + ".dll";
                var precompiledAssemblyFilePath = Path.Combine(
                    Path.GetDirectoryName(assemblyPart.Assembly.Location),
                    precompiledAssemblyFileName);

                if (File.Exists(precompiledAssemblyFilePath))
                {
                    try
                    {
                        System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(precompiledAssemblyFilePath);
                    }
                    catch (FileLoadException)
                    {
                        // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly.
                    }
                }
            }
#endif

            var precompiledAssemblyName = new AssemblyName(assemblyPart.Assembly.FullName);
            precompiledAssemblyName.Name = precompiledAssemblyName.Name + PrecompiledViewsAssemblySuffix;

            var typeName = $"{ViewInfoContainerNamespace}.{ViewInfoContainerTypeName},{precompiledAssemblyName}";
            return(Type.GetType(typeName));
        }
예제 #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages(options =>
            {
                options.Conventions.AddFolderApplicationModelConvention("/Movies",
                                                                        model => model.Filters.Add(new SampleAsyncPageFilter(Configuration)));
            });
            //.AddMvcOptions(option =>
            //{
            //    option.Filters.Add(new SampleAsyncPageFilter(Configuration));
            //});

            services.AddDbContext <RazorPagesMovieContext>(options =>
                                                           options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout        = TimeSpan.FromSeconds(10);
                options.Cookie.Name        = ".AdventureWorks.Session";
                options.Cookie.HttpOnly    = true;
                options.Cookie.IsEssential = true;
            });

            var assembly = typeof(Startup).GetTypeInfo().Assembly;
            // This creates an AssemblyPart, but does not create any related parts for items such as views.
            var part = new AssemblyPart(assembly);

            services.AddControllersWithViews()
            .ConfigureApplicationPartManager(apm => apm.ApplicationParts.Add(part));
        }
예제 #11
0
        private static Assembly GetFeatureAssembly(AssemblyPart assemblyPart)
        {
            if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty((string)assemblyPart.Assembly.Location))
            {
                return(null);
            }

            var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name
                                              + PrecompiledViewsAssemblySuffix
                                              + ".dll";

            var precompiledAssemblyFilePath = Path.Combine(
                Path.GetDirectoryName(assemblyPart.Assembly.Location),
                precompiledAssemblyFileName);

            if (File.Exists(precompiledAssemblyFilePath))
            {
                try
                {
                    return(Assembly.LoadFile(precompiledAssemblyFilePath));
                }
                catch (FileLoadException)
                {
                    // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly.
                }
            }

            return(null);
        }
예제 #12
0
        public void Add()
        {
            int n = Deployment.Current.Parts.Count;

            AssemblyPartCollection apc = new AssemblyPartCollection();

            Assert.Throws <ArgumentNullException> (delegate {
                apc.Add(null);
            }, "Add(null)");

            AssemblyPart ap1 = new AssemblyPart();

            ap1.Load(AssemblyPartTest.GetLibraryStream());
            Assert.AreEqual(String.Empty, ap1.Source, "Source-1");
            apc.Add(ap1);
            Assert.AreEqual(1, apc.Count, "Count-1");

            AssemblyPart ap2 = new AssemblyPart();

            ap2.Load(AssemblyPartTest.GetLibraryStream());
            Assert.AreEqual(String.Empty, ap2.Source, "Source-2");
            apc.Add(ap2);
            Assert.AreEqual(2, apc.Count, "Count-2");

            // no side effect on deployment
            Assert.AreEqual(n, Deployment.Current.Parts.Count, "Deployment.Current.Parts.Count");
        }
        private static IEnumerable <AssemblyPart> getAssemblyParts(StreamResourceInfo xapStreamInfo, out ObservableCollection <string> assemblyNames)
        {
            assemblyNames = new ObservableCollection <string>();
            Uri uri = new Uri("AppManifest.xaml", UriKind.Relative);
            StreamResourceInfo  resourceStream = Application.GetResourceStream(xapStreamInfo, uri);
            List <AssemblyPart> list           = new List <AssemblyPart>();

            if (resourceStream != null)
            {
                using (XmlReader reader = XmlReader.Create(resourceStream.Stream))
                {
                    if (!reader.ReadToFollowing("AssemblyPart"))
                    {
                        return(list);
                    }
                    do
                    {
                        string attribute = reader.GetAttribute("Source");
                        if (attribute != null)
                        {
                            AssemblyPart item = new AssemblyPart();
                            item.Source = attribute;
                            list.Add(item);
                            assemblyNames.Add(attribute.Replace(".dll", ""));
                        }
                    }while (reader.ReadToNextSibling("AssemblyPart"));
                }
            }
            return(list);
        }
    public void PopulateFeature_PopulatesRazorCompiledItemsFromTypeAssembly()
    {
        // Arrange
        var item1 = Mock.Of <RazorCompiledItem>(i => i.Identifier == "Item1" && i.Type == typeof(TestView));
        var item2 = Mock.Of <RazorCompiledItem>(i => i.Identifier == "Item2" && i.Type == typeof(TestPage));

        var assembly = new TestAssembly(new[]
        {
            new RazorCompiledItemAttribute(typeof(TestView), "mvc.1.0.razor-page", "Item1"),
            new RazorCompiledItemAttribute(typeof(TestView), "mvc.1.0.razor-view", "Item1"),
        });

        var part1 = new AssemblyPart(assembly);
        var part2 = new Mock <ApplicationPart>();

        part2
        .As <IRazorCompiledItemProvider>()
        .Setup(p => p.CompiledItems)
        .Returns(new[] { item1, item2, });
        var featureProvider = new RazorCompiledItemFeatureProvider();
        var feature         = new ViewsFeature();

        // Act
        featureProvider.PopulateFeature(new[] { part1, part2.Object }, feature);

        // Assert
        Assert.Equal(new[] { item1, item2 }, feature.ViewDescriptors.Select(d => d.Item));
    }
예제 #15
0
        private void LoadAssembly(Stream stream, AssemblyPart assemblyPart, Action <Assembly> callback)
        {
            Assembly a = null;

            try
            {
                Stream assemblyStream = Application.GetResourceStream(
                    new StreamResourceInfo(stream, null),
                    new Uri(assemblyPart.Source, UriKind.Relative)).Stream;
                a = assemblyPart.Load(assemblyStream);

                if (callback != null)
                {
                    callback(a);
                }
            }
            catch (NullReferenceException)
            {
                WebClient wc = new WebClient();
                wc.OpenReadCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        a = assemblyPart.Load(e.Result);
                    }

                    if (callback != null)
                    {
                        callback(a);
                    }
                };
                wc.OpenReadAsync(new Uri(assemblyPart.Source, UriKind.RelativeOrAbsolute));
            }
        }
예제 #16
0
        void TLYC1_TileClick(object sender, TileClickEventArgs e)
        {
            ma       = e.Tile.Name.ToString();
            tentitle = e.Tile.Header.ToString();
            var WbClnt = new WebClient();//Tao WebClient

            WbClnt.OpenReadCompleted += (a, b) =>
            {
                if (b.Error == null)
                {
                    AssemblyPart assmbpart = new AssemblyPart();
                    Assembly     assembly  = assmbpart.Load(b.Result);
                    Object       Obj       = assembly.CreateInstance("HPA.Announcement" + "." + "ViewAnnouncement"); //Truy xuat file dll
                    if (Obj != null)                                                                                 //Neu co file dll thi tao ChildWindow
                    {
                        ChildWindow child = (ChildWindow)assembly.CreateInstance("HPA.Announcement" + "." + "ViewAnnouncement");
                        child.Width  = (double)HtmlPage.Window.Eval("screen.availWidth") - 100;
                        child.Height = (double)HtmlPage.Window.Eval("screen.availHeight") - 100;
                        child.Show();
                    }
                    else
                    {
                        MessageBox.Show("Page not exist");
                    }                                          //Khong ton tai page thi bao loi
                }
                else
                {
                    MessageBox.Show("Page not exist");
                }                                          //Khong ton tai file dll thi bao loi
            };
            WbClnt.OpenReadAsync(new Uri("http://localhost:10511/Control/" + "HPA.Announcement" + ".dll", UriKind.Absolute));
        }
        public CollectibleAssemblyLoadContext Get(string moduleName, IServiceCollection services, ApplicationPartManager apm, IServiceScope scope, InBizModuleEnum inBizModuleEnum = InBizModuleEnum.Boot)
        {
            string folderName = inBizModuleEnum == InBizModuleEnum.Boot ? "boot" : "hot";
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext(moduleName);
            IReferenceLoader  loader              = scope.ServiceProvider.GetService <IReferenceLoader>();
            InBizModuleLoader inBizModuleLoader   = scope.ServiceProvider.GetService <InBizModuleLoader>();
            string            filePath            = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", folderName, moduleName, $"{moduleName}.dll");
            string            viewFilePath        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", folderName, moduleName, $"{moduleName}.Views.dll");
            string            referenceFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", folderName, moduleName);

            if (File.Exists(filePath))
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    Assembly assembly = context.LoadFromStream(fs);
                    context.SetEntryPoint(assembly);
                    loader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);
                    AssemblyPart controllerAssemblyPart = new AssemblyPart(assembly);
                    apm.ApplicationParts.Add(controllerAssemblyPart);
                    //services.AddAssembly(assembly);
                    foreach (var type in assembly.GetTypes())
                    {
                        if (AbpModule.IsAbpModule(type))
                        {
                            inBizModuleLoader.LoadModules(services, type, new PlugInSourceList());
                            inBizModuleLoader.ConfigureServices(services);
                            inBizModuleLoader.InitializeModules(new Volo.Abp.ApplicationInitializationContext(scope.ServiceProvider));
                        }
                    }
                    var resources = assembly.GetManifestResourceNames();
                    if (resources.Any())
                    {
                        foreach (var item in resources)
                        {
                            var stream = new MemoryStream();
                            var source = assembly.GetManifestResourceStream(item);
                            source.CopyTo(stream);
                            context.RegisterResource(item, stream.ToArray());
                        }
                    }
                }
            }
            else
            {
                return(null);
            }
            if (File.Exists(viewFilePath))
            {
                using (FileStream fsView = new FileStream(viewFilePath, FileMode.Open))
                {
                    Assembly vwAssembly = context.LoadFromStream(fsView);
                    loader.LoadStreamsIntoContext(context, referenceFolderPath, vwAssembly);

                    InBizRazorAssemblyPart moduleView = new InBizRazorAssemblyPart(vwAssembly, moduleName);
                    apm.ApplicationParts.Add(moduleView);
                }
            }
            context.Enable();
            return(context);
        }
예제 #18
0
        private static AssemblyPart GetApiAssembly()
        {
            var assembly = typeof(EntityTypesController).GetTypeInfo().Assembly;
            var part     = new AssemblyPart(assembly);

            return(part);
        }
예제 #19
0
 public System.IO.Stream GetAssemblyStream(AssemblyPart name)
 {
     System.IO.Stream result = null;
     if (!string.IsNullOrEmpty(_packageFileName) && System.IO.File.Exists(_packageFileName))
     {
         var fileInfo = new System.IO.FileInfo(_packageFileName);
         if (fileInfo.Length > 0)
         {
             using (var packageStream = System.IO.File.OpenRead(_packageFileName))
             {
                 result = new System.IO.MemoryStream();
                 if (Colosoft.IO.Xap.XapPackage.GetAssembly(packageStream, result, name))
                 {
                     result.Seek(0, System.IO.SeekOrigin.Begin);
                 }
                 else
                 {
                     result.Dispose();
                     result = null;
                 }
             }
         }
     }
     return(result);
 }
예제 #20
0
        private static List <AssemblyPart> GetAssemblyParts(StreamResourceInfo sriXap)
        {
            Uri appManifestUri = new Uri("AppManifest.xaml", UriKind.Relative);
            StreamResourceInfo  sriAppManifest = Application.GetResourceStream(sriXap, appManifestUri);
            List <AssemblyPart> list           = new List <AssemblyPart>();

            if (sriAppManifest != null)
            {
                using (XmlReader reader = XmlReader.Create(sriAppManifest.Stream))
                {
                    while (reader.Read())
                    {
                        if ((reader.NodeType == XmlNodeType.Element) &&
                            (reader.Name.Equals("AssemblyPart")))
                        {
                            while (reader.MoveToNextAttribute())
                            {
                                if (reader.Name.Equals("Source"))
                                {
                                    AssemblyPart part = new AssemblyPart();
                                    part.Source = reader.Value;
                                    list.Add(part);
                                }
                            }
                        }
                    }
                }
            }
            return(list);
        }
예제 #21
0
        private static bool IsNotSpecialAssembly(AssemblyPart ap)
        {
            if (ap.Source.Equals("System.Windows.Controls.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (ap.Source.Equals("System.Xml.Linq.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (ap.Source.Equals("System.Xml.Serialization.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (ap.Source.Equals("Microsoft.Silverlight.Testing.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (ap.Source.Equals("Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (ap.Source.Equals("StatLight.Client.Harness.MSTest.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (ap.Source.Equals("StatLight.Client.Harness.dll", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            return(true);
        }
예제 #22
0
        public void Add(Assembly featureAssembly)
        {
            _logger.LogDebug($"Adding assembly '{featureAssembly.FullName} to ApplicationPartManager.'");
            var assemblyPart = new AssemblyPart(featureAssembly);

            _appPartManager.ApplicationParts.Add(assemblyPart);
        }
        private static Type GetTypeFromAnyLoadedAssembly(string typeName)
        {
            Type t = null;

            foreach (AssemblyPart ap in Deployment.Current.Parts)
            {
                StreamResourceInfo sri = Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative));
                if (sri != null)
                {
                    Assembly theAssembly = new AssemblyPart().Load(sri.Stream);
                    if (theAssembly != null)
                    {
                        t = Type.GetType(
                            typeName + "," + theAssembly,
                            false /* don't throw on error, just return null */);
                    }
                }
                if (t != null)
                {
                    break;
                }
            }

            return(t);
        }
예제 #24
0
        private Assembly GetViewAssembly(AssemblyPart assemblyPart)
        {
            if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location))
            {
                return(null);
            }

            for (var i = 0; i < ViewAssemblySuffixes.Count; i++)
            {
                var fileName = assemblyPart.Assembly.GetName().Name + ViewAssemblySuffixes[i] + ".dll";
                var filePath = Path.Combine(Path.GetDirectoryName(assemblyPart.Assembly.Location), fileName);

                if (File.Exists(filePath))
                {
                    try
                    {
                        return(Assembly.LoadFile(filePath));
                    }
                    catch (FileLoadException)
                    {
                        // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly.
                    }
                }
            }

            return(null);
        }
        private void CreateChildPage(string asb, string cls)
        {
            var WbClnt = new WebClient();//Tao WebClient

            WbClnt.OpenReadCompleted += (a, b) =>
            {
                if (b.Error == null)
                {
                    AssemblyPart assmbpart = new AssemblyPart();
                    Assembly     assembly  = assmbpart.Load(b.Result);
                    Object       Obj       = assembly.CreateInstance(asb + "." + cls); //Truy xuat file dll
                    if (Obj != null)                                                   //Neu co file dll thi tao ChildWindow
                    {
                        ChildWindow child = (ChildWindow)assembly.CreateInstance(asb + "." + cls);
                        child.Width  = (double)HtmlPage.Window.Eval("screen.availWidth") - 100;
                        child.Height = (double)HtmlPage.Window.Eval("screen.availHeight") - 100;
                        child.Show();
                    }
                    else
                    {
                        MessageBox.Show("Page not exist");
                    }                                          //Khong ton tai page thi bao loi
                }
                else
                {
                    MessageBox.Show("Page not exist");
                }                                          //Khong ton tai file dll thi bao loi
            };
            WbClnt.OpenReadAsync(new Uri("http://localhost:10511/Control/" + asb + ".dll", UriKind.Absolute));
        }
예제 #26
0
        public void UserThread()
        {
            // created out of the thread
            AssemblyPart ap = new AssemblyPart();

            bool   complete = false;
            bool   status   = false;
            int    tid      = Thread.CurrentThread.ManagedThreadId;
            Thread t        = new Thread(() => {
                try {
                    Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, tid, "ManagedThreadId");

                    Assert.Throws <UnauthorizedAccessException> (delegate {
                        new AssemblyPart();
                    }, "ctor");
                    Assert.Throws <UnauthorizedAccessException> (delegate {
                        Assert.AreEqual(String.Empty, ap.Source, "Source");
                    }, "Source");

                    Assert.IsNull(ap.Load(Stream.Null), "Load(Stream.Null)");

                    Assert.IsNotNull(ap.Load(GetLibraryStream()), "Load");
                    status = true;
                }
                finally {
                    complete = true;
                    Assert.IsTrue(status, "Success");
                }
            });

            t.Start();
            EnqueueConditional(() => complete);
            EnqueueTestComplete();
        }
예제 #27
0
        public static void AddAdsApplicationParts(this ApplicationPartManager applicationPartManager)
        {
            Assembly     assembly = typeof(AdsController).GetTypeInfo().Assembly;
            AssemblyPart part     = new AssemblyPart(assembly);

            applicationPartManager.ApplicationParts.Add(part);
        }
예제 #28
0
        /// <summary>
        /// Load from url
        /// </summary>
        /// <param name="assemblyFileName">file or path, including .dll</param>
        /// <param name="baseDirectory">basepath, optional</param>
        /// <returns></returns>
        public static Assembly LoadFromPath(string assemblyFileName, string baseDirectory = null)
        {
            string fullFileName = baseDirectory == null ? assemblyFileName : Path.Combine(baseDirectory, assemblyFileName);

            InternalLogger.Info("Loading assembly file: {0}", fullFileName);
#if NETSTANDARD1_5
            try
            {
                var assemblyName = System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(fullFileName);
                return(Assembly.Load(assemblyName));
            }
            catch (Exception ex)
            {
                // this doesn't usually work
                InternalLogger.Warn(ex, "Fallback to AssemblyLoadContext.Default.LoadFromAssemblyPath for file: {0}", fullFileName);
                return(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(fullFileName));
            }
#elif SILVERLIGHT && !WINDOWS_PHONE
            var      stream       = Application.GetResourceStream(new Uri(assemblyFileName, UriKind.Relative));
            var      assemblyPart = new AssemblyPart();
            Assembly assembly     = assemblyPart.Load(stream.Stream);
            return(assembly);
#else
            Assembly asm = Assembly.LoadFrom(fullFileName);
            return(asm);
#endif
        }
예제 #29
0
        private static void LoadAssemblyFromStream(Stream sourceStream, AssemblyPart assemblyPart)
        {
            Stream assemblyStream = Application.GetResourceStream(new StreamResourceInfo(sourceStream, null),
                                                                  new Uri(assemblyPart.Source, UriKind.Relative)).Stream;

            assemblyPart.Load(assemblyStream);
        }
예제 #30
0
        private static IEnumerable <AssemblyPart> GetParts(Stream stream)
        {
            List <AssemblyPart> assemblyParts = new List <AssemblyPart>();

            var streamReader = new StreamReader(Application.GetResourceStream(new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml", UriKind.Relative)).Stream);

            using (XmlReader xmlReader = XmlReader.Create(streamReader))
            {
                xmlReader.MoveToContent();
                while (xmlReader.Read())
                {
                    if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "Deployment.Parts")
                    {
                        using (XmlReader xmlReaderAssemblyParts = xmlReader.ReadSubtree())
                        {
                            while (xmlReaderAssemblyParts.Read())
                            {
                                if (xmlReaderAssemblyParts.NodeType == XmlNodeType.Element && xmlReaderAssemblyParts.Name == "AssemblyPart")
                                {
                                    AssemblyPart assemblyPart = new AssemblyPart();
                                    assemblyPart.Source = xmlReaderAssemblyParts.GetAttribute("Source");
                                    assemblyParts.Add(assemblyPart);
                                }
                            }
                        }

                        break;
                    }
                }
            }

            return(assemblyParts);
        }
        private static Type GetTypeFromAnyLoadedAssembly(string typeName)
        {
            Type t = null;

            foreach (AssemblyPart ap in Deployment.Current.Parts)
            {
                StreamResourceInfo sri = Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative));
                if (sri != null)
                {
                    Assembly theAssembly = new AssemblyPart().Load(sri.Stream);
                    if (theAssembly != null)
                    {
                        t = Type.GetType(
                                        typeName + "," + theAssembly,
                                        false /* don't throw on error, just return null */);
                    }
                }
                if (t != null)
                {
                    break;
                }
            }

            return t;
        }
        private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
        {
            extensionsElement.AssertName("extensions");

            foreach (var addElement in extensionsElement.Elements("add"))
            {
                var prefix = addElement.GetOptionalAttribute("prefix", null);

                if (prefix != null)
                {
                    prefix = prefix + ".";
                }

                var type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
                if (type != null)
                {
                    configurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
                }

            #if !WINDOWS_PHONE
                var assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
                if (assemblyFile != null)
                {
                    try
                    {
            #if SILVERLIGHT
                                var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
                                var assemblyPart = new AssemblyPart();
                                Assembly asm = assemblyPart.Load(si.Stream);
            #else

                        var fullFileName = Path.Combine(baseDirectory, assemblyFile);
                        InternalLogger.Info("Loading assembly file: {0}", fullFileName);

                        var asm = Assembly.LoadFrom(fullFileName);
            #endif
                        configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }

                        InternalLogger.Error("Error loading extensions: {0}", exception);
                        if (LogManager.ThrowExceptions)
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
                        }
                    }

                    continue;
                }

                var assemblyName = addElement.GetOptionalAttribute("assembly", null);
                if (assemblyName != null)
                {
                    try
                    {
                        InternalLogger.Info("Loading assembly name: {0}", assemblyName);
            #if SILVERLIGHT
                        var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
                        var assemblyPart = new AssemblyPart();
                        Assembly asm = assemblyPart.Load(si.Stream);
            #else
                        var asm = Assembly.Load(assemblyName);
            #endif

                        configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }

                        InternalLogger.Error("Error loading extensions: {0}", exception);
                        if (LogManager.ThrowExceptions)
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
                        }
                    }

                    continue;
                }
            #endif
            }
        }