System.IO.Directory.GetCurrentDirectory()

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

3512 Examples 7

19 Source : Program.cs
with zlib License
from 0x0ade

public static void Main(string[] args) {
            XnaToFnaUtil xtf = new XnaToFnaUtil();

            Console.WriteLine($"XnaToFna {XnaToFnaUtil.Version}");
            Console.WriteLine($"using MonoMod {MonoModder.Version}");

            bool showHelp = false;
            bool showVersion = false;
            bool relinkOnly = false;

            OptionSet options = new OptionSet {
                { "h|help", "Show this message and exit.", v => showHelp = v != null },
                { "v|version", "Show the version and exit.", v => showVersion = v != null },
                { "profile=", "Choose between multiple base profiles:\ndefault, minimal, forms", v => {
                    switch (v.ToLowerInvariant()) {
                        case "default":
                            xtf.HookCompat = true;
                            xtf.HookHacks = true;
                            xtf.HookEntryPoint = false;
                            xtf.HookLocks = false;
                            xtf.FixOldMonoXML = false;
                            xtf.HookBinaryFormatter = true;
                            xtf.HookReflection = true;
                            break;

                        case "minimal":
                            xtf.HookCompat = false;
                            xtf.HookHacks = false;
                            xtf.HookEntryPoint = false;
                            xtf.HookLocks = false;
                            xtf.FixOldMonoXML = false;
                            xtf.HookBinaryFormatter = false;
                            xtf.HookReflection = false;
                            break;

                        case "forms":
                            xtf.HookCompat = true;
                            xtf.HookHacks = false;
                            xtf.HookEntryPoint = true;
                            xtf.HookLocks = false;
                            xtf.FixOldMonoXML = false;
                            xtf.HookBinaryFormatter = false;
                            xtf.HookReflection = false;
                            break;
                    }
                } },

                { "relinkonly=", "Only read and write the replacedemblies listed.", (bool v) => relinkOnly = v },

                { "hook-compat=", "Toggle Forms and P/Invoke compatibility hooks.", (bool v) => xtf.HookCompat = v },
                { "hook-hacks=", "Toggle some hack hooks, f.e.\nXNATOFNA_DISPLAY_FULLSCREEN", (bool v) => xtf.HookEntryPoint = v },
                { "hook-locks=", "Toggle if locks should be \"destroyed\" or not.", (bool v) => xtf.HookLocks = v },
                { "hook-oldmonoxml=", "Toggle basic XML serialization fixes.\nPlease try updating mono first!", (bool v) => xtf.FixOldMonoXML = v },
                { "hook-binaryformatter=", "Toggle BinaryFormatter-related fixes.", (bool v) => xtf.HookBinaryFormatter = v },
                { "hook-reflection=", "Toggle reflection-related fixes.", (bool v) => xtf.HookBinaryFormatter = v },
                { "hook-patharg=", "Hook the given method to receive fixed paths.\nCan be used multiple times.", v => xtf.FixPathsFor.Add(v) },

                { "ilplatform=", "Choose the target IL platform:\nkeep, x86, x64, anycpu, x86pref", v => xtf.PreferredPlatform = ParseEnum(v, ILPlatform.Keep) },
                { "mixeddeps=", "Choose the action performed to mixed dependencies:\nkeep, stub, remove", v => xtf.MixedDeps = ParseEnum(v, MixedDepAction.Keep) },
                { "removepublickeytoken=", "Remove the public key token of a dependency.\nCan be used multiple times.", v => xtf.DestroyPublicKeyTokens.Add(v) },
            };

            void WriteHelp(TextWriter writer) {
                writer.WriteLine("Usage: <mono> XnaToFna.exe [options] <--> FileOrDir <FileOrDir> <...>");
                options.WriteOptionDescriptions(writer);
            }

            List<string> extra;
            try {
                extra = options.Parse(args);
            } catch (OptionException e) {
                Console.Error.Write("Command parse error: ");
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine();
                WriteHelp(Console.Error);
                return;
            }

            if (showVersion) {
                return;
            }

            if (showHelp) {
                WriteHelp(Console.Out);
                return;
            }

            foreach (string arg in extra)
                xtf.ScanPath(arg);

            if (!relinkOnly && !Debugger.IsAttached) // Otherwise catches XnaToFna.vshost.exe
                xtf.ScanPath(Directory.GetCurrentDirectory());

            xtf.OrderModules();

            xtf.RelinkAll();

            xtf.Log("[Main] Done!");

            if (Debugger.IsAttached) // Keep window open when running in IDE
                Console.ReadKey();
        }

19 Source : Program.cs
with MIT License
from 0x1000000

private static string EnsureDirectory(string directory, ILogger logger, string dirAlias, bool create)
        {
            if (string.IsNullOrEmpty(directory))
            {
                directory = Directory.GetCurrentDirectory();
                logger.LogDetailed(
                    $"{dirAlias} directory was not specified, so the current directory \"{directory}\" is used as an output one.");
            }
            else if (!Path.IsPathFullyQualified(directory))
            {
                directory = Path.GetFullPath(directory, Directory.GetCurrentDirectory());
                logger.LogDetailed($"{dirAlias} directory is converted to fully qualified \"{directory}\".");
            }


            if (!Directory.Exists(directory))
            {
                if (create)
                {
                    try
                    {
                        Directory.CreateDirectory(directory);
                        logger.LogDetailed($"Directory \"{directory}\" was created.");
                    }
                    catch (Exception e)
                    {
                        throw new SqExpressCodeGenException($"Could not create directory: \"{directory}\".", e);
                    }
                }
                else
                {
                    throw new SqExpressCodeGenException($"\"{directory}\" directory does not exist.");
                }
            }

            return directory;
        }

19 Source : Program.cs
with Apache License 2.0
from 0xFireball

public static void Main(string[] args)
        {
            // Load ASP.NET Core web app
            var config = new ConfigurationBuilder()
                .AddCommandLine(args)
                .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "hosting.json"), true)
                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                .Build();

            var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }

19 Source : Startup.cs
with Apache License 2.0
from 0xFireball

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(ApplicationConfiguration.GetSection("Logging"));
            // loggerFactory.AddDebug();

            // Create default configuration
            var puConfig = new PenguinUploadConfiguration();

            // Bind configuration
            PUConfiguration.Bind(puConfig);

            var context = new PenguinUploadContext(puConfig);

            ClientAppPath = Path.Combine(Directory.GetCurrentDirectory(), ClientAppPath);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true,
                    ProjectPath = ClientAppPath,
                    ConfigFile = $"{ClientAppPath}webpack.config.js"
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // add wwwroot/
            app.UseStaticFiles();

            // set up Nancy OWIN hosting
            app.UseOwin(x => x.UseNancy(options =>
            {
                options.PreplacedThroughWhenStatusCodesAre(
                    HttpStatusCode.NotFound,
                    HttpStatusCode.InternalServerError
                );
                options.Bootstrapper = new PenguinUploadBootstrapper(context);
            }));

            // set up MVC fallback
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }

19 Source : Program.cs
with MIT License
from 1100100

static async Task Main(string[] args)
        {
            var hostBuilder = new HostBuilder().ConfigureHostConfiguration(builder =>
                {
                    builder.SetBasePath(Directory.GetCurrentDirectory());
                }).ConfigureAppConfiguration((context, builder) =>
                {
                    builder.AddJsonFile("uragano.json", false, true);
                    builder.AddCommandLine(args);
                })
                .ConfigureServices((context, service) =>
                {
                    service.AddUragano(context.Configuration, builder =>
                    {
                        builder.AddServer();
                        builder.AddClient(LoadBalancing.Polling);
                        builder.AddCircuitBreaker();
                        builder.AddExceptionlessLogger();
                        builder.AddConsul();
                        //builder.AddZooKeeper();
                    });

                }).ConfigureLogging((context, builder) =>
                {
                    builder.AddConfiguration(context.Configuration.GetSection("Logging"));
                    builder.AddConsole();
                });
            await hostBuilder.RunConsoleAsync();

            //var nodes = new List<Node> {
            //    new Node("139f9cbb-be67-460c-9092-b4b29a6e574a"),
            //    new Node("3f8fa9c8-4c56-486a-baca-bd7d4639e95b"),
            //    new Node("c2ab77c7-84c7-4310-aaff-9fe767639135"),
            //    new Node("55cf40c5-250d-4cb8-9cc7-8d1d361a53b0"),
            //    new Node("6719662f-74b5-46c7-a652-031c3771b812")
            //};
            //var x = new ConsistentHash<Node>(500);
            //nodes.ForEach(item => { x.AddNode(item, item.Host); });
            //var dic = new Dictionary<string, Node>();
            //while (true)
            //{
            //    var command = Console.ReadLine();
            //    if (command == "exit")
            //        break;
            //    if (command == "gen")
            //    {
            //        for (var i = 0; i < 100000; i++)
            //        {
            //            var id = Guid.NewGuid().ToString();
            //            var node = x.GetNodeForKey(id);
            //            dic[id] = node;
            //            node.Num++;
            //        }

            //        Console.WriteLine("OK");
            //    }

            //    if (command == "info")
            //    {
            //        nodes.ForEach(item =>
            //        {
            //            Console.WriteLine(item.ToString());
            //        });

            //    }

            //    if (command == "add")
            //    {
            //        Console.Write("请输入Key:");
            //        var k = Console.ReadLine();
            //        var node = new Node(k);
            //        nodes.Add(node);
            //        x.AddNode(node, k);
            //    }

            //    if (command == "retry")
            //    {
            //        var count = 0;
            //        foreach (var item in dic)
            //        {
            //            var node = x.GetNodeForKey(item.Key);
            //            if (node.Host != item.Value.Host)
            //            {
            //                count++;
            //                node.Num++;
            //            }
            //        }

            //        Console.WriteLine($"{count}个数据重新分配节点");
            //    }

            //}


        }

19 Source : Program.cs
with MIT License
from 1100100

static void Main(string[] args)
        {
            DapperFactory.CreateInstance().ConfigureServices(service =>
            {
                service.AddDapperForSQLite();
            }).ConfigureContainer(container =>
            {
                container.AddDapperForSQLite("Sqlite2", "sqlite2");
            }).ConfigureConfiguration(builder =>
            {
                builder.SetBasePath(Directory.GetCurrentDirectory());
                builder.AddJsonFile("appsettings.json");
            }).Build();

            DapperFactory.Step(dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            var result7 = DapperFactory.Step(dapper => { return dapper.Query("select * from Contact;"); });
            Console.WriteLine(JsonConvert.SerializeObject(result7));

            DapperFactory.StepAsync(async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            var result8 = DapperFactory.StepAsync(async dapper => await dapper.QueryAsync("select * from Contact;")).Result;
            Console.WriteLine(JsonConvert.SerializeObject(result8));


            DapperFactory.Step("sqlite2", dapper =>
             {
                 var query = dapper.Query("select * from Contact;");
                 Console.WriteLine(JsonConvert.SerializeObject(query));
             });

            var result9 = DapperFactory.Step("sqlite2", dapper => { return dapper.Query("select * from Contact;"); });
            Console.WriteLine(JsonConvert.SerializeObject(result9));

            DapperFactory.StepAsync("sqlite2", async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            var result10 = DapperFactory.StepAsync("sqlite2", async dapper => await dapper.QueryAsync("select * from Contact;")).Result;
            Console.WriteLine(JsonConvert.SerializeObject(result10));



            DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            DapperFactory.StepAsync(async context =>
            {
                var dapper = context.ResolveDapper();
                var queryAsync = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(queryAsync));
            }).Wait();

            DapperFactory.Step((context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            DapperFactory.StepAsync(async (context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            DapperFactory.Step("sqlite2", (context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            DapperFactory.StepAsync("sqlite2", async (context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            var result1 = DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                return dapper.Query("select * from Contact;");
            });
            Console.WriteLine(JsonConvert.SerializeObject(result1));

            var result2 = DapperFactory.StepAsync(context =>
            {
                var dapper = context.ResolveDapper();
                return dapper.QueryAsync("select * from Contact;");
            }).Result;
            Console.WriteLine(JsonConvert.SerializeObject(result2));

            var result3 = DapperFactory.Step((context, dapper) => dapper.Query("select * from Contact;"));
            Console.WriteLine(JsonConvert.SerializeObject(result3));

            var result4 = DapperFactory.StepAsync(async (context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;
            Console.WriteLine(JsonConvert.SerializeObject(result4));

            var result5 = DapperFactory.Step("sqlite2", (context, dapper) => dapper.Query("select * from Contact;"));
            Console.WriteLine(JsonConvert.SerializeObject(result5));

            var result6 = DapperFactory.StepAsync("sqlite2", async (context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;
            Console.WriteLine(JsonConvert.SerializeObject(result6));

            Console.ReadKey();
        }

19 Source : Program.cs
with MIT License
from 1100100

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseAutofac()
                .ConfigureHostConfiguration(builder => { builder.SetBasePath(Directory.GetCurrentDirectory()); })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureKestrel(options => { options.ListenAnyIP(1234); });
                });

19 Source : ProxyGenerator.cs
with MIT License
from 1100100

public static List<Type> GenerateProxy(List<Type> interfaces)
        {
            if (interfaces.Any(p => !p.IsInterface && !typeof(IService).IsreplacedignableFrom(p)))
                throw new ArgumentException("The proxy object must be an interface and inherit IService.", nameof(interfaces));

            var replacedemblies = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultreplacedemblyNames(DependencyContext.Default).Select(z => replacedembly.Load(new replacedemblyName(z.Name)))).Where(i => !i.IsDynamic);

            var types = replacedemblies.Select(p => p.GetType()).Except(interfaces);
            replacedemblies = types.Aggregate(replacedemblies, (current, type) => current.Append(type.replacedembly));

            var trees = interfaces.Select(GenerateProxyTree).ToList();

            if (UraganoOptions.Output_DynamicProxy_SourceCode.Value)
            {
                for (var i = 0; i < trees.Count; i++)
                {
                    File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), $"{interfaces[i].Name}.Implement.cs"),
                        trees[i].ToString());
                }
            }

            using (var stream = CompileClientProxy(trees,
                replacedemblies.Select(x => MetadataReference.CreateFromFile(x.Location))
                    .Concat(new[]
                    {
                        MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location)
                    })))
            {
                var replacedembly = replacedemblyLoadContext.Default.LoadFromStream(stream);
                return replacedembly.GetExportedTypes().ToList();
            }
        }

19 Source : UraganoBuilderExtensions.cs
with MIT License
from 1100100

public static void AddNLogLogger(this IUraganoBuilder builder, string configXmlFile = "nlog.config")
        {
            LogManager.LoadConfiguration(Path.Combine(Directory.GetCurrentDirectory(), configXmlFile));
            builder.AddLogger(new NLogLoggerProvider());
        }

19 Source : ApplicationBuilderExtensions.cs
with MIT License
from 17MKH

public static IApplicationBuilder UseDefaultPage(this IApplicationBuilder app)
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/app");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        //设置默认文档
        var defaultFilesOptions = new DefaultFilesOptions();
        defaultFilesOptions.DefaultFileNames.Clear();
        defaultFilesOptions.DefaultFileNames.Add("index.html");
        app.UseDefaultFiles(defaultFilesOptions);

        var options = new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(path),
            RequestPath = new PathString("/app")
        };

        app.UseStaticFiles(options);

        var appPath = "app";
        var rewriteOptions = new RewriteOptions().AddRedirect("^$", appPath);

        app.UseRewriter(rewriteOptions);

        return app;
    }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 1RedOne

private void RegisterClient(int thisIndex)
        {
            GetWait();
            string ThisFilePath = System.IO.Directory.GetCurrentDirectory();
            Device ThisClient = Devices[thisIndex];
            log.Info($"[{ThisClient.Name}] - Beginning to process");
            //Update UI
            FireProgress(thisIndex, "CreatingCert...", 15);
            log.Info($"[{ThisClient.Name}] - About to generate cert at {ThisFilePath}...");
            X509Certificate2 newCert = FauxDeployCMAgent.CreateSelfSignedCertificate(ThisClient.Name);
            string myPath = ExportCert(newCert, ThisClient.Name, ThisFilePath);
            log.Info($"[{ThisClient.Name}] - Cert generated at {myPath}!");
            //Update UI
            FireProgress(thisIndex, "CertCreated!", 25);
            System.Threading.Thread.Sleep(1500);
            FireProgress(thisIndex, "Registering Client...", 30);
            SmsClientId clientId;
            log.Info($"[{ThisClient.Name}] - About to register with CM...");
            try
            {
                clientId = FauxDeployCMAgent.RegisterClient(CmServer, ThisClient.Name, DomainName, myPath, Preplacedword, log);
            }
            catch (Exception e)
            {
                log.Error($"[{ThisClient.Name}] - Failed to register with {e.Message}...");
                if (noisy)
                {
                    System.Windows.MessageBox.Show(" We failed with " + e.Message);
                    throw;
                }
                FireProgress(thisIndex, "ManagementPointErrorResponse...", 100);
                return;
            }
            //SmsClientId clientId = FauxDeployCMAgent.RegisterClient(CmServer, ThisClient.Name, DomainName, myPath, Preplacedword);

            FireProgress(thisIndex, "Starting Inventory...", 50);
            FauxDeployCMAgent.SendDiscovery(CmServer, ThisClient.Name, DomainName, SiteCode, myPath, Preplacedword, clientId, log, InventoryIsChecked);

            FireProgress(thisIndex, "RequestingPolicy", 75);
            //FauxDeployCMAgent.GetPolicy(CMServer, SiteCode, myPath, Preplacedword, clientId);

            FireProgress(thisIndex, "SendingCustom", 85);
            FauxDeployCMAgent.SendCustomDiscovery(CmServer, ThisClient.Name, SiteCode, ThisFilePath, CustomClientRecords);

            FireProgress(thisIndex, "Complete", 100);
        }

19 Source : X86Assembly.cs
with MIT License
from 20chan

public static byte[] CompileToMachineCode(string asmcode)
        {
            var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
            var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
            var asmfile = $"{path}.s";
            var objfile = $"{path}.o";
            File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
            var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            var gcc = Process.Start(psi);
            gcc.WaitForExit();
            if (gcc.ExitCode == 0)
            {
                psi.FileName = "objdump";
                psi.Arguments = $"-z -M intel -d {objfile}";
                var objdump = Process.Start(psi);
                objdump.WaitForExit();
                if (objdump.ExitCode == 0)
                {
                    var output = objdump.StandardOutput.ReadToEnd();
                    var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
                    var result = new List<byte>();
                    foreach (Match match in matches)
                    {
                        result.Add((byte)Convert.ToInt32(match.Value, 16));
                    }

                    return result.TakeWhile(b => b != 0x90).ToArray();
                }
            }
            else
            {
                var err = gcc.StandardError.ReadToEnd();
            }

            throw new ArgumentException();
        }

19 Source : RedisClientBuilder.cs
with MIT License
from 2881099

public async Task OutputIntefaceAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                .DisableEncoding()
                .UseFileSystemProject(Directory.GetCurrentDirectory())
                .UseMemoryCachingProvider()
                .Build();

            var model = new TemplateClreplaced(methods.Select(_method=> _method.ToInterface()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Inteface.cshtml", model);

            using(var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }

19 Source : RedisClientBuilder.cs
with MIT License
from 2881099

public async Task OutputRedisHelperAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                .DisableEncoding()
                .UseFileSystemProject(Directory.GetCurrentDirectory())
                .UseMemoryCachingProvider()
                .Build();

            var model = new TemplateClreplaced(methods.Select(_method => _method.ToMethod()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Helper.cshtml", model);

            using (var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }

19 Source : ConsoleApp.cs
with MIT License
from 2881099

public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
			if (bat == null || bat.Any() == false) return ("", "", "");
            if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
			var proc = new System.Diagnostics.Process();
			proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
				CreateNoWindow = true,
				FileName = "cmd.exe",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				RedirectStandardOutput = true,
				WorkingDirectory = cddir
			};
			proc.Start();
			foreach (var cmd in bat)
				proc.StandardInput.WriteLine(cmd);
			proc.StandardInput.WriteLine("exit");
			var outStr = proc.StandardOutput.ReadToEnd();
			var errStr = proc.StandardError.ReadToEnd();
			proc.Close();
			var idx = outStr.IndexOf($">{bat[0]}");
			if (idx != -1) {
				idx = outStr.IndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Substring(idx + 1);
			}
			idx = outStr.LastIndexOf(">exit");
			if (idx != -1) {
				idx = outStr.LastIndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Remove(idx);
			}
			outStr = outStr.Trim();
			if (outStr == "") outStr = null;
			if (errStr == "") errStr = null;
			return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
		}

19 Source : RedisClientBuilder.cs
with MIT License
from 2881099

public async Task OutputProxyAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                .DisableEncoding()
                .UseFileSystemProject(Directory.GetCurrentDirectory())
                .UseMemoryCachingProvider()
                .Build();

            var model = new TemplateClreplaced(methods.Select(_method => _method.ToProxy()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Proxy.cshtml", model);

            using (var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }

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

public static void dump(IntPtr processhandle, uint processId, string processname)
        {
            try
            {
                bool status;
                string filename = processname + "_" + processId + ".dmp";

                using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.Write))
                {
                    status = MiniDumpWriteDump(processhandle, processId, fs.SafeFileHandle, (uint)2, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                }
                if (status)
                {
                    Console.WriteLine($"[+] {processname} process dumped successfully and saved at {Directory.GetCurrentDirectory()}\\{filename}");
                }
                else
                {
                    Console.WriteLine("Cannot Dump the process");
                    Console.WriteLine("[+] " + Marshal.GetExceptionCode());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

19 Source : Program.cs
with MIT License
from 42skillz

public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            host.Run();
        }

19 Source : Program.cs
with MIT License
from 71

public static int Main(string[] args)
        {
            string ns = null;
            string dir = Directory.GetCurrentDirectory();
            string output = Path.Combine(Directory.GetCurrentDirectory(), OUTPUT_FILENAME);
            bool makePublic = false;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "--public":
                    case "-p":
                        makePublic = true;
                        break;
                    case "--namespace":
                    case "-n":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No namespace given.");
                            return 1;
                        }

                        ns = args[++i];
                        break;
                    case "--directory":
                    case "-d":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No directory given.");
                            return 1;
                        }

                        dir = args[++i];
                        break;
                    case "--output":
                    case "-o":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No directory given.");
                            return 1;
                        }

                        output = args[++i];
                        break;
                    default:
                        Console.Error.WriteLine($"Unknown argument: '{args[i]}'.");
                        return 1;
                }
            }

            string methodRedirectionPath = Path.Combine(dir, "Redirection.Method.cs");
            string helpersPath = Path.Combine(dir, "Helpers.cs");

            if (!File.Exists(methodRedirectionPath) || !File.Exists(helpersPath))
            {
                Console.Error.WriteLine("Invalid directory given.");
                return 1;
            }

            try
            {
                // Read files
                string methodRedirectionContent = File.ReadAllText(methodRedirectionPath);
                string helpersContent = File.ReadAllText(helpersPath);

                // Parse content to trees, and get their root / clreplacedes / usings
                SyntaxTree methodRedirectionTree = SyntaxFactory.ParseSyntaxTree(methodRedirectionContent, path: methodRedirectionPath);
                SyntaxTree helpersTree = SyntaxFactory.ParseSyntaxTree(helpersContent, path: helpersPath);

                CompilationUnitSyntax methodRedirection = methodRedirectionTree.GetCompilationUnitRoot();
                CompilationUnitSyntax helpers = helpersTree.GetCompilationUnitRoot();

                UsingDirectiveSyntax[] usings = methodRedirection.Usings.Select(x => x.Name.ToString())
                    .Concat(helpers.Usings.Select(x => x.Name.ToString()))
                    .Distinct()
                    .OrderBy(x => x)
                    .Select(x => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(x)))
                    .ToArray();

                ClreplacedDeclarationSyntax methodRedirectionClreplaced = methodRedirection.DescendantNodes()
                                                                                 .OfType<ClreplacedDeclarationSyntax>()
                                                                                 .First();
                ClreplacedDeclarationSyntax helpersClreplaced = helpers.DescendantNodes()
                                                             .OfType<ClreplacedDeclarationSyntax>()
                                                             .First();

                // Set visibility of main clreplaced
                if (!makePublic)
                {
                    var modifiers = methodRedirectionClreplaced.Modifiers;
                    var publicModifier = modifiers.First(x => x.Kind() == SyntaxKind.PublicKeyword);

                    methodRedirectionClreplaced = methodRedirectionClreplaced.WithModifiers(
                        modifiers.Replace(publicModifier, SyntaxFactory.Token(SyntaxKind.InternalKeyword))
                    );
                }

                // Set visibility of helpers clreplaced
                helpersClreplaced = helpersClreplaced.WithModifiers(
                    helpersClreplaced.Modifiers.Replace(
                        helpersClreplaced.Modifiers.First(x => x.Kind() == SyntaxKind.InternalKeyword),
                        SyntaxFactory.Token(SyntaxKind.PrivateKeyword)
                    )
                );

                // Change helpers clreplaced extension methods to normal methods
                var extMethods = helpersClreplaced.DescendantNodes()
                                             .OfType<MethodDeclarationSyntax>()
                                             .Where(x => x.ParameterList.DescendantTokens().Any(tok => tok.Kind() == SyntaxKind.ThisKeyword));
                var extMethodsNames = extMethods.Select(x => x.Identifier.Text);

                helpersClreplaced = helpersClreplaced.ReplaceNodes(
                    helpersClreplaced.DescendantNodes().OfType<ParameterSyntax>().Where(x => x.Modifiers.Any(SyntaxKind.ThisKeyword)),
                    (x,_) => x.WithModifiers(x.Modifiers.Remove(x.Modifiers.First(y => y.Kind() == SyntaxKind.ThisKeyword)))
                );

                // Disable overrides
                var members = methodRedirectionClreplaced.Members;

                for (int i = 0; i < members.Count; i++)
                {
                    var member = members[i];

                    if (!(member is MethodDeclarationSyntax method))
                    {
                        if (member is ConstructorDeclarationSyntax ctor)
                            members = members.Replace(ctor, ctor.WithIdentifier(SyntaxFactory.Identifier("Redirection")));

                        continue;
                    }

                    var overrideModifier = method.Modifiers.FirstOrDefault(x => x.Kind() == SyntaxKind.OverrideKeyword);

                    if (overrideModifier == default(SyntaxToken))
                        continue;

                    method = method.WithModifiers(
                        method.Modifiers.Remove(overrideModifier)
                    );

                    members = members.Replace(member, method);
                }

                // Add missing field
                var field = SyntaxFactory.FieldDeclaration(
                    SyntaxFactory.VariableDeclaration(
                        SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
                        SyntaxFactory.SeparatedList(new[] {
                            SyntaxFactory.VariableDeclarator("isRedirecting")
                        })
                    )
                );

                const string DOCS = @"
    /// <summary>
    ///   Provides the ability to redirect calls from one method to another.
    /// </summary>
";

                var disposableType = SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(nameof(IDisposable)));

                methodRedirectionClreplaced = methodRedirectionClreplaced.WithMembers(members)
                    // Add docs
                    .WithLeadingTrivia(SyntaxFactory.Comment(DOCS))
                    // Rename to 'Redirection'
                    .WithIdentifier(SyntaxFactory.Identifier("Redirection"))
                    // Disable inheritance, but implement IDisposable
                    .WithBaseList(SyntaxFactory.BaseList().AddTypes(disposableType))
                    // Embed helpers, missing field
                    .AddMembers(field, helpersClreplaced);

                // Generate namespace (or member, if no namespace is specified)
                MemberDeclarationSyntax @namespace = ns == null
                    ? (MemberDeclarationSyntax)methodRedirectionClreplaced
                    : SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns)).AddMembers(methodRedirectionClreplaced);

                var extCalls = @namespace.DescendantNodes()
                                         .OfType<InvocationExpressionSyntax>()
                                         .Where(x => x.Expression is MemberAccessExpressionSyntax access && extMethodsNames.Contains(access.Name.Identifier.Text));
                var helpersAccess = SyntaxFactory.IdentifierName("Helpers");

                @namespace = @namespace.ReplaceNodes(
                    extCalls,
                    (x, _) => SyntaxFactory.InvocationExpression(((MemberAccessExpressionSyntax)x.Expression).WithExpression(helpersAccess)).WithArgumentList(x.ArgumentList.WithArguments(x.ArgumentList.Arguments.Insert(0, SyntaxFactory.Argument(((MemberAccessExpressionSyntax)x.Expression).Expression)))));

                // Generate syntax root
                CompilationUnitSyntax root = SyntaxFactory.CompilationUnit()
                                                          .AddUsings(usings)
                                                          .AddMembers(@namespace);

                // Print root to file
                using (FileStream fs = File.OpenWrite(output))
                using (TextWriter writer = new StreamWriter(fs))
                {
                    fs.SetLength(0);

                    Formatter.Format(root, new AdhocWorkspace()).WriteTo(writer);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error encountered:");
                Console.Error.WriteLine(e.Message);
                return 1;
            }

            return 0;
        }

19 Source : FlightPlan.cs
with MIT License
from 8bitbytes

public void Save(string path)
        {
            if (Name == null)
            {
                Name = $"FP_{System.DateTime.Now.ToString().Replace("/","-").Replace(":","")}_{System.Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8)}";
            }
            var contents = JsonConvert.SerializeObject(this);
            var dir = $@"{System.IO.Directory.GetCurrentDirectory()}\{this.Name}.json.fp";
            System.IO.File.WriteAllText(dir, contents);
        }

19 Source : PlantumlFile.cs
with MIT License
from 8T4

public static void Export(this PlantumlSession session, IEnumerable<Diagram> diagrams)
        {
            var dirPath = Directory.GetCurrentDirectory();
            var path = Path.Join(dirPath, C4Directory.DirectoryName);
            Export(session, path, diagrams);
        }

19 Source : JsonConfigurationHelper.cs
with MIT License
from a34546

public static T GetAppSettings<T>(string key, string path = "appsettings.json") where T : clreplaced, new()
        {
            var currentClreplacedDir = Directory.GetCurrentDirectory();
            IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(currentClreplacedDir)
                .Add(new JsonConfigurationSource { Path = path, Optional = false, ReloadOnChange = true })
                .Build();
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }

19 Source : WebServer.cs
with Apache License 2.0
from A7ocin

void OnGetContext(IAsyncResult async)
        {
            // start listening for the next request
            _listener.BeginGetContext(OnGetContext, null);
            var context = _listener.EndGetContext(async);
            try
            {
                if (context.Request.RawUrl == "/")
                {
                    Debug.Log("[WebServer] context.Request.RawUrl");
                    context.Response.StatusCode = 200;
                    var process = System.Diagnostics.Process.GetCurrentProcess();
                    string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
						<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
						<tr><td>Working Directory</td><td>{2}</td></tr>
						</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
                    var data = System.Text.Encoding.UTF8.GetBytes(msg);
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    context.Response.OutputStream.Close();
                    //Tried adding response close aswell like in Adamas original
                    context.Response.Close();
                }
                else
                {
                    var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
                    if (System.IO.File.Exists(filePath))
                    {
                        using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
                        {
                            var buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            context.Response.ContentLength64 = file.Length;
                            context.Response.StatusCode = 200;
                            context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                        UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
                        replacedetBundleManager.SimulateOverride = true;
                        context.Response.OutputStream.Close();
                        //Tried adding response close aswell like in Adamas original
                        context.Response.Abort();
                        return;
#endif
                    }
                }
                lock (_requestLog)
                {
                    _requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
                }
                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (HttpListenerException e)
            {
                if (e.ErrorCode == -2147467259)
                {
                    // shutdown, terminate silently
                    Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
                    context.Response.Abort();
                    return;
                }
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
        }

19 Source : CircularMultipleColorGradientSkyboxGUI.cs
with MIT License
from aadebdeb

public override void OnGUI(MaterialEditor editor, MaterialProperty[] properties)
        {
            MaterialProperty norm = FindProperty("_Norm", properties);
            editor.ShaderProperty(norm, norm.displayName);

            Material material = editor.target as Material;
            string materialRelativePath = replacedetDatabase.GetreplacedetPath(material);

            if (gradientObject == null)
            {
                string objectRelativePath = materialRelativePath + ".replacedet";
                gradientObject = replacedetDatabase.LoadreplacedetAtPath<GradientObject>(objectRelativePath);
                if (gradientObject == null)
                {
                    gradientObject = ScriptableObject.CreateInstance<GradientObject>();
                    replacedetDatabase.Createreplacedet(gradientObject, objectRelativePath);
                    replacedetDatabase.Refresh();
                }
            }

            SerializedObject data = new SerializedObject(gradientObject);
            data.Update();
            SerializedProperty gradientProperty = data.FindProperty("gradient");
            Texture2D texture = null;

            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(gradientProperty);
            if (EditorGUI.EndChangeCheck())
            {
                data.ApplyModifiedProperties();
                texture = CreateRampTexture();
                texture.wrapMode = TextureWrapMode.Clamp;
                material.SetTexture("_RampTex", texture);
                isGradientSaved = false;
            }

            if (GUILayout.Button("Save Gradient"))
            {
                if (texture == null)
                {
                    texture = CreateRampTexture();
                }

                byte[] png = texture.EncodeToPNG();
                string textureRelativePath = materialRelativePath + ".png";
                string textureAbsolutePath = Path.Combine(Directory.GetCurrentDirectory(), textureRelativePath);
                File.WriteAllBytes(textureAbsolutePath, png);

                TextureImporter textureImporter = replacedetImporter.GetAtPath(textureRelativePath) as TextureImporter;
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                replacedetDatabase.Importreplacedet(textureRelativePath);

                Texture2D savedTexture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(textureRelativePath);
                material.SetTexture("_RampTex", savedTexture);

                isGradientSaved = true;
            }

            if (!isGradientSaved)
            {
                EditorGUILayout.HelpBox("Changes to gradient has not saved yet.", MessageType.Warning);
            }
        }

19 Source : LinearMultipleColorGradientSkyboxGUI.cs
with MIT License
from aadebdeb

public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
        {
            Material material = materialEditor.target as Material;
            string materialRelativePath = replacedetDatabase.GetreplacedetPath(material);

            if (gradientObject == null)
            {
                string objectRelativePath = materialRelativePath + ".replacedet";
                gradientObject = replacedetDatabase.LoadreplacedetAtPath<GradientObject>(objectRelativePath);
                if (gradientObject == null)
                {
                    gradientObject = ScriptableObject.CreateInstance<GradientObject>();
                    replacedetDatabase.Createreplacedet(gradientObject, objectRelativePath);
                    replacedetDatabase.Refresh();
                }
            }

            SerializedObject data = new SerializedObject(gradientObject);
            data.Update();
            SerializedProperty gradientProperty = data.FindProperty("gradient");
            Texture2D texture = null;

            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(gradientProperty);
            if (EditorGUI.EndChangeCheck())
            {
                data.ApplyModifiedProperties();
                texture = CreateRampTexture();
                texture.wrapMode = TextureWrapMode.Clamp;
                material.SetTexture("_RampTex", texture);
                isGradientSaved = false;
            }

            if (GUILayout.Button("Save Gradient"))
            {
                if (texture == null)
                {
                    texture = CreateRampTexture();
                }

                byte[] png = texture.EncodeToPNG();
                string textureRelativePath = materialRelativePath + ".png";
                string textureAbsolutePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), textureRelativePath);
                File.WriteAllBytes(textureAbsolutePath, png);

                TextureImporter textureImporter = replacedetImporter.GetAtPath(textureRelativePath) as TextureImporter;
                textureImporter.wrapMode = TextureWrapMode.Clamp;
                replacedetDatabase.Importreplacedet(textureRelativePath);

                Texture2D savedTexture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(textureRelativePath);
                material.SetTexture("_RampTex", savedTexture);

                isGradientSaved = true;
            }

            if (!isGradientSaved)
            {
                EditorGUILayout.HelpBox("Changes to gradient has not saved yet.", MessageType.Warning);
            }

        }

19 Source : DellSmbiosBzh.cs
with GNU General Public License v3.0
from AaronKelley

public static bool Initialize()
        {
            bool result;

            // Check to see if the driver has already been loaded, and if so, just grab a handle to that.
            DriverHandle = ServiceMethods.CreateFile(DriverDevicePath, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);

            // If the driver is not running, install it
            if (DriverHandle == ServiceMethods.InvalidHandleValue)
            {
                string driverPath = string.Format("{0}{1}{2}", Directory.GetCurrentDirectory(), Path.DirectorySeparatorChar, DriverFilename);
                result = InstallDriver(driverPath, true);
                if (!result)
                {
                    return false;
                }

                result = StartDriver();

                if (!result)
                {
                    return false;
                }

                DriverHandle = ServiceMethods.CreateFile(DriverDevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);

                if (DriverHandle == ServiceMethods.InvalidHandleValue)
                {
                    return false;
                }
            }
            IsInitialized = true;
            return true;
        }

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

static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // fix error encoding 1252 from encoding with netcore framework

            var defaultPath = args.Length > 0 ? args[0] : "World";
            var workPath = Path.Combine(Directory.GetCurrentDirectory(), defaultPath);
            Directory.CreateDirectory(workPath);

            //Loger.LogMessage += (msg) => Console.WriteLine(msg);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Manager = new ServerManager();
            if (!Manager.StartPrepare(workPath)) return;

            var th = new Thread(CommandInput);
            th.IsBackground = true;
            th.Start();

            Manager.Start();
        }

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

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd-hh-mm");
            var fileName = Path.Combine(Directory.GetCurrentDirectory(), "!UnhandledException" + date + ".log");
            File.WriteAllText(fileName, e.ExceptionObject.ToString(), Encoding.UTF8);
        }

19 Source : Program.cs
with MIT License
from Abdulrhman5

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config
                        .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        .AddJsonFile("appsettings.json", true, true)
                        .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                        .AddJsonFile("ocelot.json")
                        .AddEnvironmentVariables();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

19 Source : Program.cs
with MIT License
from Abdulrhman5

public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var configurations = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .AddEnvironmentVariables()
                .Build();

            return Host.CreateDefaultBuilder(args)
                .UseUnityServiceProvider()
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config
                        .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        .AddJsonFile("appsettings.json", true, true)
                        .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                        .AddEnvironmentVariables();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        serverOptions.Listen(IPAddress.Any, configurations.GetValue<int>("Hosting:HttpPort"), options =>
                        {
                            options.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
                        });

                        serverOptions.Listen(IPAddress.Any, configurations.GetValue<int>("Hosting:GrpcPort"), options =>
                        {
                            options.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
                        });
                    });
                });
        }

19 Source : Program.cs
with MIT License
from Abdulrhman5

public static IHostBuilder CreateHostBuilder(string[] args) {
            var configurations = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .AddEnvironmentVariables()
                .Build();

            return Host.CreateDefaultBuilder(args)
                .UseUnityServiceProvider()
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config
                        .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        .AddJsonFile("appsettings.json", true, true)
                        .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                        .AddEnvironmentVariables();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        serverOptions.Listen(IPAddress.Any, configurations.GetValue<int>("Hosting:HttpPort"), options =>
                        {
                            options.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2;
                        });

                        serverOptions.Listen(IPAddress.Any, configurations.GetValue<int>("Hosting:GrpcPort"), options =>
                        {
                            options.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
                        });
                    });
                });
        }

19 Source : OrderingHttpApiHostMigrationsDbContextFactory.cs
with MIT License
from AbpApp

private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }

19 Source : AdministrationServiceDbContextFactory.cs
with MIT License
from abpframework

private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(
                    Path.Combine(
                        Directory.GetCurrentDirectory(),
                        $"..{Path.DirectorySeparatorChar}EShopOnAbp.AdministrationService.HttpApi.Host"
                    )
                )
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }

19 Source : IdentityServiceDbContextFactory.cs
with MIT License
from abpframework

private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(
                    Path.Combine(
                        Directory.GetCurrentDirectory(),
                        $"..{Path.DirectorySeparatorChar}EShopOnAbp.IdenreplacedyService.HttpApi.Host"
                    )
                )
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }

19 Source : PaymentServiceDbContextFactory.cs
with MIT License
from abpframework

private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../EShopOnAbp.PaymentService.HttpApi.Host/"))
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }

19 Source : CatalogServiceDbContextFactory.cs
with MIT License
from abpframework

private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../EShopOnAbp.CatalogService.HttpApi.Host"))
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }

19 Source : OrderingServiceDbContextFactory.cs
with MIT License
from abpframework

private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../EShopOnAbp.OrderingService.HttpApi.Host/"))
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }

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

private static string GetContentFolder()
        {
            var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.Shard.Host};port={ConfigManager.Config.MySql.Shard.Port};user={ConfigManager.Config.MySql.Shard.Username};preplacedword={ConfigManager.Config.MySql.Shard.Preplacedword};database={ConfigManager.Config.MySql.Shard.Database}");
            var sqlQuery = "SELECT `value` FROM config_properties_string WHERE `key` = 'content_folder';";
            var sqlCommand = new MySql.Data.MySqlClient.MySqlCommand(sqlQuery, sqlConnect);

            sqlConnect.Open();
            var sqlReader = sqlCommand.ExecuteReader();

            var content_folder = "";

            if (sqlReader.HasRows)
            {
                while (sqlReader.Read())
                {
                    content_folder = sqlReader.GetString(0);
                    break;
                }
            }
            else
                content_folder = @".\Content";

            sqlReader.Close();
            sqlCommand.Connection.Close();

            // handle relative path
            if (content_folder.StartsWith("."))
            {
                var cwd = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar;
                content_folder = cwd + content_folder;
            }

            return content_folder;
        }

19 Source : SolutionDirectory.cs
with MIT License
from adamant

public static string Get()
        {
            var directory = Directory.GetCurrentDirectory() ?? throw new InvalidOperationException("Could not get current directory");
            while (directory != null && !Directory.GetFiles(directory, "*.sln", SearchOption.TopDirectoryOnly).Any())
            {
                directory = Path.GetDirectoryName(directory) ?? throw new InvalidOperationException("Null directory name");
            }
            return directory ?? throw new InvalidOperationException("Compiler is confused, this can't be null");
        }

19 Source : TDLibHost.cs
with MIT License
from ADeltaX

public async Task CreateInstance()
        {
            TDLibHostBot = this;

            _client = new TdClient();
            TdLog.SetVerbosityLevel(0);

            _client.UpdateReceived += async (sender, update) =>
            {
                switch (update)
                {
                    case Update.UpdateOption option:
                        await _client.ExecuteAsync(new SetOption
                        {
                            DataType = option.DataType,
                            Extra = option.Extra,
                            Name = option.Name,
                            Value = option.Value
                        });
                        break;
                    case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitTdlibParameters):
                        await _client.ExecuteAsync(new SetTdlibParameters
                        {
                            Parameters = new TdlibParameters
                            {
                                ApiId = SecretKeys.API_ID,
                                ApiHash = SecretKeys.API_HASH,
                                ApplicationVersion = "1.0.0",
                                DeviceModel = "PC",
                                SystemLanguageCode = "en",
                                SystemVersion = "Win 10.0",
                                DatabaseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "tdlib"),
                                EnableStorageOptimizer = true,
                                FilesDirectory = Path.Combine(Directory.GetCurrentDirectory(), "tdlib")
                            }
                        });
                        break;
                    case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitEncryptionKey):
                        await _client.ExecuteAsync(new CheckDatabaseEncryptionKey());
                        break;
                    case Update.UpdateAuthorizationState updateAuthorizationState when updateAuthorizationState.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitCode):
                    case Update.UpdateAuthorizationState updateAuthorizationState2 when updateAuthorizationState2.AuthorizationState.GetType() == typeof(AuthorizationState.AuthorizationStateWaitPhoneNumber):
                        _authNeeded = true;
                        ResetEvent.Set();
                        break;
                    case Update.UpdateUser updateUser:
                        break;
                    case Update.UpdateConnectionState updateConnectionState when updateConnectionState.State.GetType() == typeof(ConnectionState.ConnectionStateReady):
                        ResetEvent.Set();
                        ReadyEvent.Set();
                        break;

                    case Update.UpdateMessageSendFailed uwu:
                    case Update.UpdateMessageSendSucceeded uwu2:
                        //what happens ?
                        //BIG *RIP*
                        UploadedEvent.Set();
                        break;

                    default:
                        break;
                }
            };

#if !PRODUCTION
            await Cont(TelegramBotSettings.DEV_CHANNEL);
#else
            await Cont(TelegramBotSettings.PROD_CHANNEL);
#endif
        }

19 Source : Program.cs
with MIT License
from adrianoc

public static void Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder();
            var config = configurationBuilder.AddJsonFile($"appsettings.Production.json", optional: true).Build();

            var host = new HostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseKestrel(serverOptions => { })
                        .UseIISIntegration()
                        .UseUrls(config["ApplicationUrl"])
                        .UseConfiguration(config)
                        .UseStartup<Startup>();
                })
                .Build();
            
            host.Run();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void extractnsp()
        {
            offbtn();

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            Directory.CreateDirectory(tmpdir);

            statuslabel.Content = "Extracting NSP Container...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            startbar();

            await Task.Run(() => hct.WaitForExit());

            hct.Close();

            readxml();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void repacknsp()
        {
            statuslabel.Content = "Repacking NSP Container...";

            string nspbdir = AppDomain.CurrentDomain.BaseDirectory + "\\nspBuild.pyw";
            string[] tmpfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp");
            string args = String.Join(" ", tmpfiles);

            Process nsb = new Process();
            nsb.StartInfo.FileName = nspbdir;
            nsb.StartInfo.Arguments = args;
            nsb.StartInfo.CreateNoWindow = true;
            nsb.StartInfo.UseShellExecute = true;
            nsb.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            nsb.EnableRaisingEvents = true;

            nsb.Start();

            await Task.Run(() => nsb.WaitForExit());

            nsb.Close(); 

            stopbar();

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);          

            System.Windows.MessageBox.Show("Congrats this NSP will now work on " + fwlabel.Content + "!");

            statuslabel.Content = "";
            keylabel.Content = "";
            fwlabel.Content = "";
            tidlabel.Content = "";

            onbtn();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void reextractnsp()
        {
            offbtn();

            startbar();

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            Directory.CreateDirectory(tmpdir);

            statuslabel.Content = "Extracting NSP Container...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            await Task.Run(() => hct.WaitForExit());

            hct.Close();

            decryptbsgnca();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void extractncau()
        {
            string updir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
            Directory.CreateDirectory(updir);

            statuslabel.Content = "Extracting Update NCA's...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=upd " + "\"" + upnspinputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            await Task.Run(() => hct.WaitForExit());

            hct.Close();

            applyupdate();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void carmdrm()
        {
            statuslbl.Content = "Converting File...";

            Extract("OSAC", AppDomain.CurrentDomain.BaseDirectory + "\\res", "res", "ffmpeg.exe");

            string ffdir = AppDomain.CurrentDomain.BaseDirectory + "\\res\\ffmpeg.exe";
            string arg = @"-y -activation_bytes ";
            string arg1 = @" -i ";
            string arg2 = @" -ab ";
            string arg3 = @"k -map_metadata 0 -id3v2_version 3 -vn ";
            string fileout = Path.Combine(outputdisplay.Text, Path.GetFileNameWithoutExtension(inputdisplay.Text) + GetOutExtension());
            string arguments = arg + abytes + arg1 + inputdisplay.Text + arg2 + qlabel.Content + arg3 + fileout;

            Process ffm = new Process();
            ffm.StartInfo.FileName = ffdir;
            ffm.StartInfo.Arguments = arguments;
            ffm.StartInfo.CreateNoWindow = true;
            ffm.StartInfo.RedirectStandardError = true;
            ffm.StartInfo.UseShellExecute = false;
            ffm.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            ffm.EnableRaisingEvents = true;
            Console.SetOut(new TextBoxWriter(txtConsole));
            ffm.ErrorDataReceived += (s, ea) =>
            {
                Console.WriteLine($"{ea.Data}");
            };

            scrolltimer.Tick += new EventHandler(scrolltimer_Tick);
            scrolltimer.Interval = new TimeSpan(0, 0, 1);

            ffm.Start();

            ffm.BeginErrorReadLine();
            scrolltimer.Start();

            await Task.Run(() => ffm.WaitForExit());

            ffm.Close();

            inpbutton.IsEnabled = true;

            convertbutton.IsEnabled = true;

            scrolltimer.Stop();
            scrolltimer.Tick -= new EventHandler(scrolltimer_Tick);

            enrb();
            enbslst();

            statuslbl.Content = "Conversion Complete!";

            stopbar();

            Directory.Delete(resdir, true);
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void decryptbsgnca()
        {
            offbtn();

            startbar();

            statuslabel.Content = "Decrypting Base Game NCA...";

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";

            var di = new DirectoryInfo(tmpdir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string basenca = String.Join(" ", larbnca);

            string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string replacedlkeyp = bsgreplacedlkyinput.Text;
            string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
            string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
            string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
            string arg = arg1 + arg2;
          
            Process decrnca = new Process();
            decrnca.StartInfo.FileName = nspddir;
            decrnca.StartInfo.Arguments = arg;
            decrnca.StartInfo.CreateNoWindow = true;
            decrnca.StartInfo.UseShellExecute = false;
            decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            decrnca.EnableRaisingEvents = true;

            decrnca.Start();

            await Task.Run(() => decrnca.WaitForExit());

            decrnca.Close();

            extractncau();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void applyupdate()
        {
            statuslabel.Content = "Merging NCA's...";

            string curdir = AppDomain.CurrentDomain.BaseDirectory;
            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
            string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string basenca = tmpdir + "\\NCAID_PLAIN.nca";

            var di = new DirectoryInfo(upddir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string updnca = String.Join(" ", larupdnca);

            string replacedlkeyp = updreplacedlkyinput.Text;
            string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());

            string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
            string arg2 = tmpdir + "\\exefs " + updnca;
            string arg = arg1 + arg2; 

            Process aplupd = new Process();
            aplupd.StartInfo.FileName = nspudir;
            aplupd.StartInfo.Arguments = arg;
            aplupd.StartInfo.CreateNoWindow = true;
            aplupd.StartInfo.UseShellExecute = false;
            aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            aplupd.EnableRaisingEvents = true;

            aplupd.Start();

            await Task.Run(() => aplupd.WaitForExit());

            aplupd.Close();

            stopbar();

            statuslabel.Content = "";

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);

            onbtn();

            System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
        }

19 Source : BlockchainNodeHostingService.cs
with MIT License
from AElfProject

public async Task StartAsync(BlockchainApplicationStartDto blockchainApplicationStartDto)
        {
            var builder = new WebHostBuilder()
                .ConfigureAppConfiguration(config => { config.AddJsonFile("appsettings.json"); })
                .UseKestrel((builderContext, options) =>
                {
                    options.Configure(builderContext.Configuration.GetSection("Kestrel"));
                })
                .ConfigureLogging(logger => { })
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<MainBlockchainStartup<MainChainAElfModule>>()
                .ConfigureServices(services =>
                {
                    services.Configure<ChainOptions>(o =>
                        o.ChainId = blockchainApplicationStartDto.ChainId);
                });
            await builder.Build().RunAsync();
        }

19 Source : Utils.cs
with Apache License 2.0
from aequabit

public static string WriteTempData(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            string path = null;
            try
            {
                path = Path.GetTempFileName();
            }
            catch (IOException)
            {
                path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetRandomFileName());
            }
            try
            {
                File.WriteAllBytes(path, data);
            }
            catch
            {
                path = null;
            }
            return path;
        }

See More Examples