System.Reflection.Assembly.GetEntryAssembly()

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

1560 Examples 7

19 Source : CommandLineParser.cs
with MIT License
from 0xd4d

public static void ShowHelp() {
			var exe = Path.GetFileNameWithoutExtension(replacedembly.GetEntryreplacedembly()!.Location);
			var msg = $@"Disreplacedembles jitted methods in .NET processes

-p, --pid <pid>                 Process id
-pn, --process <name>           Process name
-m, --module <name>             Name of module to disreplacedemble
-l, --load <module>             Load module (for execution) into this process and jit every method
--no-run-cctor                  Don't run all .cctors before jitting methods (used with -l)
--filename-format <fmt>         Filename format. <fmt>:
    name            => (default) member name
    tokname         => token + member name
    token           => token
-f, --file <kind>               Output file. <kind>:
    stdout          => (default) stdout
    file            => One file, use -o to set filename
    type            => One file per type, use -o to set directory
    method          => One file per method, use -o to set directory
-d, --disasm <kind>            Disreplacedembler. <kind>:
    masm            => (default) MASM syntax
    nasm            => NASM syntax
    gas             => GNU replacedembler (AT&T) syntax
    att             => same as gas
    intel           => Intel (XED) syntax
-o, --output <path>             Output filename or directory
--type <tok-or-name>            Disreplacedemble this type (wildcards supported) or type token
--type-exclude <tok-or-name>    Don't disreplacedemble this type (wildcards supported) or type token
--method <tok-or-name>          Disreplacedemble this method (wildcards supported) or method token
--method-exclude <tok-or-name>  Don't disreplacedemble this method (wildcards supported) or method token
--diffable                      Create diffable disreplacedembly
--no-addr                       Don't show instruction addresses
--no-bytes                      Don't show instruction bytes
--no-source                     Don't show source code
--heap-search                   Check the GC heap for instantiated generic types
-s, --search <path>             Add replacedembly search paths (used with -l), {Path.PathSeparator}-delimited
-h, --help                      Show this help message

<tok-or-name> can be semicolon separated or multiple options can be used. Names support wildcards.
Token ranges are also supported eg. 0x06000001-0x06001234.

Generic methods and methods in generic types aren't 100% supported. Try --heap-search.

Examples:
    {exe} -m MyModule -pn myexe -f type -o c:\out\dir --method Decode
    {exe} -p 1234 -m System.Private.CoreLib -o C:\out\dir --diffable -f type
    {exe} -l c:\path\to\mymodule.dll
";
			Console.Write(msg);
		}

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
                replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
                String resourceName = string.Format("SharpRDP.{0}.dll.bin",
                    new replacedemblyName(argtwo.Name).Name);
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                using (var rs = replacedembly.GetManifestResourceStream(resourceName))
                using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
                using (var ms = new MemoryStream())
                {
                    zs.CopyTo(ms);
                    return replacedembly.Load(ms.ToArray());
                }
            };

            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            string username = string.Empty;
            string domain = string.Empty;
            string preplacedword = string.Empty;
            string command = string.Empty;
            string execElevated = string.Empty;
            string execw = "";
            bool connectdrive = false;
            bool takeover = false;
            bool nla = false;
            
            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Console.WriteLine("[X] Error: A preplacedword is required");
                    return;
                }
                else
                {
                    if (arguments["username"].Contains("\\"))
                    {
                        string[] tmp = arguments["username"].Split('\\');
                        domain = tmp[0];
                        username = tmp[1];
                    }
                    else
                    {
                        domain = ".";
                        username = arguments["username"];
                    }
                    preplacedword = arguments["preplacedword"];
                }
            }

            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Console.WriteLine("[X] Error: A username is required");
                return;
            }
            if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
            {
                Client rdpconn = new Client();
                command = arguments["command"];
                if (arguments.ContainsKey("exec"))
                {
                    if (arguments["exec"].ToLower() == "cmd")
                    {
                        execw = "cmd";
                    }
                    else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
                    {
                        execw = "powershell";
                    }
                }
                if (arguments.ContainsKey("elevated"))
                {
                    if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
                    {
                        execElevated = "winr";
                    }
                    else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
                    {
                        execElevated = "taskmgr";
                    }
                    else
                    {
                        execElevated = string.Empty;
                    }
                }
                if (arguments.ContainsKey("connectdrive"))
                {
                    if(arguments["connectdrive"].ToLower() == "true")
                    {
                        connectdrive = true;
                    }
                }
                if (arguments.ContainsKey("takeover"))
                {
                    if (arguments["takeover"].ToLower() == "true")
                    {
                        takeover = true;
                    }
                }
                if (arguments.ContainsKey("nla"))
                {
                    if (arguments["nla"].ToLower() == "true")
                    {
                        nla = true;
                    }
                }
                string[] computerNames = arguments["computername"].Split(',');
                foreach (string server in computerNames)
                {
                    rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
                }
            }
            else
            {
                HowTo();
                return;
            }

        }

19 Source : AutofacExtensions.cs
with MIT License
from 1100100

public static ContainerBuilder AddAllControllers(this ContainerBuilder container)
        {
            container.RegisterreplacedemblyTypes(replacedembly.GetEntryreplacedembly())
                .Where(t => t.Name.EndsWith("Controller"))
                .PropertiesAutowired().WithAttributeFiltering().InstancePerLifetimeScope();
            return container;
        }

19 Source : DebuggingEditor.cs
with MIT License
from 71

protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
        {
            OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;
            DebugCometaryAttribute attribute = Attribute;

            if (compilationConfiguration == OptimizationLevel.Debug && !attribute.RunInDebug)
                return;
            if (compilationConfiguration == OptimizationLevel.Release && !attribute.RunInRelease)
                return;

            string typeName = attribute.MainClreplacedName ?? DebugCometaryAttribute.DefaultMainClreplacedName;

            if (replacedembly.GetEntryreplacedembly().GetType(typeName) != null)
                return;

            CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
            {
                CSharpCompilationOptions options = compilation.Options;
                CSharpCompilationOptions newOptions = options
                    .WithOutputKind(OutputKind.ConsoleApplication)
                    .WithMainTypeName(typeName);

                // - Make the compilation an application, allowing its execution.
                // - Redirect the entry point to the automatically generated clreplaced.
                compilation = compilation.WithOptions(newOptions);

                // Create the entry point:
                string errorFile = Path.GetTempFileName();

                CSharpSyntaxTree generatedSyntaxTree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(GetSourceText(attribute.DisplayEndOfCompilationMessage, errorFile), cancellationToken: cancellationToken);
                CompilationUnitSyntax generatedRoot = generatedSyntaxTree.GetCompilationUnitRoot(cancellationToken);

                ClreplacedDeclarationSyntax clreplacedSyntax = (ClreplacedDeclarationSyntax)generatedRoot.Members.Last();
                ClreplacedDeclarationSyntax originalClreplacedSyntax = clreplacedSyntax;

                // Edit the generated syntax's name, if needed.
                if (typeName != DebugCometaryAttribute.DefaultMainClreplacedName)
                {
                    clreplacedSyntax = clreplacedSyntax.WithIdentifier(F.Identifier(typeName));
                }

                // Change the filename and arguments.
                SyntaxList<MemberDeclarationSyntax> members = clreplacedSyntax.Members;

                FieldDeclarationSyntax WithValue(FieldDeclarationSyntax node, string value)
                {
                    VariableDeclaratorSyntax variableSyntax = node.Declaration.Variables[0];
                    LiteralExpressionSyntax valueSyntax = F.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        F.Literal(value)
                    );

                    return node.WithDeclaration(
                        node.Declaration.WithVariables(node.Declaration.Variables.Replace(
                            variableSyntax, variableSyntax.WithInitializer(F.EqualsValueClause(valueSyntax))
                        ))
                    );
                }

                FieldDeclarationSyntax WithBoolean(FieldDeclarationSyntax node, bool value)
                {
                    VariableDeclaratorSyntax variableSyntax = node.Declaration.Variables[0];
                    LiteralExpressionSyntax valueSyntax = F.LiteralExpression(value ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression);

                    return node.WithDeclaration(
                        node.Declaration.WithVariables(node.Declaration.Variables.Replace(
                            variableSyntax, variableSyntax.WithInitializer(F.EqualsValueClause(valueSyntax))
                        ))
                    );
                }

                for (int i = 0; i < members.Count; i++)
                {
                    FieldDeclarationSyntax field = members[i] as FieldDeclarationSyntax;

                    if (field == null)
                        continue;

                    string fieldName = field.Declaration.Variables[0].Identifier.Text;

                    switch (fieldName)
                    {
                        case "References":
                            field = WithValue(field, string.Join(";", compilation.References.OfType<PortableExecutableReference>().Select(x => x.FilePath)));
                            break;
                        case "Files":
                            field = WithValue(field, string.Join(";", compilation.SyntaxTrees.Select(x => x.FilePath)));
                            break;
                        case "replacedemblyName":
                            field = WithValue(field, compilation.replacedemblyName);
                            break;
                        case "ErrorFile":
                            field = WithValue(field, errorFile);
                            break;
                        case "Written":
                            field = WithBoolean(field, OutputAllTreesAttribute.Instance != null);
                            break;
                        case "BreakAtEnd":
                            field = WithBoolean(field, attribute.DisplayEndOfCompilationMessage);
                            break;
                        case "BreakAtStart":
                            field = WithBoolean(field, attribute.BreakDuringStart);
                            break;
                        default:
                            continue;
                    }

                    members = members.Replace(members[i], field);
                }

                // Return the modified compilation.
                return compilation.AddSyntaxTrees(
                    generatedSyntaxTree
                        .WithCometaryOptions(this)
                        .WithRoot(
                            generatedRoot.WithMembers(generatedRoot.Members.Replace(originalClreplacedSyntax, clreplacedSyntax.WithMembers(members))
                        )
                    )
                );
            }

            CompilationPipeline += EditCompilation;
        }

19 Source : ServiceCollectionExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

public static void AutoRegister(this IServiceCollection services)
        {
            #region 自动注入

            var allreplacedemblies = replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies().Select(replacedembly.Load);
            foreach (var serviceAsm in allreplacedemblies)
            {
                var serviceList = serviceAsm.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && !t.IsInterface);

                foreach (Type serviceType in serviceList.Where(t => typeof(IScoped).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddScoped(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => typeof(ISingleton).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddSingleton(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => typeof(ITransient).IsreplacedignableFrom(t)))
                {
                    var interfaceTypes = serviceType.GetInterfaces();

                    foreach (var interfaceType in interfaceTypes)
                    {
                        services.AddTransient(interfaceType, serviceType);
                    }
                }

                foreach (Type serviceType in serviceList.Where(t => t.IsSubclreplacedOf(typeof(BackgroundService))))
                {
                    services.AddTransient(typeof(IHostedService), serviceType);
                }
            }
            #endregion

        }

19 Source : Kernel.cs
with MIT License
from 99x

public void Initialize()
        {
            replacedembly asm;

            if (callingreplacedembly == null)
            {
                asm = replacedembly.GetEntryreplacedembly();
                if (asm == null)
                    asm = replacedembly.GetCallingreplacedembly();
            }
            else
            {
                asm = callingreplacedembly;
            }


            ResourceRepository.Initialize(asm);
        }

19 Source : Program.cs
with Apache License 2.0
from AantCoder

public async Task RegisterCommandAsync()
        {
             _messageParser = new MessageParser(_services);
             _discordClient.MessageReceived += _messageParser.Execute;
            await _commands.AddModulesAsync(replacedembly.GetEntryreplacedembly(), _services);
        }

19 Source : Service.cs
with Apache License 2.0
from AantCoder

private static void DependencyInjection()
        {
            //may better way use a native .Net Core DI
            var d = new Dictionary<int, IGenerateResponseContainer>();
            foreach (var type in replacedembly.GetEntryreplacedembly().GetTypes())
            {
                if (!type.IsClreplaced)
                {
                    continue;
                }

                if (type.GetInterfaces().Any(x => x == typeof(IGenerateResponseContainer)))
                {
                    var t = (IGenerateResponseContainer)Activator.CreateInstance(type);
                    d[t.RequestTypePackage] = t;
                }
            }

            ServiceDictionary = d;
        }

19 Source : App.xaml.cs
with Microsoft Public License
from AArnott

internal static UpdateManager CreateUpdateManager()
	{
		string channel = Thisreplacedembly.IsPrerelease ? "prerelease" : "release";
		string channelOverrideFilePath = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly()!.Location)!, "channelname.txt");
		if (File.Exists(channelOverrideFilePath))
		{
			channel = File.ReadAllText(channelOverrideFilePath).Trim();
		}

		string subchannel = RuntimeInformation.ProcessArchitecture switch
		{
			Architecture.Arm64 => "win-arm64",
			Architecture.X64 => "win-x64",
			Architecture.X86 => "win-x86",
			_ => throw new NotSupportedException("Unrecognized process architecture."),
		};

19 Source : BitmapAssetValueConverter.cs
with MIT License
from Abdesol

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            if (value is string rawUri && targetType.IsreplacedignableFrom(typeof(Bitmap)))
            {
                Uri uri;

                // Allow for replacedembly overrides
                if (rawUri.StartsWith("avares://"))
                {
                    uri = new Uri(rawUri);
                }
                else
                {
                    string replacedemblyName = replacedembly.GetEntryreplacedembly().GetName().Name;
                    uri = new Uri($"avares://{replacedemblyName}{rawUri}");
                }

                var replacedets = AvaloniaLocator.Current.GetService<IreplacedetLoader>();
                var replacedet = replacedets.Open(uri);

                return new Bitmap(replacedet);
            }

            throw new NotSupportedException();
        }

19 Source : Utils.cs
with MIT License
from acandylevey

static public string replacedemblyLoadDirectory()
        {
            string codeBase = replacedembly.GetEntryreplacedembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 Source : Utils.cs
with MIT License
from acandylevey

static public string replacedemblyExecuteablePath()
        {
            string codeBase = replacedembly.GetEntryreplacedembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            return Uri.UnescapeDataString(uri.Path);
        }

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

public static void Main(string[] args)
        {
            var consolereplacedle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.replacedle = consolereplacedle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and replacedumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the Executingreplacedembly location
            var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
                File.Copy(log4netConfigContainer, log4netConfig, true);

            var log4netFileInfo = new FileInfo("log4net.config");
            if (!log4netFileInfo.Exists)
                log4netFileInfo = new FileInfo(log4netConfig);

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {                        
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }

                    }
                }
            }

            var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
                log.Info("ACEmulator is running in a container...");
            
            var configFile = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
                File.Copy(configConfigContainer, configFile, true);

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                    DoOutOfBoxSetup(configFile);
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                        File.Copy(configConfigContainer, configFile);
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consolereplacedle = $"{ConfigManager.Config.Server.WorldName} | {consolereplacedle}";
                Console.replacedle = consolereplacedle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
            {
                log.Info($"Pruning invalid friends from all friend lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
                log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
            {
                log.Info($"Pruning invalid shortcuts from all shortcut bars...");
                ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
                log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
            {
                log.Info($"Pruning invalid squelches from all squelch lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
                log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                    AutoApplyWorldCustomizations();
            }
            else
                log.Info($"AutoUpdateWorldDatabase is disabled...");

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
                AutoApplyDatabaseUpdates();
            else
                log.Info($"AutoApplyDatabaseUpdates is disabled...");

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            // pre-load starterGear.json, abort startup if file is not found as it is required to create new characters.
            if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null)
            {
                log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
                log.Info("Precaching World Database Disabled...");

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0 ; i < 10 ; i++)
                GC.Collect();

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }

19 Source : CommonModule.cs
with MIT License
from acid-chicken

[Command("version"), Summary("バージョン情報を表示します。"), Alias("ver")]
        public async Task VersionAsync([Remainder] string comment = null)
        {
            var replacedembly = replacedembly.GetEntryreplacedembly();
            await ReplyAsync
            (
                message: Context.User.Mention,
                embed:
                    new EmbedBuilder()
                        .Withreplacedle(((replacedemblyreplacedleAttribute)Attribute.GetCustomAttribute(replacedembly, typeof(replacedemblyreplacedleAttribute))).replacedle)
                        .WithDescription(((replacedemblyDescriptionAttribute)Attribute.GetCustomAttribute(replacedembly, typeof(replacedemblyDescriptionAttribute))).Description)
                        .WithCurrentTimestamp()
                        .WithColor(Colors.Blue)
                        .WithFooter(EmbedManager.CurrentFooter)
                        .WithAuthor(Context.User)
                        .WithThumbnailUrl(DiscordClient.CurrentUser.GetAvatarUrl())
                        .AddInlineField("バージョン", ((replacedemblyInformationalVersionAttribute)Attribute.GetCustomAttribute(replacedembly, typeof(replacedemblyInformationalVersionAttribute))).InformationalVersion)
                        .AddInlineField("著作権情報", ((replacedemblyCopyrightAttribute)Attribute.GetCustomAttribute(replacedembly, typeof(replacedemblyCopyrightAttribute))).Copyright)
            ).ConfigureAwait(false);
        }

19 Source : ModuleManager.cs
with MIT License
from acid-chicken

public static Task<IEnumerable<ModuleInfo>> InstallAsync()
        {
            DiscordClient.MessageReceived += (message) => Task.WhenAny(HandleCommandAsync(message), Task.Delay(0));
            return Service.AddModulesAsync(replacedembly.GetEntryreplacedembly());
        }

19 Source : ConfigurationStore.cs
with MIT License
from actions

public override void Initialize(IHostContext hostContext)
        {
            base.Initialize(hostContext);

            var currentreplacedemblyLocation = System.Reflection.replacedembly.GetEntryreplacedembly().Location;
            Trace.Info("currentreplacedemblyLocation: {0}", currentreplacedemblyLocation);

            _binPath = HostContext.GetDirectory(WellKnownDirectory.Bin);
            Trace.Info("binPath: {0}", _binPath);

            RootFolder = HostContext.GetDirectory(WellKnownDirectory.Root);
            Trace.Info("RootFolder: {0}", RootFolder);

            _configFilePath = hostContext.GetConfigFile(WellKnownConfigFile.Runner);
            Trace.Info("ConfigFilePath: {0}", _configFilePath);

            _credFilePath = hostContext.GetConfigFile(WellKnownConfigFile.Credentials);
            Trace.Info("CredFilePath: {0}", _credFilePath);

            _migratedCredFilePath = hostContext.GetConfigFile(WellKnownConfigFile.MigratedCredentials);
            Trace.Info("MigratedCredFilePath: {0}", _migratedCredFilePath);

            _serviceConfigFilePath = hostContext.GetConfigFile(WellKnownConfigFile.Service);
            Trace.Info("ServiceConfigFilePath: {0}", _serviceConfigFilePath);
        }

19 Source : HostContext.cs
with MIT License
from actions

public string GetDirectory(WellKnownDirectory directory)
        {
            string path;
            switch (directory)
            {
                case WellKnownDirectory.Bin:
                    path = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                    break;

                case WellKnownDirectory.Diag:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        Constants.Path.DiagDirectory);
                    break;

                case WellKnownDirectory.Externals:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        Constants.Path.ExternalsDirectory);
                    break;

                case WellKnownDirectory.Root:
                    path = new DirectoryInfo(GetDirectory(WellKnownDirectory.Bin)).Parent.FullName;
                    break;

                case WellKnownDirectory.Temp:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.TempDirectory);
                    break;

                case WellKnownDirectory.Actions:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.ActionsDirectory);
                    break;

                case WellKnownDirectory.Tools:
                    // TODO: Coallesce to just check RUNNER_TOOL_CACHE when images stabilize
                    path = Environment.GetEnvironmentVariable("RUNNER_TOOL_CACHE") ?? Environment.GetEnvironmentVariable("RUNNER_TOOLSDIRECTORY") ?? Environment.GetEnvironmentVariable("AGENT_TOOLSDIRECTORY") ?? Environment.GetEnvironmentVariable(Constants.Variables.Agent.ToolsDirectory);

                    if (string.IsNullOrEmpty(path))
                    {
                        path = Path.Combine(
                            GetDirectory(WellKnownDirectory.Work),
                            Constants.Path.ToolDirectory);
                    }
                    break;

                case WellKnownDirectory.Update:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.UpdateDirectory);
                    break;

                case WellKnownDirectory.Work:
                    var configurationStore = GetService<IConfigurationStore>();
                    RunnerSettings settings = configurationStore.GetSettings();
                    ArgUtil.NotNull(settings, nameof(settings));
                    ArgUtil.NotNullOrEmpty(settings.WorkFolder, nameof(settings.WorkFolder));
                    path = Path.GetFullPath(Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        settings.WorkFolder));
                    break;

                default:
                    throw new NotSupportedException($"Unexpected well known directory: '{directory}'");
            }

            _trace.Info($"Well known directory '{directory}': '{path}'");
            return path;
        }

19 Source : Program.cs
with MIT License
from actions

private static void LoadAndSetEnv()
        {
            var binDir = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            var rootDir = new DirectoryInfo(binDir).Parent.FullName;
            string envFile = Path.Combine(rootDir, ".env");
            if (File.Exists(envFile))
            {
                var envContents = File.ReadAllLines(envFile);
                foreach (var env in envContents)
                {
                    if (!string.IsNullOrEmpty(env))
                    {
                        var separatorIndex = env.IndexOf('=');
                        if (separatorIndex > 0)
                        {
                            string envKey = env.Substring(0, separatorIndex);
                            string envValue = null;
                            if (env.Length > separatorIndex + 1)
                            {
                                envValue = env.Substring(separatorIndex + 1);
                            }

                            Environment.SetEnvironmentVariable(envKey, envValue);
                        }
                    }
                }
            }
        }

19 Source : RunnerService.cs
with MIT License
from actions

private Process CreateRunnerListener()
        {
            string exeLocation = replacedembly.GetEntryreplacedembly().Location;
            string runnerExeLocation = Path.Combine(Path.GetDirectoryName(exeLocation), "Runner.Listener.exe");
            Process newProcess = new Process();
            newProcess.StartInfo = new ProcessStartInfo(runnerExeLocation, "run --startuptype service");
            newProcess.StartInfo.CreateNoWindow = true;
            newProcess.StartInfo.UseShellExecute = false;
            newProcess.StartInfo.RedirectStandardInput = true;
            newProcess.StartInfo.RedirectStandardOutput = true;
            newProcess.StartInfo.RedirectStandardError = true;
            return newProcess;
        }

19 Source : RunnerService.cs
with MIT License
from actions

private string GetDiagnosticFolderPath()
        {
            return Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location)), "_diag");
        }

19 Source : HashFilesFunction.cs
with MIT License
from actions

protected sealed override Object EvaluateCore(
            EvaluationContext context,
            out ResultMemory resultMemory)
        {
            resultMemory = null;
            var templateContext = context.State as DistributedTask.ObjectTemplating.TemplateContext;
            ArgUtil.NotNull(templateContext, nameof(templateContext));
            templateContext.ExpressionValues.TryGetValue(PipelineTemplateConstants.GitHub, out var githubContextData);
            ArgUtil.NotNull(githubContextData, nameof(githubContextData));
            var githubContext = githubContextData as DictionaryContextData;
            ArgUtil.NotNull(githubContext, nameof(githubContext));
            githubContext.TryGetValue(PipelineTemplateConstants.Workspace, out var workspace);
            var workspaceData = workspace as StringContextData;
            ArgUtil.NotNull(workspaceData, nameof(workspaceData));

            string githubWorkspace = workspaceData.Value;
            bool followSymlink = false;
            List<string> patterns = new List<string>();
            var firstParameter = true;
            foreach (var parameter in Parameters)
            {
                var parameterString = parameter.Evaluate(context).ConvertToString();
                if (firstParameter)
                {
                    firstParameter = false;
                    if (parameterString.StartsWith("--"))
                    {
                        if (string.Equals(parameterString, "--follow-symbolic-links", StringComparison.OrdinalIgnoreCase))
                        {
                            followSymlink = true;
                            continue;
                        }
                        else
                        {
                            throw new ArgumentOutOfRangeException($"Invalid glob option {parameterString}, avaliable option: '--follow-symbolic-links'.");
                        }
                    }
                }

                patterns.Add(parameterString);
            }

            context.Trace.Info($"Search root directory: '{githubWorkspace}'");
            context.Trace.Info($"Search pattern: '{string.Join(", ", patterns)}'");

            string binDir = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            string runnerRoot = new DirectoryInfo(binDir).Parent.FullName;

            string node = Path.Combine(runnerRoot, "externals", "node12", "bin", $"node{IOUtil.ExeExtension}");
            string hashFilesScript = Path.Combine(binDir, "hashFiles");
            var hashResult = string.Empty;
            var p = new ProcessInvoker(new HashFilesTrace(context.Trace));
            p.ErrorDataReceived += ((_, data) =>
            {
                if (!string.IsNullOrEmpty(data.Data) && data.Data.StartsWith("__OUTPUT__") && data.Data.EndsWith("__OUTPUT__"))
                {
                    hashResult = data.Data.Substring(10, data.Data.Length - 20);
                    context.Trace.Info($"Hash result: '{hashResult}'");
                }
                else
                {
                    context.Trace.Info(data.Data);
                }
            });

            p.OutputDataReceived += ((_, data) =>
            {
                context.Trace.Info(data.Data);
            });

            var env = new Dictionary<string, string>();
            if (followSymlink)
            {
                env["followSymbolicLinks"] = "true";
            }
            env["patterns"] = string.Join(Environment.NewLine, patterns);

            using (var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(_hashFileTimeoutSeconds)))
            {
                try
                {
                    int exitCode = p.ExecuteAsync(workingDirectory: githubWorkspace,
                                                  fileName: node,
                                                  arguments: $"\"{hashFilesScript.Replace("\"", "\\\"")}\"",
                                                  environment: env,
                                                  requireExitCodeZero: false,
                                                  cancellationToken: tokenSource.Token).GetAwaiter().GetResult();

                    if (exitCode != 0)
                    {
                        throw new InvalidOperationException($"hashFiles('{ExpressionUtility.StringEscape(string.Join(", ", patterns))}') failed. Fail to hash files under directory '{githubWorkspace}'");
                    }
                }
                catch (OperationCanceledException) when (tokenSource.IsCancellationRequested)
                {
                    throw new TimeoutException($"hashFiles('{ExpressionUtility.StringEscape(string.Join(", ", patterns))}') couldn't finish within {_hashFileTimeoutSeconds} seconds.");
                }

                return hashResult;
            }
        }

19 Source : HostContextL0.cs
with MIT License
from actions

private void Setup([CallerMemberName] string testName = "")
        {
            _tokenSource = new CancellationTokenSource();
            _hc = new HostContext(
                hostType: "L0Test",
                logFile: Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location), $"trace_{nameof(HostContextL0)}_{testName}.log"));
        }

19 Source : TestHostContext.cs
with MIT License
from actions

public string GetDirectory(WellKnownDirectory directory)
        {
            string path;
            switch (directory)
            {
                case WellKnownDirectory.Bin:
                    path = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                    break;

                case WellKnownDirectory.Diag:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        Constants.Path.DiagDirectory);
                    break;

                case WellKnownDirectory.Externals:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Root),
                        Constants.Path.ExternalsDirectory);
                    break;

                case WellKnownDirectory.Root:
                    path = new DirectoryInfo(GetDirectory(WellKnownDirectory.Bin)).Parent.FullName;
                    break;

                case WellKnownDirectory.Temp:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.TempDirectory);
                    break;

                case WellKnownDirectory.Actions:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.ActionsDirectory);
                    break;

                case WellKnownDirectory.Tools:
                    path = Environment.GetEnvironmentVariable("RUNNER_TOOL_CACHE");

                    if (string.IsNullOrEmpty(path))
                    {
                        path = Path.Combine(
                            GetDirectory(WellKnownDirectory.Work),
                            Constants.Path.ToolDirectory);
                    }
                    break;

                case WellKnownDirectory.Update:
                    path = Path.Combine(
                        GetDirectory(WellKnownDirectory.Work),
                        Constants.Path.UpdateDirectory);
                    break;

                case WellKnownDirectory.Work:
                    path = Path.Combine(
                        _tempDirectoryRoot,
                        WellKnownDirectory.Work.ToString());
                    break;

                default:
                    throw new NotSupportedException($"Unexpected well known directory: '{directory}'");
            }

            _trace.Info($"Well known directory '{directory}': '{path}'");
            return path;
        }

19 Source : HostContextL0.cs
with MIT License
from actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void SecretMaskerForProxy()
        {
            try
            {
                Environment.SetEnvironmentVariable("http_proxy", "http://user:[email protected]:8888");

                // Arrange.
                Setup();

                // replacedert.
                var logFile = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location), $"trace_{nameof(HostContextL0)}_{nameof(SecretMaskerForProxy)}.log");
                var tempFile = Path.GetTempFileName();
                File.Delete(tempFile);
                File.Copy(logFile, tempFile);
                var content = File.ReadAllText(tempFile);
                replacedert.DoesNotContain("preplacedword123", content);
                replacedert.Contains("http://user:***@127.0.0.1:8888", content);
            }
            finally
            {
                Environment.SetEnvironmentVariable("http_proxy", null);
                // Cleanup.
                Teardown();
            }
        }

19 Source : ApplicationViewModel.cs
with MIT License
from Actipro

private static string GetSampleProjectPath() {
			var uri = new Uri(replacedembly.GetEntryreplacedembly().GetName().CodeBase);
			var path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(uri.LocalPath), @"..\..\.."));
			return path;
		}

19 Source : ConnectedInstruction.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

private static void DynamicallyParseExpressionDirectlyAgainstKDBDataInDirectMemmoryPointerFashion(string expression, out CompilerParameters cpd, out string codeD)
        {
            #region DynamicCreationWithDirectPointersToKDBSource
            cpd = new CompilerParameters()
            {
                GenerateExecutable = false,
                Outputreplacedembly = "outputreplacedemblyName",
                GenerateInMemory = true
            };
            cpd.Referencedreplacedemblies.Add("mscorlib.dll");
            cpd.Referencedreplacedemblies.Add("System.dll");
            cpd.Referencedreplacedemblies.Add("ActuarialIntelligence.Domain.dll");
            cpd.Referencedreplacedemblies.Add(replacedembly.GetEntryreplacedembly().Location);
            //StringBuilder sb = new StringBuilder();
            // This is Dangerous as it is open to code injection by design. Any implementation of this pattern
            // must be secured by the implementer

            // The string can contain any valid c# code
            codeD = @"

                using System;
                using System.Collections.Generic;
                using ActuarialIntelligence.Domain.Financial_Instrument_Objects;
                namespace ActuarialIntelligence.Domain.ConnectedInstruction
                {
                    public clreplaced RuntimeClreplaced
                    {
                        public static List<double> Main (IList<IList<double>> gridValues)
                        {
                            return ActionFunc(gridValues ,(u, v, w, x, y, z) => " + expression + @"); 
                        }

                        public static List<double> ActionFunc(IList<IList<double>> gridValues,
                            Func<double, double, double,
                            double, double, double, double> expression)
                        {
                            var result = new List<double>();
                            var c = new ConnectedInstruction();
                            var rowN = c.GetNumberOfRows();
                            for(int i=2;i<rowN;i++)
                            {
                                var calc = expression((double)c.GetField(i,0), (double)c.GetField(i,1), (double)c.GetField(i,2), (double)c.GetField(i,3), (double)c.GetField(i,4), (double)c.GetField(i,5));                            
                                result.Add(calc);
                            }
                            int cnt =0;
                            foreach(var val in result)
                            {
                                Console.WriteLine(rowN.ToString() + ""  "" + val.ToString());
                                if(cnt == 20)
                                {
                                    break;
                                }
                                    cnt++;
                            }
                            c.DisposeQconnection();
                            return result;
                        }
                    }
                }

                ";
            // "+ expression + @" 
            #endregion
        }

19 Source : ConnectedInstruction_BACKUP_44876.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

private static void ParseExpressionAgainstLoadedInMemoryData(string expression, out CompilerParameters cp, out string code)
        {
            #region DynamicCodeInjectionForEfficientParsingOfScript
            cp = new CompilerParameters()
            {
                GenerateExecutable = false,
                Outputreplacedembly = "outputreplacedemblyName",
                GenerateInMemory = true
            };
            cp.Referencedreplacedemblies.Add("mscorlib.dll");
            cp.Referencedreplacedemblies.Add("System.dll");
            cp.Referencedreplacedemblies.Add("ActuarialIntelligence.Domain.dll");
            cp.Referencedreplacedemblies.Add(replacedembly.GetEntryreplacedembly().Location);
            //StringBuilder sb = new StringBuilder();
            // This is Dangerous as it is open to code injection by design. Any implementation of this pattern
            // must be secured by the implementer

            // The string can contain any valid c# code and Rajah knows is best best stored in separate text clreplaced file
            code = @"

                using System;
                using System.Collections.Generic;
                namespace ActuarialIntelligence.Domain.ConnectedInstruction
                {
                    public clreplaced RuntimeClreplaced
                    {
                        public static void Main (IList<IList<double>> gridValues)
                        {
<<<<<<< HEAD
                            ActionFunc(gridValues ,(u, v, w, x, y, z) => " + expression + @"); 
=======
                            return ActionFunc(gridValues ,(u, v, w, x, y, z) => " + expression + @"); 
>>>>>>> Integrated KDB ConnectedInstruction and parser objects. Tested
                        }

                        public static void ActionFunc(IList<IList<double>> gridValues,
                            Func<double, double, double,
                            double, double, double, double> expression)
                        {
                            //var result = new List<double>();
                            foreach (var row in gridValues)
                            {
                                var calc = expression(row[0], row[1], row[2], row[3], row[4], row[5]);
                                row.Add(calc);
<<<<<<< HEAD
=======
                                result.Add(calc);
>>>>>>> Integrated KDB ConnectedInstruction and parser objects. Tested
                                //Console.WriteLine(calc.ToString());
                            }
                        }
                    }
                }

                ";
            // "+ expression + @" 
            #endregion
        }

19 Source : ConnectedInstruction_BACKUP_44876.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

private static void DynamicallyParseExpressionDirectlyAgainstKDBDataInDirectMemmoryPointerFashion(string expression, out CompilerParameters cpd, out string codeD)
        {
            #region DynamicCreationWithDirectPointersToKDBSource
            cpd = new CompilerParameters()
            {
                GenerateExecutable = false,
                Outputreplacedembly = "outputreplacedemblyName",
                GenerateInMemory = true
            };
            cpd.Referencedreplacedemblies.Add("mscorlib.dll");
            cpd.Referencedreplacedemblies.Add("System.dll");
            cpd.Referencedreplacedemblies.Add("ActuarialIntelligence.Domain.dll");
            cpd.Referencedreplacedemblies.Add(replacedembly.GetEntryreplacedembly().Location);
            //StringBuilder sb = new StringBuilder();
            // This is Dangerous as it is open to code injection by design. Any implementation of this pattern
            // must be secured by the implementer

            // The string can contain any valid c# code
            codeD = @"

                using System;
                using System.Collections.Generic;
                namespace ActuarialIntelligence.Domain.ConnectedInstruction
                {
                    public clreplaced RuntimeClreplaced
                    {
                        public static List<double> Main (IList<IList<double>> gridValues)
                        {
                            return ActionFunc(gridValues ,(u, v, w, x, y, z) => " + expression + @"); 
                        }

                        public static List<double> ActionFunc(IList<IList<double>> gridValues,
                            Func<double, double, double,
                            double, double, double, double> expression)
                        {
                            var result = new List<double>();
                            var c = new ConnectedInstruction();
                            var rowN = c.GetNumberOfRows();
                            for(int i=2;i<rowN;i++)
                            {
                                var calc = expression((double)c.GetField(i,0), (double)c.GetField(i,1), (double)c.GetField(i,2), (double)c.GetField(i,3), (double)c.GetField(i,4), (double)c.GetField(i,5));                            
                            }
                            c.DisposeQconnection();
                            return result;
                        }
                    }
                }

                ";
            // "+ expression + @" 
            #endregion
        }

19 Source : ConnectedInstruction.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

private static void ParseExpressionAgainstLoadedInMemoryData(string expression, out CompilerParameters cp, out string code)
        {
            #region DynamicCodeInjectionForEfficientParsingOfScript
            cp = new CompilerParameters()
            {
                GenerateExecutable = false,
                Outputreplacedembly = "outputreplacedemblyName",
                GenerateInMemory = true
            };
            cp.Referencedreplacedemblies.Add("mscorlib.dll");
            cp.Referencedreplacedemblies.Add("System.dll");
            cp.Referencedreplacedemblies.Add("ActuarialIntelligence.Domain.dll");
            cp.Referencedreplacedemblies.Add(replacedembly.GetEntryreplacedembly().Location);
            //StringBuilder sb = new StringBuilder();
            // This is Dangerous as it is open to code injection by design. Any implementation of this pattern
            // must be secured by the implementer

            // The string can contain any valid c# code and Rajah knows is best best stored in separate text clreplaced file
            code = @"

                using System;
                using System.Collections.Generic;
                namespace ActuarialIntelligence.Domain.ConnectedInstruction
                {
                    public clreplaced RuntimeClreplaced
                    {
                        public static List<double> Main (IList<IList<double>> gridValues)
                        {
                            return ActionFunc(gridValues ,(u, v, w, x, y, z) => " + expression + @"); 
                        }

                        public static List<double> ActionFunc(IList<IList<double>> gridValues,
                            Func<double, double, double,
                            double, double, double, double> expression)
                        {
                            var result = new List<double>();
                            foreach (var row in gridValues)
                            {
                                var calc = expression(row[0], row[1], row[2], row[3], row[4], row[5]);
                                row.Add(calc);
                                result.Add(calc);
                                //Console.WriteLine(calc.ToString());
                            }
                            return result;
                        }
                    }
                }

                ";
            // "+ expression + @" 
            #endregion
        }

19 Source : ConnectedInstruction_LOCAL_44876.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static IList<IList<double>> ParseExpressionAndRunAgainstInMemmoryModel(IList<IList<double>> GridValues, string expression)
        {
            gridValues = GridValues;
            #region HandleNullGrids
            if (gridValues == null)
            {
                gridValues = new List<IList<double>>();
                gridValues.Add(new List<double>() { 1d, 2d, 3d, 4d, 5d, 6d, 0d });
                gridValues.Add(new List<double>() { 1d, 2d, 3d, 4d, 5d, 6d, 0d });
                gridValues.Add(new List<double>() { 1d, 2d, 3d, 4d, 5d, 6d, 0d });
            }
            #endregion            

            var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
            var cp = new CompilerParameters()
            {
                GenerateExecutable = false,
                Outputreplacedembly = "outputreplacedemblyName",
                GenerateInMemory = true
            };

            cp.Referencedreplacedemblies.Add("mscorlib.dll");
            cp.Referencedreplacedemblies.Add("System.dll");
            cp.Referencedreplacedemblies.Add(replacedembly.GetEntryreplacedembly().Location);
            //StringBuilder sb = new StringBuilder();
            // This is Dangerous as it is open to code injection by design. Any implementation of this pattern
            // must be secured by the implementer
            #region DynamicCodeInjectionForEfficientParsingOfScript
            // The string can contain any valid c# code
            string code = @"

                using System;
                using System.Collections.Generic;
                namespace ActuarialIntelligence.Domain.ConnectedInstruction
                {
                    public clreplaced RuntimeClreplaced
                    {
                        public static void Main (IList<IList<double>> gridValues)
                        {
                            ActionFunc(gridValues ,(u, v, w, x, y, z) => " + expression + @"); 
                        }

                        public static void ActionFunc(IList<IList<double>> gridValues,
                            Func<double, double, double,
                            double, double, double, double> expression)
                        {
                            //var result = new List<double>();
                            foreach (var row in gridValues)
                            {
                                var calc = expression(row[0], row[1], row[2], row[3], row[4], row[5]);
                                row.Add(calc);
                                //Console.WriteLine(calc.ToString());
                            }
                        }
                    }
                }

                ";// "+ expression + @" 
            #endregion
            // "results" will usually contain very detailed error messages
            var results = csc.CompilereplacedemblyFromSource(cp, code);
            InvokeAndErrorhandle(results);
            return gridValues;
        }

19 Source : RabbitMqClientProvider.cs
with MIT License
from ad313

private void CreateConnection()
        {
            Config.Check();

            ConnectionFactory = new ConnectionFactory
            {
                UserName = Config.UserName,
                Preplacedword = Config.Preplacedword,
                HostName = Config.HostName,
                Port = Config.Port,
                VirtualHost = Config.VirtualHost,
                AutomaticRecoveryEnabled = true
            };
            
            var name = $"{replacedembly.GetEntryreplacedembly()?.GetName().Name.ToLower()}_{Guid.NewGuid()}";
            Connection = ConnectionFactory.CreateConnection(name);
            Connection.ConnectionShutdown += Connection_ConnectionShutdown;
            Connection.ConnectionBlocked += Connection_ConnectionBlocked;
            Connection.ConnectionUnblocked += Connection_ConnectionUnblocked;
            
            _logger.LogInformation($"{DateTime.Now} RabbitMQ 连接成功:Host:{Config.HostName},UserName:{Config.UserName} [{name}]");

            Channel = Connection.CreateModel();
        }

19 Source : VideoSource.cs
with MIT License
from adamfisher

public static VideoSource FromResource(string resource, replacedembly replacedembly = default(replacedembly))
        {
			if (string.IsNullOrEmpty (resource))
				return null;
			
			if (!Path.HasExtension (resource))
				throw new Exception ($"The specified resource '{resource}' must contain a valid file extension.");

            var foundResource = false;
			var format = Path.GetExtension (resource)?.Replace (".", string.Empty);
            replacedembly parameterreplacedembly = null, callingreplacedembly = null, entryreplacedembly = null;

            if (replacedembly != null)
            {
                parameterreplacedembly = replacedembly;
                foundResource = replacedembly.ContainsManifestResource(resource);
            }

            if (!foundResource)
            {
                replacedembly = replacedembly.GetCallingreplacedembly();
                callingreplacedembly = replacedembly;
                foundResource = replacedembly.ContainsManifestResource(resource);
            }

            if (!foundResource)
            {
                replacedembly = replacedembly.GetEntryreplacedembly();
                entryreplacedembly = replacedembly;
                foundResource = replacedembly.ContainsManifestResource(resource);
            }
            
            if (!foundResource)
            {
                var resourceNames = new List<string>();

                if (parameterreplacedembly != null)
                    resourceNames.AddRange(parameterreplacedembly.GetManifestResourceNames());
                if (callingreplacedembly != null)
                    resourceNames.AddRange(callingreplacedembly.GetManifestResourceNames());
                if (entryreplacedembly != null)
                    resourceNames.AddRange(entryreplacedembly.GetManifestResourceNames());

                Log.Error($"Unable to locate the embedded resource '{resource}'. " +
                          $"Possible candidates are: {Environment.NewLine}{string.Join(Environment.NewLine, resourceNames)}");

                return null;
            }

			return FromStream(() => replacedembly.GetEmbeddedResourceStream(resource), format);
        }

19 Source : TargetCollectionExtensions.cs
with Apache License 2.0
from adamralph

private static async Task<string> GetMessagePrefix(TextWriter diagnosticsWriter)
        {
            var messagePrefix = "Bullseye";

            if (replacedembly.GetEntryreplacedembly() is replacedembly entryreplacedembly)
            {
                messagePrefix = entryreplacedembly.GetName().Name;
            }
            else
            {
                await diagnosticsWriter.WriteLineAsync($"{messagePrefix}: Failed to get the entry replacedembly. Using default message prefix \"{messagePrefix}\".").Tax();
            }

            return messagePrefix;
        }

19 Source : AntiTampering.cs
with GNU General Public License v3.0
from Agasper

public static void AddCallToUnity(ModuleDefMD unityModule, string hash)
        {
            log.Info("Adding hash to Unity...");

            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string applicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef tamperClreplaced = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(UnityCertificate).MetadataToken));
            MethodDef checkerMethod = tamperClreplaced.FindMethod("GetHash");

            typeModule.Types.Remove(tamperClreplaced);
            unityModule.Types.Add(tamperClreplaced);

            checkerMethod.Body.Instructions[1].Operand = hash;

            //foreach (var i in checkerMethod.Body.Instructions)
            //    Console.WriteLine(i);
        }

19 Source : AntiTampering.cs
with GNU General Public License v3.0
from Agasper

public static void AddCallToModule(ModuleDefMD module)
        {
            log.Info("Adding hash checking to the replacedembly...");
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string applicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef tamperClreplaced = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(AsertSigning).MetadataToken));

            typeModule.Types.Remove(tamperClreplaced);
            module.Types.Add(tamperClreplaced);

            MethodDef cctor = module.GlobalType.FindOrCreateStaticConstructor();

            //foreach (var p in cctor.Body.Instructions)
                //Console.WriteLine(p);

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, tamperClreplaced.FindMethod("Expose")));


            //var t = Type.GetType("UnityEngine.UnityCertificate, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
            //Console.WriteLine(t);
            //Console.WriteLine(t.GetMethod("GetHash", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public));
            //var methodInfo = t.GetMethod("GetHash", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            //string h__ = methodInfo.Invoke(null, null).ToString();

            //throw new Exception("asd");




            //foreach (TypeDef type in module.Types)
            //{
            //    if (type.IsGlobalModuleType) 
            //        continue;
                
            //    foreach (MethodDef method in type.Methods)
            //    {
            //        if (!method.HasBody) 
            //            continue;
            //        if (method.IsConstructor)
            //        {
            //            method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Nop));
            //            method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));
            //        }
            //    }
            //}
        }

19 Source : ConstantProtection.cs
with GNU General Public License v3.0
from Agasper

void InjectMasker()
        {
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string applicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef maskClreplaced = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(O).MetadataToken));
            typeModule.Types.Remove(maskClreplaced);
            module.Types.Add(maskClreplaced);

            intMaskMethod = maskClreplaced.FindMethod("_");
            intKey = rnd.Next();
            intMaskMethod.Body.Instructions[2].OpCode = OpCodes.Ldc_I4;
            intMaskMethod.Body.Instructions[2].Operand = intKey;

            strMaskMethod = maskClreplaced.FindMethod("_d");
            strKey = (byte)rnd.Next(2, 255);
            strMaskMethod.Body.Instructions[3].OpCode = OpCodes.Ldc_I4;
            strMaskMethod.Body.Instructions[3].Operand = (int)strKey;

            //var mm = maskClreplaced.FindMethod("_d");
            //Console.WriteLine(mm);
            //Console.WriteLine(mm.HasBody);
            //foreach (var i in mm.Body.Instructions)
            //    Console.WriteLine(i);
            //throw new Exception("Stop");

            log.InfoFormat("Keys generated. Str: {0}, Int: {1}", strKey, intKey);
        }

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

public static void Main(string[] args)
        {
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string ApplicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            XmlConfigurator.Configure(new FileInfo(Path.Combine(ApplicationPath, "logging.xml")));

            log.Info("Asert Unity Build Protection");
            log.Info("Copyright (c) 2017 - Alexander Melkozerov");
            log.Info("-------------------------------------------------");

            Arguments parsedArgs = new Arguments(args);

            if (!parsedArgs.ContainsArg("filename"))
            {
                PrintUsage();
                return;
            }
            string filename = parsedArgs["filename"];


            if (parsedArgs.ContainsArg("anreplacedamper") && !parsedArgs.ContainsArg("unitylib"))
            {
                log.Error("You're going to use anti tampering protection, but forgot to specify location of the unityengine.dll with --unitylib argument");
                return;
            }

            Asert asert = new Asert(filename)
            {
                StrongRenaming = !parsedArgs.ContainsArg("softrenaming"),
                RenameEvents = parsedArgs.ContainsArg("renameevents") || parsedArgs.ContainsArg("renameall"),
                RenameProps = parsedArgs.ContainsArg("renameprops") || parsedArgs.ContainsArg("renameall"),
                RenameFields = parsedArgs.ContainsArg("renamefields") || parsedArgs.ContainsArg("renameall"),
                RenameTypes = parsedArgs.ContainsArg("renametypes") || parsedArgs.ContainsArg("renameall"),
                RenameMethodParams = parsedArgs.ContainsArg("renamemethodparams") || parsedArgs.ContainsArg("renameall"),
                RenameMethods = parsedArgs.ContainsArg("renamemethods") || parsedArgs.ContainsArg("renameall"),

                HideStrings = parsedArgs.ContainsArg("hidestrings"),
                HideIntegers = parsedArgs.ContainsArg("hideintegers"),
                EncryptStrings = parsedArgs.ContainsArg("encryptstrings"),

            };

			if (parsedArgs.ContainsArg("anreplacedamper"))
				asert.AnreplacedamperingProtect();
            asert.ProtectConstants();
            asert.PerformRenaming();
            asert.Save(filename);
            if (parsedArgs.ContainsArg("anreplacedamper"))
            {
                asert.AnreplacedamperingInjectUnity(asert.AnreplacedamperingSign(filename), parsedArgs["unitylib"]);
            }
        }

19 Source : DownloadManager.cs
with GNU General Public License v3.0
from aglab2

public bool GetData()
        {
            try
            {
                string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                Directory.CreateDirectory(exePath + "\\layout\\");
                RepositoryContent content = task.Result.First();
                byte[] data = Convert.FromBase64String(content.EncodedContent);

                File.WriteAllBytes(exePath + "\\layout\\" + path, data);
            }
            catch (Exception)
            {
                isDataAcquired = true;
                return false;
            }
            isDataAcquired = true;
            return true;
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void UpdateStars(object sender)
        {
            isEmulatorStarted = false;
            isHackLoaded = false;
            isOffsetsFound = false;

            try
            {
                if (um.IsCompleted())
                {
                    if (!isUpdateRequested && !um.IsUpdated())
                    {
                        isUpdateRequested = true;
                        this.SafeInvoke((MethodInvoker)delegate
                        {
                            DialogResult result = MessageBox.Show(String.Format("Update for Star Display available!\n\n{0}\nDo you want to download it now? Press cancel to skip update", um.UpdateName()), "Update",
                            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
                            if (result == DialogResult.Yes)
                            {
                                Process.Start(um.DownloadPath());
                            }
                            if (result == DialogResult.Cancel)
                            {
                                um.WritebackUpdate();
                            }
                        });
                    }
                }
            }
            catch (Exception) { }

            try
            {
                //if (slf != null && slf.sm != null && slf.sm.isServer)
                //    goto bla;

                if (mm.ProcessActive())
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
                
                isEmulatorStarted = true;

                // Well, that's just a minor magic but it works
                if (mm.Getreplacedle().Contains("-"))
                    isHackLoaded = true;

                if (!mm.isMagicDone())
                {
                    if (magicThread == null || !magicThread.IsAlive)
                    {
                        magicThread = new Thread(doMagicThread);
                        magicThread.Start();
                    }

                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); });
                    return;
                }
                
                isOffsetsFound = true;


                try
                {
                    // Just do nothing
                    if (!mm.isReadyToRead())
                        return;

                    mm.PerformRead();
                }
                catch (Exception)
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
 
                bool mmIsInvalidated = mm == null ? false : mm.CheckInvalidated();
                bool gmIsInvalidated = gm == null ? false : gm.CheckInvalidated();
                bool dmIsInvalidated = dm == null ? false : dm.CheckInvalidated();
                bool smIsInvalidated = false;
                if (slf != null && slf.sm != null)
                    smIsInvalidated = slf.sm.CheckInvalidated();

                bool nmIsInvalidated = false;
                if (slf != null && slf.nm != null)
                    nmIsInvalidated = slf.nm.CheckInvalidated();

                if (smIsInvalidated && slf.sm.dropFile)
                {
                    slf.sm.dropFile = false;
                    mm.Stars = new byte[MemoryManager.FileLength];
                    mm.WriteToFile(ld.starsShown);
                    mm.isStarsInvalidated = true;
                }

                if (mmIsInvalidated && mm.isStarsInvalidated)
                {
                    mm.isStarsInvalidated = false;
                    if (slf != null && slf.sm != null)
                    {
                        slf.sm.SendData(mm.Stars);
                    }

                    Console.WriteLine("MM Invalidated!");
                }

                if (gmIsInvalidated)
                    Console.WriteLine("GM Invalidated!");
                if (dmIsInvalidated)
                    Console.WriteLine("DM Invalidated!");

                if (smIsInvalidated)
                {
                    Console.WriteLine("SM Invalidated!");
                    {
                        byte[] stars = slf.sm.AcquiredData;

                        bool shouldSendHelp = false;
                        for (int i = 0; i < stars.Count(); i++)
                        {
                            byte diff = (byte)(mm.Stars[i] ^ stars[i]);
                            if ((mm.Stars[i] & diff) != 0)
                                shouldSendHelp = true;

                            otherStars[i] |= (byte)(diff & stars[i]);
                            mm.Stars[i] = (byte)(mm.Stars[i] | stars[i]);
                        }

                        if (shouldSendHelp)
                        {
                            slf.sm.SendData(mm.Stars);
                        }

                        mm.WriteToFile(ld.starsShown);
                    }
                    if (!mm.IsDecomp)
                    {
                        var location = mm.GetLocation();
                        var netData = slf.sm.getNetData();
                        foreach (var item in netData)
                        {
                            var player = item.Key;
#if DEBUG == false
                            if (player != slf.GetPlayerName())
#endif
                            {
                                var data = item.Value;

                                if (slf is object && slf.nm is object)
                                {
                                    var id = slf.nm.RegisterPlayer(player);
                                    if (data.location == location)
                                        mm.WriteNetState(id, data.state);
                                    else
                                        mm.WriteNetState(id, null);
                                }
                            }
                        }
                    }
                }

                if (nmIsInvalidated)
                {
                    if (!mm.IsDecomp)
                    {
                        mm.WriteNetPatch();
                        var state = mm.GetMarioState();
                        if (slf.sm is object)
                        {
                            slf.sm.SendNet64Data(slf.GetNet64Name(), state, mm.GetLocation());
                        }

                        if (slf.nm.mustReload)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                mm.WriteNetState(i, null);
                            }
                            slf.nm.mustReload = false;
                        }

                        this.SafeInvoke((MethodInvoker)delegate { slf.UpdatePlayers(slf.nm.GetPlayers()); });
                    }
                }

                // We do not draw anything!
                if (!mmIsInvalidated && !gmIsInvalidated && !smIsInvalidated && !dmIsInvalidated)
                {
                    return;
                }

                gm.TestFont();

                if (enableAutoDeleteToolStripMenuItem.Checked)
                {
                    try
                    {
                        mm.DeleteStars();
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Can not modify savefiles. Trying launching with elevated rights!", "Write Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        enableAutoDeleteToolStripMenuItem.Checked = false;
                    }
                }

                //Display stars routine
                baseImage = new Bitmap(starPicture.Width, starPicture.Width * 4);

                Graphics baseGraphics = Graphics.FromImage(baseImage);
                baseGraphics.Clear(Color.Black);
                baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                gm.graphics = Graphics.FromImage(baseImage);

                if (!sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false))
                {
                    TextHighlightAction act = mm.GetCurrentLineAction(ld);
                    if (act != null)
                    {
                        gm.AddLineHighlight(act);
                    }
                }

                UInt16 currentCRC = mm.GetRomCRC();
                if (currentCRC != oldCRC || rm == null || dmIsInvalidated)
                {
                    oldCRC = currentCRC;
                    try
                    {
                        rm = new ROMManager(mm.GetROM());
                        try
                        {
                            if (dm != null)
                            {
                                dm.GetData();
                            }

                            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                            LoadLayoutNoInvalidate(exePath + "\\layout\\" + rm.GetROMName() + ".jsml", false);
                        }
                        catch (IOException)
                        {
                            try
                            {
                                dm = new DownloadManager(rm.GetROMName() + ".jsml");
                            }
                            catch(Exception) { }
                            LoadDefaultLayoutNoInvalidate();
                        }

                        gm.IsFirstCall = true;
                    }
                    catch (IndexOutOfRangeException) //can be generated by box reader
                    { }
                    catch (Exception)
                    { oldCRC = 0; }

                    InvalidateCache();
                }

                int lineOffset = 0;
                var actions = sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false) ?
                    mm.GetCollectablesOnlyDrawActions(ld, rm) : 
                    mm.GetDrawActions(ld, rm, enableLockoutToolStripMenuItem.Checked ? otherStars : null);

                if (actions == null) return;

                foreach (var entry in actions)
                {
                    lineOffset += entry.Execute(gm, lineOffset, sm);
                }
                
                baseGraphics.Dispose();
                this.SafeInvoke(delegate {
                    menuStrip.Enabled = true;
                    starPicture.Image = baseImage;
                    starPicture.Height = (int) (lineOffset * gm.SHeight) + 10;
                    this.Height = (int)(lineOffset * gm.SHeight) + 48;
                });
            }
            catch (Win32Exception)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (NullReferenceException)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (ObjectDisposedException)
            {
            }
            finally
            {
                int period = (isEmulatorStarted && isHackLoaded && isOffsetsFound) ? updatePeriod : scanPeriod;
                timer.Change(period, Timeout.Infinite);
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
#if XD
            foreach (var layoutPath in Directory.EnumerateFiles("C:\\Data\\layouts"))
            {
                var ext = Path.GetExtension(layoutPath);
                if (ext != ".sml")
                    continue;

                var jsmlPath = Path.ChangeExtension(layoutPath, ".jsml");
                if (File.Exists(jsmlPath))
                    continue;

                LoadLayout(layoutPath);
                SaveLayout(jsmlPath);
            }
#endif

            try
            {
                do
                {
                    string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                    LoadLayout(exePath + "\\layout\\" + rm.GetROMName() + ".jsml", true);
                } while (false);
            }
            catch (IOException){
                var result = MessageBox.Show("Cannot find layout for this hack. Do you want to load layout from file?", "Layour Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.Yes)
                {
                    loadFromToolStripMenuItem_Click(sender, e);
                }
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void LoadSettings()
        {
            IFormatter formatter = new BinaryFormatter();
            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            Stream stream = new FileStream(exePath + "\\settings.cfg", FileMode.Open, FileAccess.Read, FileShare.None);
            sm = (SettingsManager)formatter.Deserialize(stream);
            stream.Close();
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void loadToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            if (!File.Exists(exePath + "\\settings.cfg"))
            {
                sm = new SettingsManager();
                return;
            }

            try
            {
                LoadSettings();
                MessageBox.Show("Settings loaded successfully!", "Settings", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception)
            {
                MessageBox.Show("Your settings seems to be unavailable or corrupted, loading defaults", "Settings Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                sm = new SettingsManager();
            }

            InvalidateCache();
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

void SaveSettings()
        {
            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(exePath + "\\settings.cfg", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, sm);
            stream.Close();
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                string layoutDir = exePath + "\\layout\\";
                Directory.CreateDirectory(layoutDir);
                string name = layoutDir + rm.GetROMName() + ".jsml";
                if (File.Exists(name))
                {
                    var result = MessageBox.Show("Layout for this hack already exists! Do you want to overwrite it?", "Layour Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                    if (result == DialogResult.No) throw new IOException();
                }
                SaveLayout(name);
            }
            catch (IOException)
            {
                var result = MessageBox.Show("Cannot save layout for this hack. Do you want to save layout to different file?", "Layour Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.Yes)
                {
                    saveAsToolStripMenuItem_Click(sender, e);
                }
            }
        }

19 Source : AboutAppViewModel.cs
with MIT License
from ahmed-abdelrazek

public async Task OnLoadedAsync()
        {
            await Task.Run(() =>
            {
                AppVersion = "رقم الاصدار: " + new replacedemblyInfo(System.Reflection.replacedembly.GetEntryreplacedembly()).Version;
            });
        }

19 Source : FilesSample.cs
with The Unlicense
from ahotko

private void GetExecutableLocation()
        {
            var uri = new Uri(replacedembly.GetEntryreplacedembly().GetName().CodeBase);
            string location = new FileInfo(uri.AbsolutePath).FullName;

            Console.WriteLine($"Executable Location = {location}");
        }

19 Source : DatContainer.cs
with GNU Affero General Public License v3.0
from aianlinb

public static void ReloadDefinitions(string filePath = "DatDefinitions.json") {
			filePath = Path.GetFullPath(filePath, Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location));
			var json = JsonDoreplacedent.Parse(File.ReadAllBytes(filePath), new() { CommentHandling = JsonCommentHandling.Skip });
			try {
				DatDefinitions = new();
				foreach (var dat in json.RootElement.EnumerateObject())
					DatDefinitions.Add(dat.Name, dat.Value.EnumerateObject().Select(p => new KeyValuePair<string, string>(p.Name, p.Value.GetString())).ToArray());
			} finally {
				json.Dispose();
			}
		}

19 Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb

private async void OnLoaded(object sender, RoutedEventArgs e) {
            if (SteamMode)
                replacedle += " (SteamMode)";
            if (BundleMode)
                replacedle += " (SteamMode)";
            // Version Check
            try {
                var http = new HttpClient {
                    Timeout = TimeSpan.FromSeconds(2)
                };
                http.DefaultRequestHeaders.Add("User-Agent", "VisualGGPK2");
                var json = await http.GetStringAsync("https://api.github.com/repos/aianlinb/LibGGPK2/releases");
                var match = Regex.Match(json, "(?<=\"tag_name\":\"v).*?(?=\")");
                var currentVersion = replacedembly.GetEntryreplacedembly().GetName().Version;
                var versionText = $"{currentVersion.Major}.{currentVersion.Minor}.{currentVersion.Build}";
                if (match.Success && match.Value != versionText && MessageBox.Show(this, $"Found a new update on GitHub!\n\nCurrent Version: {versionText}\nLatest Version: {match.Value}\n\nDownload now?", "VisualGGPK2", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
                    Process.Start(new ProcessStartInfo("https://github.com/aianlinb/LibGGPK2/releases") { UseShellExecute = true });
                    Close();
                    return;
                }
                http.Dispose();
            } catch { }

            // GGPK Selection
            if (FilePath == null) {
                var ofd = new OpenFileDialog {
                    DefaultExt = "ggpk",
                    FileName = SteamMode ? "_.index.bin" : "Content.ggpk",
                    Filter = SteamMode ? "Index Bundle File|*.index.bin" : "GGPK File|*.ggpk"
                };

                var setting = Properties.Settings.Default;
                if (setting.GGPKPath == "") {
                    setting.Upgrade();
                    setting.Save();
                }
                if (setting.GGPKPath == "") {
                    string path;
                    path = Registry.CurrentUser.OpenSubKey(@"Software\GrindingGearGames\Path of Exile")?.GetValue("InstallLocation") as string;
                    if (path != null && File.Exists(path + @"\Content.ggpk")) // Get POE path
                        ofd.InitialDirectory = path.TrimEnd('\\');
                } else
                    ofd.InitialDirectory = setting.GGPKPath;

                if (ofd.ShowDialog() == true) {
                    setting.GGPKPath = Directory.GetParent(FilePath = ofd.FileName).FullName;
                    setting.Save();
                } else {
                    Close();
                    return;
                }
            }

            // Initial GGPK
            await Task.Run(() => ggpkContainer = new GGPKContainer(FilePath, BundleMode, SteamMode));
            
            // Initial ContextMenu
            var mi = new MenuItem { Header = "Export" };
            mi.Click += OnExportClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Replace" };
            mi.Click += OnReplaceClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Recovery" };
            mi.Click += OnRecoveryClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Convert dds to png" };
            mi.Click += OnSavePngClicked;
            TreeMenu.Items.Add(mi);

            var imageMenu = new ContextMenu();
            mi = new MenuItem { Header = "Save as png" };
            mi.Click += OnSavePngClicked;
            imageMenu.Items.Add(mi);
            ImageView.ContextMenu = imageMenu;

            var root = CreateNode(ggpkContainer.rootDirectory);
            Tree.Items.Add(root); // Initial TreeView
            root.IsExpanded = true;

            FilterButton.IsEnabled = true;
            if (!SteamMode)
                AllowGameOpen.IsEnabled = true;

            // Mark the free spaces in data section of dat files
            DatReferenceDataTable.CellStyle = new Style(typeof(DataGridCell));
            DatReferenceDataTable.CellStyle.Setters.Add(new EventSetter(LoadedEvent, new RoutedEventHandler(OnCellLoaded)));

            // Make changes to DatContainer after editing DatTable
            DatTable.CellEditEnding += OnDatTableCellEdit;
            // Make changes to DatContainer after editing DatReferenceDataTable
            DatReferenceDataTable.CellEditEnding += OnDatReferenceDataTableCellEdit;

            TextView.AppendText("\r\n\r\nDone!\r\n");
        }

19 Source : Program.cs
with The Unlicense
from AigioL

static void Main(string[] args)
        {
            TryMain();
            void TryMain()
            {
                try
                {
                    Main();
                }
                catch (Exception ex)
                {
                    var index = byte.MinValue;
                    while (ex != null)
                    {
                        if (index++ > sbyte.MaxValue) break;
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        ex = ex.InnerException;
                    }
                }
                Console.ReadLine();
            }
            void Main()
            {
                // ReSharper disable PossibleNullReferenceException
                var entryreplacedembly = replacedembly.GetEntryreplacedembly();
                var replacedle = entryreplacedembly.FullName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
                // ReSharper disable once replacedignNullToNotNullAttribute
                if (!replacedle.IsNullOrWhiteSpace()) Console.replacedle = replacedle;
                var rootPath = Path.GetDirectoryName(entryreplacedembly.Location);
                if (rootPath == null) throw new ArgumentNullException(nameof(rootPath));
                var sofilepath = args?.FirstOrDefault(x => x != null && File.Exists(x) && Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase));
                if (sofilepath == null)
                {
                    var sofilepaths = Directory.GetFiles(rootPath).Where(x => Path.GetExtension(x).Equals(GetSoFileExtension(), StringComparison.OrdinalIgnoreCase)).ToArray();
                    sofilepath =
                       sofilepaths.FirstOrDefault(x => Path.GetFileName(x).Equals(GetSoDefaultFileName(), StringComparison.OrdinalIgnoreCase)) ??
                       sofilepaths.FirstOrDefault();
                }
                if (sofilepath == null) ReadLineAndExit("Can not find the .so file.");
                // ReSharper disable once replacedignNullToNotNullAttribute
                var bytes = File.ReadAllBytes(sofilepath);
                var elf = Elf.FromFile(sofilepath);
                var rodata = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".rodata"));
                if (rodata == null) ReadLineAndExit(".rodata not found.");
                var packedFiles = new List<string>();
                var addr = (uint)rodata.Addr;
                while (true)
                {
                    //up to 16 bytes of alignment
                    uint i;
                    for (i = 0; i < 16; i++)
                        if (bytes[addr + i] != 0)
                            break;

                    if (i == 16)
                        break; //We found all the files
                    addr += i;

                    var name = GetString(bytes, addr);
                    if (name.IsNullOrWhiteSpace())
                        break;

                    //We only care about dlls
                    if (!name.EndsWith(".dll"))
                        break;

                    packedFiles.Add(name);
                    addr += (uint)name.Length + 1u;
                }
                var data = elf.Header.SectionHeaders.FirstOrDefault(x => x.Name.Equals(".data"));
                if (data == null) ReadLineAndExit(".data not found.");
                int ixGzip = 0;
                addr = (uint)data.Offset;
                var output = Path.Combine(rootPath, "replacedemblies");
                if (!Directory.Exists(output)) Directory.CreateDirectory(output);
                Console.WriteLine($"output:{output}");
                foreach (var item in packedFiles)
                {
                    ixGzip = findNextGZIPIndex(bytes, ixGzip);
                    if (ixGzip > 0)
                    {
                        var ptr = ixGzip;
                        var length = GetBigEndianUInt32(bytes, addr + 8);
                        var compressedbytes = new byte[length];
                        if (ptr + length <= bytes.LongLength)
                        {
                            Array.Copy(bytes, ptr, compressedbytes, 0, length);
                            try
                            {
                                var decompbytes = Decompress(compressedbytes);
                                var path = Path.Combine(output, item);
                                File.WriteAllBytes(path, decompbytes);
                                Console.WriteLine($"file:{item}");
                                addr += 0x10;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Failed to decompress file: {item} {e.Message}.");
                            }
                        }
                    }
                }
                TryOpenDir(output);
                // ReSharper restore PossibleNullReferenceException
            }
            void ReadLineAndExit(string writeLine = null)
            {
                if (writeLine != null) Console.WriteLine(writeLine);
                Console.ReadLine();
                Environment.Exit(0);
            }
            string GetSoFileExtension() => ".so";
            string GetSoDefaultFileName() => "libmonodroid_bundle_app" + GetSoFileExtension();
            string GetString(byte[] bytes, uint address)
            {
                int maxLength = 255;
                for (int i = (int)address; i < address + maxLength; i++)
                {
                    if (bytes[i] == 0)
                    {
                        maxLength = i - (int)address;
                        break;
                    }
                }
                var buffer = new byte[maxLength];
                Array.Copy(bytes, address, buffer, 0, maxLength);
                return Encoding.ASCII.GetString(buffer);
            }
            int findNextGZIPIndex(byte[] bytes, int ixGzip)
            {
                for (var j = ixGzip + 2; j < bytes.Length; j++)
                {
                    if (bytes[j - 1] == 0x1f && bytes[j] == 0x8b)
                    {
                        ixGzip = j - 1;
                        return ixGzip;
                    }
                }
                return 0;
            }
            byte[] Decompress(byte[] data)
            {
                using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var resultStream = new MemoryStream())
                {
                    zipStream.CopyTo(resultStream);
                    return resultStream.ToArray();
                }
            }
            uint GetBigEndianUInt32(byte[] bytes, uint address)
            {
                var byte1 = (uint)bytes[(int)address + 3] << 24;
                var byte2 = (uint)bytes[(int)address + 2] << 16;
                var byte3 = (uint)bytes[(int)address + 1] << 8;
                var byte4 = bytes[(int)address];
                return byte1 + byte2 + byte3 + byte4;
            }
            void TryOpenDir(string dirpath)
            {
                try
                {
                    Process.Start(dirpath);
                }
                catch
                {
                    // ignored
                }
            }
        }

19 Source : RawInputApp.cs
with GNU General Public License v3.0
from aiportal

private IRecordPolicy CreateRecordPolicy()
		{
			IRecordPolicy policy = null;
			try
			{
				if (!string.IsNullOrEmpty(Global.Config.RecordPolicy))
				{
					string path = System.IO.Path.Combine(Application.StartupPath, "Policy.dll");
					if (System.IO.File.Exists(path))
					{
						var replacedembly = System.Reflection.replacedembly.LoadFrom(path);
						if (replacedembly != null)
							policy = replacedembly.CreateInstance(Global.Config.RecordPolicy) as IRecordPolicy;
					}
					else
					{
						var replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
						if (replacedembly != null)
							policy = replacedembly.CreateInstance(Global.Config.RecordPolicy) as IRecordPolicy;
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			if (policy == null)
				policy = new GenericPolicy();
			return policy;
		}

See More Examples