System.Reflection.Assembly.Load(string)

Here are the examples of the csharp api System.Reflection.Assembly.Load(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

515 Examples 7

19 Source : CrossAppDomainAssemblyResolver.cs
with MIT License
from atifaziz

public string GetreplacedemblyPath (string name)
            {
                var replacedem = System.Reflection.replacedembly.Load (name);
                if (replacedem != null)
                    return replacedem.Location;
                return null;
            }

19 Source : Utilities.cs
with MIT License
from Auros

public static void replacedemblyFromPath(string inputPath, out replacedembly replacedembly, out string path)
        {
            string[] parameters = inputPath.Split(':');
            switch (parameters.Length)
            {
                case 1:
                    path = parameters[0];
                    replacedembly = replacedembly.Load(path.Substring(0, path.IndexOf('.')));
                    break;
                case 2:
                    path = parameters[1];
                    replacedembly = replacedembly.Load(parameters[0]);
                    break;
                default:
                    throw new Exception($"Could not process resource path {inputPath}");
            }
        }

19 Source : DbSearchHelper.cs
with MIT License
from awesomedotnetcore

public static IQueryable GetIQueryable(object obj, string funcName, string enreplacedyName, string nameSpace)
        {
            Type type = obj.GetType();
            MethodInfo method = type.GetMethod(funcName);
            var enreplacedyType = replacedembly.Load(nameSpace).GetTypes().Where(x => x.Name.ToLower().Contains(enreplacedyName.ToLower())).FirstOrDefault();
            if (enreplacedyType.IsNullOrEmpty())
                throw new Exception("请输入有效的实体名!");

            var iQueryable = (IQueryable)method.MakeGenericMethod(enreplacedyType).Invoke(obj, null);

            return iQueryable;
        }

19 Source : QueryResolver.cs
with MIT License
from azist

private CrudQueryHandler searchForScript(string name)
    {
      var asm = replacedembly.Load(m_Scriptreplacedembly);
      var asmname = asm.FullName;
      var ic = asmname.IndexOf(',');
      if (ic > 0)
        asmname = asmname.Substring(0, ic);
      var resources = asm.GetManifestResourceNames();

      var resName = name + ComponentDirector.ScriptFileSuffix;

      var res = resources.FirstOrDefault(r => r.EqualsIgnoreCase(resName) || r.EqualsIgnoreCase(asmname + "." + resName));

      if (res != null)
      {
        using (var stream = asm.GetManifestResourceStream(res))
        using (var reader = new StreamReader(stream))
        {
          var script = reader.ReadToEnd();
          var qsource = new QuerySource(name, script);
          return ComponentDirector.MakeScriptQueryHandler(qsource);
        }
      }
      return null;
    }

19 Source : Startup.cs
with Apache License 2.0
from Azure-App-Service

public void ConfigureServices(IServiceCollection services)
        {
            Console.WriteLine(@"Configure Services : " + DateTime.Now.ToString("hh.mm.ss.ffffff"));
            FileSystemHelpers.DeleteDirectorySafe("/home/site/locks/deployment");
            services.Configure<FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 52428800;
                options.ValueCountLimit = 500000;
                options.KeyLengthLimit = 500000;
            });

            services.AddRoutereplacedyzer();

            // Kudu.Services contains all the Controllers 
            var kuduServicesreplacedembly = replacedembly.Load("Kudu.Services");

            services.AddMvcCore()
                .AddRazorPages()
                .AddAuthorization()
                .AddJsonFormatters()
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
                .AddApplicationPart(kuduServicesreplacedembly).AddControllersreplacedervices()
                .AddApiExplorer();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {replacedle = "Kudu API Docs"});
                // Setting the comments path for the Swagger JSON and UI.
                var xmlFile = $"Kudu.Services.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services.AddGZipCompression();

            services.AddDirectoryBrowser();

            services.AddDataProtection();

            services.AddLogging(
                builder =>
                {
                    builder.AddFilter("Microsoft", LogLevel.Warning)
                        .AddFilter("System", LogLevel.Warning)
                        .AddConsole();
                });

            services.AddSingleton<IHttpContextAccessor>(new HttpContextAccessor());
            services.TryAddSingleton<ISystemEnvironment>(SystemEnvironment.Instance);
            services.AddSingleton<ILinuxConsumptionEnvironment, LinuxConsumptionEnvironment>();
            services.AddSingleton<ILinuxConsumptionInstanceManager, LinuxConsumptionInstanceManager>();
            services.AddSingleton<IFileSystemPathProvider, FileSystemPathProvider>();
            services.AddSingleton<IStorageClient, StorageClient>();

            KuduWebUtil.EnsureHomeEnvironmentVariable();

            KuduWebUtil.EnsureSiteBitnessEnvironmentVariable();

            var fileSystemPathProvider = new FileSystemPathProvider(new MeshPersistentFileSystem(SystemEnvironment.Instance,
                new MeshServiceClient(SystemEnvironment.Instance, new HttpClient()), new StorageClient(SystemEnvironment.Instance)));
            IEnvironment environment = KuduWebUtil.GetEnvironment(_hostingEnvironment, fileSystemPathProvider);

            _webAppRuntimeEnvironment = environment;

            services.AddSingleton(_ => new HttpClient());
            services.AddSingleton<IMeshServiceClient>(s =>
            {
                if (environment.IsOnLinuxConsumption)
                {
                    var httpClient = s.GetService<HttpClient>();
                    var systemEnvironment = s.GetService<ISystemEnvironment>();
                    return new MeshServiceClient(systemEnvironment, httpClient);
                }
                else
                {
                    return new NullMeshServiceClient();
                }
            });
            services.AddSingleton<IMeshPersistentFileSystem>(s =>
            {
                if (environment.IsOnLinuxConsumption)
                {
                    var meshServiceClient = s.GetService<IMeshServiceClient>();
                    var storageClient = s.GetService<IStorageClient>();
                    var systemEnvironment = s.GetService<ISystemEnvironment>();
                    return new MeshPersistentFileSystem(systemEnvironment, meshServiceClient, storageClient);
                }
                else
                {
                    return new NullMeshPersistentFileSystem();
                }
            });

            KuduWebUtil.EnsureDotNetCoreEnvironmentVariable(environment);

            // CORE TODO Check this
            // fix up invalid /home/site/deployments/settings.xml
            KuduWebUtil.EnsureValidDeploymentXmlSettings(environment);

            // Add various folders that never change to the process path. All child processes will inherit this
            KuduWebUtil.PrependFoldersToPath(environment);

            // Add middleware for Linux Consumption authentication and authorization
            // when KuduLIte is running in service fabric mesh
            services.AddLinuxConsumptionAuthentication();
            services.AddLinuxConsumptionAuthorization(environment);

            // General
            services.AddSingleton<IServerConfiguration, ServerConfiguration>();

            // CORE TODO Looks like this doesn't ever actually do anything, can refactor out?
            services.AddSingleton<IBuildPropertyProvider>(new BuildPropertyProvider());

            _noContextDeploymentsSettingsManager =
                new DeploymentSettingsManager(new XmlSettings.Settings(KuduWebUtil.GetSettingsPath(environment)));
            TraceServices.TraceLevel = _noContextDeploymentsSettingsManager.GetTraceLevel();

            // Per request environment
            services.AddScoped(sp =>
                KuduWebUtil.GetEnvironment(_hostingEnvironment, sp.GetRequiredService <IFileSystemPathProvider>(), sp.GetRequiredService<IDeploymentSettingsManager>()));

            services.AddDeploymentServices(environment);

            /*
             * CORE TODO Refactor ITracerFactory/ITracer/GetTracer()/
             * ILogger needs serious refactoring:
             * - Names should be changed to make it clearer that ILogger is for deployment
             *   logging and ITracer and friends are for Kudu tracing
             * - ILogger is a first-clreplaced citizen in .NET core and has it's own meaning. We should be using it
             *   where appropriate (and not name-colliding with it)
             * - ITracer vs. ITraceFactory is redundant and confusing.
             * - TraceServices only serves to confuse stuff now that we're avoiding
             */
            Func<IServiceProvider, ITracer> resolveTracer = KuduWebUtil.GetTracer;
            ITracer CreateTracerThunk() => resolveTracer(services.BuildServiceProvider());

            // First try to use the current request profiler if any, otherwise create a new one
            var traceFactory = new TracerFactory(() =>
            {
                var sp = services.BuildServiceProvider();
                var context = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
                return TraceServices.GetRequestTracer(context) ?? resolveTracer(sp);
            });

            services.AddScoped<ITracer>(sp =>
            {
                var context = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
                return TraceServices.GetRequestTracer(context) ?? NullTracer.Instance;
            });

            services.AddSingleton<ITraceFactory>(traceFactory);

            TraceServices.SetTraceFactory(CreateTracerThunk);

            services.AddSingleton<IDictionary<string, IOperationLock>>(
                KuduWebUtil.GetNamedLocks(traceFactory, environment));

            // CORE TODO ShutdownDetector, used by LogStreamManager.
            //var shutdownDetector = new ShutdownDetector();
            //shutdownDetector.Initialize()

            var noContextTraceFactory = new TracerFactory(() =>
                KuduWebUtil.GetTracerWithoutContext(environment, _noContextDeploymentsSettingsManager));

            services.AddTransient<Ireplacedytics>(sp => new replacedytics(sp.GetRequiredService<IDeploymentSettingsManager>(),
                sp.GetRequiredService<IServerConfiguration>(),
                noContextTraceFactory));

            // CORE TODO
            // Trace shutdown event
            // Cannot use shutdownDetector.Token.Register because of race condition
            // with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute
            // Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager);

            // LogStream service
            services.AddLogStreamService(_webAppRuntimeEnvironment,traceFactory);

            // Deployment Service
            services.AddWebJobsDependencies();

            services.AddScoped<ILogger>(KuduWebUtil.GetDeploymentLogger);

            services.AddScoped<IDeploymentManager, DeploymentManager>();
            
            services.AddScoped<IFetchDeploymentManager, FetchDeploymentManager>();

            services.AddScoped<IScanManager, ScanManager>();
            
            services.AddScoped<ISSHKeyManager, SSHKeyManager>();

            services.AddScoped<IRepositoryFactory>(
                sp => KuduWebUtil.GetDeploymentLock(traceFactory, environment).RepositoryFactory =
                    new RepositoryFactory(
                        sp.GetRequiredService<IEnvironment>(), sp.GetRequiredService<IDeploymentSettingsManager>(),
                        sp.GetRequiredService<ITraceFactory>()));

            services.AddScoped<IApplicationLogsReader, ApplicationLogsReader>();

            // Git server
            services.AddGitServer(KuduWebUtil.GetDeploymentLock(traceFactory, environment));

            // Git Servicehook Parsers
            services.AddGitServiceHookParsers();

            services.AddScoped<ICommandExecutor, CommandExecutor>();

            // Required for proxying requests to dotnet-monitor. Increase
            // the default time to a bigger number because memory dump requests
            // can take a few minutes to finish
            services.AddHttpClient("DotnetMonitorProxyClient", client =>
            {
                client.Timeout = TimeSpan.FromMinutes(10);
            });

            services.AddProxies();

            // KuduWebUtil.MigrateSite(environment, noContextDeploymentsSettingsManager);
            // RemoveOldTracePath(environment);
            // RemoveTempFileFromUserDrive(environment);

            // CORE TODO Windows Fix: Temporary fix for https://github.com/npm/npm/issues/5905
            //EnsureNpmGlobalDirectory();
            //EnsureUserProfileDirectory();

            //// Skip SSL Certificate Validate
            //if (Environment.SkipSslValidation)
            //{
            //    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //}

            //// Make sure webpages:Enabled is true. Even though we set it in web.config, it could be overwritten by
            //// an Azure AppSetting that's supposed to be for the site only but incidently affects Kudu as well.
            ConfigurationManager.AppSettings["webpages:Enabled"] = "true";

            //// Kudu does not rely owin:appStartup.  This is to avoid Azure AppSetting if set.
            if (ConfigurationManager.AppSettings?["owin:appStartup"] != null)
            {
                // Set the appSetting to null since we cannot use AppSettings.Remove(key) (ReadOnly exception!)
                ConfigurationManager.AppSettings["owin:appStartup"] = null;
            }

            //RegisterRoutes(kernel, RouteTable.Routes);

            //// Register the default hubs route: ~/signalr
            //GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);
            //GlobalConfiguration.Configuration.Filters.Add(
            //    new TraceDeprecatedActionAttribute(
            //        kernel.Get<Ireplacedytics>(),
            //        kernel.Get<ITraceFactory>()));
            //GlobalConfiguration.Configuration.Filters.Add(new EnsureRequestIdHandlerAttribute());

            //FileTarget target = LogManager.Configuration.FindTargetByName("file") as FileTarget;
            //String logfile = _webAppRuntimeEnvironment.LogFilesPath + "/.txt";
            //target.FileName = logfile;
        }

19 Source : MenuRenderer.cs
with MIT License
from BEagle1984

private static string GetSilverbackVersion() =>
            replacedembly.Load("Silverback.Core").GetName().Version?.ToString(3) ?? "x.x.x";

19 Source : AssemblyLoader.cs
with Apache License 2.0
from beetlex-io

public void Loadreplacedembly(string path)
		{

			DirectoryInfo directory = new DirectoryInfo(path);
			foreach (FileInfo item in directory.GetFiles("*.dll"))
			{
				try
				{
					string filename = Path.GetFileNameWithoutExtension(item.FullName);
					replacedembly replacedembly = replacedembly.Load(filename);
					foreach (Type type in replacedembly.GetTypes())
					{
						if (type.GetInterface("Beetle.DTCore.ITestCase") != null && !type.IsAbstract)
						{
							ITestCase tcase = (ITestCase)Activator.CreateInstance(type);
							mTests.Add(tcase);
						}
					}
					AddReference(item.FullName);
					//foreach (Type type in replacedembly.GetTypes())
					//{
					//    if (type.GetInterface("Glue4Net.IAppModule") != null)
					//    {
					//        mModules.Add((IAppModule)Activator.CreateInstance(type));
					//    }
					//}
				}

				catch (Exception e_)
				{
					if (Log != null)
						Log.Error("<{0}> domain load {1} replacedembly error:{2}", AppName, item.Name, e_.Message);
				}
			}
			if (CompilerFiles)
			{
				LoadVB(path);
				LoadCS(path);
			}
		}

19 Source : TestTools.cs
with MIT License
from BepInEx

public void replacedemblyLoad(string replacedemblyName)
			{
				_ = replacedembly.Load(replacedemblyName);
			}

19 Source : LuaReflection.cs
with MIT License
from bjfumac

bool Loadreplacedembly(string name)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].GetName().Name == name)
                {
                    return true;
                }
            }                

            replacedembly replacedembly = replacedembly.Load(name);

            if (replacedembly == null)
            {
                replacedembly = replacedembly.Load(replacedemblyName.GetreplacedemblyName(name));
            }

            if (replacedembly != null && !list.Contains(replacedembly))
            {
                list.Add(replacedembly);
            }

            return replacedembly != null;
        }

19 Source : RuntimeUtilities.cs
with MIT License
from BlazorExtensions

static public Func<Object, Object> GetFunc(string replacedemblyFile, string typeName, string methodName)
        {
            Console.WriteLine($"CS::GetFunc: replacedemblyFile: {replacedemblyFile} | TypeName: {typeName} | MethodName: {methodName} ");
            try {
                var replacedembly = replacedembly.Load(replacedemblyFile);
                var wrap = ClrFuncReflectionWrap.Create(replacedembly, typeName, methodName);
                Console.WriteLine("CS::GetFunc::End");
                return new Func<Object, Object>(wrap.Call);
            }
            catch (Exception exc)
            {
                Console.WriteLine($"CS::GetFunc::Exception - {exc.Message}");
                throw exc;
            }

        }

19 Source : IdentityRepositoryFactory.cs
with Apache License 2.0
from bluedoctor

public static IIdenreplacedyRepository CreateInstance()
        {
            if (_IIdenreplacedyRepository != null)
                return _IIdenreplacedyRepository;
            string cnfig = System.Configuration.ConfigurationManager.AppSettings["IdenreplacedyRepository"];
            if (string.IsNullOrEmpty(cnfig))
                throw new Exception("请在appSettings配置名称为 IdenreplacedyRepository 的IIdenreplacedyRepository 接口实现类,例如:\"PWMIS.OAuth2.AuthorizationCenter.Repository.SimpleIdenreplacedyRepository,PWMIS.OAuth2.AuthorizationCenter\"");
            string[] arrTemp = cnfig.Split(',');
            string providerreplacedembly = arrTemp[1];
            string providerType = arrTemp[0];
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.Load(providerreplacedembly);
            object provider = replacedembly.CreateInstance(providerType);
            if (provider is IIdenreplacedyRepository)
            {
                IIdenreplacedyRepository result = provider as IIdenreplacedyRepository;
                _IIdenreplacedyRepository = result;
                return result;
            }
            else
            {
                throw new InvalidOperationException("当前指定的的提供程序不是 IIdenreplacedyRepository 接口实现类,请确保应用程序进行了正确的配置(在appSettings配置名称为 IdenreplacedyRepository 的配置)。");
            }
        }

19 Source : StaticLuaCallbacks.cs
with MIT License
from blueberryzzz

[MonoPInvokeCallback(typeof(LuaCSFunction))]
        public static int Loadreplacedembly(RealStatePtr L)
        {
#if UNITY_WSA && !UNITY_EDITOR
            return LuaAPI.luaL_error(L, "xlua.load_replacedembly no support in uwp!");
#else
            try
            {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
                string replacedemblyName = LuaAPI.lua_tostring(L, 1);

                replacedembly replacedembly = null;

                try
                {
                    replacedembly = replacedembly.Load(replacedemblyName);
                }
                catch (BadImageFormatException)
                {
                    // The replacedemblyName was invalid.  It is most likely a path.
                }

                if (replacedembly == null)
                {
                    replacedembly = replacedembly.Load(replacedemblyName.GetreplacedemblyName(replacedemblyName));
                }

                if (replacedembly != null && !translator.replacedemblies.Contains(replacedembly))
                {
                    translator.replacedemblies.Add(replacedembly);
                }
                return 0;
            }
            catch (System.Exception e)
            {
                return LuaAPI.luaL_error(L, "c# exception in xlua.load_replacedembly:" + e);
            }
#endif
        }

19 Source : ExceptronClient.cs
with GNU General Public License v3.0
from bonarr

private string GetMaximumFrameworkVersion()
        {
            var clrVersion = Environment.Version;

            if (clrVersion.Major == 2)
            {
                //Check if 2.0 or 3.5
                try
                {
                    replacedembly.Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                    return "3.5";
                }
                catch (Exception)
                {
                }

                return "2.0";
            }

            if (clrVersion.Major == 4)
            {
                //Check if 4.0 or 4.5
                try
                {
                    replacedembly.Load("System.Threading.Tasks.Parallel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                    return "4.5";
                }
                catch (Exception)
                {
                }

                return "4.0";
            }

            return "Unknown";
        }

19 Source : ReflectionExtensionFixture.cs
with GNU General Public License v3.0
from bonarr

[Test]
        public void should_get_properties_from_models()
        {
            var models = replacedembly.Load("NzbDrone.Core").ImplementationsOf<ModelBase>();

            foreach (var model in models)
            {
                model.GetSimpleProperties().Should().NotBeEmpty();
            }
        }

19 Source : ReflectionExtensionFixture.cs
with GNU General Public License v3.0
from bonarr

[Test]
        public void should_be_able_to_get_implementations()
        {
            var models = replacedembly.Load("NzbDrone.Core").ImplementationsOf<ModelBase>();

            models.Should().NotBeEmpty();
        }

19 Source : PlatformValidation.cs
with GNU General Public License v3.0
from bonarr

private static bool IsreplacedemblyAvailable(string replacedemblyString)
        {
            try
            {
                replacedembly.Load(replacedemblyString);
                return true;
            }
            catch (Exception e)
            {
                Logger.Warn("Couldn't load {0}", e.Message);
                return false;
            }

        }

19 Source : AutoMoqer.cs
with GNU General Public License v3.0
from bonarr

private void RegisterPlatformLibrary(IUnityContainer container)
        {
            var replacedemblyName = "NzbDrone.Windows";

            if (OsInfo.IsNotWindows)
            {
                replacedemblyName = "NzbDrone.Mono";
            }

            if (!File.Exists(replacedemblyName + ".dll"))
            {
                return;
            }

            replacedembly.Load(replacedemblyName);
        }

19 Source : DependencyInspector.cs
with MIT License
from bonsai-rx

Configuration.PackageReference[] GetWorkflowPackageDependencies(string[] fileNames)
        {
            var replacedemblies = new HashSet<replacedembly>();
            foreach (var path in fileNames)
            {
                var metadata = WorkflowBuilder.ReadMetadata(path);
                using (var markupReader = new StringReader(metadata.WorkflowMarkup))
                using (var reader = XmlReader.Create(markupReader))
                {
                    reader.ReadToFollowing(WorkflowElementName);
                    using (var workflowReader = reader.ReadSubtree())
                    {
                        while (workflowReader.ReadToFollowing(ExpressionElementName))
                        {
                            if (!workflowReader.HasAttributes) continue;
                            if (workflowReader.GetAttribute(TypeAttributeName, XsiAttributeValue) == IncludeWorkflowTypeName)
                            {
                                var includePath = workflowReader.GetAttribute(PathAttributeName);
                                var separatorIndex = includePath != null ? includePath.IndexOf(replacedemblySeparator) : -1;
                                if (separatorIndex >= 0 && !Path.IsPathRooted(includePath))
                                {
                                    var replacedemblyName = includePath.Split(new[] { replacedemblySeparator }, 2)[0];
                                    if (!string.IsNullOrEmpty(replacedemblyName))
                                    {
                                        var replacedembly = replacedembly.Load(replacedemblyName);
                                        replacedemblies.Add(replacedembly);
                                    }
                                }
                            }
                        }
                    }
                }

                replacedemblies.Add(typeof(WorkflowBuilder).replacedembly);
                replacedemblies.AddRange(metadata.GetExtensionTypes().Select(type => type.replacedembly));

                var layoutPath = Path.ChangeExtension(path, Path.GetExtension(path) + Constants.LayoutExtension);
                if (File.Exists(layoutPath))
                {
                    var visualizerMap = new Lazy<IDictionary<string, Type>>(() =>
                        TypeVisualizerLoader.GetVisualizerTypes(packageConfiguration)
                                            .Select(descriptor => descriptor.VisualizerTypeName).Distinct()
                                            .Select(typeName => Type.GetType(typeName, false))
                                            .Where(type => type != null)
                                            .ToDictionary(type => type.FullName)
                                            .Wait());

                    using (var reader = XmlReader.Create(layoutPath))
                    {
                        var layout = (VisualizerLayout)VisualizerLayout.Serializer.Deserialize(reader);
                        foreach (var settings in GetVisualizerSettings(layout))
                        {
                            var typeName = settings.VisualizerTypeName;
                            if (typeName == null) continue;
                            if (visualizerMap.Value.TryGetValue(typeName, out Type type))
                            {
                                replacedemblies.Add(type.replacedembly);
                            }
                        }
                    }
                }
            }

            var packageMap = packageConfiguration.GetPackageReferenceMap();
            var dependencies = packageConfiguration.GetreplacedemblyPackageReferences(
                replacedemblies.Select(replacedembly => replacedembly.GetName().Name),
                packageMap);
            if (File.Exists(scriptEnvironment.ProjectFileName))
            {
                dependencies = dependencies.Concat(
                    from id in scriptEnvironment.GetPackageReferences()
                    where packageConfiguration.Packages.Contains(id)
                    select packageConfiguration.Packages[id]);
            }

            return dependencies.ToArray();
        }

19 Source : TypeVisualizerLoader.cs
with MIT License
from bonsai-rx

TypeVisualizerDescriptor[] GetReflectionTypeVisualizerAttributes(string replacedemblyRef)
        {
            var typeVisualizers = Enumerable.Empty<TypeVisualizerAttribute>();
            try
            {
                var replacedembly = replacedembly.Load(replacedemblyRef);
                var visualizerAttributes = replacedembly.GetCustomAttributes(typeof(TypeVisualizerAttribute), true).Cast<TypeVisualizerAttribute>();
                typeVisualizers = typeVisualizers.Concat(visualizerAttributes);
                typeVisualizers = typeVisualizers.Concat(GetCustomAttributeTypes(replacedembly));
            }
            catch (FileLoadException ex) { Trace.TraceError("{0}", ex); }
            catch (FileNotFoundException ex) { Trace.TraceError("{0}", ex); }
            catch (BadImageFormatException ex) { Trace.TraceError("{0}", ex); }

            return typeVisualizers.Distinct().Select(data => new TypeVisualizerDescriptor(data)).ToArray();
        }

19 Source : WorkflowElementLoader.cs
with MIT License
from bonsai-rx

WorkflowElementDescriptor[] GetReflectionWorkflowElementTypes(string replacedemblyRef)
        {
            var types = Enumerable.Empty<WorkflowElementDescriptor>();
            try
            {
                var replacedembly = replacedembly.Load(replacedemblyRef);
                types = types.Concat(GetWorkflowElements(replacedembly));
            }
            catch (FileLoadException ex) { Trace.TraceError("{0}", ex); }
            catch (FileNotFoundException ex) { Trace.TraceError("{0}", ex); }
            catch (BadImageFormatException ex) { Trace.TraceError("{0}", ex); }

            return types.Distinct().ToArray();
        }

19 Source : IncludeWorkflowBuilder.cs
with MIT License
from bonsai-rx

static Stream GetWorkflowStream(string path, bool embeddedResource)
        {
            if (embeddedResource)
            {
                var nameElements = path.Split(new[] { replacedemblySeparator }, 2);
                if (string.IsNullOrEmpty(nameElements[0]))
                {
                    throw new InvalidOperationException(
                        "The embedded resource path \"" + path +
                        "\" must be qualified with a valid replacedembly name.");
                }

                var replacedembly = System.Reflection.replacedembly.Load(nameElements[0]);
                var resourceName = string.Join(ExpressionHelper.MemberSeparator, nameElements);
                var workflowStream = replacedembly.GetManifestResourceStream(resourceName);
                if (workflowStream == null)
                {
                    throw new InvalidOperationException(
                        "The specified embedded resource \"" + nameElements[1] +
                        "\" was not found in replacedembly \"" + nameElements[0] + "\"");
                }

                return workflowStream;
            }
            else
            {
                if (!File.Exists(path))
                {
                    throw new InvalidOperationException("The specified workflow could not be found.");
                }

                return File.OpenRead(path);
            }
        }

19 Source : ElementIcon.cs
with MIT License
from bonsai-rx

public ElementIcon GetDefaultIcon()
        {
            var name = Name;
            if (name != defaultName)
            {
                string replacedemblyName;
                var path = Path.ChangeExtension(name, null);
                path = ResolveEmbeddedPath(path, out replacedemblyName);
                var separatorIndex = path.LastIndexOf(ExpressionHelper.MemberSeparator);
                if (separatorIndex < 0) return null;
                path = path.Substring(0, separatorIndex);
                if (!string.IsNullOrEmpty(replacedemblyName))
                {
                    try
                    {
                        var replacedembly = replacedembly.Load(replacedemblyName);
                        return GetNamespaceIcon(path, replacedembly, includeElement);
                    }
                    catch (SystemException) { }
                }
                return GetNamespaceIcon(path, replacedemblyName, includeElement);
            }

            if (resourceQualifier != null)
            {
                return GetNamespaceIcon(resourceQualifier.Namespace, resourceQualifier.replacedembly);
            }
            else
            {
                var separatorIndex = name.IndexOf(replacedemblySeparator);
                if (separatorIndex >= 0)
                {
                    return new ElementIcon(name.Substring(0, separatorIndex), includeElement);
                }

                return null;
            }
        }

19 Source : ElementIcon.cs
with MIT License
from bonsai-rx

public Stream GetStream()
        {
            var name = RemoveInvalidPathChars(Name);
            if (string.IsNullOrEmpty(name))
            {
                return null;
            }

            var includedType = false;
            if (name != defaultName)
            {
                includedType = IsIncludeElement;
                name = Path.ChangeExtension(name, SvgExtension);
            }
            else if (Path.GetExtension(name) != SvgExtension)
            {
                name += SvgExtension;
            }

            string replacedemblyName;
            name = ResolveEmbeddedPath(name, out replacedemblyName);

            var iconPath = ResolvePath(name, includedType ? string.Empty : replacedemblyName);
            if (!string.IsNullOrEmpty(iconPath))
            {
                return new FileStream(iconPath, FileMode.Open, FileAccess.Read);
            }

            replacedembly replacedembly;
            if (resourceQualifier == null || !string.IsNullOrEmpty(replacedemblyName))
            {
                if (string.IsNullOrEmpty(replacedemblyName))
                {
                    replacedemblyName = Path.GetFileNameWithoutExtension(name);
                    name = replacedemblyName + ExpressionHelper.MemberSeparator + replacedemblyName + SvgExtension;
                }

                try { replacedembly = replacedembly.Load(replacedemblyName); }
                catch (SystemException) { return null; }
            }
            else replacedembly = resourceQualifier.replacedembly;

            if (!replacedembly.IsDynamic)
            {
                var resourceStream = replacedembly.GetManifestResourceStream(name);
                if (resourceStream == null && DefaultManifestResources.TryGetValue(name, out name))
                {
                    resourceStream = typeof(ElementIcon).replacedembly.GetManifestResourceStream(name);
                }
                return resourceStream;
            }
            else return null;
        }

19 Source : ResourceConfiguration.cs
with MIT License
from bonsai-rx

protected Stream OpenResource(string path)
        {
            const char replacedemblySeparator = ':';
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("Missing resource path while loading " + ToString() + ".", "path");
            }

            var separatorIndex = path.IndexOf(replacedemblySeparator);
            if (separatorIndex >= 0 && !Path.IsPathRooted(path))
            {
                var nameElements = path.Split(new[] { replacedemblySeparator }, 2);
                if (string.IsNullOrEmpty(nameElements[0]))
                {
                    throw new ArgumentException(
                        "The embedded resource path \"" + path +
                        "\" in " + ToString() + " must be qualified with a valid replacedembly name.",
                        "path");
                }

                var replacedembly = System.Reflection.replacedembly.Load(nameElements[0]);
                var resourceName = string.Join(ExpressionHelper.MemberSeparator, nameElements);
                var resourceStream = replacedembly.GetManifestResourceStream(resourceName);
                if (resourceStream == null)
                {
                    throw new ArgumentException(
                        "The specified embedded resource \"" + nameElements[1] +
                        "\" was not found in replacedembly \"" + nameElements[0] +
                        "\" while loading " + ToString() + ".",
                        "path");
                }

                return resourceStream;
            }
            else
            {
                if (!File.Exists(path))
                {
                    throw new ArgumentNullException("path", "The specified path \"" + path + "\" was not found while loading " + ToString() + ".");
                }

                return File.OpenRead(path);
            }
        }

19 Source : TaskInfo.cs
with MIT License
from brthor

public async Task<object> ExecuteTask()
        {
            var replacedembly = replacedembly.Load(replacedemblyName);
            var type = replacedembly.GetType(TypeName);
            
            var staticMethod = type.GetMethod(MethodName, 
                BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, 
                null, 
                ArgTypes, 
                null);

            if (staticMethod != null)
            {
                return await InvokeMethod(staticMethod, null);
            }
            
            var instanceMethod = type.GetMethod(MethodName, 
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, 
                null, 
                ArgTypes, 
                null);
            
            if (instanceMethod == null)
            {
                throw new UnableToDeserializeDelegateException();
            }

            var instance = Activator.CreateInstance(type);
            
            return await InvokeMethod(instanceMethod, instance);
        }

19 Source : Program.cs
with MIT License
from CacoCode

private static void GenerateExtensionsReadmes(string[] args)
        {
            var clreplacedes = replacedembly.Load("LBON.Extensions").GetTypes().Where(a => a.Name.EndsWith("Extensions")).ToList();
            foreach (var item in clreplacedes)
            {
                //var filePath = Path.Combine(args[0], $"{item.Name.ToUpper()}_README.md");
                var dirPath = Path.Combine("Readmes", args[0]);
                var filePath = Path.Combine(dirPath, $"{item.Name.ToUpper()}_README.md");

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                using (var fileStream = new FileStream(filePath, FileMode.CreateNew))
                {
                    string content = $"# {item.Name}";
                    if (item.Name == "StringExtensions")
                    {

                    }
                    var methods = item.GetMethods().Where(a => a.IsPublic && a.IsStatic).ToList();
                    foreach (var method in methods)
                    {
                        content += @$"
- <code>{method.Name}</code> {method.GetCustomAttribute<DescriptionAttribute>()?.Description}";
                    }
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    fileStream.Write(data, 0, data.Length);
                }
                Console.WriteLine($"已生成 {item.Name.ToUpper()}_README.md");
            }
        }

19 Source : Program.cs
with MIT License
from CacoCode

private static void GenerateHeleperReadmes(string[] args)
        {
            var clreplacedes = replacedembly.Load("LBON.Helper").GetTypes().Where(a => a.Name.EndsWith("Helper")).ToList();
            foreach (var item in clreplacedes)
            {
                var dirPath = Path.Combine("Readmes", args[1]);
                var filePath = Path.Combine(dirPath, $"{item.Name.ToUpper()}_README.md");
                //var filePath = Path.Combine(args[1], $"{item.Name.ToUpper()}_README.md");
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                using (var fileStream = new FileStream(filePath, FileMode.CreateNew))
                {
                    string content = $"# {item.Name}";
                    var methods = item.GetMethods().Where(a => a.IsPublic && a.IsStatic).ToList();
                    foreach (var method in methods)
                    {
                        content += @$"
- <code>{method.Name}</code>";
                    }
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    fileStream.Write(data, 0, data.Length);
                }
                Console.WriteLine($"已生成 {item.Name.ToUpper()}_README.md");
            }
        }

19 Source : ComponentAutoBindToolInspector.cs
with MIT License
from CatImmortal

private string[] GetTypeNames(Type typeBase, string[] replacedemblyNames)
    {
        List<string> typeNames = new List<string>();
        foreach (string replacedemblyName in replacedemblyNames)
        {
            replacedembly replacedembly = null;
            try
            {
                replacedembly = replacedembly.Load(replacedemblyName);
            }
            catch
            {
                continue;
            }

            if (replacedembly == null)
            {
                continue;
            }

            Type[] types = replacedembly.GetTypes();
            foreach (Type type in types)
            {
                if (type.IsClreplaced && !type.IsAbstract && typeBase.IsreplacedignableFrom(type))
                {
                    typeNames.Add(type.FullName);
                }
            }
        }

        typeNames.Sort();
        return typeNames.ToArray();
    }

19 Source : ComponentAutoBindToolInspector.cs
with MIT License
from CatImmortal

private object CreateHelperInstance(string helperTypeName, string[] replacedemblyNames)
    {
        foreach (string replacedemblyName in replacedemblyNames)
        {
            replacedembly replacedembly = replacedembly.Load(replacedemblyName);

            object instance = replacedembly.CreateInstance(helperTypeName);
            if (instance != null)
            {
                return instance;
            }
        }

        return null;
    }

19 Source : AssemblyHelper.cs
with Apache License 2.0
from ccnetcore

public static List<Type> GetClreplaced(string replacedemblyFile, string clreplacedName = null, string spaceName=null)
        {
            replacedembly replacedembly = replacedembly.Load(replacedemblyFile);
            return replacedembly.GetTypes().Where(m => m.IsClreplaced 
            && clreplacedName == null?true:m.Name==clreplacedName
            && spaceName == null ? true :m.Namespace == spaceName
             ).ToList();
        }

19 Source : ClrTypeOptions.cs
with MIT License
from ch-robinson

public static Type ResolveType(this IClrTypeOptions options)
        {
            var replacedemblies = options.replacedemblyNames
                .Select(name =>
                {
                    try
                    {
                        return replacedembly.Load(name);
                    }
                    catch (FileNotFoundException)
                    {
                        // nbd
                    }
                    catch (FileLoadException)
                    {
                        // also nbd
                    }

                    try
                    {
                        return replacedembly.LoadFrom(Path.GetFullPath(name));
                    }
                    catch (FileNotFoundException)
                    {
                        throw new ProgramException(message: $"{name} could not be found. Make sure that you’ve provided either a recognizable name (e.g. System.Runtime) or a valid replacedembly path.");
                    }
                    catch (BadImageFormatException)
                    {
                        throw new ProgramException(message: $"{name} is not valid. Check that the path you’re providing points to a valid replacedembly file.");
                    }
                })
                .Append(typeof(object).replacedembly) // ensure System.Runtime is included by default
                .ToDictionary(replacedembly => replacedembly.GetName());

            try
            {
                return Type.GetType(
                    options.TypeName,
                    replacedemblyResolver: name => replacedemblies.GetValueOrDefault(name),
                    typeResolver: (replacedembly, name, ignoreCase) =>
                    {
                        if (replacedembly == null)
                        {
                            foreach (var candidate in replacedemblies.Values)
                            {
                                if (candidate.GetType(name, ignoreCase: ignoreCase, throwOnError: false) is Type result)
                                {
                                    return result;
                                }
                            }

                            return null;
                        }

                        return replacedembly.GetType(name, ignoreCase: ignoreCase, throwOnError: false);
                    },
                    ignoreCase: true,
                    throwOnError: true
                );
            }
            catch (TypeLoadException)
            {
                throw new ProgramException(message: "The type could not be found. You may need to provide additional replacedemblies.");
            }
        }

19 Source : IOCFactory.cs
with Apache License 2.0
from chancezheng

public static T2 CreateInstance<T1,T2>(T1 t1 ,string asmName= "DesktopUniversalFrame") where T1 : clreplaced where T2 : clreplaced
        {
            replacedembly replacedembly = replacedembly.Load(asmName);
            Type type = replacedembly.GetType(typeof(T2).Name);
            T2 instance = (T2)Activator.CreateInstance(type, new object[] { t1 });
            return instance;
        }

19 Source : IOCFactory.cs
with Apache License 2.0
from chancezheng

public static T CreateInstance<T>(string asmName = "DesktopUniversalFrame")
        {
            replacedembly replacedembly = replacedembly.Load(asmName);
            Type type = replacedembly.GetType(typeof(T).FullName);
            T instance = (T)Activator.CreateInstance(type);
            return instance;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Cheerpipe

private static replacedembly CurrentDomain_replacedemblyResolve(object sender, ResolveEventArgs args)
        {
            var otherCompanyDlls = new DirectoryInfo(@"C:\Program Files (x86)\GIGABYTE\RGBFusion\").GetFiles("*.dll");
            var dll = otherCompanyDlls.FirstOrDefault(fi => fi.Name == args.Name);
            if (dll == null)
            {
                return null;
            }

            return replacedembly.Load(dll.FullName);
        }

19 Source : DirtyScriptsCompilationTool.cs
with MIT License
from chenwansal

[MenuItem("Tools/DirtyScriptsCompilation/Compile %_T")]
        static void CompileDirtyScripts() {

            var stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            // 找到触发编译完成的方法
            // 以及 out 方法参数 1
            MethodInfo invokeMethod = FindInvokerInEditorCompilation(out object invoker);

            // 方法参数 2
            Type type = System.Reflection.replacedembly.Load("UnityEditor").GetType("UnityEditor.Scripting.Compilers.CompilerMessage");
            var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(type));

            var model = GetOrCreateAsmCacheModelSo();
            List<string> dirties = model.GetDirtyScripts();

            List<UnityEditorreplacedembly> compiledList = new List<UnityEditorreplacedembly>();

            // 编译
            foreach (var path in dirties) {

                var asm = model.GetreplacedemblyWithPath(path);
                if (compiledList.Contains(asm)) {
                    continue;
                }

                // 编译 asm
                EditorUtility.CompileCSharp(asm.sourceFiles, asm.allReferences, asm.defines, asm.outputPath);
                Debug.Log($"编译 asm: {asm.name}, sourceFilesCount: {asm.sourceFiles.Length.ToString()}, refsCount: {asm.allReferences.Length.ToString()}, outPath: {asm.outputPath}");

                invokeMethod.Invoke(invoker, new object[] { asm.outputPath, list });

                compiledList.Add(asm);

            }

            stopwatch.Stop();

            // 无脚本
            if (dirties.Count == 0) {
                Debug.Log($"不存在脏脚本, 无需编译, 耗时: {stopwatch.ElapsedMilliseconds.ToString()}");
            } else {
                Debug.Log($"合计编译 DirtyScripts 数量: {dirties.Count}, 耗时: {stopwatch.ElapsedMilliseconds.ToString()}");
            }

            // 清空 DirtyScripts
            dirtyHandleQueue.Clear();
            model.CleanDirtyScripts();

        }

19 Source : DirtyScriptsCompilationTool.cs
with MIT License
from chenwansal

static MethodInfo FindInvokerInEditorCompilation(out object invoker) {

            Type[] allType = System.Reflection.replacedembly.Load("UnityEditor").GetTypes();
            Type ecInterface = null;
            foreach (var type in allType) {
                if (type.Name.Contains("EditorCompilationInterface")) {
                    ecInterface = type;
                }
            }
            object ec = ecInterface.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public).GetValue(null);

            MethodInfo invokeMethod = ec.GetType().GetMethod("InvokereplacedemblyCompilationFinished", BindingFlags.Public | BindingFlags.Instance);

            invoker = ec;

            return invokeMethod;

        }

19 Source : AppDomainTypeFinder.cs
with MIT License
from chinabeacon

protected virtual void AddConfiguredreplacedemblies(List<string> addedreplacedemblyNames, List<replacedembly> replacedemblies)
        {
            foreach (string replacedemblyName in replacedemblyNames)
            {
                replacedembly replacedembly = replacedembly.Load(replacedemblyName);
                if (!addedreplacedemblyNames.Contains(replacedembly.FullName))
                {
                    replacedemblies.Add(replacedembly);
                    addedreplacedemblyNames.Add(replacedembly.FullName);
                }
            }
        }

19 Source : Init.cs
with MIT License
from chrisnas

private static void ForcereplacedemblyLoad(replacedemblyName replacedemblyName)
        {
            var codeBase = replacedemblyName.CodeBase;

            if (codeBase.StartsWith("file://"))
            {
                codeBase = codeBase.Substring(8).Replace('/', '\\');
            }

            ResolveEventHandler replacedemblyResolve = (sender, args) => args.Name == replacedemblyName.FullName ? replacedembly.LoadFrom(codeBase) : null;

            AppDomain.CurrentDomain.replacedemblyResolve += replacedemblyResolve;

            replacedembly.Load(replacedemblyName.FullName);

            AppDomain.CurrentDomain.replacedemblyResolve -= replacedemblyResolve;
        }

19 Source : AssemblyLoadProxy.cs
with MIT License
from chstetco

public IreplacedemblyWrapper Load(string replacedemblyString)
        {
            return new replacedemblyWrapper(replacedembly.Load(replacedemblyString));
        }

19 Source : AutoMapperConfigurationExtensions.cs
with MIT License
from cocosip

public static void CreateAutoAttributeMaps(this IMapperConfigurationExpression configuration, Type type, Type[] targetTypes, MemberList memberList)
        {
            //Get all the properties in the source that have the AutoMapKeyAttribute
            var sourceKeysPropertyInfo = type.GetProperties()
                                             .Where(w => w.GetCustomAttribute<AutoMapKeyAttribute>() != null)
                                             .Select(s => s).ToList();

            foreach (var targetType in targetTypes)
            {
                if (!sourceKeysPropertyInfo.Any())
                {
                    configuration.CreateMap(type, targetType, memberList);
                    continue;
                }

                BinaryExpression equalityComparer = null;

                //In a lambda expression represent the source exemple : (source) => ...
                ParameterExpression sourceParameterExpression = Expression.Parameter(type, "source");
                //In a lambda expression represent the target exemple : (target) => ...
                ParameterExpression targetParameterExpression = Expression.Parameter(targetType, "target");


                //We could use multiple AutoMapKey to compare the determine equality
                foreach (PropertyInfo propertyInfo in sourceKeysPropertyInfo)
                {
                    //In a lambda expression represent a specfic property of a parameter exemple : (source) => source.Id
                    MemberExpression sourcePropertyExpression = Expression.Property(sourceParameterExpression, propertyInfo);

                    //Find the target a property with the same name to compare with
                    //Exemple if we have in source the attribut AutoMapKey on the Property Id we want to get Id in the target to compare agaisnt
                    var targetPropertyInfo = targetType.GetProperty(sourcePropertyExpression.Member.Name);

                    //It happen if the property with AutoMapKeyAttribute does not exist in target
                    if (targetPropertyInfo is null)
                    {
                        continue;
                    }

                    //In a lambda expression represent a specfic property of a parameter exemple : (target) => target.Id
                    MemberExpression targetPropertyExpression = Expression.Property(targetParameterExpression, targetPropertyInfo);

                    //Compare the property defined by AutoMapKey in the source agaisnt the same property in the target
                    //Exemple (source, target) => source.Id == target.Id
                    BinaryExpression equal = Expression.Equal(sourcePropertyExpression, targetPropertyExpression);

                    if (equalityComparer is null)
                    {
                        equalityComparer = equal;
                    }
                    else
                    {
                        //If we compare multiple key we want to make an and condition between
                        //Exemple : (source, target) => source.Email == target.Email && source.UserName == target.UserName
                        equalityComparer = Expression.And(equalityComparer, equal);
                    }
                }

                //If there is not match for AutoMapKey in the target
                //In this case we add the default mapping
                if (equalityComparer is null)
                {
                    configuration.CreateMap(type, targetType, memberList);
                    continue;
                }

                //We need to make a generic type of Func<SourceType, TargetType, bool> to invoke later Expression.Lambda
                var funcGenericType = typeof(Func<,,>).MakeGenericType(type, targetType, typeof(bool));

                //Make a method info of Expression.Lambda<Func<SourceType, TargetType, bool>> to call later
                var lambdaMethodInfo = typeof(Expression).GetMethod("Lambda", 2, 1).MakeGenericMethod(funcGenericType);

                //Make the call to Expression.Lambda
                var expressionLambdaResult = lambdaMethodInfo.Invoke(null, new object[] { equalityComparer, new ParameterExpression[] { sourceParameterExpression, targetParameterExpression } });

                //Get the method info of IMapperConfigurationExpression.CreateMap<Source, Target>
                var createMapMethodInfo = configuration.GetType().GetMethod("CreateMap", 1, 2).MakeGenericMethod(type, targetType);

                //Make the call to configuration.CreateMap<Source, Target>().
                var createMapResult = createMapMethodInfo.Invoke(configuration, new object[] { memberList });

                var autoMapperCollectionreplacedembly = replacedembly.Load("AutoMapper.Collection");

                var autoMapperCollectionTypes = autoMapperCollectionreplacedembly.GetTypes();

                var equalityComparisonGenericMethodInfo = autoMapperCollectionTypes
                                         .Where(w => !w.IsGenericType && !w.IsNested)
                                         .SelectMany(s => s.GetMethods()).Where(w => w.Name == "EqualityComparison")
                                         .FirstOrDefault()
                                         .MakeGenericMethod(type, targetType);

                //Make the call to EqualityComparison
                //Exemple configuration.CreateMap<Source, Target>().EqualityComparison((source, target) => source.Id == target.Id)
                equalityComparisonGenericMethodInfo.Invoke(createMapResult, new object[] { createMapResult, expressionLambdaResult });
            }
        }

19 Source : GeneratorFactory.cs
with MIT License
from codecentric

public static ImmutableArray<Diagnostic> RunGenerator(string source)
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(SourceText.From(source, Encoding.UTF8));

            //var parseOptions = TestOptions.Regular;
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                .WithOptimizationLevel(OptimizationLevel.Debug)
                .WithGeneralDiagnosticOption(ReportDiagnostic.Default);

            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).replacedembly.Location),
                MetadataReference.CreateFromFile(typeof(GenerateAutomaticInterfaceAttribute).replacedembly.Location),
                MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(replacedembly.Load("System.Runtime, Version=4.2.2.0").Location)
        };

            Compilation compilation = CSharpCompilation.Create("testgenerator", new[] { syntaxTree }, references, compilationOptions).WithReferences(references);
            var diagnostics = compilation.GetDiagnostics();
            if (!VerifyDiagnostics(diagnostics, new[] { "CS0012", "CS0616", "CS0246" }))
            {
                // this will make the test fail, check the input source code!
                return diagnostics;
            }

            var generator = new AutomaticInterfaceGenerator();
            ISourceGenerator[] generators = { generator};            
            var driver = CSharpGeneratorDriver.Create(generators, parseOptions: (CSharpParseOptions)compilation.SyntaxTrees.First().Options);
            driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);

            return generatorDiagnostics;
        }

19 Source : Program.cs
with MIT License
from codewitch-honey-crisis

static replacedembly _Loadreplacedembly(string asm)
		{
			replacedembly result = null;
			try
			{
				result = replacedembly.Load(asm);
			}
			catch { };
			if (null == result)
			{
				try
				{
					result = replacedembly.LoadFile(asm);
				}
				catch { }
			}
			return result;
		}

19 Source : M.cs
with MIT License
from CoFlows

public void LoadRaw(List<RawEntry> rawEntries)
        {
            lock(editLock)
            {
                this.Timestamp = DateTime.Now;
                
                if(rawEntries == null)
                    return;

                if(permission() == AccessType.Denied)
                    return;

                

                foreach (var rawEntry in rawEntries)
                {

                    string entryID = rawEntry.EntryID;
                    string typeName = rawEntry.Type;
                    string replacedemblyName = rawEntry.replacedembly;

                    try
                    {
                        if (type == null)
                        {
                            type = Type.GetType(typeName);
                            if(type == null)
                            {
                                var replacedembly = M._systemreplacedemblies.ContainsKey(typeName) ? M._systemreplacedemblies[typeName] : (M._compiledreplacedemblyNames.ContainsKey(typeName) ? M._compiledreplacedemblies[M._compiledreplacedemblyNames[typeName]] : System.Reflection.replacedembly.Load(replacedemblyName));
                                type = replacedembly.GetType(M._systemreplacedemblyNames.ContainsKey(typeName) ? M._systemreplacedemblyNames[typeName] : typeName);
                            }
                        }

                        DateTime d1 = DateTime.Now;
                        object obj = type == typeof(Nullable) || type == typeof(string) ? rawEntry.Entry : Newtonsoft.Json.JsonConvert.DeserializeObject(rawEntry.Entry as string, type);
                        DateTime d2 = DateTime.Now;

                        this.AddInternal(entryID, obj, typeName, replacedemblyName);
                    }
                    catch (Exception e)
                    {
                        this.AddInternal(entryID, rawEntry.Entry, typeName, replacedemblyName);
                    }
                }

                this.loaded = true;
            }
        }

19 Source : MFactory.cs
with MIT License
from CoFlows

public M Find(string id, Type type, M m = null)
        {
            lock (objLock)
            {
                string searchString = "ID = '" + id + "'";
                string targetString = null;

                DateTime t0 = DateTime.Now;
                DataTable table = Database.DB["Kernel"].GetDataTable(_mainTableName, targetString, searchString);
                DateTime t1 = DateTime.Now;

                DataRowCollection rows = table.Rows;

                m = m == null ? new M() : m;

                if (rows.Count == 0)
                {
                    m.loaded = true;
                    return m;
                }

                

                var dict = new Dictionary<string, Type>();
                foreach (DataRow r in rows)
                {

                    string entryID = GetValue<string>(r, "EntryID");
                    string entryString = GetValue<string>(r, "Entry");

                    string typeName = GetValue<string>(r, "Type");
                    string replacedemblyName = GetValue<string>(r, "replacedembly");

                    Type tp = type;


                    try
                    {
                        if (type == null)
                        {
                            
                            try
                            {

                                tp = Type.GetType(typeName);
                                if(tp == null && !dict.ContainsKey(typeName))
                                {
                                    replacedembly replacedembly = M._systemreplacedemblies.ContainsKey(typeName) ? M._systemreplacedemblies[typeName] : (M._compiledreplacedemblyNames.ContainsKey(typeName) ? M._compiledreplacedemblies[M._compiledreplacedemblyNames[typeName]] : System.Reflection.replacedembly.Load(replacedemblyName));
                                    tp = replacedembly.GetType(M._systemreplacedemblyNames.ContainsKey(typeName) ? M._systemreplacedemblyNames[typeName] : typeName);
                                    dict.Add(typeName, tp);
                                }
                            }
                            catch
                            {
                                tp = null;
                            }

                            if(!dict.ContainsKey(typeName))
                                dict.Add(typeName, tp);
                        }

                        tp = dict.ContainsKey(typeName) ? dict[typeName] : tp;

                        string filtered_string = entryString.Replace((char)27, '"').Replace((char)26, '\'');
                        if(tp != typeof(Nullable) && filtered_string.StartsWith("\"") && filtered_string.EndsWith("\""))
                            filtered_string = filtered_string.Substring(1, filtered_string.Length - 2).Replace("\\\"", "\"");
                        object obj = tp == typeof(Nullable) || tp == typeof(string) ? filtered_string : Newtonsoft.Json.JsonConvert.DeserializeObject(filtered_string, tp);

                        m.AddInternal(entryID, obj, typeName, replacedemblyName);
                    }
                    catch (Exception e)
                    {
                        m.AddInternal(entryID, entryString.Replace((char)27, '"').Replace((char)26, '\''), typeName, replacedemblyName);
                    }
                }
                m.loaded = true;
                return m;
            }
        }

19 Source : assemblymanager.cs
with MIT License
from CoFlows

public static replacedembly Loadreplacedembly(string name)
        {
            replacedembly replacedembly = null;
            try
            {
                replacedembly = replacedembly.Load(name);
            }
            catch (Exception e)
            {
                
                // if (!(e is System.IO.FileNotFoundException))
                //     Console.WriteLine(e);
                //{
                //    throw;
                //}
            }
            return replacedembly;
        }

19 Source : BaseDbContext.cs
with Apache License 2.0
from Coldairarrow

private static void InitModelType()
        {
            var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies().Union(new replacedembly[] { replacedembly.Load("Coldairarrow.Enreplacedy") });
            List<Type> allTypes = new List<Type>();
            replacedemblies.ForEach(areplacedembly =>
            {
                allTypes.AddRange(areplacedembly.GetTypes());
            });
            List<Type> types = allTypes
                .Where(x => x.GetCustomAttribute(typeof(TableAttribute), false) != null && x.FullName.Contains(GlobalSwitch.DefaultEnreplacedyNamespace))
                .ToList();

            types.ForEach(aType =>
            {
                _modelTypes.Add(aType);
                _modelTypeMap[GetIdenreplacedy(aType)] = aType;
            });
        }

19 Source : BaseDbContext.cs
with Apache License 2.0
from Coldairarrow

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //modelBuilder.Enreplacedy<TheEnreplacedy>();
            //以下代码最终目的就是将所有需要的实体类调用上面的方法加入到DbContext中,成为其中的一部分
            var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
            var enreplacedyMethod = typeof(ModelBuilder).GetMethod("Enreplacedy", new Type[] { });
            List<Type> types = replacedembly.Load("Coldairarrow.Enreplacedy").GetTypes()
                .Where(x => x.GetCustomAttribute(typeof(TableAttribute), false) != null && x.FullName.Contains(_enreplacedyNamespace))
                .ToList();

            foreach (var type in types)
            {
                enreplacedyMethod.MakeGenericMethod(type).Invoke(modelBuilder, null);
            }
        }

19 Source : DistributedLockExtentions.cs
with Apache License 2.0
from Coldairarrow

private static IServiceCollection AddDependency(this IServiceCollection services)
        {
            services.AddSingleton(typeof(IDistributedLock), serviceProvider =>
            {
                var options = serviceProvider.GetService<IOptions<DistributedLockOptions>>().Value;
                string replacedemblyName = $"Colder.DistributedLock.{options.LockType}";
                Type implementType;
                try
                {
                    implementType = replacedembly.Load(replacedemblyName).GetTypes()
                        .Where(x => typeof(IDistributedLock).IsreplacedignableFrom(x))
                        .FirstOrDefault();
                }
                catch
                {
                    throw new Exception($"请安装包:{replacedemblyName}");
                }

                return ActivatorUtilities.CreateInstance(serviceProvider, implementType);
            });

            return services;
        }

19 Source : MessageBusFactory.cs
with Apache License 2.0
from Coldairarrow

public static IMessageBus GetBusInstance(IServiceProvider serviceProvider, MessageBusOptions options)
        {
            AbstractProvider provider;

            string replacedemblyName = $"Colder.MessageBus.{options.Transport}";
            try
            {
                replacedembly replacedembly = replacedembly.Load(replacedemblyName);

                var type = replacedembly.GetType($"{replacedemblyName}.{options.Transport}Provider");

                provider = Activator.CreateInstance(type, new object[] { serviceProvider, options }) as AbstractProvider;
            }
            catch
            {
                throw new Exception($"请安装nuget包:{replacedemblyName}");
            }

            return provider.GetBusInstance();
        }

19 Source : DbModelFactory.cs
with MIT License
from Coldairarrow

private static void InitModelType()
        {
            var replacedemblies = new replacedembly[] { replacedembly.Load("Coldairarrow.Enreplacedy") };
            List<Type> allTypes = new List<Type>();
            replacedemblies.ForEach(areplacedembly =>
            {
                allTypes.AddRange(areplacedembly.GetTypes());
            });
            List<Type> types = allTypes
                .Where(x => x.GetCustomAttribute(typeof(TableAttribute), false) != null)
                .ToList();

            types.ForEach(aType =>
            {
                _modelTypeMap[aType.Name] = aType;
            });
        }

See More Examples