System.IO.Directory.SetCurrentDirectory(string)

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

362 Examples 7

19 Source : SmokeTests_ExampleWalkUsingBreadcrumbView.cs
with MIT License
from ABTSoftware

[OneTimeSetUp]
        public void FixtureSetup()
        {
            var dir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            Directory.SetCurrentDirectory(dir);
            _theApp = FlaUI.Core.Application.Launch(new ProcessStartInfo("SciChart.Examples.Demo.exe", "/uiautomationTestMode"));
            _automation = new UIA3Automation();
            _mainWindow = _theApp.GetMainWindow(_automation);

            // Get any example button and click it 
            var examplesWrapPanel = WaitForElement(() => _mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("ExamplesWrapPanel")));
            var exampleButton = WaitForElement(() => examplesWrapPanel?.FindFirstDescendant(cf => cf.ByAutomationId("Band Series Chart")).AsButton());
            exampleButton?.WaitUntilClickable();
            exampleButton?.Invoke();

            // Click the 'Got it!' help button
            var tipsView = WaitForElement(() => _mainWindow.FindFirstDescendant(cf => cf.ByAutomationId("TipsView")));
            var goreplacedButton = WaitForElement(() => tipsView.FindFirstDescendant(cf => cf.ByAutomationId("TipsView.GoreplacedButton"))?.AsButton());
            goreplacedButton?.WaitUntilClickable();
            goreplacedButton?.Invoke();

            // Now application state should be in the example view
        }

19 Source : CLIFixture.cs
with MIT License
from AdrianWilczynski

public void Dispose()
        {
            Directory.SetCurrentDirectory(_originalWorkingDirectory);
            Directory.Delete(Temp, true);
        }

19 Source : ConvertCommandShould.cs
with MIT License
from AdrianWilczynski

[Fact]
        public void ConvertCurrentDirectoryWhenNoInputProvided()
        {
            Prepare(nameof(ConvertCurrentDirectoryWhenNoInputProvided));

            Directory.SetCurrentDirectory(nameof(ConvertCurrentDirectoryWhenNoInputProvided));

            try
            {
                File.WriteAllText("File1.cs", "clreplaced Item4 { }");
                File.WriteAllText("File2.cs", "clreplaced Item5 { }");

                _convertCommand.OnExecute();

                replacedert.True(File.Exists("file1.ts"));
                replacedert.True(File.Exists("file2.ts"));
            }
            finally
            {
                Directory.SetCurrentDirectory("..");
            }
        }

19 Source : ConvertCommandShould.cs
with MIT License
from AdrianWilczynski

[Fact]
        public void ConvertDirectoryIntoProvidedOutputDirectory()
        {
            Prepare(nameof(ConvertDirectoryIntoProvidedOutputDirectory));

            var inputDirectoryPath = Path.Join(nameof(ConvertDirectoryIntoProvidedOutputDirectory), "Input");
            Directory.CreateDirectory(inputDirectoryPath);

            Directory.SetCurrentDirectory(inputDirectoryPath);

            try
            {
                File.WriteAllText("File1.cs", "clreplaced Item8 { }");
                File.WriteAllText("File2.cs", "clreplaced Item9 { }");
                File.WriteAllText("File3.cs", "clreplaced Item10 { }");

                var outputDirectoryPath = Path.Join("..", "Output");

                _convertCommand.Input = ".";
                _convertCommand.Output = outputDirectoryPath;

                _convertCommand.OnExecute();

                var convertedFiles = Directory.GetFiles(outputDirectoryPath)
                    .Where(f => f.EndsWith(".ts"))
                    .Select(Path.GetFileName);

                replacedert.Equal(new[] { "file1.ts", "file2.ts", "file3.ts" }, convertedFiles);
            }
            finally
            {
                Directory.SetCurrentDirectory(Path.Join("..", ".."));
            }
        }

19 Source : ResourceTestBase.cs
with MIT License
from adrianoc

[SetUp]
        public void Setup()
        {
            cecilifiedCode = string.Empty;
            Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory);
        }

19 Source : ConvertCommandShould.cs
with MIT License
from AdrianWilczynski

[Fact]
        public void UseOptionsFromConfigurationFile()
        {
            Prepare(nameof(UseOptionsFromConfigurationFile));

            Directory.SetCurrentDirectory(nameof(UseOptionsFromConfigurationFile));

            try
            {
                var codeConverterMock = new Mock<ICodeConverter>();
                codeConverterMock
                    .Setup(c => c.ConvertToTypeScript(It.IsAny<string>(), It.IsAny<CodeConversionOptions>()))
                    .Returns("interface Item16 { }");

                var fileNameConverterMock = new Mock<IFileNameConverter>();
                fileNameConverterMock
                    .Setup(f => f.ConvertToTypeScript(It.IsAny<string>(), It.IsAny<ModuleNameConversionOptions>()))
                    .Returns("item.ts");

                File.WriteAllText(ConfigurationFile.FileName, "{ \"preserveCasing\": true }");

                File.WriteAllText("Item.cs", "clreplaced Item16 { }");

                var command = new ConvertCommand(codeConverterMock.Object, fileNameConverterMock.Object);

                command.OnExecute();

                replacedert.True(command.PreserveCasing);
                codeConverterMock.Verify(c =>
                    c.ConvertToTypeScript(
                        It.IsAny<string>(),
                        It.Is<CodeConversionOptions>(o => !o.ToCamelCase)),
                    Times.Once);
            }
            finally
            {
                Directory.SetCurrentDirectory("..");
            }
        }

19 Source : InitializeCommandShould.cs
with MIT License
from AdrianWilczynski

[Fact]
        public void CreateConfigurationFile()
        {
            Prepare(nameof(CreateConfigurationFile));

            Directory.SetCurrentDirectory(nameof(CreateConfigurationFile));

            try
            {
                _initializeCommand.PreserveCasing = true;
                _initializeCommand.OnExecute();

                replacedert.True(File.Exists(ConfigurationFile.FileName));
                replacedert.Contains("\"preserveCasing\": true,", File.ReadAllText(ConfigurationFile.FileName));
            }
            finally
            {
                Directory.SetCurrentDirectory("..");
            }
        }

19 Source : PythonScript.cs
with MIT License
from allisterb

public override bool Init()
        {
            Operation init = Begin("Initializing embedded Python interpreter");
            if (PythonEngine.IsInitialized && (HomeDir != string.Empty || ModulePath != string.Empty || Args.Count > 0))
            {
                Error("Python engine is already initialized and cannot be initilaized with another script or aditional arguments.");
                init.Cancel();
                return false;
            }

            string originalDirectory = Directory.GetCurrentDirectory();

            try
            {
                SetVirtualEnvDir();
                SetBinDir();
                if (binDir.IsNotEmpty())
                {

                    Directory.SetCurrentDirectory(binDir);
                }
                SetPythonPath();
                PythonEngine.Initialize(Args);
            }
            catch (DllNotFoundException dnfe)
            {
                if (HomeDir.IsEmpty())
                {
                    Error(dnfe, $"Could not find the system-wide python36 shared library. Add Python 3.6 to your PATH environment variable or use the -P option to set the path to a Python 3.6 interpreter directory.");
                }
                else
                {
                    Error(dnfe, $"Could not find python36 shared library in {HomeDir}.");
                }
            }
            catch (Exception e)
            {
                Error(e, "Exception thrown initalizing Python engine.");
            }
            finally
            {
                if (Directory.GetCurrentDirectory() != originalDirectory)
                {
                    Directory.SetCurrentDirectory(originalDirectory);
                }
            }

            if (!PythonEngine.IsInitialized)
            {
                Error("Could not initalize Python engine.");
                init.Cancel();
                return false;
            }

            Info("Python version {0} from {1}.", PythonEngine.Version.Trim(), binDir.IsEmpty() ? Runtime.PythonDLL : Path.Combine(binDir, Runtime.PythonDLL.WithDllExt()));
            Modules = GetModules();
            Info("{0} Python modules installed.", Modules.Count(m => !m.StartsWith("__")));
            HasPipModule = Modules.Contains("pip");
            if (!HasPipModule)
            {
                Warn("Python pip module is not installed.");
            }
            else
            {
                PipModules = GetPipModules();
                Info("{0} pip modules installed.", PipModules.Count);
            }

            foreach (string m in RequiredModules)
            {
                if (!Modules.Contains(m))
                {
                    Error("Python {0} module is not installed.", m);
                    init.Cancel();
                    return false;
                }
            }

            init.Complete();
            return true;
        }

19 Source : Program.cs
with MIT License
from AlturosDestinations

static int Main(string[] args)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            var log4netConfig = new FileInfo("log4net.config");
            if (!log4netConfig.Exists)
            {
                Console.WriteLine("[Warning] Cannot found a log4net.config");
            }

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

            var exitCode = HostFactory.Run(x =>
            {
                x.Service<Controller>();
                x.RunAsLocalSystem();
                x.SetDescription("Alturos Yolo WebService");
                x.SetDisplayName("Alturos.Yolo.WebService");
                x.SetServiceName("Alturos.Yolo.WebService");
            });

            return (int)exitCode;
        }

19 Source : Netch.cs
with MIT License
from AmazingDM

[STAThread]
        public static void Main(string[] args)
        {
            if (args.Contains("-console"))
            {
                if (!NativeMethods.AttachConsole(-1))
                {
                    NativeMethods.AllocConsole();
                }
            }

            // 创建互斥体防止多次运行
            using (var mutex = new Mutex(false, "Global\\Netch"))
            {
                // 设置当前目录
                Directory.SetCurrentDirectory(Global.NetchDir);
                Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process) + ";" + Path.Combine(Global.NetchDir, "bin"), EnvironmentVariableTarget.Process);

                // 预创建目录
                var directories = new[] {"mode", "data", "i18n", "logging"};
                foreach (var item in directories)
                {
                    if (!Directory.Exists(item))
                    {
                        Directory.CreateDirectory(item);
                    }
                }

                // 加载配置
                Configuration.Load();

                // 加载语言
                i18N.Load(Global.Settings.Language);

                // 检查是否已经运行
                /*if (!mutex.WaitOne(0, false))
                {
                    OnlyInstance.Send(OnlyInstance.Commands.Show);
                    Logging.Info("唤起单实例");

                    // 退出进程
                    Environment.Exit(1);
                }*/

                // 清理上一次的日志文件,防止淤积占用磁盘空间
                if (Directory.Exists("logging"))
                {
                    var directory = new DirectoryInfo("logging");

                    foreach (var file in directory.GetFiles())
                    {
                        file.Delete();
                    }

                    foreach (var dir in directory.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                }

                Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}");
                Task.Run(() =>
                {
                    Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}");
                });
                Task.Run(() =>
                {
                    Logging.Info("启动单实例");
                    OnlyInstance.Server();
                });

                // 绑定错误捕获
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += Application_OnException;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(Global.MainForm = new MainForm());
            }
        }

19 Source : Program.cs
with MIT License
from Analogy-LogViewer

[STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.replacedemblyLoad += CurrentDomain_replacedemblyLoad;
            DevExpress.UserSkins.BonusSkins.Register();
            WindowsFormsSettings.LoadApplicationSettings();
            WindowsFormsSettings.SetDPIAware();
            replacedogyLogManager.Instance.LogInformation($"OS: {Environment.OSVersion.Version}", nameof(Program));
            if (Environment.OSVersion.Version.Major >= 10)
            {
                WindowsFormsSettings.ForceDirectXPaint();
            }
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            AppDomain.CurrentDomain.replacedemblyResolve += CurrentDomain_replacedemblyResolve;
            WindowsFormsSettings.DefaultFont = Settings.FontSettings.UIFont;
            WindowsFormsSettings.DefaultMenuFont = Settings.FontSettings.MenuFont;
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            if (Settings.EnableFirstChanceException)
            {
                AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            }
            Settings.OnEnableFirstChanceExceptionChanged += (s, e) =>
            {
                if (e)
                {
                    AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
                }
                else
                {
                    AppDomain.CurrentDomain.FirstChanceException -= CurrentDomain_FirstChanceException;
                }
            };
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();
#if NETCOREAPP3_1 || NET
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
#endif
            Settings.IncreaseNumberOfLaunches();
            if (!string.IsNullOrEmpty(Settings.ApplicationSkinName))
            {
                if (!string.IsNullOrEmpty(Settings.ApplicationSvgPaletteName))
                {
                    UserLookAndFeel.Default.SetSkinStyle(Settings.ApplicationSkinName, Settings.ApplicationSvgPaletteName);
                }
                else
                {
                    UserLookAndFeel.Default.SetSkinStyle(Settings.ApplicationSkinName);
                }

                UserLookAndFeel.Default.Style = Settings.ApplicationStyle;
            }

            UserLookAndFeel.Default.StyleChanged += (s, e) =>
            {
                UserLookAndFeel laf = (UserLookAndFeel)s;
                Settings.ApplicationSkinName = laf.ActiveSkinName;
                Settings.ApplicationStyle = laf.Style;
                Settings.ApplicationSvgPaletteName = laf.ActiveSvgPaletteName;

            };

            if (UserSettingsManager.UserSettings.SingleInstance &&
                Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
            {

                if (Environment.GetCommandLineArgs().Length == 2)
                {
                    var otherreplacedogy = GetAlreadyRunningInstance();
                    if (otherreplacedogy != null)
                    {
                        SendDataMessage(otherreplacedogy, Environment.GetCommandLineArgs()[1]);
                    }
                }
                else
                {
                    XtraMessageBox.Show("Single instance is on. Exiting this instance", "replacedogy");
                }

                return;
            }

            if (Settings.IsFirstRun)
            {
               //FirstTimeRunForm f = new FirstTimeRunForm();
               //f.ShowDialog();
            }
            if (Settings.MainFormType == MainFormType.RibbonForm)
            {
                Application.Run(new MainForm());
            }
            else
            {
                Application.Run(new FluentDesignMainForm());
            }

        }

19 Source : FileHelper.cs
with Apache License 2.0
from anjoy8

public static void FolderCreate(string orignFolder, string NewFloder)
        {
            Directory.SetCurrentDirectory(orignFolder);
            Directory.CreateDirectory(NewFloder);
        }

19 Source : NUnitTestRunnerInitializer.cs
with Apache License 2.0
from apache

[OneTimeSetUp]
        public void RunBeforeAnyTests()
        {
            Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory);
        }

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

static int Main(string[] args)
        {
            bool showHelp = false;
            bool showUsage = false;

            string rootPath = null;
            string privateKeyFile = null;

            OptionSet argParser = new OptionSet()
            {
                { "h|help", "Print this message and exit.", v => { showHelp = v != null; } },
                { "r|root=", "The path to the root of the repository. Required.", v => { rootPath = v; } },
                { "k|key=", "Provide the path to the private key file that will be used to sign the modules. Required.", v => { privateKeyFile = v; } },
            };

            List<string> unrecognised = argParser.Parse(args);

            if (unrecognised.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine("Unrecognised argument" + (unrecognised.Count > 1 ? "s" : "") + ": " + unrecognised.Aggregate((a, b) => a + " " + b));
                showUsage = true;
            }

            if (string.IsNullOrEmpty(rootPath) && !showHelp)
            {
                Console.WriteLine();
                Console.WriteLine("The root path is required!");
                showUsage = true;
            }

            if (string.IsNullOrEmpty(privateKeyFile) && !showHelp)
            {
                Console.WriteLine();
                Console.WriteLine("The private key file is required!");
                showUsage = true;
            }

            if (showUsage || showHelp)
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("BuildRepositoryModuleDatabase");
                Console.WriteLine();
                Console.WriteLine("Usage:");
                Console.WriteLine();
                Console.WriteLine("  BuildRepositoryModuleDatabase {-h|--help}");
                Console.WriteLine("  BuildRepositoryModuleDatabase --root <root_path> --key <key_file>");                
            }

            if (showHelp)
            {
                Console.WriteLine();
                Console.WriteLine("Options:");
                Console.WriteLine();
                argParser.WriteOptionDescriptions(Console.Out);
                return 0;
            }

            if (showUsage)
            {
                return 64;
            }

            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;

            Directory.SetCurrentDirectory(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location));

            string[] files = Directory.GetFiles(Path.Combine(rootPath, "src", "Modules"), "*.cs");

            VectSharp.SVG.Parser.ParseImageURI = VectSharp.MuPDFUtils.ImageURIParser.Parser(VectSharp.SVG.Parser.ParseSVGURI);

            File.Delete(Modules.ModuleListPath);

            TreeViewer.ModuleMetadata[] modules = new TreeViewer.ModuleMetadata[files.Length];

            if (!Directory.Exists("references"))
            {
                Directory.CreateDirectory("references");
            }

            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine();
            Console.WriteLine("Compiling modules...");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Gray;

            for (int i = 0; i < files.Length; i++)
            {
                Console.WriteLine(Path.GetFileName(files[i]));
                if (!File.Exists(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references")))
                {
                    References[Path.GetFileName(files[i])] = new List<string>(baseReferences);
                }
                else
                {
                    References[Path.GetFileName(files[i])] = new List<string>(File.ReadAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references")));
                }

                bool compiledWithoutErrors = false;

                while (!compiledWithoutErrors)
                {
                    try
                    {
                        modules[i] = TreeViewer.ModuleMetadata.CreateFromSource(File.ReadAllText(files[i]), References[Path.GetFileName(files[i])].ToArray());
                        compiledWithoutErrors = true;
                    }
                    catch (Exception e)
                    {
                        HashSet<string> newReferences = new HashSet<string>();

                        string msg = e.Message;

                        while (msg.Contains("You must add a reference to replacedembly '"))
                        {
                            msg = msg.Substring(msg.IndexOf("You must add a reference to replacedembly '") + "You must add a reference to replacedembly '".Length);
                            newReferences.Add(msg.Substring(0, msg.IndexOf(",")));
                        }

                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine();
                        Console.WriteLine(e.Message);
                        Console.WriteLine();
                        Console.ForegroundColor = ConsoleColor.Gray;

                        if (newReferences.Count == 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.Write("Which references should I add? ");
                            Console.ForegroundColor = ConsoleColor.Gray;
                            string[] newRefs = Console.ReadLine().Split(',');

                            foreach (string sr in newRefs)
                            {
                                string refName = sr.Trim();
                                if (refName.EndsWith(".dll"))
                                {
                                    refName = refName.Substring(0, refName.Length - 4);
                                }

                                newReferences.Add(refName);
                            }
                            Console.WriteLine();
                        }

                        Console.WriteLine("Adding references: ");

                        foreach (string sr in newReferences)
                        {
                            References[Path.GetFileName(files[i])].Add(sr + ".dll");
                            Console.WriteLine("\t" + sr + ".dll");
                        }

                    }
                }
                File.WriteAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references"), References[Path.GetFileName(files[i])]);
            }

            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine();
            Console.WriteLine("Checking for unnecessary references...");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Gray;

            for (int i = 0; i < files.Length; i++)
            {
                Console.WriteLine(Path.GetFileName(files[i]));

                List<string> toBeRemoved = new List<string>();
                List<string> originalReferences = References[Path.GetFileName(files[i])];

                for (int j = 0; j < originalReferences.Count; j++)
                {
                    List<string> currentReferences = new List<string>(originalReferences);
                    currentReferences.Remove(originalReferences[j]);

                    try
                    {
                        TreeViewer.ModuleMetadata.CreateFromSource(File.ReadAllText(files[i]), currentReferences.ToArray());
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("\tRemoving " + originalReferences[j]);
                        Console.ForegroundColor = ConsoleColor.Gray;
                        toBeRemoved.Add(originalReferences[j]);
                    }
                    catch
                    {

                    }
                }

                for (int j = 0; j < toBeRemoved.Count; j++)
                {
                    References[Path.GetFileName(files[i])].Remove(toBeRemoved[j]);
                }

                File.WriteAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references"), References[Path.GetFileName(files[i])]);
            }

            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine();
            Console.WriteLine("Exporting modules and rendering manuals...");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Gray;


            Directory.CreateDirectory(Path.Combine(rootPath, "Modules"));

            VectSharp.Markdown.MarkdownRenderer renderer = new VectSharp.Markdown.MarkdownRenderer() { BaseFontSize = 12 };

            Func<string, string, (string, bool)> imageUriResolver = renderer.ImageUriResolver;

            List<string> imagesToDelete = new List<string>();

            Dictionary<string, string> imageCache = new Dictionary<string, string>();

            renderer.ImageUriResolver = (imageUri, baseUri) =>
            {
                if (!imageCache.TryGetValue(baseUri + "|||" + imageUri, out string cachedImage))
                {
                    if (!imageUri.StartsWith("data:"))
                    {
                        bool wasDownloaded;

                        (cachedImage, wasDownloaded) = imageUriResolver(imageUri, baseUri);

                        if (wasDownloaded)
                        {
                            imagesToDelete.Add(cachedImage);
                        }

                        imageCache.Add(baseUri + "|||" + imageUri, cachedImage);
                    }
                    else
                    {
                        string tempFile = Path.GetTempFileName();
                        if (File.Exists(tempFile))
                        {
                            File.Delete(tempFile);
                        }

                        Directory.CreateDirectory(tempFile);

                        string uri = imageUri;

                        string mimeType = uri.Substring(uri.IndexOf(":") + 1, uri.IndexOf(";") - uri.IndexOf(":") - 1);

                        string type = uri.Substring(uri.IndexOf(";") + 1, uri.IndexOf(",") - uri.IndexOf(";") - 1);

                        if (mimeType == "image/svg+xml")
                        {
                            int offset = uri.IndexOf(",") + 1;

                            string data;

                            switch (type)
                            {
                                case "base64":
                                    data = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(uri.Substring(offset)));
                                    break;
                            }
                        }

                        VectSharp.Page pag = VectSharp.SVG.Parser.ParseImageURI(imageUri, true);
                        VectSharp.SVG.SVGContextInterpreter.SavereplacedVG(pag, Path.Combine(tempFile, "temp.svg"));

                        imagesToDelete.Add(Path.Combine(tempFile, "temp.svg"));

                        cachedImage = Path.Combine(tempFile, "temp.svg");

                        imageCache.Add(baseUri + "|||" + imageUri, cachedImage);
                    }
                }
                else
                {
                    Console.WriteLine("Fetching {0} from cache.", imageUri);
                }

                return (cachedImage, false);
            };


            List<ModuleHeader> moduleHeaders = new List<ModuleHeader>();

            foreach (TreeViewer.ModuleMetadata module in modules)
            {
                Directory.CreateDirectory(Path.Combine(rootPath, "Modules", module.Id));
                string modulePath = Path.Combine(rootPath, "Modules", module.Id, module.Id + ".v" + module.Version.ToString() + ".json.zip");
                module.Sign(privateKeyFile);
                module.Export(modulePath, true, true, true);

                string markdownSource = module.BuildReadmeMarkdown();

                Console.WriteLine("Rendering {0} - {1}", module.Name, module.Id);

                Markdig.Syntax.MarkdownDoreplacedent markdownDoreplacedent = Markdig.Markdown.Parse(markdownSource, new Markdig.MarkdownPipelineBuilder().UseGridTables().UsePipeTables().UseEmphasisExtras().UseGenericAttributes().UseAutoIdentifiers().UseAutoLinks().UseTaskLists().UseListExtras().UseCitations().UseMathematics().Build());

                VectSharp.Doreplacedent doc = renderer.Render(markdownDoreplacedent, out Dictionary<string, string> linkDestinations);
                VectSharp.PDF.PDFContextInterpreter.SaveAsPDF(doc, Path.Combine(rootPath, "Modules", module.Id, "Readme.pdf"), linkDestinations: linkDestinations);

                TreeViewer.ModuleMetadata.Install(modulePath, true, false);

                ModuleHeader header = new ModuleHeader(module);
                moduleHeaders.Add(header);
            }

            foreach (string imageFile in imagesToDelete)
            {
                System.IO.File.Delete(imageFile);
                System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(imageFile));
            }

            string serializedModuleHeaders = System.Text.Json.JsonSerializer.Serialize(moduleHeaders, Modules.DefaultSerializationOptions);
            using (FileStream fs = new FileStream(Path.Combine(rootPath, "Modules", "modules.json.gz"), FileMode.Create))
            {
                using (GZipStream compressionStream = new GZipStream(fs, CompressionLevel.Optimal))
                {
                    using (StreamWriter sw = new StreamWriter(compressionStream))
                    {
                        sw.Write(serializedModuleHeaders);
                    }
                }
            }

            using (StreamWriter sw = new StreamWriter(Path.Combine(rootPath, "Modules", "Readme.md")))
            {
                sw.WriteLine("# Module repository");
                sw.WriteLine();
                sw.WriteLine("This folder contains a collection of modules maintained by the developer(s) of TreeViewer. All the modules are signed and tested before being included in this repository.");
                sw.WriteLine();
                sw.WriteLine("The modules can be loaded or installed by using the `Load from repository...` or `Install from repository...` options in the module manager window.");
                sw.WriteLine("Alternatively, the module `json.zip` files can be downloaded and loaded or installed manually using the `Load...` or `Install...` options.");
                sw.WriteLine();
                sw.WriteLine("Click on the name of any module to open the folder containing the module's manual and `json.zip` file.");
                sw.WriteLine();
                sw.WriteLine("## List of currently available modules");
                sw.WriteLine();

                foreach (ModuleHeader header in moduleHeaders)
                {
                    sw.WriteLine("<br />");
                    sw.WriteLine();
                    sw.WriteLine("### [" + header.Name + "](" + header.Id + ")");
                    sw.WriteLine();
                    sw.WriteLine("_Version " + header.Version.ToString() + ", by " + header.Author + "_");
                    sw.WriteLine();
                    sw.WriteLine("**Description**: " + header.HelpText);
                    sw.WriteLine();
                    sw.WriteLine("**Module type**: " + header.ModuleType.ToString());
                    sw.WriteLine();
                    sw.WriteLine("**Module ID**: `" + header.Id + "`");
                    sw.WriteLine();
                }
            }

            return 0;
        }

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

static async Task Main(string[] args)
        {
            ConsoleColor defaultBackground = Console.BackgroundColor;
            ConsoleColor defaultForeground = Console.ForegroundColor;

            Console.WriteLine();
            Console.WriteLine("MuPDFCore test suite");
            Console.WriteLine();
            Console.WriteLine("Loading tests...");

            replacedembly testreplacedembly = replacedembly.Getreplacedembly(typeof(MuPDFWrapperTests));

            Type[] types = testreplacedembly.GetTypes();

            List<(string, Func<Task>)> tests = new List<(string, Func<Task>)>();
            HashSet<string> filesToDeploy = new HashSet<string>();

            for (int i = 0; i < types.Length; i++)
            {
                bool found = false;

                Attribute[] typeAttributes = Attribute.GetCustomAttributes(types[i]);

                foreach (Attribute attr in typeAttributes)
                {
                    if (attr is TestClreplacedAttribute)
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                {
                    MethodInfo[] methods = types[i].GetMethods(BindingFlags.Public | BindingFlags.Instance);

                    foreach (MethodInfo method in methods)
                    {
                        bool foundMethod = false;

                        foreach (Attribute attr in method.GetCustomAttributes())
                        {
                            if (attr is TestMethodAttribute)
                            {
                                foundMethod = true;
                            }

                            if (attr is DeploymenreplacedemAttribute dia)
                            {
                                filesToDeploy.Add(dia.Path);
                            }
                        }

                        if (foundMethod)
                        {
                            Type type = types[i];

                            tests.Add((types[i].Name + "." + method.Name, async () =>
                            {
                                object obj = Activator.CreateInstance(type);
                                object returnValue = method.Invoke(obj, null);

                                if (returnValue is Task task)
                                {
                                    await task;
                                }
                            }
                            ));
                        }
                    }
                }
            }

            int longestTestNameLength = (from el in tests select el.Item1.Length).Max();

            Console.WriteLine();
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.Write("  Found {0} tests.  ", tests.Count.ToString());
            Console.BackgroundColor = defaultBackground;
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("{0} files will be deployed:", filesToDeploy.Count.ToString());

            foreach (string sr in filesToDeploy)
            {
                Console.WriteLine("    " + sr);
            }

            Console.WriteLine();

            string deploymentPath = Path.GetTempFileName();
            File.Delete(deploymentPath);
            Directory.CreateDirectory(deploymentPath);

            foreach (string sr in filesToDeploy)
            {
                File.Copy(sr, Path.Combine(deploymentPath, Path.GetFileName(sr)));
            }

            string originalCurrentDirectory = Directory.GetCurrentDirectory();
            Directory.SetCurrentDirectory(deploymentPath);

            Console.WriteLine("Deployment completed.");
            Console.WriteLine();
            Console.WriteLine("Running tests...");
            Console.WriteLine();

            List<(string, Func<Task>)> failedTests = new List<(string, Func<Task>)>();

            for (int i = 0; i < tests.Count; i++)
            {
                Console.Write(tests[i].Item1 + new string(' ', longestTestNameLength - tests[i].Item1.Length + 1));

                bool failed = false;

                Stopwatch sw = Stopwatch.StartNew();

                try
                {
                    await tests[i].Item2();
                    sw.Stop();
                }
                catch (Exception ex)
                {
                    sw.Stop();
                    failed = true;
                    failedTests.Add(tests[i]);

                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.Write("   Failed    ");
                    Console.BackgroundColor = defaultBackground;

                    Console.Write("    {0}ms", sw.ElapsedMilliseconds.ToString());

                    Console.WriteLine();

                    while (ex.InnerException != null)
                    {
                        Console.WriteLine(ex.Message);
                        ex = ex.InnerException;
                    }

                    Console.WriteLine(ex.Message);
                }

                if (!failed)
                {
                    Console.BackgroundColor = ConsoleColor.Green;
                    Console.Write("  Succeeded  ");
                    Console.BackgroundColor = defaultBackground;
                    Console.Write("    {0}ms", sw.ElapsedMilliseconds.ToString());
                }

                Console.WriteLine();
            }

            Console.WriteLine();

            if (failedTests.Count < tests.Count)
            {
                Console.BackgroundColor = ConsoleColor.Green;
                Console.Write("  {0} tests succeeded  ", tests.Count - failedTests.Count);
                Console.BackgroundColor = defaultBackground;
                Console.WriteLine();
            }

            if (failedTests.Count > 0)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.Write("  {0} tests failed  ", failedTests.Count);
                Console.BackgroundColor = defaultBackground;
                Console.WriteLine();

                Console.WriteLine();
                Console.WriteLine("Failed tests:");
                Console.ForegroundColor = ConsoleColor.Red;

                for (int i= 0; i < failedTests.Count; i++)
                {
                    Console.WriteLine("    {0}", failedTests[i].Item1);
                }

                Console.WriteLine();
                Console.ForegroundColor = defaultForeground;

                Console.WriteLine();
                Console.WriteLine("The failed tests will now be repeated one by one.");

                for (int i = 0; i < failedTests.Count; i++)
                {
                    Console.WriteLine();
                    Console.WriteLine("Press any key to continue...");
                    Console.WriteLine();
                    Console.ReadKey();
                    Console.Write(failedTests[i].Item1 + new string(' ', longestTestNameLength - failedTests[i].Item1.Length + 1));

                    bool failed = false;

                    try
                    {
                        await failedTests[i].Item2();
                    }
                    catch (Exception ex)
                    {
                        failed = true;

                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.Write("   Failed    ");
                        Console.BackgroundColor = defaultBackground;

                        Console.WriteLine();

                        while (ex.InnerException != null)
                        {
                            Console.WriteLine(ex.Message);
                            ex = ex.InnerException;
                        }

                        Console.WriteLine(ex.Message);
                    }

                    if (!failed)
                    {
                        Console.BackgroundColor = ConsoleColor.Green;
                        Console.Write("  Succeeded  ");
                        Console.BackgroundColor = defaultBackground;
                    }

                    Console.WriteLine();
                }
            }

            Directory.SetCurrentDirectory(originalCurrentDirectory);
            Directory.Delete(deploymentPath, true);
        }

19 Source : TestAmbientOcclusion.cs
with MIT License
from Arlorean

[OneTimeSetUp]
        public void SetUp() {
            Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory);
        }

19 Source : TestBase.cs
with Apache License 2.0
from aspnet

private int RunWebServerViaEngine(string serverName, string applicationName, string configFileName, bool https)
        {
            int port = GetAvailablePort(https);
            string scheme = https ? "https" : "http";

            string sourceDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            string targetDirectory = BuildTargetDirectory(
                sourceDirectory,
                configFileName,
                applicationName,
                scheme,
                port);

            Directory.SetCurrentDirectory(targetDirectory);

            var options = new StartOptions(scheme + "://localhost:" + port + "/")
            {
                ServerFactory = serverName,
                AppStartup = applicationName,
            };
            options.Settings["boot"] = "Domain";

            IDisposable server = WebApp.Start(options);

            _disposing.Token.Register(() =>
            {
                server.Dispose();
                try
                {
                    Directory.Delete(targetDirectory, true);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Cleanup error {0}", ex.Message));
                }
            });

            return port;
        }

19 Source : TestBase.cs
with Apache License 2.0
from aspnet

private int RunWebServerSystemWeb(string applicationName, string configFileName, bool https)
        {
            var tcs = new TaskCompletionSource<object>();

            int port = GetAvailablePort(https);

            string sourceDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            string targetDirectory = BuildTargetDirectory(
                sourceDirectory,
                configFileName,
                applicationName,
                https ? "https" : "http",
                port);

            Directory.SetCurrentDirectory(targetDirectory);

            string targetHostConfig = Path.Combine(targetDirectory, "ApplicationHost.config");

            string programFile32 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
            string iisExpressExe = Path.Combine(programFile32, "IIS Express", "iisexpress.exe");

            var info = new ProcessStartInfo
            {
                WorkingDirectory = targetDirectory,
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                ErrorDialog = false,
                CreateNoWindow = false,
                FileName = iisExpressExe,
                Arguments = "/config:\"" + targetHostConfig + "\" /trace:error",
            };

            // Log.Debug("Executing {0}", Definition.Command);
            Process process = Process.Start(info);

            process.OutputDataReceived += OutputDataReceived;
            process.ErrorDataReceived += OutputDataReceived;
            process.Exited += (a, b) => tcs.TrySetResult(null);
            process.EnableRaisingEvents = true;

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            _disposing.Token.Register(() =>
            {
                tcs.Task.Wait(250);
                if (!process.HasExited)
                {
                    process.Kill();
                    tcs.Task.Wait();
                }
                try
                {
                    Directory.Delete(targetDirectory, true);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Cleanup error {0}", ex.Message));
                }
            });

            // Wait for the server to get started.
            Thread.Sleep(1000);

            return port;
        }

19 Source : CD.cs
with BSD 3-Clause "New" or "Revised" License
from aura-systems

public override ReturnInfo Execute(List<string> arguments)
        {
            string dir = arguments[0];
            try
            {
                if (dir == "..")
                {
                    Directory.SetCurrentDirectory(Kernel.current_directory);
                    var root = Kernel.vFS.GetDirectory(Kernel.current_directory);
                    if (Kernel.current_directory == Kernel.current_volume)
                    {
                    }
                    else
                    {
                        Kernel.current_directory = root.mParent.mFullPath;
                    }
                }
                else if (dir == Kernel.current_volume)
                { 
                    Kernel.current_directory = Kernel.current_volume;
                }
                else
                {
                    if (Directory.Exists(Kernel.current_directory + dir))
                    {
                        Directory.SetCurrentDirectory(Kernel.current_directory);
                        Kernel.current_directory = Kernel.current_directory + dir + @"\";
                    }
                    else if (File.Exists(Kernel.current_directory + dir))
                    {
                        L.Text.Display("errorthisisafile");
                    }
                    else
                    {
                        L.Text.Display("directorydoesntexist");
                    }
                }
                return new ReturnInfo(this, ReturnCode.OK);
            }
            catch (Exception ex)
            {
                return new ReturnInfo(this, ReturnCode.ERROR, ex.Message);
            }
        }

19 Source : Logout.cs
with BSD 3-Clause "New" or "Revised" License
from aura-systems

public static void c_Logout()
        {
            Kernel.Logged = false;
            Kernel.userLevelLogged = "";
            Kernel.userLogged = "";
            Directory.SetCurrentDirectory(Kernel.current_directory);
            Kernel.current_directory = Kernel.current_volume;
            Console.Clear();
        }

19 Source : FormBackground.cs
with MIT License
from AutoItConsulting

private void TimerHandleOptionsChangeEvent()
        {
            // Lock so no chance of receiving another new options file during processing
            lock (_namedPiperServerThreadLock)
            {
                if (_eventNewOptionsAvailable.WaitOne(0))
                {
                    _eventNewOptionsAvailable.Reset();

                    // Save data
                    _osdBackgroundDir = _namedPipeXmlPayload.OsdBackgroundDir;
                    _options = _namedPipeXmlPayload.Options;

                    // Change fields based on updated options data
                    OptionsXmlOptionsObjectToFields(_options);

                    // Change the working dir to match the last AutoIt.OSDBackground.exe that was run
                    Directory.SetCurrentDirectory(_namedPipeXmlPayload.OsdBackgroundWorkingDir);

                    // Redraw the background and progress bar (size and/or color might have new options)
                    RefreshBackgroundImage(true);
                    ProgressBarRedraw();
                }
            }
        }

19 Source : FileSystemArchive.cs
with GNU Lesser General Public License v2.1
from axiom3d

protected void changeDirectory(string dir)
        {
#if !(SILVERLIGHT || WINDOWS_PHONE)
            Directory.SetCurrentDirectory(dir);
#else
			CurrentDirectory = dir;
#endif
        }

19 Source : UnitTest.cs
with MIT License
from Azure-Samples

private static async Task RunSampleAsync(string service, string project, string path)
        {
            Console.WriteLine($"Service: {service}, Project: {project}, File: {path}");

            var DLL = replacedembly.LoadFrom(path);

            foreach (Type type in DLL.GetExportedTypes())
            {
                Directory.SetCurrentDirectory(Path.GetDirectoryName(path));
                foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
                {
                    var paras = new List<string>();
                    foreach (var para in method.GetParameters())
                    {
                        string paraName = $"{service}." + para.Name;

                        if (!TestContext.Properties.ContainsKey(paraName))
                        {
                            throw new Exception($"The configuration '{paraName}' is missing.");
                        }

                        paras.Add(TestContext.Properties[paraName].ToString());
                    }

                    Console.WriteLine($"{project}: {method.Name}");

                    if (method.ReturnType == typeof(Task))
                    {
                        await(Task)method.Invoke(null, paras.ToArray());
                    }
                    else
                    {
                        method.Invoke(null, paras.ToArray());
                    }

                    // Delay one second to control TPS
                    await Task.Delay(1000);
                }
            }

            Console.WriteLine();
        }

19 Source : CleanUp.cs
with MIT License
from AzureAD

[InlineData("webapp2\\webapp2-singleorg", "dotnet new webapp --auth SingleOrg")]
        [InlineData("webapp2\\webapp2-singleorg-callsgraph", "dotnet new webapp --auth SingleOrg --calls-graph")]
        //[InlineData("webapp2\\webapp2-singleorg-callswebapi", "dotnet new webapp2 --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("webapp2\\webapp2-b2c", "dotnet new webapp --auth IndividualB2C")]
        //[InlineData("webapp2\\webapp2-b2c-callswebapi", "dotnet new webapp2 --auth IndividualB2C --called-api-url \"https://localhost:44332/api/todolist\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/tasks/read\"")]
        //[InlineData("webapi2\\webapi2-noauth", "dotnet new webapi2")]
        [InlineData("webapi2\\webapi2-singleorg", "dotnet new webapi --auth SingleOrg")]
        //[InlineData("webapi2\\webapi2-singleorg-callsgraph", "dotnet new webapi2 --auth SingleOrg --calls-graph")]
        //[InlineData("webapi2\\webapi2-singleorg-callswebapi", "dotnet new webapi2 --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("webapi2\\webapi2-b2c", "dotnet new webapi --auth IndividualB2C")]
        //[InlineData("webapi2\\webapi2-b2c-callswebapi", "dotnet new webapi2 --auth IndividualB2C --called-api-url \"https://localhost:44332/api/todolist\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/tasks/read\"")]
        //[InlineData("mvc2\\mvc2-noauth", "dotnet new mvc2")]
        [InlineData("mvc2\\mvc2-singleorg", "dotnet new mvc --auth SingleOrg")]
        //[InlineData("mvc2\\mvc2-singleorg-callsgraph", "dotnet new mvc2 --auth SingleOrg --calls-graph")]
        //[InlineData("mvc2\\mvc2-singleorg-callswebapi", "dotnet new mvc2 --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("mvc2\\mvc2-b2c", "dotnet new mvc --auth IndividualB2C")]
        //[InlineData("mvc2\\mvc2-b2c-callswebapi", "dotnet new mvc2 --auth IndividualB2C --called-api-url \"https://localhost:44332/api/todolist\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/tasks/read\"")]
        //[InlineData("blazorserver2\\blazorserver2-noauth", "dotnet new blazorserver2")]
        //[InlineData("blazorserver2\\blazorserver2-singleorg", "dotnet new blazorserver2 --auth SingleOrg")]
        //[InlineData("blazorserver2\\blazorserver2-singleorg-callsgraph", "dotnet new blazorserver2 --auth SingleOrg --calls-graph")]
        //[InlineData("blazorserver2\\blazorserver2-singleorg-callswebapi", "dotnet new blazorserver2 --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        //[InlineData("blazorserver2\\blazorserver2-b2c", "dotnet new blazorserver2 --auth IndividualB2C")]
        //[InlineData("blazorserver2\\blazorserver2-b2c-callswebapi", "dotnet new blazorserver2 --auth IndividualB2C --called-api-url \"https://localhost:44332/api/todolist\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/tasks/read\"")]
        //[InlineData("blazorwasm2\\blazorwasm2-noauth", "dotnet new blazorwasm2")]
        //[InlineData("blazorwasm2\\blazorwasm2-singleorg", "dotnet new blazorwasm2 --auth SingleOrg")]
        //[InlineData("blazorwasm2\\blazorwasm2-singleorg-callsgraph", "dotnet new blazorwasm2 --auth SingleOrg --calls-graph")]
        //[InlineData("blazorwasm2\\blazorwasm2-singleorg-callswebapi", "dotnet new blazorwasm2 --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        //[InlineData("blazorwasm2\\blazorwasm2-singleorg-hosted", "dotnet new blazorwasm2 --auth SingleOrg  --hosted")]
        //[InlineData("blazorwasm2\\blazorwasm2-singleorg-callsgraph-hosted", "dotnet new blazorwasm2 --auth SingleOrg --calls-graph --hosted")]
        //[InlineData("blazorwasm2\\blazorwasm2-singleorg-callswebapi-hosted", "dotnet new blazorwasm2 --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\" --hosted")]
        //[InlineData("blazorwasm2\\blazorwasm2-b2c", "dotnet new blazorwasm2 --auth IndividualB2C")]
        //[InlineData("blazorwasm2\\blazorwasm2-b2c-hosted", "dotnet new blazorwasm2 --auth IndividualB2C  --hosted")]
        //[InlineData("blazorwasm2\\blazorwasm2-b2c-callswebapi-hosted", "dotnet new blazorwasm2 --auth IndividualB2C --called-api-url \"https://localhost:44332/api/todolist\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/tasks/read\" --hosted")]
        //[Theory()]
        [Theory(Skip = "run manually")]
        public async Task CleanupApp(string folder, string command)
        {
            // Create the folder
            string executionFolder = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            string folderToCreate = Path.Combine(executionFolder, "Tests", folder);

            string currentDirectory = Directory.GetCurrentDirectory();

            // Run the tool
            try
            {
                Directory.SetCurrentDirectory(folderToCreate);

                string tenantId = folder.Contains("b2c") ? "fabrikamb2c.onmicrosoft.com" : null;
                await Program.Main(tenantId: tenantId, unregister:true);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
            }
        }

19 Source : E2ETests.cs
with MIT License
from AzureAD

[InlineData("webapp\\webapp-noauth", "dotnet new webapp")]
        [InlineData("webapp\\webapp-singleorg", "dotnet new webapp --auth SingleOrg")]
        [InlineData("webapp\\webapp-singleorg-callsgraph", "dotnet new webapp --auth SingleOrg --calls-graph")]
        [InlineData("webapp\\webapp-singleorg-callswebapi", "dotnet new webapp --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("webapp\\webapp-b2c", "dotnet new webapp --auth IndividualB2C")]
        [InlineData("webapp\\webapp-b2c-callswebapi", "dotnet new webapp --auth IndividualB2C --called-api-url \"https://fabrikamb2chello.azurewebsites.net/hello\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read\"")]
        [InlineData("webapi\\webapi-noauth", "dotnet new webapi")]
        [InlineData("webapi\\webapi-singleorg", "dotnet new webapi --auth SingleOrg")]
        [InlineData("webapi\\webapi-singleorg-callsgraph", "dotnet new webapi --auth SingleOrg --calls-graph")]
        [InlineData("webapi\\webapi-singleorg-callswebapi", "dotnet new webapi --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("webapi\\webapi-b2c", "dotnet new webapi --auth IndividualB2C")]
        [InlineData("mvc\\mvc-noauth", "dotnet new mvc")]
        [InlineData("mvc\\mvc-singleorg", "dotnet new mvc --auth SingleOrg")]
        [InlineData("mvc\\mvc-singleorg-callsgraph", "dotnet new mvc --auth SingleOrg --calls-graph")]
        [InlineData("mvc\\mvc-singleorg-callswebapi", "dotnet new mvc --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("mvc\\mvc-b2c", "dotnet new mvc --auth IndividualB2C")]
        [InlineData("mvc\\mvc-b2c-callswebapi", "dotnet new mvc --auth IndividualB2C --called-api-url \"https://fabrikamb2chello.azurewebsites.net/hello\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read\"")]
        [InlineData("blazorserver\\blazorserver-noauth", "dotnet new blazorserver")]
        [InlineData("blazorserver\\blazorserver-singleorg", "dotnet new blazorserver --auth SingleOrg")]
        [InlineData("blazorserver\\blazorserver-singleorg-callsgraph", "dotnet new blazorserver --auth SingleOrg --calls-graph")]
        [InlineData("blazorserver\\blazorserver-singleorg-callswebapi", "dotnet new blazorserver --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("blazorserver\\blazorserver-b2c", "dotnet new blazorserver --auth IndividualB2C")]
        [InlineData("blazorserver\\blazorserver-b2c-callswebapi", "dotnet new blazorserver --auth IndividualB2C --called-api-url \"https://fabrikamb2chello.azurewebsites.net/hello\" --called-api-scopes \"https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read\"")]
        [InlineData("blazorwasm\\blazorwasm-noauth", "dotnet new blazorwasm")]
        [InlineData("blazorwasm\\blazorwasm-singleorg", "dotnet new blazorwasm --auth SingleOrg")]
        [InlineData("blazorwasm\\blazorwasm-singleorg-callsgraph", "dotnet new blazorwasm --auth SingleOrg --calls-graph")]
        [InlineData("blazorwasm\\blazorwasm-singleorg-callswebapi", "dotnet new blazorwasm --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\"")]
        [InlineData("blazorwasm\\blazorwasm-singleorg-hosted", "dotnet new blazorwasm --auth SingleOrg  --hosted")]
        [InlineData("blazorwasm\\blazorwasm-singleorg-callsgraph-hosted", "dotnet new blazorwasm --auth SingleOrg --calls-graph --hosted")]
        [InlineData("blazorwasm\\blazorwasm-singleorg-callswebapi-hosted", "dotnet new blazorwasm --auth SingleOrg --called-api-url \"https://graph.microsoft.com/beta/me\" --called-api-scopes \"user.read\" --hosted")]
        [InlineData("blazorwasm\\blazorwasm-b2c", "dotnet new blazorwasm --auth IndividualB2C")]
        [InlineData("blazorwasm\\blazorwasm2-b2c-hosted", "dotnet new blazorwasm --auth IndividualB2C  --hosted")]
        [Theory]
        public async Task TestNewAppEndToEnd(string folder, string command)
        {
            // Create the folder
            string executionFolder = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            executionFolder = "C:\\temp\\test-provisionning";
            string folderToCreate = Path.Combine(executionFolder, "Tests", folder);

            // dotnet new command to create the project
            RunProcess(command, folderToCreate, " --force");

            // Add a secret if needed
            if (command.Contains("--calls"))
            {
                try
                {
                    RunProcess("dotnet user-secrets init", 
                        command.Containts("--hosted") ? Path.Combine(folderToCreate, "Server") : folderToCreate;
                }
                catch
                {
                    // Silent catch
                }
            }

            string currentDirectory = Directory.GetCurrentDirectory();

            // Run the tool
            try
            {
                Directory.SetCurrentDirectory(folderToCreate);
                string tenantId = folder.Contains("b2c") ?
                    "fabrikamb2c.onmicrosoft.com" :
                    "testprovisionningtool.onmicrosoft.com";
                await Program.Main(tenantId: tenantId, username: null, clientId: null,
                    folder: null, clientSecret: null, unregister: null, susiPolicyId: null, apiClientId:null, appIdUri:null);
            }
            catch (Exception ex)
            {
                testOutput.WriteLine(ex.ToString());
                replacedert.True(false);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
            }

            testOutput.WriteLine($"{folderToCreate}");
        }

19 Source : E2ETests.cs
with MIT License
from AzureAD

public async Task TestUpdateAppEndToEnd(string folder, string command)
        {
            // Create the folder
            string executionFolder = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            executionFolder = "C:\\temp\\test-provisionning";
            string folderToCreate = Path.Combine(executionFolder, "Tests", folder);

            // dotnet new command to create the project
            RunProcess(command, folderToCreate, " --force");

            // Add a secret if needed
            if (command.Contains("--calls"))
            {
                try
                {
                    RunProcess("dotnet user-secrets init", folderToCreate);
                }
                catch
                {
                    // Silent catch
                }
            }

            string currentDirectory = Directory.GetCurrentDirectory();

            // Run the tool
            try
            {
                Directory.SetCurrentDirectory(folderToCreate);

                Directory.SetCurrentDirectory(folderToCreate);
                string tenantId = folder.Contains("b2c") ?
                    "fabrikamb2c.onmicrosoft.com" :
                    "testprovisionningtool.onmicrosoft.com";
                await Program.Main(tenantId: tenantId, username: null, clientId: null,
                    folder: null, clientSecret: null, unregister: null, susiPolicyId: null, apiClientId: null, appIdUri: null);
            }
            catch (Exception ex)
            {
                testOutput.WriteLine(ex.ToString());
                replacedert.True(false);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
            }

            testOutput.WriteLine($"{folderToCreate}");
        }

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

public static void GetCd(string [] param)
        {
            try
            {
                if (Directory.Exists(param[0]))
                    Directory.SetCurrentDirectory(param[0]);
                Console.WriteLine("[*] Current directory {0}", Directory.GetCurrentDirectory());
            }
            catch (Exception)
            {
                Console.WriteLine("[*] Error executing cd");
            }
        }

19 Source : Program.cs
with The Unlicense
from BAndysc

private static void FixCurrentDirectory()
        {
            var exePath = new FileInfo(replacedembly.GetExecutingreplacedembly().Location);
            if (exePath.Directory != null)
                Directory.SetCurrentDirectory(exePath.Directory.FullName);
        }

19 Source : Program.cs
with MIT License
from bcssov

private static void Main()
        {
            short indent = 1;
            var sb = new StringBuilder();
            sb.AppendLine("// This file was automatically generated");
            sb.AppendLine("// Do not modify.");
            sb.AppendLine("// Use the LocalizationResourceGenerator instead.");
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("");
            sb.AppendLine("namespace IronyModManager.Shared");
            sb.AppendLine("{");
            sb.AppendLine(FormatIndentation(indent, "public static clreplaced LocalizationResources"));
            sb.AppendLine(FormatIndentation(indent, "{"));

            var exePath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            Directory.SetCurrentDirectory(exePath);

            var obj = JObject.Parse(File.ReadAllText(LocalizationResourcePath));

            static void ParseLocalization(StringBuilder sb, short indent, JProperty property, List<string> prefixes, short prevIndent)
            {
                var origIndent = indent;
                indent++;
                sb.AppendLine(FormatIndentation(indent, $"public static clreplaced {property.Name}"));
                sb.AppendLine(FormatIndentation(indent, "{"));

                if (property.Value.Type == JTokenType.Object)
                {
                    short propIndent = (short)(indent + 1);
                    prefixes.Add(property.Name);
                    sb.AppendLine(FormatIndentation(propIndent, $"public const string Prefix = \"{string.Join(".", prefixes)}.\";"));
                    foreach (var item in property.Value.Children<JProperty>())
                    {
                        if (item.Value.Type == JTokenType.Object)
                        {
                            ParseLocalization(sb, indent, item, new List<string>(prefixes), origIndent);
                        }
                        else
                        {
                            ParseProperty(sb, propIndent, item);
                        }
                    }
                }

                sb.AppendLine(FormatIndentation(indent, "}"));
            };

            static void ParseProperty(StringBuilder sb, short indent, JProperty property)
            {
                sb.AppendLine(FormatIndentation(indent, $"public const string {property.Name} = Prefix + \"{property.Name}\";"));
            }

            foreach (var o in obj.Children<JProperty>())
            {
                ParseLocalization(sb, indent, o, new List<string>(), indent);
            }
            sb.AppendLine(FormatIndentation(indent, "}"));
            sb.AppendLine("}");
            File.WriteAllText(LocalizationResourceOutPath, sb.ToString());
        }

19 Source : Program.cs
with MIT License
from Beffyman

static void Main()
		{
			string rootDir = Path.GetDirectoryName(typeof(Program).replacedembly.Location);
			Console.WriteLine($"Root Dir: {rootDir}");
			Directory.SetCurrentDirectory(rootDir);

			Console.WriteLine("Starting Generator");
			var webApp = GoUpUntilDirectory(WEBAPP, FAILURE_DIR);
			var blazor = GoUpUntilDirectory(BLAZOR, FAILURE_DIR);
			var functions = GoUpUntilDirectory(FUNCTIONS, FAILURE_DIR);
			var functions2 = GoUpUntilDirectory(FUNCTIONS2, FAILURE_DIR);

			if (!(Generate(webApp)
				&& Generate(blazor)
				&& Generate(functions)
				&& Generate(functions2)))
			{
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
			}

		}

19 Source : BigBlueButtonFacade.cs
with MIT License
from berkayalcin

public async Task StartAsync()
        {
            if (!_isDownloadWebcamVideo && !_isDownloadPresentation)
                throw new Exception("Either Presentaton or Desk-share Video Must Be Selected");

            if (!Directory.Exists(_outputDirectory))
                Directory.CreateDirectory(_outputDirectory);

            Directory.SetCurrentDirectory(_outputDirectory);

            bool downloadVideoResponse = false,
                downloadPresentationResponse = false,
                hasAudio = false;

            _webDriver = WebDriverFactory.Create(_webDriverType, _url);


            _bigBlueButtonDoreplacedentParser = new BigBlueButtonDoreplacedentParser(_webDriver, Options);

            var deskShareVideoName = $"{_outputFileName}-desk";
            var webcamVideoName = $"{_outputFileName}-webcam";
            var audioOutputName = $"{_outputFileName}-output";
            var presentationName = $"{_outputFileName}-presentation";
            var tmpPresentationName = $"{_outputFileName}-tmp";

            var downloadDeskShareThread = new Thread(() =>
            {
                if (_isDownloadDeskShareVideo)
                {
                    var response = DownloadVideo(deskShareVideoName).GetAwaiter().GetResult();
                    downloadVideoResponse = response.IsSuccess;
                }
            });

            var downloadWebcamThread = new Thread(() =>
            {
                if (_isDownloadWebcamVideo)
                {
                    var response = DownloadWebcam(webcamVideoName).GetAwaiter().GetResult();
                    hasAudio = response.IsSuccess;
                }
            });

            var downloadPresentationThread = new Thread(() =>
            {
                if (_isDownloadPresentation)
                {
                    var response = DownloadPresentation(tmpPresentationName).GetAwaiter().GetResult();
                    downloadPresentationResponse = response.IsSuccess;
                }
            });


            downloadDeskShareThread.Start();
            downloadWebcamThread.Start();
            downloadPresentationThread.Start();

            downloadWebcamThread.Join();
            downloadDeskShareThread.Join();
            downloadPresentationThread.Join();


            if (!downloadVideoResponse && !downloadPresentationResponse)
                throw new BigBlueButtonDoreplacedentException("Neither Video Nor Presentation Couldn't Be Downloaded.");


            var audioInputPath = AppDomainHelpers.GetPath(_outputDirectory, webcamVideoName, ".mp4");
            var audioOutputPath = AppDomainHelpers.GetPath(_outputDirectory, $"{audioOutputName}", ".mp3");
            var deskShareInputPath = AppDomainHelpers.GetPath(_outputDirectory, $"{deskShareVideoName}", ".mp4");
            var videoOutputPath = AppDomainHelpers.GetPath(_outputDirectory, _outputFileName, ".mp4");
            var presentationOutputPath = AppDomainHelpers.GetPath(_outputDirectory, presentationName, ".mp4");
            var tmpPresentationPath = AppDomainHelpers.GetPath(_outputDirectory, tmpPresentationName, ".mp4");
            if (downloadVideoResponse)
            {
                if (hasAudio)
                    await _videoService.ExtractAndAddAudio(audioInputPath, audioOutputPath, deskShareInputPath,
                        videoOutputPath, _outputDirectory, _isUseMulreplacedhread, true);
                else
                    File.Move(deskShareInputPath, videoOutputPath, true);
            }

            if (downloadPresentationResponse)
            {
                if (hasAudio)
                    await _videoService.ExtractAndAddAudio(audioInputPath, audioOutputPath, tmpPresentationPath,
                        presentationOutputPath, _outputDirectory, _isUseMulreplacedhread, true);
                else
                    File.Move(tmpPresentationPath, presentationOutputPath, true);
            }


            RemoveTempFiles(
                audioOutputName,
                deskShareVideoName,
                tmpPresentationName
            );
            _webDriver.Quit();
        }

19 Source : BigBlueButtonFacade.cs
with MIT License
from berkayalcin

private async Task<FacadeInnerResponseModel> DownloadPresentation(string presentationName)
        {
            Console.WriteLine("Downloading Presentation");
            var presentation = _bigBlueButtonDoreplacedentParser.GetPresentation();
            if (!presentation.IsSuccess)
                return new FacadeInnerResponseModel()
                {
                    ErrorMessage = ExceptionCodeConstants.NoPresentationFound,
                    IsSuccess = false
                };


            var tempDirectory = $"temp-{presentationName}";
            Directory.CreateDirectory(tempDirectory);
            Directory.SetCurrentDirectory(tempDirectory);

            var presentationItems = presentation.Items.ToList();

            Parallel.ForEach(presentationItems, presentationItem =>
            {
                var index = presentationItems.IndexOf(presentationItem);

                _fileDownloader.DownloadPngFileAsync(presentationItem.Source,
                    index.ToString(),
                    null,
                    null
                ).GetAwaiter().GetResult();
                presentationItems[index].LocalSource = $"{index}.png";
            });

            Directory.SetCurrentDirectory(Directory.GetParent(Directory.GetCurrentDirectory()).FullName);

            await _presentationService.CreatePresentation(presentationItems, tempDirectory, $"{presentationName}.mp4",
                null, true);


            return new FacadeInnerResponseModel()
            {
                IsSuccess = true
            };
        }

19 Source : PresentationService.cs
with MIT License
from berkayalcin

public async Task CreatePresentation(List<PresentationItem> presentationItems,
            string directory,
            string outputFileName,
            string audioPath = null,
            bool useMulreplacedhread = false)
        {
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            Directory.SetCurrentDirectory(directory);
            var tempOutput = $"temp_{outputFileName}";
            var threadCount = useMulreplacedhread ? Environment.ProcessorCount.ToString() : "1";
            await using var streamWriter = new StreamWriter("videoList.txt");

            var parallelLoopResult = Parallel.ForEach(presentationItems, (presentationItem, state, index) =>
            {
                var videoPath = $"{index}.mp4";
                var presentationItemOut = 1.0 / (presentationItem.Out - presentationItem.In);
                var duration = TimeSpan.FromSeconds(presentationItem.Out - presentationItem.In).ToString(@"hh\:mm\:ss");
                try
                {
                    var conversionResult = FFmpeg.Conversions.New()
                        .AddParameter($"-threads {threadCount}")
                        .AddParameter($"-framerate {presentationItemOut:0.00000}")
                        .AddParameter($"-i {presentationItem.LocalSource}")
                        .AddParameter("-vcodec libx264")
                        .AddParameter("-crf 27")
                        .AddParameter("-preset veryfast")
                        .AddParameter("-vf fps=5")
                        .AddParameter("-pix_fmt yuv420p")
                        .AddParameter("-ss 00:00:00")
                        .AddParameter($"-t {duration}")
                        .AddParameter(videoPath)
                        .SetOverwriteOutput(true)
                        .Start().GetAwaiter().GetResult();
                }
                catch (Exception e)
                {
                    throw;
                }

                File.Delete(presentationItem.LocalSource);
            });

            for (var i = 0; i < presentationItems.Count; i++)
            {
                var videoPath = $"{i}.mp4";
                await streamWriter.WriteLineAsync($"file '{videoPath}'");
            }

            streamWriter.Close();

            await FFmpeg.Conversions.New()
                .AddParameter("-f concat")
                .AddParameter("-safe 0")
                .AddParameter("-i videoList.txt -c copy")
                .AddParameter(tempOutput)
                .Start();


            if (!string.IsNullOrEmpty(audioPath))
            {
                await _videoService.AddAudio(tempOutput, audioPath, outputFileName);
                File.Delete(tempOutput);
                return;
            }


            for (int i = 0; i < presentationItems.Count; i++)
            {
                if (File.Exists($"{i}.mp4"))
                    File.Delete($"{i}.mp4");
                if (File.Exists($"{i}.png"))
                    File.Delete($"{i}.png");
            }

            File.Delete("videoList.txt");

            var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
            var newFileDestination = Path.Combine(parentDirectory, outputFileName);
            File.Move(tempOutput, newFileDestination, true);
            Thread.Sleep(4000);
            Directory.SetCurrentDirectory(Directory.GetParent(Directory.GetCurrentDirectory()).FullName);
            Directory.Delete(directory);
        }

19 Source : ProjectHelper.cs
with MIT License
from BionicFramework

public static void RestoreAdjustedDir() {
      if (adjustedDir != null) Directory.SetCurrentDirectory(adjustedDir);
    }

19 Source : ProjectHelper.cs
with MIT License
from BionicFramework

public static ProjectInfo[] GetProjectFiles(bool onParent = false) {
      var projectInfoList = GetProjectInfoList();
      if (projectInfoList.Length == 1 && projectInfoList[0].projectType != ProjectType.Standalone && !onParent) {
        adjustedDir = Directory.GetCurrentDirectory();
        Directory.SetCurrentDirectory(ToOSPath("../"));
        projectInfoList = GetProjectFiles(true);
      }

      return projectInfoList;
    }

19 Source : StartCommand.cs
with MIT License
from BionicFramework

private static int SetupBionic() {
      Logger.Info("Preparing your Bionic Project...");

      // 1. Get project file name
      var projectFiles = ProjectHelper.GetProjectFiles();
      if (projectFiles.IsNullOrEmpty()) {
        Logger.Error("No C# project found. Please make sure you are in the root of a C# project.");
        return 1;
      }

      var currentDir = Directory.GetCurrentDirectory();

      foreach (var pi in projectFiles) {
        if (pi.projectType == ProjectType.Unknown) continue;

        Directory.SetCurrentDirectory(pi.dir);

        if (pi.projectType != ProjectType.HostedServer) {
          // 2. Create App.scss
          var alreadyStarted = InitAppCss();

          if (alreadyStarted) {
            alreadyStarted = Prompt.GetYesNo(
              "Project seems to have already been started. Are you sure you want to continue?",
              false,
              promptColor: ConsoleColor.DarkGreen
            );
            if (!alreadyStarted) {
              Logger.Confirm("Ok! Bionic start canceled.");
              return 0;
            }
          }

          // 3. Inject App.css in index.html
          InjectAppCssInIndexHtml();

          // 4. Inject targets in .csproj
          IntroduceProjectTargets(pi);

          // 5. Install Bionic Templates
          InstallBionicTemplates();

          // 6. Add Bionic Extensions
          InstallBionicExtensions();

          // 7. Add Bionic Extension Injectable Attribute to Startup.cs
          UpdateStartup(pi);
        }
        else {
          // 1. Its Hosted ... Inject targets in .csproj
          var client = projectFiles.FirstOrDefault(p => p.projectType == ProjectType.HostedClient);
          if (client.filename == null) {
            Logger.Error("Unable to start project. Client directory for Hosted Blazor project was not found.");
            return 1;
          }

          IntroduceProjectTargets(pi, Path.GetRelativePath(pi.dir, client.dir));
        }

        Directory.SetCurrentDirectory(currentDir);
      }

      ProjectHelper.RestoreAdjustedDir();

      return 0;
    }

19 Source : StartCommand.cs
with MIT License
from BionicFramework

private static int SetupBionic() {
      Logger.Info("Preparing your Bionic Project...");

      // 1. Get project file name
      var projectFiles = ProjectHelper.GetProjectFiles();
      if (projectFiles.IsNullOrEmpty()) {
        Logger.Error("No C# project found. Please make sure you are in the root of a C# project.");
        return 1;
      }

      var currentDir = Directory.GetCurrentDirectory();

      foreach (var pi in projectFiles) {
        if (pi.projectType == ProjectType.Unknown) continue;

        Directory.SetCurrentDirectory(pi.dir);

        if (pi.projectType != ProjectType.HostedServer) {
          // 2. Create App.scss
          var alreadyStarted = InitAppCss();

          if (alreadyStarted) {
            alreadyStarted = Prompt.GetYesNo(
              "Project seems to have already been started. Are you sure you want to continue?",
              false,
              promptColor: ConsoleColor.DarkGreen
            );
            if (!alreadyStarted) {
              Logger.Confirm("Ok! Bionic start canceled.");
              return 0;
            }
          }

          // 3. Inject App.css in index.html
          InjectAppCssInIndexHtml();

          // 4. Inject targets in .csproj
          IntroduceProjectTargets(pi);

          // 5. Install Bionic Templates
          InstallBionicTemplates();

          // 6. Add Bionic Extensions
          InstallBionicExtensions();

          // 7. Add Bionic Extension Injectable Attribute to Startup.cs
          UpdateStartup(pi);
        }
        else {
          // 1. Its Hosted ... Inject targets in .csproj
          var client = projectFiles.FirstOrDefault(p => p.projectType == ProjectType.HostedClient);
          if (client.filename == null) {
            Logger.Error("Unable to start project. Client directory for Hosted Blazor project was not found.");
            return 1;
          }

          IntroduceProjectTargets(pi, Path.GetRelativePath(pi.dir, client.dir));
        }

        Directory.SetCurrentDirectory(currentDir);
      }

      ProjectHelper.RestoreAdjustedDir();

      return 0;
    }

19 Source : Program.cs
with MIT License
from blish-hud

[STAThread]
        private static void Main(string[] args) {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));

            // TODO: Get SetDllDirectory("") working so that we can protect ourselves from this
            HandleArcDps11Contingency();

            StartupArgs = args;
            var settings = Cli.Parse<ApplicationSettings>(args);

            if (settings.MainProcessId.HasValue) {
                // The only current subprocess is our DebugHelper
                RunDebugHelper(settings.MainProcessId.Value);
                return;
            }

            if (settings.CliExitEarly) return;

            EnableLogging();

            Logger.Debug("Launched from {launchDirectory} with args {launchOptions}.", Directory.GetCurrentDirectory(), string.Join(" ", args));

            string mutexName = string.IsNullOrEmpty(ApplicationSettings.Instance.MumbleMapName) ? $"{APP_GUID}" : $"{APP_GUID}:{ApplicationSettings.Instance.MumbleMapName}";
            using (Mutex singleInstanceMutex = new Mutex(true, mutexName, out bool ownsMutex)) {
                try {
                    if (!ownsMutex) {
                        // we don't own the mutex - try to acquire.
                        try {
                            if (!(ownsMutex = singleInstanceMutex.WaitOne(TimeSpan.Zero, true))) {
                                Logger.Warn("Blish HUD is already running!");
                                return;
                            }
                        } catch (AbandonedMutexException ex) {
                            // log exception, but mutex still acquired
                            Logger.Warn(ex, "Caught AbandonedMutexException, previous Blish HUD instance terminated non-gracefully.");
                        }
                    }

                    using (var game = new BlishHud()) {
                        game.Run();
                    }

                } finally {
                    if (ownsMutex) {
                        // only release if we acquired ownership
                        // .Dispose() only closes the wait handle 
                        // and doesn't release the mutex - this can
                        // cause AbandonedMutexException next run
                        singleInstanceMutex.ReleaseMutex();
                    }

                    if (RestartOnExit) {
                        var currentStartInfo = Process.GetCurrentProcess().StartInfo;
                        currentStartInfo.FileName = Application.ExecutablePath;
                        currentStartInfo.Arguments = string.Join(" ", StartupArgs);

                        Process.Start(currentStartInfo);
                    }
                }
            }
        }

19 Source : Program.cs
with GNU General Public License v2.0
from bp2008

static void Main()
		{
			string exePath = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
			Globals.Initialize(exePath);
			Directory.SetCurrentDirectory(Globals.ApplicationDirectoryBase);

			Application.ThreadException += Application_ThreadException;
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

			if (Environment.UserInteractive)
			{
				string replacedle = "DahuaSunriseSunset " + replacedembly.GetEntryreplacedembly().GetName().Version.ToString() + " Service Manager";
				Logger.Info(replacedle + " Startup");
				string ServiceName = "DahuaSunriseSunset";
				ButtonDefinition btnConfigure = new ButtonDefinition("Configure Service", btnConfigure_Click);
				ButtonDefinition btnSimulateSunrise = new ButtonDefinition("Simulate Sunrise", btnSimulateSunrise_Click);
				ButtonDefinition btnViewNextTimes = new ButtonDefinition("View rise/set", btnViewNextTimes_Click);
				ButtonDefinition btnSimulateSunset = new ButtonDefinition("Simulate Sunset", btnSimulateSunset_Click);
				ButtonDefinition[] customButtons = new ButtonDefinition[] { btnConfigure, btnSimulateSunrise, btnViewNextTimes, btnSimulateSunset };

				Application.Run(sm = new ServiceManager(replacedle, ServiceName, customButtons));
			}
			else
			{
				ServiceBase[] ServicesToRun;
				ServicesToRun = new ServiceBase[]
				{
				new DahuaSunriseSunsetService()
				};
				ServiceBase.Run(ServicesToRun);
			}
		}

19 Source : Bootstrapper.cs
with MIT License
from Bphots

protected override void Configure()
        {
            App.AppPath = AppDomain.CurrentDomain.BaseDirectory;
            Directory.SetCurrentDirectory(App.AppPath);

            var args = Environment.GetCommandLineArgs();

            try
            {
                var configurationSettings = new CustomConfigurationSettings();
                BpHelperConfigParser.PopulateConfigurationSettings(configurationSettings);
                UserDataConfigParser.PopulateUserDataSettings();
                App.CustomConfigurationSettings = configurationSettings;
                App.NextConfigurationSettings = configurationSettings;
            }
            catch (Exception)
            {
                //Ignored
            }
            
            if (args.Any(arg => arg.ToLower() == "/log"))
            {
                LogUtil.NoLog = false;
                OcrEngine.Debug = true;
            }

            if (args.Any(arg => arg.ToLower() == "/devtool"))
            {
                App.DevTool = true;
            }

            if (args.Any(arg => arg.ToLower() == "/debugv2"))
            {
                LogUtil.NoLog = false;
                OcrEngine.Debug = true;
                App.Debug = true;
            }

            if (args.Any(arg => arg.ToLower() == "/debugv2"))
            {
                LogUtil.NoLog = false;
                OcrEngine.Debug = true;
                App.Debug = true;
            }

            if (args.Any(arg => arg.ToLower() == "/forceupdate"))
                App.ForceUpdate = true;

            try
            {
                if (args.Any(arg => arg.ToLower().StartsWith("/upload")))
                {
                    var dateString = args.First(arg => arg.ToLower().StartsWith("/upload")).Substring(7);
                    App.UploadMinimumAcceptableTime = DateTime.Parse(dateString).ToUniversalTime();
                }
                else
                    App.UploadMinimumAcceptableTime = Const.HotsweekAcceptTime;
            }
            catch
            {
                App.UploadMinimumAcceptableTime = DateTime.Now;
            }

            if (args.Any(arg => arg.ToLower() == "/errortest"))
            {
                ErrorView _errorView = new ErrorView(ViewModelBase.L("NoMatchResolution"),
                    ViewModelBase.L("MSG_NoMatchResolution"), "https://www.bphots.com/articles/errors/test");
                _errorView.ShowDialog();
            }
        }

19 Source : manager.cs
with BSD 2-Clause "Simplified" License
from chengse66

private void locations_click(object o, EventArgs e)
	{
		using (FolderBrowserDialog folder = new FolderBrowserDialog())
		{
			folder.SelectedPath = Directory.GetCurrentDirectory();

			if (DialogResult.OK == folder.ShowDialog())
			{
				Directory.SetCurrentDirectory(folder.SelectedPath);

				locations.Text = locations.Text + folder.SelectedPath + "\r\n";
			}
		}
	}

19 Source : DirectoryHelper.cs
with GNU Lesser General Public License v3.0
from cnAbp

public static IDisposable ChangeCurrentDirectory(string targetDirectory)
        {
            var currentDirectory = Directory.GetCurrentDirectory();

            if (currentDirectory.Equals(targetDirectory, StringComparison.OrdinalIgnoreCase))
            {
                return NullDisposable.Instance;
            }

            Directory.SetCurrentDirectory(targetDirectory);

            return new DisposeAction(() =>
            {
                Directory.SetCurrentDirectory(currentDirectory);
            });
        }

19 Source : FileHelper.cs
with MIT License
from cq-panda

public static void FolderCreate(string OrignFolder, string NewFloder)
        {
            Directory.SetCurrentDirectory(OrignFolder.ReplacePath());
            Directory.CreateDirectory(NewFloder.ReplacePath());
        }

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

private static void Main(string[] args)
		{
			StartTime = DateTime.Now;
			var windows = Type.GetType("Mono.Runtime") == null;
			//var ci = new CultureInfo("en-GB");
			//System.Threading.Thread.CurrentThread.CurrentCulture = ci;

			if (windows)
			{
				// set the working path to the exe location
				Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
			}

			try
			{
				if (!Directory.Exists("MXdiags"))
				{
					Directory.CreateDirectory("MXdiags");
				}
			}
			catch (UnauthorizedAccessException)
			{
				Console.WriteLine("Error, no permission to read/create folder /MXdiags");
			}
			catch (Exception ex)
			{
				Console.WriteLine($"Error while attempting to read/create folder /MXdiags, error message: {ex.Message}");
			}


			var logfile = "MXdiags" + Path.DirectorySeparatorChar + "ServiceConsoleLog.txt";
			var logfileOld = "MXdiags" + Path.DirectorySeparatorChar + "ServiceConsoleLog-Old.txt";
			try
			{
				if (File.Exists(logfileOld))
					File.Delete(logfileOld);

				if (File.Exists(logfile))
					File.Move(logfile, logfileOld);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed to roll-over the Console log file: " + ex.Message);
			}

			svcTextListener = new TextWriterTraceListener(logfile);
			svcTextListener.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "Starting on " + (windows ? "Windows" : "Linux"));
			svcTextListener.Flush();

			if (!windows)
			{
				// Use reflection, so no attempt to load Mono dll on Windows
				svcTextListener.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "Creating SIGTERM monitor");
				svcTextListener.Flush();

				var posixAsm = replacedembly.Load("Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756");
				var unixSignalType = posixAsm.GetType("Mono.Unix.UnixSignal");
				var unixSignalWaitAny = unixSignalType.GetMethod("WaitAny", new[] { unixSignalType.MakeArrayType() });
				var signumType = posixAsm.GetType("Mono.Unix.Native.Signum");

				var signals = Array.CreateInstance(unixSignalType, 1);
				signals.SetValue(Activator.CreateInstance(unixSignalType, signumType.GetField("SIGTERM").GetValue(null)), 0);

				Thread signalThread = new Thread(delegate ()
				{
					while (!exitSystem)
					{
						// Wait for a signal to be delivered
						unixSignalWaitAny?.Invoke(null, new object[] {signals});

						var msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "Exiting system due to external SIGTERM signal";
						Console.WriteLine(msg);
						svcTextListener.WriteLine(msg);

						if (replacedulus != null)
						{
							msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "replacedulus terminating";
							Console.WriteLine(msg);
							svcTextListener.WriteLine(msg);
							replacedulus.LogMessage("Exiting system due to external SIGTERM signal");
							replacedulus.LogMessage("replacedulus terminating");
							replacedulus.Stop();
							//allow main to run off
							Thread.Sleep(500);
							msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "replacedulus has shutdown";
							Console.WriteLine(msg);
							svcTextListener.WriteLine(msg);
						}

						exitSystem = true;
					}
				});

				signalThread.Start();

				// Now we need to catch the console Ctrl-C
				Console.CancelKeyPress += (s, ev) =>
				{
					if (replacedulus != null)
					{
						replacedulus.LogConsoleMessage("Ctrl+C pressed");
						replacedulus.LogConsoleMessage("\nreplacedulus terminating");
						replacedulus.Stop();
						//allow main to run off
						Thread.Sleep(500);
					}
					Trace.WriteLine("replacedulus has shutdown");
					ev.Cancel = true;
					exitSystem = true;
				};

			}

			AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

#if DEBUG
			debug = true;
			//Debugger.Launch();
#endif

			for (int i = 0; i < args.Length; i++)
			{
				try
				{
					switch (args[i])
					{
						case "-lang" when args.Length >= i:
						{
							var lang = args[++i];

							CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(lang);
							CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(lang);
							break;
						}
						case "-port" when args.Length >= i:
							httpport = Convert.ToInt32(args[++i]);
							break;
						case "-debug":
							// Switch on debug and data logging from the start
							debug = true;
							break;
						case "-wsport":
							i++;
							Console.WriteLine("The use of the -wsport command line parameter is deprecated");
							break;
						case "-install" when windows:
						{
							if (SelfInstaller.InstallMe())
							{
								Console.WriteLine("replacedulus MX is now installed to run as service");
								Environment.Exit(0);
							}
							else
							{
								Console.WriteLine("replacedulus MX failed to install as service");
								Environment.Exit(1);
							}

							break;
						}
						case "-install":
							Console.WriteLine("You can only install replacedulus MX as a service in Windows");
							Environment.Exit(1);
							break;
						case "-uninstall" when windows:
						{
							if (SelfInstaller.UninstallMe())
							{
								Console.WriteLine("replacedulus MX is no longer installed to run as service");
								Environment.Exit(0);
							}
							else
							{
								Console.WriteLine("replacedulus MX failed uninstall itself as service");
								Environment.Exit(1);
							}

							break;
						}
						case "-uninstall":
							Console.WriteLine("You can only uninstall replacedulus MX as a service in Windows");
							Environment.Exit(1);
							break;
						case "-service":
							service = true;
							break;
						default:
							Console.WriteLine($"Invalid command line argument \"{args[i]}\"");
							Usage();
							break;
					}
				}
				catch
				{
					Usage();
				}
			}

			using (appMutex = new Mutex(false, "Global\\" + AppGuid))
			{
				// Interactive seems to be always false under mono :(

				if (windows && !Environment.UserInteractive)
				{
					// Windows and not interactive - must be a service
					svcTextListener.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "Running as a Windows service");
					svcTextListener.Flush();
					service = true;
					// Launch as a Windows Service
					ServiceBase.Run(new replacedulusService());
				}
				else
				{
					if (Environment.UserInteractive ||(!windows && !service))
					{
						// Windows interactive or Linux and no service flag
						svcTextListener.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "Running interactively");
						service = false;
					}
					else
					{
						// Must be a Linux service
						svcTextListener.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "Running as a Linux service");
						service = true;
					}
					svcTextListener.Flush();
					// Launch normally - Linux Service runs like this too
					RunAsAConsole(httpport, debug);
				}

				while (!exitSystem)
				{
					Thread.Sleep(500);
				}

				try
				{
					if (appMutex.WaitOne(0, false))
					{
						appMutex.ReleaseMutex();
					}
					Environment.Exit(0);
				}
				catch {}
			}
		}

19 Source : MainWindow.xaml.cs
with MIT License
from cyberark

void windowRunPowerShell(string args)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                Directory.SetCurrentDirectory("../../ZBANG/ACLight-master");
                // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
                // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
                PowerShellInstance.AddScript("Set-ExecutionPolicy Bypreplaced");
                string script = File.ReadAllText("ACLight.ps1");
                PowerShellInstance.AddScript(script);
                //PowerShellInstance.AddCommand("Import-Module").AddArgument("ACLight.psm1");
                Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                string outputlog = "-------------------------------------------\n";
                foreach (PSObject outpureplacedem in PSOutput)
                {
                }
                PowerShellInstance.Commands.Clear();
                PowerShellInstance.AddCommand("Start-ACLsreplacedysis");

                IAsyncResult result = PowerShellInstance.BeginInvoke();

                // do something else until execution has completed.
                // this could be sleep/wait, or perhaps some other work
                while (result.IsCompleted == false)
                {
                    Console.Write(".");
                    Thread.Sleep(1000);
                    // might want to place a timeout here...
                }
                Console.WriteLine("Finished!");

                outputlog += "-------------------------------------------\n";
                File.AppendAllText( /*"..\\..\\ZBANG\\log.txt"*/logFileName, "\n\nzBang Launched at " + DateTime.Now.ToString() + "\n" + outputlog + "\n");
            } // endusing powershell
        }

19 Source : CompileTimeRegistrationInfoSerializationTests.cs
with MIT License
from dadhi

[SetUp]
        public void SetupTestDirectory()
        {
            _temporaryTestDirectory = Path.GetRandomFileName();
            Directory.CreateDirectory(_temporaryTestDirectory);

            _originalDirectory = Directory.GetCurrentDirectory();
            Directory.SetCurrentDirectory(_temporaryTestDirectory);
        }

19 Source : CompileTimeRegistrationInfoSerializationTests.cs
with MIT License
from dadhi

[TearDown]
        public void TearDownTestDirectory()
        {
            Directory.SetCurrentDirectory(_originalDirectory);
            if (Directory.Exists(_temporaryTestDirectory))
                Directory.Delete(_temporaryTestDirectory, true);
        }

19 Source : Program.cs
with MIT License
from danielwertheim

static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            try
            {
                var logConfig = new LoggerConfiguration()
                    .ReadFrom.AppSettings()
                    .Enrich.FromLogContext();

                var logger = Log.Logger = logConfig.CreateLogger();

                logger.Information("Running in Directory='{Directory}' using UserName='{UserName}'",
                    Directory.GetCurrentDirectory(),
                    System.Security.Principal.WindowsIdenreplacedy.GetCurrent().Name);

                var host = new LightNuGetServerHostService(
                    GetRequiredAppSetting("host:baseaddress"),
                    GetRequiredAppSetting("lightnugetserver:settingsfilepath"));

                if (Environment.UserInteractive)
                    host.RunAsConsole(args);
                else
                    ServiceBase.Run(host);
            }
            finally
            {
                Log.Logger.Information("Exiting");

                Log.CloseAndFlush();
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from DanzaG

private void TextureInject_Click(object sender, RoutedEventArgs e)
        {
            TR2Level instance = new TR2Level();
            TR2LevelReader reader = new TR2LevelReader();
            TR2LevelWriter writer = new TR2LevelWriter();

            string CurrentDir = Directory.GetCurrentDirectory();

            string LvlName = TR2LevelNames.AsList[ImportLevel.SelectedIndex];

            instance = reader.ReadLevel(LvlName);

            int ExtensionIndex = LvlName.IndexOf('.');

            Directory.SetCurrentDirectory(CurrentDir + "\\TexturePacks\\" + LvlName.Remove(ExtensionIndex)+ "\\" + PackDirectory.Text);

            for (int i = 0; i < instance.NumImages; i++)
            {
                instance.Images16[i].Pixels = TextureUtilities.ImportFrom32PNG(LvlName + i + ".png");
            }

            writer.WriteLevelToFile(instance, LvlName);

            Directory.SetCurrentDirectory(CurrentDir);
        }

19 Source : MainWindow.xaml.cs
with MIT License
from DanzaG

private void TextureInject_Click(object sender, RoutedEventArgs e)
        {
            TR2Level instance = new TR2Level();
            TR2LevelReader reader = new TR2LevelReader();
            TR2LevelWriter writer = new TR2LevelWriter();

            string CurrentDir = Directory.GetCurrentDirectory();

            string LvlName = TR2LevelNames.AsList[ImportLevel.SelectedIndex];

            instance = reader.ReadLevel(LvlName);

            int ExtensionIndex = LvlName.IndexOf('.');

            Directory.SetCurrentDirectory(CurrentDir + "\\TexturePacks\\" + LvlName.Remove(ExtensionIndex)+ "\\" + PackDirectory.Text);

            for (int i = 0; i < instance.NumImages; i++)
            {
                instance.Images16[i].Pixels = TextureUtilities.ImportFrom32PNG(LvlName + i + ".png");
            }

            writer.WriteLevelToFile(instance, LvlName);

            Directory.SetCurrentDirectory(CurrentDir);
        }

See More Examples