System.IO.File.ReadAllText(string)

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

7727 Examples 7

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish

private void getAccountData()
        {
            var JsonAccounts = JsonConvert.DeserializeObject<jsonObject>(File.ReadAllText(SAVE_FILE_NAME));
            for (int i = 0; i < JsonAccounts.count; i++)
            {
                AccountController.addAccount(JsonAccounts.accounts[i].username, JsonAccounts.accounts[i].preplacedword, JsonAccounts.accounts[i].desktopAuth);
            }
        }

19 Source : Settings.xaml.cs
with GNU General Public License v3.0
from 00000vish

public static void readSettingFile()
    {
        try
        {
            var JsonData = JsonConvert.DeserializeObject<SettingJson>(File.ReadAllText(SETTING_FILE));
            jsonSetting = JsonData;
        }
        catch (Exception)
        {
            SteamTwoProperties.reset();
            SteamTwoProperties.updateSettingFile();
        }
    }

19 Source : PhiChartFileReader.cs
with MIT License
from 0thElement

public void ReadChart()
        {
            CurrentChart = JsonConvert.DeserializeObject<PhiChart>(File.ReadAllText(Path.Combine(Application.dataPath, "Scripts", "testChart.json")));
            PhiChartView.Instance.Refresh();
        }

19 Source : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(true, "/notes", "", "", "Admin Notes", "Get or set some administrative notes.")]
        public static void Notes(Frontend f, HttpRequestEventArgs c) {
            string path = Path.ChangeExtension(f.Settings.FilePath, ".notes.txt");
            string text;

            if (c.Request.HttpMethod == "POST") {
                try {
                    using (StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true))
                        text = sr.ReadToEnd();
                    File.WriteAllText(path, text);
                    f.RespondJSON(c, new {
                        Info = "Success."
                    });
                    return;
                } catch (Exception e) {
                    f.RespondJSON(c, new {
                        Error = e.ToString()
                    });
                    return;
                }
            }

            if (!File.Exists(path)) {
                f.Respond(c, "");
                return;
            }

            try {
                text = File.ReadAllText(path);
                f.Respond(c, text);
            } catch (Exception e) {
                f.RespondJSON(c, new {
                    Error = e.ToString()
                });
                return;
            }
        }

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

public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
        {
            List<NodeModel> result = new List<NodeModel>();
				
            var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);

            files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));

            var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
            var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);

            foreach (var tree in trees)
            {
                var semantic = cSharpCompilation.GetSemanticModel(tree);

                foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
                {
                    var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
                    
                    var isSuitable = clreplacedSymbol != null 
                                 && !clreplacedSymbol.IsAbstract 
                                 && clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
                                 && IsExpr(clreplacedSymbol) 
                                 && clreplacedSymbol.Name.StartsWith("Expr");
                        
                    if (!isSuitable)
                    {
                        continue;
                    }

                    var properties = GetProperties(clreplacedSymbol);

                    var subNodes = new List<SubNodeModel>();
                    var modelProps = new List<SubNodeModel>();

                    foreach (var constructor in clreplacedSymbol.Constructors)
                    {
                        foreach (var parameter in constructor.Parameters)
                        {
                            INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;

                            var correspondingProperty = properties.FirstOrDefault(prop =>
                                string.Equals(prop.Name,
                                    parameter.Name,
                                    StringComparison.CurrentCultureIgnoreCase));

                            if (correspondingProperty == null)
                            {
                                throw new Exception(
                                    $"Could not find a property for the constructor arg: '{parameter.Name}'");
                            }

                            var ta = replacedyzeSymbol(ref pType);

                            var subNodeModel = new SubNodeModel(correspondingProperty.Name,
                                parameter.Name,
                                pType.Name,
                                ta.ListName,
                                ta.IsNullable,
                                ta.HostTypeName);
                            if (ta.Expr)
                            {
                                subNodes.Add(subNodeModel);
                            }
                            else
                            {
                                modelProps.Add(subNodeModel);
                            }

                        }
                    }

                    result.Add(new NodeModel(clreplacedSymbol.Name,
                        modelProps.Count == 0 && subNodes.Count == 0,
                        subNodes,
                        modelProps));
                }
            }

            result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));

            return result;

            bool IsExpr(INamedTypeSymbol symbol)
            {
                if (symbol.Name == "IExpr")
                {
                    return true;
                }
                while (symbol != null)
                {
                    if (symbol.Interfaces.Any(HasA))
                    {
                        return true;
                    }
                    symbol = symbol.BaseType;
                }

                return false;


                bool HasA(INamedTypeSymbol iSym)
                {
                    if (iSym.Name == "IExpr")
                    {
                        return true;
                    }

                    return IsExpr(iSym);
                }
            }

            List<ISymbol> GetProperties(INamedTypeSymbol symbol)
            {
                List<ISymbol> result = new List<ISymbol>();
                while (symbol != null)
                {
                    result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
                    symbol = symbol.BaseType;
                }

                return result;
            }

            Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
            {
                string listName = null;
                string hostType = null;
                if (typeSymbol.ContainingType != null)
                {
                    var host = typeSymbol.ContainingType;
                    hostType = host.Name;
                }

                var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;

                if (nullable && typeSymbol.Name == "Nullable")
                {
                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                if (typeSymbol.IsGenericType)
                {
                    if (typeSymbol.Name.Contains("List"))
                    {
                        listName = typeSymbol.Name;
                    }

                    if (typeSymbol.Name == "Nullable")
                    {
                        nullable = true;
                    }

                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
            }
        }

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

public string ReadAllText(string path)
        {
            return File.ReadAllText(path);
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

public static byte[] GetMasterKey(string LocalStateFolder)
        {
            //Key saved in Local State file
            string filePath = LocalStateFolder + @"\Local State";
            byte[] masterKey = new byte[] { };

            if (File.Exists(filePath) == false)
                return null;

            //Get key with regex.
            var pattern = new System.Text.RegularExpressions.Regex("\"encrypted_key\":\"(.*?)\"", System.Text.RegularExpressions.RegexOptions.Compiled).Matches(File.ReadAllText(filePath));

            foreach (System.Text.RegularExpressions.Match prof in pattern)
            {
                if (prof.Success)
                    masterKey = Convert.FromBase64String((prof.Groups[1].Value)); //Decode base64
            }

            //Trim first 5 bytes. Its signature "DPAPI"
            byte[] temp = new byte[masterKey.Length - 5];
            Array.Copy(masterKey, 5, temp, 0, masterKey.Length - 5);

            try
            {
                return ProtectedData.Unprotect(temp, null, DataProtectionScope.CurrentUser);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

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

static void powershell_clm(String file_tmp)
        {
            Console.WriteLine("[+] Powershell CLM bypreplaced!\n");
            Runspace rs = RunspaceFactory.CreateRunspace();
            String op_file = file_tmp;
            PowerShell ps = PowerShell.Create();
            while (true)
            {
                Console.Write("PS:>");
                string input = Console.ReadLine();
                if (input == "exit")
                {
                    break;
                }
                ps.AddScript(input + " | Out-File -FilePath " + op_file);
                ps.Invoke();
                string output = File.ReadAllText(op_file);
                Console.WriteLine(output);
                File.Delete(op_file);
            }
            rs.Close();
        }

19 Source : SQLManager.cs
with MIT License
from 1100100

private T DeserializeXml<T>(string url)
        {
            using var reader = new StringReader(File.ReadAllText(url));
            var xz = new XmlSerializer(typeof(T));
            return (T)xz.Deserialize(reader);
        }

19 Source : Dumper.cs
with MIT License
from 13xforever

private List<string> EnumeratePhysicalDrivesLinux()
        {
            var cdInfo = "";
            try
            {
                cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
            }
            catch (Exception e)
            {
                Log.Debug(e, e.Message);
            }
            var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
            return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
                    .Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
                    .Distinct()
                    .ToList();

        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

void findMultiplayerVersion()
        {
            string mj;
            string mlj;
            // check for the json data
            if(File.Exists(bsl + @"/UserData/BeatSaberMultiplayer.json"))
            {
                mj = bsl + @"/UserData/BeatSaberMultiplayer.json";
                if (File.Exists(bsl + @"/Plugins/BeatSaberMultiplayer.dll")) {
                    // multiplayer is installed
                    string json = System.IO.File.ReadAllText(mj);
                    dynamic bsmj = JsonConvert.DeserializeObject(json);
                    label8.Text = "Multiplayer Version: " + bsmj["_modVersion"];
                }
                else
                {
                    // no multiplayer
                    label8.Text = "Multiplayer Version: Not Installed";
                }
            }
            else
            {
                // no multiplayer
                label8.Text = "Multiplayer Version: Not Installed";
            }

            if (File.Exists(bsl + @"/UserData/BeatSaberMultiplayer.json"))
            {
                mlj = bsl + @"/UserData/BeatSaberMultiplayerLite.json";
                if (File.Exists(bsl + @"/Plugins/BeatSaberMultiplayerLite.dll"))
                {
                    // multiplayer is installed
                    string json = System.IO.File.ReadAllText(mlj);
                    dynamic bsmj = JsonConvert.DeserializeObject(json);
                    label9.Text = "MultiplayerLite Version: " + bsmj["_modVersion"];
                }
                else
                {
                    // no multiplayer
                    label9.Text = "MultiplayerLite Version: Not Installed";
                }
            }
            else
            {
                // no multiplayer
                label9.Text = "MultiplayerLite Version: Not Installed";
            }
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

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

public static Dictionary<string, dynamic> DeserializeYamlFile(string ruleFilePath, Options o)
        {
            var contents = File.ReadAllText(ruleFilePath);
            if (!contents.Contains("tags"))
            {
                Console.WriteLine($"Ignoring rule {ruleFilePath} (no tags)");
                return null;
            }
            if (o.Warning)
                contents = contents.Replace(Environment.NewLine + Environment.NewLine,
                        Environment.NewLine)
                    .Remove(0, contents.IndexOf("tags", StringComparison.Ordinal));
            if (contents.Contains("---"))
                contents = contents.Remove(contents.IndexOf("---", StringComparison.Ordinal));
            var deserializer = new YamlDotNet.Serialization.Deserializer();
            var dict = deserializer.Deserialize<Dictionary<string, dynamic>>(contents);
            return dict;
        }

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

public static Dictionary<string, List<string>> ParseRuleFile(string ruleFilePath)
        {
            Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
            var contents = new StringReader(File.ReadAllText(ruleFilePath));
            string line = contents.ReadLine();
                while (line != null)
                {
                    try
                    {
                        //if the line contains a mitre_technique
                        if (line.Contains("mitre_technique_id "))
                        {
                            List<string> techniques = new List<string>();
                            //get all indexes from all technique ids and add them all to a list
                            IEnumerable<int> indexes = Regex.Matches(line, "mitre_technique_id ").Cast<Match>().Select(m => m.Index + "mitre_technique_id ".Length);
                            foreach (int index in indexes) 
                                techniques.Add(line.Substring(index, line.IndexOfAny(new [] { ',', ';' }, index) - index));
                            int head = line.IndexOf("msg:\"") + "msg:\"".Length;
                            int tail = line.IndexOf("\"", head);
                            string msg = line.Substring(head, tail - head);
                            head = line.IndexOf("sid:") + "sid:".Length;
                            tail = line.IndexOfAny(new char[] { ',', ';' }, head);
                            string sid = line.Substring(head, tail - head);
                            //for each found technique add the sid along with the message to the content
                            foreach( string technique in techniques)
                            {
                                if (res.ContainsKey(technique))
                                    res[technique].Add($"{sid} - {msg}");
                                else
                                    res.Add(technique, new List<string> { $"{sid} - {msg}" });
                            }
                        }
                        line = contents.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(line);
                        Console.WriteLine(e.Message);
                        line = contents.ReadLine();
                }
                }
                return res;
            }

19 Source : Function.cs
with GNU Affero General Public License v3.0
from 3CORESec

private void initConfig()
        {
            _alerts = new List<ISender>();
            config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
            if (string.IsNullOrEmpty(config.SlackPath))
                config.SlackPath = Environment.GetEnvironmentVariable("SLACKPATH");
            if (string.IsNullOrEmpty(config.WebhookChannel))
                config.WebhookChannel = Environment.GetEnvironmentVariable("WEBHOOKCHANNEL");
            if (string.IsNullOrEmpty(config.WebHookToken))
                config.WebHookToken = Environment.GetEnvironmentVariable("WEBHOOKTOKEN");
            if (string.IsNullOrEmpty(config.PostUrl))
                config.PostUrl = Environment.GetEnvironmentVariable("POSTURL");
            var type = typeof(ISender);
            var types = AppDomain.CurrentDomain.Getreplacedemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsreplacedignableFrom(p) && !p.IsInterface && !p.IsAbstract);
            types.ToList().ForEach(type => {
                ConstructorInfo ctor = type.GetConstructor(new[] { typeof(Storage<SessionLog>), typeof(Config), typeof(IMemoryCache) });
                ISender instance = ctor.Invoke(new object[] { _storage, config, memoryCache }) as ISender;
                _alerts.Add(instance);
            });
        }

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static void LoadErr(Dictionary<int, string> dict, string path)
		{
			if (!File.Exists(path))
			{
				MainWindow.Logger.Warn("Error Code File Missing: {0}", path);
				return;
			}

			string FileContents;

			try
			{
				FileContents = File.ReadAllText(path);
			}
			catch (Exception ex)
			{
                MainWindow.Logger.Error(ex.Message);
				return;
			}

			Regex LineParser = new Regex(@"""([0-9]+)"",""[^\n\r""]*"",""([^\n\r""]*)""");     //test here https://regex101.com/r/hO5zI1/4

			MatchCollection mc = LineParser.Matches(FileContents);

			foreach (Match m in mc)
			{
				try //shouldn't be needed as regex matched already
				{
					int number = int.Parse(m.Groups[1].Value);

					dict.Add(number, m.Groups[2].Value);
				}
				catch { }
			}
		}

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static void LoadSettings(Dictionary<int, Tuple<string, string, string>> dict, string path)
		{
			if (!File.Exists(path))
			{
                MainWindow.Logger.Warn("GRBL Settings File Missing: {0}", path);
				return;
			}

			string FileContents;

			try
			{
				FileContents = File.ReadAllText(path);
			}
			catch (Exception ex)
			{
                MainWindow.Logger.Error(ex.Message);
				return;
			}

			Regex LineParser = new Regex(@"""([0-9]+)"",""([^\n\r""]*)"",""([^\n\r""]*)"",""([^\n\r""]*)""");

			MatchCollection mc = LineParser.Matches(FileContents);

			foreach (Match m in mc)
			{
				try //shouldn't be needed as regex matched already
				{
					int number = int.Parse(m.Groups[1].Value);

					dict.Add(number, new Tuple<string, string, string>(m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value));
				}
				catch { }
			}
		}

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

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

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

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

19 Source : Stub.cs
with Apache License 2.0
from 42skillz

public static IWebClient AWebClientWith(string showId, string layoutTheaterJsonFileName, string bookedSeatsJsonFileName)
        {
            var webClient = Subsreplacedute.For<IWebClient>();
            var jsonDirPath = Path.Combine(GetExecutingreplacedemblyDirectoryFullPath(), "AuditoriumLayouts");
            webClient.GetAsync(Arg.Is<string>(s => s.EndsWith($"/api/v1/data_for_auditoriumSeating/{showId}")))
                .Returns(new HttpResponseMessage {StatusCode = HttpStatusCode.OK, Content = new StringContent(File.ReadAllText($"{Path.Combine(jsonDirPath, layoutTheaterJsonFileName)}"))});

            webClient.GetAsync(Arg.Is<string>(s => s.EndsWith($"api/v1/data_for_reservation_seats/{showId}")))
                .Returns(new HttpResponseMessage {StatusCode = HttpStatusCode.OK, Content = new StringContent(File.ReadAllText($"{Path.Combine(jsonDirPath, bookedSeatsJsonFileName)}"))});

            return webClient;
        }

19 Source : EntryPoint.cs
with MIT License
from 5minlab

internal static void BuildCommon(string configFilePath, string outputFilePath) {
            var content = File.ReadAllText(configFilePath);
            var config = new Config(content);

            var currModifiers = config.CreateCurrentModifiers();
            var nextModifiers = config.CreateConfigModifiers();

            foreach (var m in nextModifiers) {
                var tokens = m.GetType().ToString().Split('.');
                var name = tokens[tokens.Length - 1];
                Debug.LogFormat("[MinamoLog] {0}: {1}", name, m.GetConfigText());
                m.Apply();
            }

            var executor = config.PlayerBuild;
            Debug.LogFormat("[MinamoLog] {0}: {1}", "PlayerBuildExecutor", executor.GetConfigText());
            executor.Build(outputFilePath);

            // restore
            foreach (var m in currModifiers) {
                m.Apply();
            }
        }

19 Source : Menu_ConfigFile.cs
with MIT License
from 5minlab

void Load(string filepath, out IModifier[] modifiers, out PlayerBuildExecutor executor) {
            var jsontext = File.ReadAllText(filepath);
            var config = new Config(jsontext);

            modifiers = config.CreateConfigModifiers();
            executor = config.PlayerBuild;
        }

19 Source : LyricsFetcher.cs
with MIT License
from 71

public static bool GetLocalLyrics(string songId, List<Subreplacedle> subreplacedles)
        {
            string songDirectory = Loader.CustomLevels.Values.FirstOrDefault(x => x.levelID == songId)?.customLevelPath;

            Debug.Log($"[Beat Singer] Song directory: {songDirectory}.");

            if (songDirectory == null)
                return false;

            // Find JSON lyrics
            string jsonFile = Path.Combine(songDirectory, "lyrics.json");

            if (File.Exists(jsonFile))
            {
                PopulateFromJson(File.ReadAllText(jsonFile), subreplacedles);

                return true;
            }

            // Find SRT lyrics
            string srtFile = Path.Combine(songDirectory, "lyrics.srt");

            if (File.Exists(srtFile))
            {
                using (FileStream fs = File.OpenRead(srtFile))
                using (StreamReader reader = new StreamReader(fs))
                {
                    PopulateFromSrt(reader, subreplacedles);

                    return true;
                }

            }

            return false;
        }

19 Source : DebugProgramTemplate.cs
with MIT License
from 71

public static int Main(string[] args)
    {
        try
        {
            Diagnosticreplacedyzer replacedyzer = new Cometaryreplacedyzer();
            CSharpParseOptions parseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "DEBUGGING" });

            if (IsWrittenToDisk && ShouldBreakAtStart)
                Debugger.Break();

            CompilationWithreplacedyzers compilation = CSharpCompilation.Create(
                replacedemblyName + "+Debugging",
                Files.Split(';').Select(x => CSharpSyntaxTree.ParseText(File.ReadAllText(x), parseOptions)),
                References.Split(';').Select(x => MetadataReference.CreateFromFile(x))
            ).Withreplacedyzers(ImmutableArray.Create(replacedyzer));

            ExecuteAsync(compilation).Wait();

            return 0;
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e.Message);
            Console.Error.WriteLine();
            Console.Error.WriteLine(e.StackTrace);

            Console.ReadKey();

            return 1;
        }
    }

19 Source : Program.cs
with MIT License
from 71

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Disable overrides
                var members = methodRedirectionClreplaced.Members;

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

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

                        continue;
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return 0;
        }

19 Source : ExtendableEnums.cs
with MIT License
from 7ark

static KeyValuePair<string, string> FindAllScriptFiles(string startDir, string enumToFind)
    {
        try
        {
            foreach (string file in Directory.GetFiles(startDir))
            {
                if ((file.Contains(".cs") || file.Contains(".js")) && !file.Contains(".meta"))
                {
                    string current = File.ReadAllText(file);
                    string currentTrimmed = current.Replace(" ", "").Replace("\n", "").Replace("\t", "").Replace("\r", "");
                    if (currentTrimmed.Contains(enumToFind.Replace(" ", "") + "{"))
                        return new KeyValuePair<string, string>(current, file);
                }
            }
            foreach (string dir in Directory.GetDirectories(startDir))
            {
                KeyValuePair<string, string> result = FindAllScriptFiles(dir, enumToFind);
                if (result.Key != "NOPE")
                    return result;
            }
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
        return new KeyValuePair<string, string>("NOPE", "NOPE");
    }

19 Source : ToolsService.cs
with Apache License 2.0
from 91270

public bool CreateServices(string strPath, string strSolutionName, string tableName)
        {
            try
            {

                string saveFileName = $"{tableName.Replace("_", "")}Service.cs";

                #region 遍历子目录查找相同IService

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

                GetFiles(strPath, sourecFiles);

                string readFilePath = sourecFiles.FirstOrDefault(m => m.Contains(saveFileName));

                string value = "";

                if (!string.IsNullOrEmpty(readFilePath))
                {
                    value = GetCustomValue(File.ReadAllText(readFilePath), "#region CustomInterface \r\n", "        #endregion\r\n");
                }

                #endregion

                #region 模板样式
                var clreplacedTemplate = $"" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"// <auto-generated>\r\n" +
                    $"//     此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
                    $"//     如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
                    $"//     author MEIAM\r\n" +
                    $"// </auto-generated>\r\n" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"using { strSolutionName }.Model;\r\n" +
                    $"using { strSolutionName }.Model.Dto;\r\n" +
                    $"using { strSolutionName }.Model.View;\r\n" +
                    $"using System.Collections.Generic;\r\n" +
                    $"using System.Threading.Tasks;\r\n" +
                    $"using SqlSugar;\r\n" +
                    $"using System.Linq;\r\n" +
                    $"using System;\r\n" +
                    $"\r\n" +
                    $"namespace { strSolutionName }.Interfaces\r\n" +
                    $"{{\r\n" +
                    $"    public clreplaced {tableName.Replace("_", "")}Service : BaseService<{tableName}>, I{tableName.Replace("_", "")}Service\r\n" +
                    $"    {{\r\n" +
                    $"\r\n" +
                    $"        public {tableName.Replace("_", "")}Service(IUnitOfWork unitOfWork) : base(unitOfWork)\r\n" +
                    $"        {{\r\n" +
                    $"        }}\r\n" +
                    $"\r\n" +
                    $"        #region CustomInterface \r\n" +
                    $"{(string.IsNullOrWhiteSpace(value) ? "" : value)}" +
                    $"        #endregion\r\n" +
                    $"\r\n" +
                    $"    }}\r\n" +
                    $"}}\r\n";
                #endregion

                File.WriteAllText($"{ strPath }\\{saveFileName}", clreplacedTemplate);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

19 Source : ToolsService.cs
with Apache License 2.0
from 91270

public bool CreateIServices(string strPath, string strSolutionName, string tableName)
        {
            try
            {

                string saveFileName = $"I{tableName.Replace("_", "")}Service.cs";

                #region 遍历子目录查找相同IService

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

                GetFiles(strPath, sourecFiles);

                string readFilePath = sourecFiles.FirstOrDefault(m => m.Contains(saveFileName));

                string value = "";

                if (!string.IsNullOrEmpty(readFilePath))
                {
                    value = GetCustomValue(File.ReadAllText(readFilePath), "#region CustomInterface \r\n", "        #endregion");
                }

                #endregion

                #region 模板样式
                var clreplacedTemplate = $"" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"// <auto-generated>\r\n" +
                    $"//     此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
                    $"//     如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
                    $"//     author MEIAM\r\n" +
                    $"// </auto-generated>\r\n" +
                    $"//------------------------------------------------------------------------------\r\n" +
                    $"using { strSolutionName }.Model;\r\n" +
                    $"using { strSolutionName }.Model.Dto;\r\n" +
                    $"using { strSolutionName }.Model.View;\r\n" +
                    $"using System.Collections.Generic;\r\n" +
                    $"using System.Threading.Tasks;\r\n" +
                    $"using SqlSugar;\r\n" +
                    $"using System.Linq;\r\n" +
                    $"using System;\r\n" +
                    $"\r\n" +
                    $"namespace { strSolutionName }.Interfaces\r\n" +
                    $"{{\r\n" +
                    $"    public interface I{tableName.Replace("_", "")}Service : IBaseService<{tableName}>\r\n" +
                    $"    {{\r\n" +
                    $"\r\n" +
                    $"        #region CustomInterface \r\n" +
                    $"{(string.IsNullOrWhiteSpace(value) ? "" : value)}" +
                    $"        #endregion\r\n" +
                    $"\r\n" +
                    $"    }}\r\n" +
                    $"}}\r\n";
                #endregion

                File.WriteAllText($"{ strPath }\\{ saveFileName }", clreplacedTemplate);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

19 Source : Manga.cs
with GNU General Public License v3.0
from 9vult

public bool LoadSettings()
        {
            Logger.Log("Loading settings for manga '" + name + "'");
            if (!File.Exists(mangaDirectory.FullName + "\\settings"))
            {
                Logger.Warn("Settings file did not exist");
                //File.Create(mangaDirectory.FullName + "\\settings");
                CreateSettings();
                return false;
            }

            string file = File.ReadAllText(mangaDirectory.FullName + "\\settings");

            string[] units = file.Split('|');

            if (settings != null)
                settings = null;

            if (units.Length < 3)
            {
                Logger.Warn("Settings length < 3, creating blank name");
                string[] temp = new string[3];
                temp[0] = units[0];
                temp[1] = units[1];
                temp[2] = "";
                units = temp;
            }

            settings = new MangaSettingsContainer
            {
                lang = units[0],
                group = units[1],
                name = units[2]
            };
            return true;
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void AddManga(string api, string num, bool isUpdate)
        {
            string json;
            if (api != null)
            {
                using (var wc = new System.Net.WebClient())
                {
                    json = wc.DownloadString(api);
                }
            }
            else
            {
                json = File.ReadAllText(homeFolder + "\\" + num + "\\manga.json");
            }

            // Deserialize the JSON file
            dynamic contents = JsonConvert.DeserializeObject(json);
            string mangaName = contents.manga.replacedle;
            string mangaDirectory = homeFolder + "\\" + num;

            if (!Directory.Exists(mangaDirectory))
            {
                Logger.Log("Creating directory '" + mangaDirectory + "' and related files");
                Directory.CreateDirectory(mangaDirectory);
                File.WriteAllText(mangaDirectory + "\\manga.json", json); // Write the JSON to a file
                File.WriteAllText(mangaDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
            }
            File.WriteAllText(mangaDirectory + "\\downloading", ""); // Create "Downloading" file

            Manga m = new Manga(mangaName, new DirectoryInfo(mangaDirectory), "1", "1");

            if (!isUpdate)
            {
                DialogResult result = new FrmMangaSettings(m).ShowDialog();
                MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");
            }
            m.LoadSettings();
            downloadManager.AddMDToQueue(m, contents.chapter, isUpdate);
            RefreshContents();
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void RefreshContents()
        {
            Logger.Log("Refreshing");
            lstManga.Items.Clear();
            lstHentai.Items.Clear();
            mangas.Clear();
            DirectoryInfo root = new DirectoryInfo(homeFolder);
            DirectoryInfo[] dirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly);

            foreach (DirectoryInfo dir in dirs)
            {
                // Logger.Log("Refreshing data for directory '" + dir.Name + "'");
                if (dir.Name == "update")
                    continue;
                else if (!dir.Name.StartsWith("h"))
                {
                    var json = File.ReadAllText(dir.FullName + "\\manga.json");
                    var tracker = File.ReadAllText(dir.FullName + "\\tracker");
                    string[] trackerData = tracker.Split('|');
                    // Deserialize the JSON file
                    dynamic contents = JsonConvert.DeserializeObject(json);
                    string mangaName = contents.manga.replacedle;
                    Manga m = new Manga(mangaName, dir, trackerData[0], trackerData[1]);
                    m.LoadSettings();
                    if (m.settings.name == "" || m.settings.name == null)
                    {
                        m.SaveSettings(m.settings.lang, m.settings.group, mangaName);
                        m.LoadSettings();
                    }

                    mangas.Add(m);
                    string name = m.settings.name;
                    if (name.Length > 21)
                    {
                        name = name.Substring(0, 21);
                    }
                    else
                    {
                        name = name.PadRight(21);
                    }
                    lstManga.Items.Add(name + "  »  c" + trackerData[0] + ",p" + trackerData[1]);
                }
                else // Hentai
                {
                    string replacedle = File.ReadAllText(dir.FullName + "\\replacedle");
                    var tracker = File.ReadAllText(dir.FullName + "\\tracker");
                    string[] trackerData = tracker.Split('|');

                    Manga m = new Manga(replacedle, dir, trackerData[0], trackerData[1]);
                    mangas.Add(m);
                    string name = m.name;
                    if (name.Length > 21)
                    {
                        name = name.Substring(0, 21);
                    }
                    else
                    {
                        name = name.PadRight(21);
                    }
                    lstHentai.Items.Add(name + "  »  p" + trackerData[1]);
                }
            }
            if (lstManga.Items.Count > 0)
            {
                lstManga.SelectedIndex = 0;
            }
            if (lstHentai.Items.Count > 0)
            {
                lstHentai.SelectedIndex = 0;
            }
        }

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

static void ExecuteFlightPlan(SdkWrapper wrapper)
        {
            try
            {
                var fp = TelloSdkCoreNet.flightplans.FlightPlan.Materialize(System.IO.File.ReadAllText(@"/Users/peterhallock/Doreplacedents/git/TelloSdkCoreNet/TestApp/TestApp\FP_4-10-18 102058 PM_b59c89eb.json.fp"));
                wrapper.ExecuteFlightPlan(fp);
            }
            catch (Exception ex)
            {
                WriteError(ex.Message);
                Console.ReadLine();
            }
            
        }

19 Source : Program.cs
with MIT License
from a-downing

static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();
            var replacedembler = new MicroVM.replacedembler();
            var cpu = new MicroVM.CPU(new Peripheral(), 0x80000000);

            // entry point, and some functions for compiled code to call into
            string asmCode = @"
            print:
                ldr r0 sp -8
                str r0 0x80000000
                ret

            randInt:
                rngi r0
                ret

            _start:
                mov bp sp
                call main

                #test strb/ldrb
                mov r0 0xaaaaaabb
                strb r0 0xdeadbeef
                ldrb r0 0xdeadbeef

                jmp end
                #jmp _start
            ";

            // code generated from compiler
            asmCode += System.IO.File.ReadAllText("code.asm");
            asmCode += "\nend:\nnop";

            bool success = replacedembler.Compile(asmCode, 1024);

            if(!success) {
                foreach(var error in replacedembler.errors) {
                    Print(error);
                }

                return;
            }

            replacedembler.LoadProgramToCPU(cpu);
            MicroVM.CPU.Status st;

            // test interrupt 0 (isr_0_name)
            //cpu.Interrupt(0);

            // pc will be one of the 1000, 1001... codes to identify the bugs on failure
            if(!cpu.Cycle(out st, 2000)) {
                if(st == MicroVM.CPU.Status.OUT_OF_INSTRUCTIONS) {
                    Print($"program finished");
                } else {
                    Print($"cpu error: {st.ToString()}");
                }
                
                Print($"cpu.pc: {cpu.pc}");
            }

            // simple performace test, currently ~70 million instructions/s
            /*const int numCycles = 1000000;
            stopWatch.Start();

            for(int i = 0; i < numCycles / 100; i++) {
                if(!cpu.Cycle(out st, 100)) {
                    if(st == MicroVM.CPU.Status.OUT_OF_INSTRUCTIONS) {
                        Print($"program finished");
                    } else {
                        Print($"cpu error: {st.ToString()}");
                    }
                    
                    Print($"cpu.pc: {cpu.pc}");
                    break;
                }
            }

            stopWatch.Stop();
            double elapsedTime = stopWatch.Elapsed.TotalMilliseconds / 1000;
            Print($"{numCycles} in {elapsedTime}s ({(float)(numCycles / elapsedTime)} instructions/s)");*/
        }

19 Source : Program.cs
with MIT License
from a1xd

static void Main(string[] args)
        {
            try
            {
                VersionHelper.ValidOrThrow();
            }
            catch (InteropException e)
            {
                Exit(e.Message);
            }

            try
            {
                if (args.Length != 1)
                {
                    if (File.Exists(DefaultPath))
                    {
                        Exit(Usage);
                    }
                    else
                    {
                        File.WriteAllText(DefaultPath, DriverConfig.GetDefault().ToJSON());
                        Exit($"{Usage}\n(generated default settings file '{DefaultPath}')");
                    }
                }
                else
                {
                    var result = DriverConfig.Convert(File.ReadAllText(args[0]));
                    if (result.Item2 == null)
                    {
                        result.Item1.Activate();
                    }
                    else
                    {
                        Exit($"Bad settings:\n\n{result.Item2}");
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Exit(e.Message);
            }
            catch (JsonException e)
            {
                Exit($"Settings format invalid:\n\n{e.Message}");
            }
            catch (Exception e)
            {
                Exit($"Error:\n\n{e}");
            }
        }

19 Source : obfuscator.cs
with MIT License
from aaaddress1

public static bool obfuscaAsm(string asmPath, string outObfAsmPath)
        {
            label_extra_count = 0;
            junk_count = 0;
            obfuscat_code_count = 0;

            string asmCode = System.IO.File.ReadAllText(asmPath);

            string[] gadgets = asmCode.Split('\n');
            string fixCode = "";
            string extCode = ".section	.text$junk,\x22wx\x22\n";

            string currFuncNameMatch = "";
            for (int i = 0; i < gadgets.Length; i++)
            {
                Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = (i * 100 / gadgets.Length) + "%"; });
                var currLine = gadgets[i];

                Match m = new Regex(@"(.+):\r").Match(gadgets[i]);
                if (m.Success && i < gadgets.Length - 2)
                {
                    currFuncNameMatch = m.Groups[1].Value;
                    if (gadgets[i + 2].Contains("cfi_startproc"))
                    {
                        logMsg("found func::" + currFuncNameMatch + "() at #" + i, Color.Blue);
                        fixCode += gadgets[i] + "\n\r" + gadgets[i + 1] + "\n\r" + gadgets[i + 2] + "\n\r";
                        i += 2;
                        continue;
                    }
                    else currFuncNameMatch = "";
                }

                if (currFuncNameMatch != "")
                {
                    string getJunk = "", getExtra = "";
                    if (Properties.Settings.Default.cnfseCode)
                    {
                        obfuscatCode(gadgets[i], ref getJunk, ref getExtra);
                        fixCode += getJunk;
                        extCode += getExtra;
                    }
                    else
                        fixCode += gadgets[i] + "\n\r";

                    getJunk = ""; getExtra = "";
                    if (Properties.Settings.Default.insrtJunk)
                    {
                        randJunk(ref getJunk, ref getExtra);
                        fixCode += getJunk;
                        extCode += getExtra;
                        if (gadgets[i].Contains("cfi_endproc")) currFuncNameMatch = "";
                    }
                }
                else
                    fixCode += gadgets[i] + "\n\r";
            }
            Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = "100%"; });
            logMsg(string.Format(
                "[\tOK\t] obfuscate result:         \n" +
                " - generate {0} junk codes         \n" +
                " - generate {1} obfuscated codes   \n" +
                " - generate {2} function pieces    \n", junk_count, obfuscat_code_count, label_extra_count), Color.Green);

            System.IO.File.WriteAllText(outObfAsmPath, fixCode + "\n" + extCode);
            return true;
        }

19 Source : UI.cs
with MIT License
from aaaddress1

private void refreshUi(object sender, EventArgs e)
        {
            /* i'm too lazy to make a editor for C/C++ :P,
             * and this editor is really useful!!
             * https://github.com/PavelTorgashov/FastColoredTextBox */
            fastColoredTextBox.Language = FastColoredTextBoxNS.Language.CSharp;

            if (srcPath == "")
                srcPath = Path.Combine(Application.StartupPath, "main.cpp");

            if (!File.Exists(srcPath))
                File.WriteAllText(srcPath, Properties.Resources.templateSrc);

            fastColoredTextBox.InsertText(File.ReadAllText(srcPath));

            asmPath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + ".s");
            obfAsmPath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + "_obf.s");
            exePath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + ".exe");
            this.Text = string.Format("puzzCode [{0}] by [email protected]", new FileInfo(srcPath).Name);

            logBox.Clear();
            logMsg(demostr, Color.Blue);

            compiler.logText = this.logBox;
            obfuscator.logText = this.logBox;

            this.splitContainer.Panel2Collapsed = true;

            if (!new DirectoryInfo(Properties.Settings.Default.gwPath).Exists)
            {
                MessageBox.Show("please choose your MinGW path.");
                (new config()).ShowDialog();
                if (!new DirectoryInfo(Properties.Settings.Default.gwPath).Exists)
                {
                    MessageBox.Show("sorry, MinGW not found :(");
                    Application.Exit();
                }
            }
        }

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

static int Main(string[] args)
        {
            var config = File.ReadAllText("app.conf");
            var conf = ConfigurationFactory.ParseString(config)
                .WithFallback(OpsConfig.GetOpsConfig())
                .WithFallback(ClusterSharding.DefaultConfig())
                .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem = ActorSystem.Create("AkkaTrader", conf.BootstrapFromDocker());

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                var sharding = ClusterSharding.Get(actorSystem);

                var shardRegionProxy = sharding.StartProxy("orderBook", "trade-processor", new StockShardMsgRouter());
                foreach (var stock in AvailableTickerSymbols.Symbols)
                {
                    var max = (decimal)ThreadLocalRandom.Current.Next(20, 45);
                    var min = (decimal) ThreadLocalRandom.Current.Next(10, 15);
                    var range = new PriceRange(min, 0.0m, max);

                    // start bidders
                    foreach (var i in Enumerable.Repeat(1, ThreadLocalRandom.Current.Next(1, 2)))
                    {
                        actorSystem.ActorOf(Props.Create(() => new BidderActor(stock, range, shardRegionProxy)));
                    }

                    // start askers
                    foreach (var i in Enumerable.Repeat(1, ThreadLocalRandom.Current.Next(1, 2)))
                    {
                        actorSystem.ActorOf(Props.Create(() => new AskerActor(stock, range, shardRegionProxy)));
                    }
                }
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);
            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance);
            pbm.RegisterCommandPalette(RemoteCommands.Instance);
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return 0;
        }

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

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

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

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

static int Main(string[] args)
        {
            var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();
            if (string.IsNullOrEmpty(mongoConnectionString))
            {
                Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                return -1;
            }
            else
            {
                Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
            }

            var config = File.ReadAllText("app.conf");
            var conf = ConfigurationFactory.ParseString(config).WithFallback(GetMongoHocon(mongoConnectionString))
                .WithFallback(OpsConfig.GetOpsConfig())
                .WithFallback(ClusterSharding.DefaultConfig())
                .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem = ActorSystem.Create("AkkaPricing", conf.BootstrapFromDocker());
            var readJournal = actorSystem.ReadJournalFor<MongoDbReadJournal>(MongoDbReadJournal.Identifier);
            var priceViewMaster = actorSystem.ActorOf(Props.Create(() => new PriceViewMaster()), "prices");

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
            var sharding = ClusterSharding.Get(actorSystem);

            var shardRegion = sharding.Start("priceAggregator",
                s => Props.Create(() => new MatchAggregator(s, readJournal)),
                ClusterShardingSettings.Create(actorSystem),
                new StockShardMsgRouter());

            // used to seed pricing data
            var singleton = ClusterSingletonManager.Props(
                Props.Create(() => new PriceInitiatorActor(readJournal, shardRegion)),
                ClusterSingletonManagerSettings.Create(
                    actorSystem.Settings.Config.GetConfig("akka.cluster.price-singleton")));

                // start the creation of the pricing views
                priceViewMaster.Tell(new PriceViewMaster.BeginTrackPrices(shardRegion));
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);
            void RegisterPalette(CommandPaletteHandler h)
            {
                if (pbm.RegisterCommandPalette(h))
                {
                    Console.WriteLine("Petabridge.Cmd - Registered {0}", h.Palette.ModuleName);
                }
                else
                {
                    Console.WriteLine("Petabridge.Cmd - DID NOT REGISTER {0}", h.Palette.ModuleName);
                }
            }


            RegisterPalette(ClusterCommands.Instance);
            RegisterPalette(RemoteCommands.Instance);
            RegisterPalette(ClusterShardingCommands.Instance);
            RegisterPalette(new PriceCommands(priceViewMaster));
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return 0;
        }

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

static int Main(string[] args)
        {
            var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STR")?.Trim();
            if (string.IsNullOrEmpty(mongoConnectionString))
            {
                Console.WriteLine("ERROR! MongoDb connection string not provided. Can't start.");
                return -1;
            }
            else
            {
                Console.WriteLine("Connecting to MongoDb at {0}", mongoConnectionString);
            }

            var config = File.ReadAllText("app.conf");
            var conf = ConfigurationFactory.ParseString(config).WithFallback(GetMongoHocon(mongoConnectionString))
                .WithFallback(OpsConfig.GetOpsConfig())
                .WithFallback(ClusterSharding.DefaultConfig())
                .WithFallback(DistributedPubSub.DefaultConfig());

            var actorSystem = ActorSystem.Create("AkkaTrader", conf.BootstrapFromDocker());

            Cluster.Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                var sharding = ClusterSharding.Get(actorSystem);

                var shardRegion = sharding.Start("orderBook", s => OrderBookActor.PropsFor(s), ClusterShardingSettings.Create(actorSystem),
                    new StockShardMsgRouter());
            });

            // start Petabridge.Cmd (for external monitoring / supervision)
            var pbm = PetabridgeCmd.Get(actorSystem);
            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance);
            pbm.RegisterCommandPalette(RemoteCommands.Instance);
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            return 0;
        }

19 Source : JsonConfigurator.cs
with MIT License
from Abc-Arbitrage

private static string? ReadFileContentWithRetry(string filepath)
        {
            const int numberOfRetries = 3;
            const int delayOnRetry = 1000;

            for (var i = 0; i < numberOfRetries; i++)
            {
                try
                {
                    return File.ReadAllText(filepath);
                }
                catch (IOException)
                {
                    Thread.Sleep(delayOnRetry);
                }
            }

            return null;
        }

19 Source : GltfUtility.cs
with Apache License 2.0
from abist-co-ltd

public static async Task<GltfObject> ImportGltfObjectFromPathAsync(string uri)
        {
            if (!SyncContextUtility.IsMainThread)
            {
                Debug.LogError("ImportGltfObjectFromPathAsync must be called from the main thread!");
                return null;
            }

            if (string.IsNullOrWhiteSpace(uri))
            {
                Debug.LogError("Uri is not valid.");
                return null;
            }

            GltfObject gltfObject;
            bool useBackgroundThread = Application.isPlaying;

            if (useBackgroundThread) { await BackgroundThread; }

            if (uri.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase))
            {
                string gltfJson = File.ReadAllText(uri);

                gltfObject = GetGltfObjectFromJson(gltfJson);

                if (gltfObject == null)
                {
                    Debug.LogError("Failed load Gltf Object from json schema.");
                    return null;
                }
            }
            else if (uri.EndsWith(".glb", StringComparison.OrdinalIgnoreCase))
            {
                byte[] glbData;

#if WINDOWS_UWP

                if (useBackgroundThread)
                {
                    try
                    {
                        var storageFile = await StorageFile.GetFileFromPathAsync(uri);

                        if (storageFile == null)
                        {
                            Debug.LogError($"Failed to locate .glb file at {uri}");
                            return null;
                        }

                        var buffer = await FileIO.ReadBufferAsync(storageFile);

                        using (DataReader dataReader = DataReader.FromBuffer(buffer))
                        {
                            glbData = new byte[buffer.Length];
                            dataReader.ReadBytes(glbData);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e.Message);
                        return null;
                    }
                }
                else
                {
                    glbData = UnityEngine.Windows.File.ReadAllBytes(uri);
                }
#else
                using (FileStream stream = File.Open(uri, FileMode.Open))
                {
                    glbData = new byte[stream.Length];

                    if (useBackgroundThread)
                    {
                        await stream.ReadAsync(glbData, 0, (int)stream.Length);
                    }
                    else
                    {
                        stream.Read(glbData, 0, (int)stream.Length);
                    }
                }
#endif

                gltfObject = GetGltfObjectFromGlb(glbData);

                if (gltfObject == null)
                {
                    Debug.LogError("Failed to load GlTF Object from .glb!");
                    return null;
                }
            }
            else
            {
                Debug.LogError("Unsupported file name extension.");
                return null;
            }

            gltfObject.Uri = uri;

            try
            {
                gltfObject.Name = Path.GetFileNameWithoutExtension(uri);
            }
            catch (ArgumentException)
            {
                Debug.LogWarning("Uri contained invalid character");
                gltfObject.Name = DefaultObjectName;
            }

            gltfObject.UseBackgroundThread = useBackgroundThread;
            await gltfObject.ConstructAsync();

            if (gltfObject.GameObjectReference == null)
            {
                Debug.LogError("Failed to construct Gltf Object.");
            }

            if (useBackgroundThread) { await Update; }

            return gltfObject;
        }

19 Source : ControllerPopupWindow.cs
with Apache License 2.0
from abist-co-ltd

public static void Show(MixedRealityControllerMapping controllerMapping, SerializedProperty interactionsList, Handedness handedness = Handedness.None)
        {
            if (window != null)
            {
                window.Close();
            }

            window = null;

            window = CreateInstance<ControllerPopupWindow>();
            window.thisWindow = window;
            window.replacedleContent = new GUIContent($"{controllerMapping.Description} - Input Action replacedignment");
            window.currentControllerMapping = controllerMapping;
            window.currentInteractionList = interactionsList;
            isMouseInRects = new bool[interactionsList.arraySize];

            string editorWindowOptionsPath = ResolveEditorWindowOptionsPath();
            if (!File.Exists(editorWindowOptionsPath))
            {
                var empty = new ControllerInputActionOptions
                {
                    Controllers = new List<ControllerInputActionOption>
                    {
                        new ControllerInputActionOption
                        {
                            Controller = 0,
                            Handedness = Handedness.None,
                            InputLabelPositions = new[] {new Vector2(0, 0)},
                            IsLabelFlipped = new []{false}
                        }
                    }
                };

                File.WriteAllText(editorWindowOptionsPath, JsonUtility.ToJson(empty, true));
                replacedetDatabase.Refresh(ImportreplacedetOptions.ForceUpdate);
            }
            else
            {
                controllerInputActionOptions = JsonUtility.FromJson<ControllerInputActionOptions>(File.ReadAllText(editorWindowOptionsPath));

                if (controllerInputActionOptions.Controllers.Any(option => option.Controller == controllerMapping.SupportedControllerType && option.Handedness == handedness))
                {
                    window.currentControllerOption = controllerInputActionOptions.Controllers.FirstOrDefault(option => option.Controller == controllerMapping.SupportedControllerType && option.Handedness == handedness);

                    if (window.currentControllerOption != null && window.currentControllerOption.IsLabelFlipped == null)
                    {
                        window.currentControllerOption.IsLabelFlipped = new bool[interactionsList.arraySize];
                    }
                }
            }

            var windowSize = new Vector2(controllerMapping.HasCustomInteractionMappings ? 896f : 768f, 512f);
            window.maxSize = windowSize;
            window.minSize = windowSize;
            window.CenterOnMainWin();
            window.ShowUtility();

            defaultLabelWidth = EditorGUIUtility.labelWidth;
            defaultFieldWidth = EditorGUIUtility.fieldWidth;
        }

19 Source : UnityPlayerBuildTools.cs
with Apache License 2.0
from abist-co-ltd

public static void ParseBuildCommandLine(ref IBuildInfo buildInfo)
        {
            string[] arguments = Environment.GetCommandLineArgs();

            for (int i = 0; i < arguments.Length; ++i)
            {
                switch (arguments[i])
                {
                    case "-autoIncrement":
                        buildInfo.AutoIncrement = true;
                        break;
                    case "-sceneList":
                        buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(arguments[++i]));
                        break;
                    case "-sceneListFile":
                        string path = arguments[++i];
                        if (File.Exists(path))
                        {
                            buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(File.ReadAllText(path)));
                        }
                        else
                        {
                            Debug.LogWarning($"Scene list file at '{path}' does not exist.");
                        }
                        break;
                    case "-buildOutput":
                        buildInfo.OutputDirectory = arguments[++i];
                        break;
                    case "-colorSpace":
                        buildInfo.ColorSpace = (ColorSpace)Enum.Parse(typeof(ColorSpace), arguments[++i]);
                        break;
                    case "-scriptingBackend":
                        buildInfo.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), arguments[++i]);
                        break;
                    case "-x86":
                    case "-x64":
                    case "-arm":
                    case "-arm64":
                        buildInfo.BuildPlatform = arguments[i].Substring(1);
                        break;
                    case "-debug":
                    case "-master":
                    case "-release":
                        buildInfo.Configuration = arguments[i].Substring(1).ToLower();
                        break;
                    case "-logDirectory":
                        buildInfo.LogDirectory = arguments[++i];
                        break;
                }
            }
        }

19 Source : MixedRealityStandardShaderGUI.cs
with Apache License 2.0
from abist-co-ltd

[MenuItem("Mixed Reality Toolkit/Utilities/Upgrade MRTK Standard Shader for Lightweight Render Pipeline")]
        protected static void UpgradeShaderForLightweightRenderPipeline()
        {
            if (EditorUtility.DisplayDialog("Upgrade MRTK Standard Shader?", 
                                            "This will alter the MRTK Standard Shader for use with Unity's Lightweight Render Pipeline. You cannot undo this action.", 
                                            "Ok", 
                                            "Cancel"))
            {
                string path = replacedetDatabase.GetreplacedetPath(StandardShaderUtility.MrtkStandardShader);

                if (!string.IsNullOrEmpty(path))
                {
                    try
                    {
                        string upgradedShader = File.ReadAllText(path);
                        upgradedShader = upgradedShader.Replace("Tags{ \"RenderType\" = \"Opaque\" \"LightMode\" = \"ForwardBase\" }",
                                                                "Tags{ \"RenderType\" = \"Opaque\" \"LightMode\" = \"LightweightForward\" }");
                        upgradedShader = upgradedShader.Replace("//#define _LIGHTWEIGHT_RENDER_PIPELINE",
                                                                "#define _LIGHTWEIGHT_RENDER_PIPELINE");
                        File.WriteAllText(path, upgradedShader);
                        replacedetDatabase.Refresh();

                        Debug.LogFormat("Upgraded {0} for use with the Lightweight Render Pipeline.", path);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
                else
                {
                    Debug.LogErrorFormat("Failed to get replacedet path to: {0}", StandardShaderUtility.MrtkStandardShaderName);
                }
            }
        }

19 Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd

internal static bool IsMSBuildForUnityEnabled()
        {
            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return false;
            }

            // Load the manifest file.
            string manifestFileContents = File.ReadAllText(manifestPath);
            if (string.IsNullOrWhiteSpace(manifestFileContents))
            {
                return false;
            }

            // Read the package manifest a line at a time.
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (line.Contains(MSBuildPackageName))
                        {
                            // Split the line into packageName : packageVersion
                            string[] lineComponents = line.Split(new char[] { ':' }, 2);

                            return IsAppropriateMBuildVersion(MSBuildPackageVersion, lineComponents[1]);
                        }
                    }
                }
            }

            return false;
        }

19 Source : AssemblyDefinition.cs
with Apache License 2.0
from abist-co-ltd

public static replacedemblyDefinition Load(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                Debug.LogError("An replacedembly definition file name must be specified.");
                return null;
            }

            FileInfo file = new FileInfo(fileName);
            if (!file.Exists)
            {
                Debug.LogError($"The {fileName} file could not be found.");
                return null;
            }

            return JsonUtility.FromJson<replacedemblyDefinition>(File.ReadAllText(file.FullName));
        }

19 Source : EcojiTests.cs
with MIT License
from abock

[Theory]
    [MemberData(nameof(FileTestCases))]
    public void RoundTripFile(
        string testName, // for logging; Xunit truncates the paths early 🙄
        string inputFile,
        string ecojiReferenceFile)
    {
        replacedert.NotNull(testName); // hush warning xUnit1026

        const int wrap = 76; // reference ecoji was produced with default wrap

        var inputBytes = File.ReadAllBytes(inputFile);
        var expectedEcojiString = File.ReadAllText(ecojiReferenceFile);
        
        var actualEcojiString = Ecoji.Encode(
            inputBytes, 
            new Ecoji.EncodingOptions(wrap: wrap, newLine: "\n"));

        replacedert.Equal(expectedEcojiString, actualEcojiString);

        var roundTripBytes = Ecoji.Decode(actualEcojiString);

        replacedert.Equal(inputBytes, roundTripBytes);
    }

19 Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy

[MenuItem("Oculus/Video/Disable Native Android Video Player")]
    public static void DisableNativeVideoPlayer()
    {
        if (File.Exists(videoPlayerFileName))
        {
            File.Move(videoPlayerFileName, disabledPlayerFileName);
            File.Move(videoPlayerFileName + ".meta", disabledPlayerFileName + ".meta");
        }

        replacedetDatabase.Importreplacedet(disabledPlayerFileName);
        replacedetDatabase.Deletereplacedet(videoPlayerFileName);

        // Disable audio plugins
        PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
        PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);

        if (audio360 != null && audio360exo29 != null)
        {
            audio360.SetCompatibleWithPlatform(BuildTarget.Android, false);
            audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, false);
            audio360.SaveAndReimport();
            audio360exo29.SaveAndReimport();
        }

        // remove exoplayer and sourcesets from gradle file (leave other parts since they are harmless).
        if (File.Exists(gradleTemplatePath))
        {
            // parse the gradle file to check the current version:
            string currentFile = File.ReadAllText(gradleTemplatePath);

            List<string> lines = new List<string>(currentFile.Split('\n'));

            int dependencies = GoToSection("dependencies", lines);
            int exoplayer = FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines);
            if (exoplayer != -1)
            {
                lines.RemoveAt(exoplayer);
            }

            int android = GoToSection("android", lines);
            int sourceSets = FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines);
            if (sourceSets != -1)
            {
                lines.RemoveAt(sourceSets);
            }

            File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
        }
    }

19 Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy

[MenuItem("Oculus/Video/Enable Native Android Video Player")]
    public static void EnableNativeVideoPlayer()
    {
        // rename NativeJavaPlayer.java.DISABLED to NativeJavaPlayer.java
        if (File.Exists(disabledPlayerFileName))
        {
            File.Move(disabledPlayerFileName, videoPlayerFileName);
            File.Move(disabledPlayerFileName + ".meta", videoPlayerFileName + ".meta");
        }

        replacedetDatabase.Importreplacedet(videoPlayerFileName);
        replacedetDatabase.Deletereplacedet(disabledPlayerFileName);

        // Enable audio plugins
        PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
        PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);

        if (audio360 != null && audio360exo29 != null)
        {
            audio360.SetCompatibleWithPlatform(BuildTarget.Android, true);
            audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, true);
            audio360.SaveAndReimport();
            audio360exo29.SaveAndReimport();
        }

        // Enable gradle build with exoplayer
        EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;

        // create android plugins directory if it doesn't exist
        if (!Directory.Exists(androidPluginsFolder))
        {
            Directory.CreateDirectory(androidPluginsFolder);
        }

        if (!File.Exists(gradleTemplatePath))
        {
            if (File.Exists(gradleTemplatePath + ".DISABLED"))
            {
                File.Move(disabledGradleTemplatePath, gradleTemplatePath);
                File.Move(disabledGradleTemplatePath + ".meta", gradleTemplatePath+".meta");
            }
            else
            {
                File.Copy(internalGradleTemplatePath, gradleTemplatePath);
            }
            replacedetDatabase.Importreplacedet(gradleTemplatePath);
        }

        // parse the gradle file to check the current version:
        string currentFile = File.ReadAllText(gradleTemplatePath);

        List<string> lines = new List<string>(currentFile.Split('\n'));

        var gradleVersion = new System.Text.RegularExpressions.Regex("com.android.tools.build:gradle:([0-9]+\\.[0-9]+\\.[0-9]+)").Match(currentFile).Groups[1].Value;

        if (gradleVersion == "2.3.0")
        {
            // add google() to buildscript/repositories
            int buildscriptRepositories = GoToSection("buildscript.repositories", lines);

            if (FindInScope("google\\(\\)", buildscriptRepositories + 1, lines) == -1)
            {
                lines.Insert(GetScopeEnd(buildscriptRepositories + 1, lines), "\t\tgoogle()");
            }

            // add google() and jcenter() to allprojects/repositories
            int allprojectsRepositories = GoToSection("allprojects.repositories", lines);

            if (FindInScope("google\\(\\)", allprojectsRepositories + 1, lines) == -1)
            {
                lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tgoogle()");
            }
            if (FindInScope("jcenter\\(\\)", allprojectsRepositories + 1, lines) == -1)
            {
                lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tjcenter()");
            }
        }

        // add "compile 'com.google.android.exoplayer:exoplayer:2.9.5'" to dependencies
        int dependencies = GoToSection("dependencies", lines);
        if (FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines) == -1)
        {
            lines.Insert(GetScopeEnd(dependencies + 1, lines), "\tcompile 'com.google.android.exoplayer:exoplayer:2.9.5'");
        }

        int android = GoToSection("android", lines);

        // add compileOptions to add Java 1.8 compatibility
        if (FindInScope("compileOptions", android + 1, lines) == -1)
        {
            int compileOptionsIndex = GetScopeEnd(android + 1, lines);
            lines.Insert(compileOptionsIndex, "\t}");
            lines.Insert(compileOptionsIndex, "\t\ttargetCompatibility JavaVersion.VERSION_1_8");
            lines.Insert(compileOptionsIndex, "\t\tsourceCompatibility JavaVersion.VERSION_1_8");
            lines.Insert(compileOptionsIndex, "\tcompileOptions {");
        }

        // add sourceSets if Version < 2018.2
#if !UNITY_2018_2_OR_NEWER

        if (FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines) == -1)
        {
            lines.Insert(GetScopeEnd(android + 1, lines), "\tsourceSets.main.java.srcDir \"" + gradleSourceSetPath + "\"");
        }
#endif

        File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
    }

19 Source : OVRGradleGeneration.cs
with MIT License
from absurd-joy

public void OnPostGenerateGradleAndroidProject(string path)
	{
		UnityEngine.Debug.Log("OVRGradleGeneration triggered.");

		var targetOculusPlatform = new List<string>();
		if (OVRDeviceSelector.isTargetDeviceQuest)
		{
			targetOculusPlatform.Add("quest");
		}
		OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
		UnityEngine.Debug.LogFormat("Quest = {0}", OVRDeviceSelector.isTargetDeviceQuest);

#if UNITY_2019_3_OR_NEWER
		string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle");
#else
		string gradleBuildPath = Path.Combine(path, "build.gradle");
#endif
		bool v2SigningEnabled = true;

		if (File.Exists(gradleBuildPath))
		{
			try
			{
				string gradle = File.ReadAllText(gradleBuildPath);
				int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");

				if (v2Signingindex != -1)
				{
					//v2 Signing flag found, ensure the correct value is set based on platform.
					if (v2SigningEnabled)
					{
						gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
						System.IO.File.WriteAllText(gradleBuildPath, gradle);
					}
				}
				else
				{
					//v2 Signing flag missing, add it right after the key store preplacedword and set the value based on platform.
					int keyPreplacedIndex = gradle.IndexOf("keyPreplacedword");
					if (keyPreplacedIndex != -1)
					{
						int v2Index = gradle.IndexOf("\n", keyPreplacedIndex) + 1;
						if(v2Index != -1)
						{
							gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n");
							System.IO.File.WriteAllText(gradleBuildPath, gradle);
						}
					}
				}
			}
			catch (System.Exception e)
			{
				UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
			}
		}
		else
		{
			UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
		}

		PatchAndroidManifest(path);
	}

See More Examples