System.IO.File.ReadAllText(string, System.Text.Encoding)

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

1952 Examples 7

19 View Source File : GenerateCommand.cs
License : MIT License
Project Creator : 188867052

private int Initialize()
        {
            try
            {
                CommondConfig config = new CommondConfig();

                // From console.
                if (!string.IsNullOrEmpty(this.ProjectName))
                {
                    string fileFullPath = Directory.GetFiles(".", $"{this.ProjectName}.csproj", SearchOption.AllDirectories).FirstOrDefault();
                    if (string.IsNullOrEmpty(fileFullPath))
                    {
                        System.Console.Write($"Project {this.ProjectName} is not exist.");
                        return 1;
                    }

                    config.ProjectPath = new FileInfo(fileFullPath).DirectoryName;
                    config.ProjectName = this.ProjectName;
                    config.GenerateMethod = this.GenerateMethod == "1" || this.GenerateMethod.Equals("true", StringComparison.InvariantCultureIgnoreCase);
                }
                else
                {
                    // From appsettings.json.
                    this.ConfigJsonPath = Directory.GetFiles(".", "appsettings.json", SearchOption.AllDirectories).FirstOrDefault();
                    if (string.IsNullOrEmpty(this.ConfigJsonPath))
                    {
                        this.Console.WriteLine("No appsettings.json file found, will generate code with default setting.");
                    }

                    string appSettings = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(this.ConfigJsonPath)).RouteGenerator.ToString();
                    config = JsonConvert.DeserializeObject<CommondConfig>(appSettings);
                    if (string.IsNullOrEmpty(config.ProjectName))
                    {
                        System.Console.Write($"Please provide ProjectName.");
                        return 1;
                    }

                    string fileFullPath = Directory.GetFiles(".", $"{config.ProjectName}.csproj", SearchOption.AllDirectories).FirstOrDefault();
                    if (string.IsNullOrEmpty(fileFullPath))
                    {
                        System.Console.Write($"Project {config.ProjectName} is not exist.");
                        return 1;
                    }

                    config.ProjectPath = new FileInfo(fileFullPath).DirectoryName;
                }

                this.Config = config;
                this.Console.WriteLine(JsonConvert.SerializeObject(config, Formatting.Indented));

                if (string.IsNullOrEmpty(this.Config.OutPutFile))
                {
                    this.Config.OutPutFile = "Routes.Generated.cs";
                }

                if (!this.Config.OutPutFile.EndsWith(".cs"))
                {
                    this.Config.OutPutFile += ".cs";
                }

                if (string.IsNullOrEmpty(this.Config.ProjectName))
                {
                    this.Console.WriteLine($"Please provide ProjectName.");
                    return 1;
                }
            }
            catch (Exception ex)
            {
                this.Console.WriteLine("Read config file error.");
                this.Console.WriteLine(ex.Message);
                this.Console.WriteLine(ex.StackTrace);
                return 1;
            }

            return 0;
        }

19 View Source File : ConfigManager.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void Load()
    {
        // Load the config file if its not possible create one with the default values
        if (!File.Exists(Application.dataPath + FILE_NAME))
        {
            CreateConfigFile();
            // Set the default config variables to the settings.
            SetValuesByConfigObject(defaultConfig);
        }
        else
        {
            string loadedString = File.ReadAllText(Application.dataPath + FILE_NAME);

            ConfigObject loadedConfig;
            try
            {
                loadedConfig = JsonUtility.FromJson<ConfigObject>(loadedString);
                Debug.Log("Config File Loaded Successfully");
            }
            catch
            {
                loadedConfig = defaultConfig;
                CreateConfigFile();
            }

            // Set the loaded config variables to the settings.
            // If the Json file was corrupted or was unable to deserialize then 
            // we simply apply the default config values.
            SetValuesByConfigObject(loadedConfig);
        }
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8x8

static RSA ReadPrivateKeyFromFile(String privateKeyFilePath, PKType pkType)
        {
            var rsa = RSA.Create();
            var privateKeyContent = File.ReadAllText(privateKeyFilePath, System.Text.Encoding.UTF8);
            privateKeyContent = privateKeyContent.Replace(pkType == PKType.PKCS1 ? Program.BEGIN_PKCS1_PRIVATE_KEY : Program.BEGIN_PKCS8_PRIVATE_KEY, "");
            privateKeyContent = privateKeyContent.Replace(pkType == PKType.PKCS1 ? Program.END_PKCS1_PRIVATE_KEY : Program.END_PKCS8_PRIVATE_KEY, "");
            var privateKeyDecoded = Convert.FromBase64String(privateKeyContent);
            if (pkType == PKType.PKCS1)
            {
                rsa.ImportRSAPrivateKey(privateKeyDecoded, out _);
            }
            else
            {
                rsa.ImportPkcs8PrivateKey(privateKeyDecoded, out _);
            }

            return rsa;
        }

19 View Source File : Hentai.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public static HentaiType GetSource(DirectoryInfo dir)
        {
            try
            {
                string input = File.ReadAllText(FileHelper.GetFilePath(dir, "manga.json"));
                MangaInfo info = JsonConvert.DeserializeObject<MangaInfo>(input);
                switch (info.Source)
                {
                    case "nhentai":
                        return HentaiType.NHENTAI;
                    default:
                        return HentaiType.NULL;
                }
            }
            catch (Exception)
            {
                return HentaiType.NULL;
            }
        }

19 View Source File : Manga.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public static MangaType GetSource(DirectoryInfo dir)
        {
            try
            {
                string input = File.ReadAllText(FileHelper.GetFilePath(dir, "manga.json"));
                MangaInfo info = JsonConvert.DeserializeObject<MangaInfo>(input);
                switch (info.Source)
                {
                    case "mangadex":
                        return MangaType.MANGADEX;
                    case "kissmanga":
                        return MangaType.KISSMANGA;
                    default:
                        return MangaType.NULL;
                }
            }
            catch (Exception)
            {
                return MangaType.NULL;
            }
        }

19 View Source File : Title.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public static replacedleType GetType(DirectoryInfo dir)
        {
            try
            {
                string input = File.ReadAllText(FileHelper.GetFilePath(dir, "manga.json"));
                MangaInfo info = JsonConvert.DeserializeObject<MangaInfo>(input);
                switch (info.Type)
                {
                    case "manga":
                        return replacedleType.MANGA;
                    case "hentai":
                        return replacedleType.HENTAI;
                    default:
                        return replacedleType.NULL;
                }
            } catch (Exception)
            {
                return replacedleType.NULL;
            }
        }

19 View Source File : KissManga.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Load(bool doChapters)
        {
            string input = File.ReadAllText(FileHelper.GetFilePath(mangaRoot, "manga.json"));
            MangaInfo info = JsonConvert.DeserializeObject<MangaInfo>(input);

            id = info.Id;
            name = info.Name;
            userlang = info.LangCode;
            usergroup = info.Group;
            userreplacedle = info.UserName;
            currentchapter = info.Chapter;
            currentpage = info.Page;
            lastchapter = info.Latest;

            if (doChapters)
                _PopulateChapters();
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Load(bool doChapters)
        {
            string input = File.ReadAllText(FileHelper.GetFilePath(mangaRoot, "manga.json"));
            MangaInfo info = JsonConvert.DeserializeObject<MangaInfo>(input);       

            id = info.Id;
            name = info.Name;
            userlang = info.LangCode;
            usergroup = info.Group;
            userreplacedle = info.UserName;
            currentchapter = info.Chapter;
            currentpage = info.Page;
            lastchapter = info.Latest;

            if (doChapters)
                _PopulateChapters();
        }

19 View Source File : Nhentai.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Load()
        {
            string input = File.ReadAllText(FileHelper.GetFilePath(hentaiRoot, "manga.json"));
            MangaInfo info = JsonConvert.DeserializeObject<MangaInfo>(input);

            id = info.Id;
            name = info.Name;
            userreplacedle = info.UserName;
            currentpage = info.Page;

            _PopulateChapters();
        }

19 View Source File : FrmHentaiSettings.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void FrmHentaiSettings_Load(object sender, EventArgs e)
        {
            if (File.Exists(m.mangaDirectory.FullName + "\\replacedle"))
            {
                txtName.Text = File.ReadAllText(m.mangaDirectory.FullName + "\\replacedle");
            }
        }

19 View Source File : FrmStartPage.cs
License : GNU General Public License v3.0
Project Creator : 9vult

private void BtnHentaiSettings_Click(object sender, EventArgs e)
        {
            foreach (Manga m in mangas)
            {
                if (File.Exists(m.mangaDirectory.FullName + "\\replacedle"))
                {
                    string replacedle = File.ReadAllText(m.mangaDirectory.FullName + "\\replacedle");
                    if (replacedle.StartsWith(lstHentai.SelectedItem.ToString().Split('»')[0].Trim()))
                    {
                        new FrmHentaiSettings(m).ShowDialog();
                        break;
                    }
                }
            }
            RefreshContents();
        }

19 View Source File : SettingsManager.cs
License : MIT License
Project Creator : a1xd

private DriverConfig InitActiveAndGetUserConfig()
        {
            var path = Constants.DefaultSettingsFileName;
            if (File.Exists(path))
            {
                try
                {
                    var (cfg, err) = DriverConfig.Convert(File.ReadAllText(path));

                    if (err == null)
                    {
                        if (GuiSettings.AutoWriteToDriverOnStartup)
                        {
                            if (!TryActivate(cfg, out string _))
                            {
                                throw new Exception("deserialization succeeded but TryActivate failed");
                            }
                        }
                        else
                        {
                            ActiveConfig = DriverConfig.GetActive();
                        }

                        return cfg;
                    }
                }
                catch (JsonException e)
                {
                    System.Diagnostics.Debug.WriteLine($"bad settings: {e}");
                }
            }

            ActiveConfig = DriverConfig.GetActive();
            File.WriteAllText(path, ActiveConfig.ToJSON());
            return ActiveConfig;
        }

19 View Source File : GUISettings.cs
License : MIT License
Project Creator : a1xd

public static GUISettings MaybeLoad()
        {
            GUISettings settings = null;

            try
            {
                settings = JsonConvert.DeserializeObject<GUISettings>(
                    File.ReadAllText(Constants.GuiConfigFileName));
            }
            catch (Exception ex)
            {
                if (!(ex is JsonException || ex is FileNotFoundException))
                {
                    throw;
                }
            }

            return settings;
        }

19 View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063

private void lkbReadSend_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog ofdg = new OpenFileDialog();
            if (ofdg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                string file = ofdg.FileName;//得到选择的文件的完整路径
                txtSendData.Text = System.IO.File.ReadAllText(file, Encoding.Default);//把读出来的数据显示在textbox中
            }
        }

19 View Source File : ConfigurationStore.cs
License : MIT License
Project Creator : actions

public RunnerSettings GetSettings()
        {
            if (_settings == null)
            {
                RunnerSettings configuredSettings = null;
                if (File.Exists(_configFilePath))
                {
                    string json = File.ReadAllText(_configFilePath, Encoding.UTF8);
                    Trace.Info($"Read setting file: {json.Length} chars");
                    configuredSettings = StringUtil.ConvertFromJson<RunnerSettings>(json);
                }

                ArgUtil.NotNull(configuredSettings, nameof(configuredSettings));
                _settings = configuredSettings;
            }

            return _settings;
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

public static T LoadObject<T>(string path)
        {
            string json = File.ReadAllText(path, Encoding.UTF8);
            return StringUtil.ConvertFromJson<T>(json);
        }

19 View Source File : JobRunner.cs
License : MIT License
Project Creator : actions

private void LoadFromTelemetryFile(List<JobTelemetry> jobTelemetry)
        {
            try
            {
                var telemetryFilePath = HostContext.GetConfigFile(WellKnownConfigFile.Telemetry);
                if (File.Exists(telemetryFilePath))
                {
                    var telemetryData = File.ReadAllText(telemetryFilePath, Encoding.UTF8);
                    var telemetry = new JobTelemetry
                    {
                        Message = $"Runner File Telemetry:\n{telemetryData}",
                        Type = JobTelemetryType.General
                    };
                    jobTelemetry.Add(telemetry);
                    IOUtil.DeleteFile(telemetryFilePath);
                }
            }
            catch (Exception e)
            {
                Trace.Error("Error when trying to load telemetry from telemetry file");
                Trace.Error(e);
            }
        }

19 View Source File : CodeFile.cs
License : MIT License
Project Creator : adamant

public static CodeFile Load(string path, FixedList<string> @namespace)
        {
            var fullPath = Path.GetFullPath(path);
            return new CodeFile(new CodePath(fullPath, @namespace), new CodeText(File.ReadAllText(fullPath, Encoding)));
        }

19 View Source File : CodePath.cs
License : MIT License
Project Creator : adamant

public CodeFile Load()
        {
            var text = File.ReadAllText(Path, CodeFile.Encoding);
            return new CodeFile(this, new CodeText(text));
        }

19 View Source File : TestCase.cs
License : MIT License
Project Creator : adamant

protected string LoadCode() => File.ReadAllText(FullCodePath, CodeFile.Encoding);

19 View Source File : ConformanceTests.cs
License : MIT License
Project Creator : adamant

private static string ExpectedOutput(
            string code,
            string channel,
            string testCasePath)
        {
            // First check if there is a file for the expected output
            var match = Regex.Match(code, string.Format(CultureInfo.InvariantCulture, ExpectedOutputFileFormat, channel));
            var path = match.Groups["file"]?.Captures.SingleOrDefault()?.Value;
            if (path != null)
            {
                var testCaseDirectory = Path.GetDirectoryName(testCasePath) ?? throw new InvalidOperationException();
                path = Path.Combine(testCaseDirectory, path);
                return File.ReadAllText(path);
            }

            // Then look for inline expected output
            match = Regex.Match(code, string.Format(CultureInfo.InvariantCulture, ExpectedOutputFormat, channel));
            return match.Groups["output"]?.Captures.SingleOrDefault()?.Value ?? "";
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : adamant

private static void WriteIfChanged(string filePath, string code)
        {
            var previousCode = File.Exists(filePath)
                ? File.ReadAllText(filePath, new UTF8Encoding(false, true))
                : null;
            if (code != previousCode) File.WriteAllText(filePath, code);
        }

19 View Source File : GenerateSourceOnlyPackageNuspecsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (PartNuspecFiles == null)
            {
                Log.LogMessage("No source-only packages found");
                return true; //nothing to process
            }

            //process the source files
            foreach (var sourceFile in PartNuspecFiles)
            {
                var partNuspecFileNameFull = sourceFile.GetMetadata("FullPath");

                //Get the partial (partnuspec) file
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = partNuspecFileNameFull + ".tmp.nuspec";
                Log.LogMessage($"Loading {partNuspecFileNameFull}");
                var partNuspecFileContent = File.ReadAllText(partNuspecFileNameFull);
                partNuspecFileContent = partNuspecFileContent.Replace("%%CURRENT_VERSION%%", PackageVersionFull);
                var outXDoc = XDoreplacedent.Parse(partNuspecFileContent);
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                //Check package ID
                var packageId = metadataXElement.Element(ns + "id")?.Value;
                if (packageId == null) throw new Exception($"Can't find the package ID for {partNuspecFileNameFull}");

                //Process version - global version from solution of base version from partial file
                var versionOriginal = GetOrCreateElement(metadataXElement, "version", ns)?.Value;
                var version = PackageVersionFull;
                if (!string.IsNullOrEmpty(versionOriginal))
                {
                    //base version set in NuProp
                    //get ext version from PackageVersionFull
                    //0.1.0-dev.441.181206212308+53.master.37f08fc-dirty
                    //0.1.0+442.181206212418.master.37f08fc-dirty
                    var idx = 0;
                    while (char.IsDigit(PackageVersionFull[idx]) || PackageVersionFull[idx] == '.')
                    {
                        idx++;
                    }

                    version = versionOriginal + PackageVersionFull.Substring(idx);
                }

                //Enrich the NuSpec
                SetOrCreateElement(metadataXElement, "version", ns, version);
                SetOrCreateElement(metadataXElement, "authors", ns, Authors);
                SetOrCreateElement(metadataXElement, "replacedle", ns, packageId);
                SetOrCreateElement(metadataXElement, "owners", ns, Authors);
                SetOrCreateElement(metadataXElement, "description", ns, $"Source only package {packageId}", false); //don't override if exists
                SetOrCreateElement(metadataXElement, "requireLicenseAcceptance", ns, PackageRequireLicenseAcceptance);
                if (!string.IsNullOrEmpty(PackageLicense))
                {
                    SetOrCreateElement(metadataXElement, "license", ns, PackageLicense).
                        Add(new XAttribute("type","expression"));
                }
                else
                {
                    SetOrCreateElement(metadataXElement, "licenseUrl", ns, PackageLicenseUrl);
                }
                SetOrCreateElement(metadataXElement, "projectUrl", ns, PackageProjectUrl);
                SetOrCreateElement(metadataXElement, "iconUrl", ns, PackageIconUrl);
                SetOrCreateElement(metadataXElement, "copyright", ns, Copyright);
                SetOrCreateElement(metadataXElement, "developmentDependency", ns, "true");
                GetEmptyOrCreateElement(metadataXElement, "repository", ns).
                                    Add(new XAttribute("url", RepositoryUrl),
                                        new XAttribute("type", "git"),
                                        new XAttribute("branch", GitBranch),
                                        new XAttribute("commit", GitCommit));

                //Save the temporary NuSpec file
                var outXDocStr = outXDoc.ToString();
                File.WriteAllText(outFile, outXDocStr);
                Log.LogMessage($"Generated source only nuspec file {outFile}");
            }

            return true;
        }

19 View Source File : ProcessNuPropsTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (SourceFiles == null)
            {
                Log.LogMessage("No source code available");
                return true; //nothing to process
            }

            //process the source files
            var anyPackageAvailable = false;
            foreach (var sourceFile in SourceFiles)
            {
                var fileNameFull = sourceFile.GetMetadata("FullPath");
                var fileName = new FileInfo(fileNameFull).Name;

                //Get the NuProps from XML Doreplacedentation Comments <NuProp.xxxx>
                var sourceContent = File.ReadAllText(fileNameFull);
                var sourceLines = sourceContent.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //Extract all comments
                var stringBuilder = new StringBuilder();
                foreach (var contentLine in sourceLines)
                {
                    var sourceLine = contentLine.Trim();
                    if (sourceLine.StartsWith("///"))
                    {
                        stringBuilder.AppendLine(sourceLine.Substring(3));
                    }
                }

                //Get all comments in single XML - encapsulate the whole bunch with dummy tag "doc" allowing the XDoreplacedent to parse it
                var xDoreplacedent = XDoreplacedent.Parse("<doc>" + stringBuilder + "</doc>");
                //Get NuProp comments
                var nuPropElements = xDoreplacedent.Descendants()
                    .Where(n => n is XElement e && e.Name.LocalName.StartsWith("NuProp.")).ToList();

                if (nuPropElements.Count <= 0) continue; //no NuProps - continue with the next file

                //Has some NuProp -> process
                //<NuProp.Id></NuProp.Id> - package ID (mandatory)
                //<NuProp.Version></NuProp.Version>   - package version base (major.minor.patch) - optional          
                //<NuProp.Description></NuProp.Description> - package description (optional)
                //<NuProp.Tags></NuProp.Tags> - package tags (optional)
                //<NuProp.Using id = "" version=""/> - package imports (optional). Version is optional
                //<NuProp.Needs id="" /> - "external" imports needed (optional) - not included in package, just info when consuming!!!

                var nuPropId = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Id")?.Value.Trim();
                var nuPropVersion = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Version")?.Value.Trim();
                var nuPropDescription = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Description")?.Value.Trim();
                var nuPropTags = nuPropElements.FirstOrDefault(e => e.Name.LocalName == "NuProp.Tags")?.Value.Trim();

                var nuPropsIncludes = IncludesEnum.None;
                var nuPropIncludesStr = nuPropElements
                    .FirstOrDefault(e => e.Name.LocalName == "NuProp.Includes" && e.Attribute("type")?.Value != null)?
                    .Attribute("type")?.Value;
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (nuPropIncludesStr)
                {
                    case "Folder": nuPropsIncludes = IncludesEnum.Folder; break;
                    case "FolderRecursive": nuPropsIncludes = IncludesEnum.FolderRecursive; break;
                }

                var nuPropUsings = nuPropElements.Where(e => e.Name.LocalName == "NuProp.Using" && e.Attribute("id")?.Value != null).ToList();

                if (string.IsNullOrEmpty(nuPropId))
                {
                    Log.LogWarning($"NuProp.Id not found for {fileName}");
                    continue;
                }

                //Build the partial NuSpec file
                anyPackageAvailable = true;
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = fileNameFull + ".partnuspec";
                var outXDoc = File.Exists(outFile) ? XDoreplacedent.Load(outFile) : new XDoreplacedent();
                var outXDocStrOriginal = outXDoc.ToString();
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                SetOrCreateElement(metadataXElement, "id", ns, nuPropId);
                SetOrCreateElement(metadataXElement, "version", ns, nuPropVersion, false); //don't create if the nuPropVersion is empty/not set
                SetOrCreateElement(metadataXElement, "description", ns, nuPropDescription, false); //don't create if the nuPropDescription is empty/not set
                SetOrCreateElement(metadataXElement, "tags", ns, nuPropTags, false); //don't create if the nuPropTags is empty/not set

                GetEmptyOrCreateElement(metadataXElement, "contentFiles", ns)
                    .Add(new XElement(ns + "files", //<files include="cs/**/*.*" buildAction="Compile" />
                        new XAttribute("include", "cs/**/*.*"),
                        new XAttribute("buildAction", "Compile")));


                //Dependencies
                var dependenciesXElement = GetEmptyOrCreateElement(metadataXElement, "dependencies", ns);
                if (nuPropUsings.Count > 0)
                {
                    //have some dependencies
                    foreach (var nuPropUsing in nuPropUsings)
                    {
                        // ReSharper disable once PossibleNullReferenceException - should not be null based on Where clause for nuPropUsings
                        var depId = nuPropUsing.Attribute("id").Value;
                        var depVersion = nuPropUsing.Attribute("version")?.Value;
                        var dependencyXElement = new XElement(ns + "dependency", new XAttribute("id", depId), new XAttribute("include", "all"));
                        if (string.IsNullOrEmpty(depVersion)) depVersion = "%%CURRENT_VERSION%%";
                        dependencyXElement.Add(new XAttribute("version", depVersion));
                        dependenciesXElement.Add(dependencyXElement);
                    }
                }
                else
                {
                    //Clean dependencies
                    dependenciesXElement.Remove();
                }

                //<files>
                //    < file src = "src.cs" target = "content\App_Packages\pkg_id\src.cs" />
                //    < file src = "src.cs" target = "contentFiles\cs\any\App_Packages\pkg_id\src.cs" />
                //</ files >
                var files = GetEmptyOrCreateElement(packageXElement, "files", ns);
                files.Add(
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{fileName}")),
                    new XElement(ns + "file", new XAttribute("src", fileName),
                        new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{fileName}")));

                if (nuPropsIncludes != IncludesEnum.None)
                {
                    var mainItemDir = sourceFile.GetMetadata("RootDir") + sourceFile.GetMetadata("Directory");
                    Log.LogMessage($"MainItemDir:{mainItemDir}");
                    IEnumerable<ITaskItem> itemsToAdd;
                    switch (nuPropsIncludes)
                    {
                        case IncludesEnum.Folder:
                            itemsToAdd = SourceFiles.Where(itm =>
                                itm.GetMetadata("RootDir") + itm.GetMetadata("Directory") == mainItemDir &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        case IncludesEnum.FolderRecursive:
                            itemsToAdd = SourceFiles.Where(itm =>
                                (itm.GetMetadata("RootDir") + itm.GetMetadata("Directory")).StartsWith(mainItemDir) &&
                                itm.GetMetadata("FullPath") != fileNameFull);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }

                    foreach (var item in itemsToAdd)
                    {
                        var itemFileFull = item.GetMetadata("FullPath");
                        Log.LogMessage($"itemFileFull:{itemFileFull}");
                        var itemFileRel = itemFileFull.Substring(mainItemDir.Length);
                        files.Add(
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"content\\App_Packages\\{nuPropId}\\{itemFileRel}")),
                            new XElement(ns + "file", new XAttribute("src", itemFileRel),
                                new XAttribute("target", $"contentFiles\\cs\\any\\App_Packages\\{nuPropId}\\{itemFileRel}")));
                    }
                }

                var outXDocStrNew = outXDoc.ToString();
                if (outXDocStrNew == outXDocStrOriginal) continue;

                //change - > save
                File.WriteAllText(outFile, outXDocStrNew);
                Log.LogMessage($"Generated/updated {outFile}");
            }

            if (!anyPackageAvailable)
            {
                Log.LogMessage("No source-only packages found");
            }
            return true;
        }

19 View Source File : ConfigureWritable.cs
License : MIT License
Project Creator : ADefWebserver

public void Update(Action<T> applyChanges)
        {
            var fileProvider = _environment.ContentRootFileProvider;
            var fileInfo = fileProvider.GetFileInfo(_file);
            var physicalPath = fileInfo.PhysicalPath;

            var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
            var sectionObject = jObject.TryGetValue(_section, out JToken section) ?
                JsonConvert.DeserializeObject<T>(section.ToString()) : (Value ?? new T());

            applyChanges(sectionObject);

            jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
            File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
        }

19 View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio

private async void UpdateManager_PageAppeared(object sender, PageNotificationEventArgs e)
        {
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
            _outputPane.OutputString($"The page '{e.PageId}' is now visible.");
            _outputPane.OutputString(Environment.NewLine);

            System.Diagnostics.Debug.WriteLine($"The page '{e.PageId}' is now visible.");

            try
            {
                EnvDTE.Projecreplacedem appPi = _dte.Solution.FindProjecreplacedem("App.xaml");
                if (appPi != null)
                {
                    foreach (Projecreplacedem pi in appPi.ContainingProject.Projecreplacedems)
                    {
                        if (!pi.Name.Contains(".xaml"))
                            continue;

                        string fileName = pi.FileNames[0];
                        XDoreplacedent xdoc = XDoreplacedent.Load(fileName);
                        XNamespace xnsp = "http://schemas.microsoft.com/winfx/2009/xaml";
                        string pageId = xdoc.Root.Attribute(xnsp + "Clreplaced").Value;
                        if (pageId != e.PageId)
                            continue;

                        var doreplacedent = pi.Doreplacedent;
                        string localPath = pi.Properties.Item("LocalPath").Value?.ToString();
                        string xaml = System.IO.File.ReadAllText(localPath);

                        await UpdateManager.Current.SendXamlAsync(pageId, xaml, false);
                    }
                }
            }
            catch(Exception ex)
            {
                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
                _outputPane.OutputString(Environment.NewLine);
                _outputPane.OutputString(ex.ToString());
                _outputPane.OutputString(Environment.NewLine);

                System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

19 View Source File : Settings.cs
License : MIT License
Project Creator : adlez27

public void LoadRecList()
        {
            if (init && File.Exists(RecListFile))
            {
                RecList.Clear();
                HashSet<string> uniqueStrings = new HashSet<string>();

                Encoding e;
                if (ReadUnicode)
                {
                    e = Encoding.UTF8;
                }
                else
                {
                    e = CodePagesEncodingProvider.Instance.GetEncoding(932);
                }

                var ext = Path.GetExtension(RecListFile);

                if (ext == ".txt")
                {
                    if (Path.GetFileName(RecListFile) == "OREMO-comment.txt")
                    {
                        var rawText = File.ReadAllLines(RecListFile, e);
                        foreach(string rawLine in rawText)
                        {
                            var line = rawLine.Split("\t");
                            if (!uniqueStrings.Contains(line[0]))
                            {
                                RecList.Add(new RecLisreplacedem(this, line[0], line[1]));
                                uniqueStrings.Add(line[0]);
                            }
                        }
                    }
                    else
                    {
                        string[] textArr;
                        if (SplitWhitespace)
                        {
                            var rawText = File.ReadAllText(RecListFile, e);
                            rawText = Regex.Replace(rawText, @"\s{2,}", " ");
                            textArr = Regex.Split(rawText, @"\s");
                        }
                        else
                        {
                            textArr = File.ReadAllLines(RecListFile, e);
                        }

                        foreach (string line in textArr)
                        {
                            if (!uniqueStrings.Contains(line))
                            {
                                RecList.Add(new RecLisreplacedem(this, line));
                                uniqueStrings.Add(line);
                            }
                        }
                    }
                }
                else if (ext == ".arl")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var tempDict = deserializer.Deserialize<Dictionary<string, string>>(rawText);
                    foreach (var item in tempDict)
                    {
                        RecList.Add(new RecLisreplacedem(this, item.Key, item.Value));
                    }
                }
                else if (ext == ".csv")
                {
                    using (TextFieldParser parser = new TextFieldParser(RecListFile))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        while (!parser.EndOfData)
                        {
                            string[] line = parser.ReadFields();
                            var text = line[0].Substring(0,line[0].Length - 4);
                            if (!uniqueStrings.Contains(text))
                            {
                                RecList.Add(new RecLisreplacedem(this, text, line[1]));
                                uniqueStrings.Add(text);
                            }
                        }
                    }
                    CopyIndex();
                }
                else if (ext == ".reclist")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var reclist = deserializer.Deserialize<WCTReclist>(rawText);
                    foreach(var line in reclist.Files)
                    {
                        if (!uniqueStrings.Contains(line.Filename))
                        {
                            RecList.Add(new RecLisreplacedem(this, line.Filename, line.Description));
                            uniqueStrings.Add(line.Filename);
                        }
                    }
                }
                else if (ext == ".ust"){
                    var rawText = File.ReadAllLines(RecListFile, e);
                    foreach (var line in rawText)
                    {
                        if (line.StartsWith("Lyric="))
                        {
                            var lyric = line.Substring(6);
                            if (lyric != "R" && lyric != "r" && lyric != "" && !uniqueStrings.Contains(lyric))
                            {
                                RecList.Add(new RecLisreplacedem(this, lyric));
                                uniqueStrings.Add(lyric);
                            }
                        }
                    }
                }
            }
        }

19 View Source File : ClonesManager.cs
License : MIT License
Project Creator : adrenak

public static string GetArgument()
        {
            string argument = "";
            if (IsClone())
            {
                string argumentFilePath = Path.Combine(GetCurrentProjectPath(), ClonesManager.ArgumentFileName);
                if (File.Exists(argumentFilePath))
                {
                    argument = File.ReadAllText(argumentFilePath, System.Text.Encoding.UTF8);
                }
            }

            return argument;
        }

19 View Source File : ClonesManagerWindow.cs
License : MIT License
Project Creator : adrenak

private void OnGUI()
        {
            /// If it is a clone project...
            if (ClonesManager.IsClone())
            {
                //Find out the original project name and show the help box
                string originalProjectPath = ClonesManager.GetOriginalProjectPath();
                if (originalProjectPath == string.Empty)
                {
                    /// If original project cannot be found, display warning message.
                    EditorGUILayout.HelpBox(
                        "This project is a clone, but the link to the original seems lost.\nYou have to manually open the original and create a new clone instead of this one.\n",
                        MessageType.Warning);
                }
                else
                {
                    /// If original project is present, display some usage info.
                    EditorGUILayout.HelpBox(
                        "This project is a clone of the project '" + Path.GetFileName(originalProjectPath) + "'.\nIf you want to make changes the project files or manage clones, please open the original project through Unity Hub.",
                        MessageType.Info);
                }

                //Clone project custom argument.
                GUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Arguments", GUILayout.Width(70));
                if (GUILayout.Button("?", GUILayout.Width(20)))
                {
                    Application.OpenURL(ExternalLinks.CustomArgumentHelpLink);
                }
                GUILayout.EndHorizontal();

                string argumentFilePath = Path.Combine(ClonesManager.GetCurrentProjectPath(), ClonesManager.ArgumentFileName);
                //Need to be careful with file reading / writing since it will effect the deletion of
                //  the clone project(The directory won't be fully deleted if there's still file inside being read or write).
                //The argument file will be deleted first at the beginning of the project deletion process
                //to prevent any further being read and write.
                //Will need to take some extra cautious if want to change the design of how file editing is handled.
                if (File.Exists(argumentFilePath))
                {
                    string argument = File.ReadAllText(argumentFilePath, System.Text.Encoding.UTF8);
                    string argumentTextAreaInput = EditorGUILayout.TextArea(argument,
                        GUILayout.Height(50),
                        GUILayout.MaxWidth(300)
                    );
                    File.WriteAllText(argumentFilePath, argumentTextAreaInput, System.Text.Encoding.UTF8);
                }
                else
                {
                    EditorGUILayout.LabelField("No argument file found.");
                }
            }
            else// If it is an original project...
            {
                if (isCloneCreated)
                {
                    GUILayout.BeginVertical("HelpBox");
                    GUILayout.Label("Clones of this Project");

                    //List all clones
                    clonesScrollPos =
                         EditorGUILayout.BeginScrollView(clonesScrollPos);
                    var cloneProjectsPath = ClonesManager.GetCloneProjectsPath();
                    for (int i = 0; i < cloneProjectsPath.Count; i++)
                    {

                        GUILayout.BeginVertical("GroupBox");
                        string cloneProjectPath = cloneProjectsPath[i];

                        bool isOpenInAnotherInstance = ClonesManager.IsCloneProjectRunning(cloneProjectPath);

                        if (isOpenInAnotherInstance == true)
                            EditorGUILayout.LabelField("Clone " + i + " (Running)", EditorStyles.boldLabel);
                        else
                            EditorGUILayout.LabelField("Clone " + i);


                        GUILayout.BeginHorizontal();
                        EditorGUILayout.TextField("Clone project path", cloneProjectPath, EditorStyles.textField);
                        if (GUILayout.Button("View Folder", GUILayout.Width(80)))
                        {
                            ClonesManager.OpenProjectInFileExplorer(cloneProjectPath);
                        }
                        GUILayout.EndHorizontal();

                        GUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("Arguments", GUILayout.Width(70));
                        if (GUILayout.Button("?", GUILayout.Width(20)))
                        {
                            Application.OpenURL(ExternalLinks.CustomArgumentHelpLink);
                        }
                        GUILayout.EndHorizontal();

                        string argumentFilePath = Path.Combine(cloneProjectPath, ClonesManager.ArgumentFileName);
                        //Need to be careful with file reading/writing since it will effect the deletion of
                        //the clone project(The directory won't be fully deleted if there's still file inside being read or write).
                        //The argument file will be deleted first at the beginning of the project deletion process 
                        //to prevent any further being read and write.
                        //Will need to take some extra cautious if want to change the design of how file editing is handled.
                        if (File.Exists(argumentFilePath))
                        {
                            string argument = File.ReadAllText(argumentFilePath, System.Text.Encoding.UTF8);
                            string argumentTextAreaInput = EditorGUILayout.TextArea(argument,
                                GUILayout.Height(50),
                                GUILayout.MaxWidth(300)
                            );
                            File.WriteAllText(argumentFilePath, argumentTextAreaInput, System.Text.Encoding.UTF8);
                        }
                        else
                        {
                            EditorGUILayout.LabelField("No argument file found.");
                        }

                        EditorGUILayout.Space();
                        EditorGUILayout.Space();
                        EditorGUILayout.Space();


                        EditorGUI.BeginDisabledGroup(isOpenInAnotherInstance);

                        if (GUILayout.Button("Open in New Editor"))
                        {
                            ClonesManager.OpenProject(cloneProjectPath);
                        }

                        GUILayout.BeginHorizontal();
                        if (GUILayout.Button("Delete"))
                        {
                            bool delete = EditorUtility.DisplayDialog(
                                "Delete the clone?",
                                "Are you sure you want to delete the clone project '" + ClonesManager.GetCurrentProject().name + "_clone'?",
                                "Delete",
                                "Cancel");
                            if (delete)
                            {
                                ClonesManager.DeleteClone(cloneProjectPath);
                            }
                        }

                        GUILayout.EndHorizontal();
                        EditorGUI.EndDisabledGroup();
                        GUILayout.EndVertical();

                    }
                    EditorGUILayout.EndScrollView();

                    if (GUILayout.Button("Add new clone"))
                    {
                        ClonesManager.CreateCloneFromCurrent();
                    }

                    GUILayout.EndVertical();
                    GUILayout.FlexibleSpace();
                }
                else
                {
                    /// If no clone created yet, we must create it.
                    EditorGUILayout.HelpBox("No project clones found. Create a new one!", MessageType.Info);
                    if (GUILayout.Button("Create new clone"))
                    {
                        ClonesManager.CreateCloneFromCurrent();
                    }
                }
            }
        }

19 View Source File : ConvertCommand.cs
License : MIT License
Project Creator : AdrianWilczynski

private void OnInputIsFile()
        {
            var content = File.ReadAllText(Input);
            var converted = _codeConverter.ConvertToTypeScript(content, CodeConversionOptions);
            var outputPath = GetOutputFilePath(Input, Output, CodeConversionOptions);

            CreateOrUpdateFile(outputPath, converted, PartialOverride);
        }

19 View Source File : ConvertCommand.cs
License : MIT License
Project Creator : AdrianWilczynski

private void OnInputIsDirectory()
        {
            var files = FileSystem.GetFilesWithExtension(Input, "cs")
                .Select(f => new
                {
                    OutputPath = GetOutputFilePath(f, Output, CodeConversionOptions),
                    Content = _codeConverter.ConvertToTypeScript(File.ReadAllText(f), CodeConversionOptions)
                })
                .Where(f => !string.IsNullOrWhiteSpace(f.Content))
                .GroupBy(f => f.OutputPath)
                .Select(g => g.First());

            foreach (var file in files)
            {
                CreateOrUpdateFile(file.OutputPath, file.Content, PartialOverride);
            }
        }

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            var originalFilePath = Path.Join(nameof(ConvertSingleSimpleFile), "SimpleItem.cs");

            File.WriteAllText(originalFilePath, "clreplaced SimpleItem { }");

            _convertCommand.Input = originalFilePath;

            _convertCommand.OnExecute();

            var generatedFilePath = Path.Join(nameof(ConvertSingleSimpleFile), "simpleItem.ts");

            replacedert.True(File.Exists(generatedFilePath));
            replacedert.Equal("export interface SimpleItem {\r\n\r\n}", File.ReadAllText(generatedFilePath));
        }

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            var originalFilePath = Path.Join(nameof(UseAngularConventionsWhenRequested), "ShoppingCarreplacedem.cs");

            File.WriteAllText(originalFilePath, @"clreplaced ShoppingCarreplacedem
{
    public int Id { get; set; }
}");

            _convertCommand.Input = originalFilePath;
            _convertCommand.AngularMode = true;

            _convertCommand.OnExecute();

            var generatedFilePath = Path.Join(nameof(UseAngularConventionsWhenRequested), "shopping-cart-item.model.ts");

            replacedert.True(File.Exists(generatedFilePath));
            replacedert.Equal(@"export interface ShoppingCarreplacedem {
  id: number;
}",
            File.ReadAllText(generatedFilePath));
        }

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            var inputFilePath = Path.Join(nameof(PreserveContentOutsideOfMarkerComments), "Item.cs");
            var outputFilePath = Path.Join(nameof(PreserveContentOutsideOfMarkerComments), "item.ts");

            File.WriteAllText(outputFilePath, @"// above

// @cs2ts-begin-auto-generated
export interface Item {

}
// @cs2ts-end-auto-generated

// below");
            File.WriteAllText(inputFilePath, "clreplaced UpdatedItem { }");

            _convertCommand.Input = inputFilePath;
            _convertCommand.Output = outputFilePath;
            _convertCommand.PartialOverride = true;

            _convertCommand.OnExecute();

            var overriddenOutput = File.ReadAllText(outputFilePath);

            replacedert.Contains("// above", overriddenOutput);
            replacedert.Contains("// below", overriddenOutput);
            replacedert.Contains("interface UpdatedItem", overriddenOutput);
        }

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            var originalFilePath = Path.Join(nameof(PreserveCasing), "Item.cs");
            var outputFilePath = Path.Join(nameof(PreserveCasing), "item.ts");

            File.WriteAllText(originalFilePath, @"clreplaced Item12
{
    public int MyProperty { get; set; }
}");

            _convertCommand.Input = originalFilePath;
            _convertCommand.Output = outputFilePath;
            _convertCommand.PreserveCasing = true;

            _convertCommand.OnExecute();

            replacedert.Contains("MyProperty: number;", File.ReadAllText(outputFilePath));
        }

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            var originalFilePath = Path.Join(nameof(PreserveInterfacePrefix), "IItemBase.cs");

            File.WriteAllText(originalFilePath, "interface IItemBase { }");

            _convertCommand.Input = originalFilePath;
            _convertCommand.PreserveInterfacePrefix = true;

            _convertCommand.OnExecute();

            var outputFilePath = Path.Join(nameof(PreserveInterfacePrefix), "iItemBase.ts");

            replacedert.True(File.Exists(outputFilePath));
            replacedert.Contains("export interface IItemBase", File.ReadAllText(outputFilePath));
        }

19 View Source File : ConvertCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            var sourceFilePath = Path.Join(nameof(GenerateSimpleImports), "Item.cs");

            File.WriteAllText(sourceFilePath, @"clreplaced Item15
{
    public ShoppingCarreplacedem MyProperty { get; set; }
}");

            _convertCommand.Input = sourceFilePath;
            _convertCommand.ImportGeneration = ImportGenerationMode.Simple;
            _convertCommand.UseKebabCase = true;
            _convertCommand.AppendModelSuffix = true;

            _convertCommand.OnExecute();

            replacedert.StartsWith("import { ShoppingCarreplacedem } from \"./shopping-cart-item.model\";",
                File.ReadAllText(Path.Join(nameof(GenerateSimpleImports), "item.model.ts")));
        }

19 View Source File : InitializeCommandShould.cs
License : MIT License
Project Creator : AdrianWilczynski

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

            Directory.SetCurrentDirectory(nameof(CreateConfigurationFile));

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

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

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string ReadString(string filename)
        {
            return !File.Exists(filename)
                ? null
                : File.ReadAllText(filename, GetEncoding(filename));
        }

19 View Source File : MainWindow_Dat.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

private void OnImportClicked(object sender, RoutedEventArgs e) {
			var dat = DatTable.Tag as DatContainer;
			var ofd = new OpenFileDialog() {
				FileName = dat.Name + ".csv",
				DefaultExt = "csv",
				Filter = "*.csv|*.csv|*.*|*.*"
			};
			if (ofd.ShowDialog() != true)
				return;
			try {
				dat.FromCsv(File.ReadAllText(ofd.FileName));
				ShowDatFile(dat);
				MessageBox.Show(this, $"Imported from " + ofd.FileName, "Done", MessageBoxButton.OK, MessageBoxImage.Information);
			} catch (Exception ex) {
				MessageBox.Show(this, ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

19 View Source File : addForm.cs
License : MIT License
Project Creator : ajohns6

private void addButton_Click(object sender, EventArgs e)
        {
            PAK pak = new PAK();

            pak.modName = this.nameText.Text;
            pak.modCreator = this.creatorText.Text;
            pak.modType = this.typeCombo.Text;
            pak.modDesc = this.descText.Text;
            pak.modFile = filename;
            pak.modDir = filename.Substring(0, filename.Length - 4);

            if (!Directory.Exists(Path.Combine(mainForm.pakDir, "~" + pak.modDir)))
            {
                Directory.CreateDirectory(Path.Combine(mainForm.pakDir, "~" + pak.modDir));
                File.Copy(this.fileText.Text, Path.Combine(mainForm.pakDir, "~" + pak.modDir, pak.modFile));
            }
            else
            {
                MessageBox.Show("A directory already exists for this PAK filename.\n\nIf you still wish to add this PAK file, you must either rename this PAK file or delete the existing directory.",
                    "Directory Already Exists",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            string jsonString = File.ReadAllText(mainForm.localJSON);
            var list = JsonConvert.DeserializeObject<List<PAK>>(jsonString);
            list.Add(pak);
            var convertedJSON = JsonConvert.SerializeObject(list);
            File.WriteAllText(mainForm.localJSON, convertedJSON);

            this.Close();
        }

19 View Source File : LicenseHeader.cs
License : Apache License 2.0
Project Creator : akarnokd

private static void VisitSources(string path)
        {
            var found = false;

            var ci = Environment.GetEnvironmentVariable("CI") != null;

            var sb = new StringBuilder();

            foreach (var entry in Directory.EnumerateFiles(path, "*.cs", SearchOption.AllDirectories))
            {
                var entryForward = entry.Replace("\\", "/");
                if (entryForward.Contains("replacedemblyInfo") 
                    || entryForward.Contains("Temporary")
                    || entryForward.Contains("/obj/")
                    || entryForward.Contains("/Debug/")
                    || entryForward.Contains("/Release/"))
                {
                    continue;
                }
                
                var text = File.ReadAllText(entry, Encoding.UTF8);
                if (!text.Contains("\r\n"))
                {
                    text = text.Replace("\n", "\r\n");
                }
                if (!text.StartsWith(HeaderLines))
                {
                    sb.Append(entry).Append("\r\n");
                    found = true;
                    if (!ci)
                    {
                        File.WriteAllText(entry, HeaderLines + text, Encoding.UTF8);
                    }
                }
            }

            if (found)
            {
                throw new InvalidOperationException("Missing header found and added. Please rebuild the project of " + path + "\r\n" + sb);
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

public void LoadConfig()
        {
            if (File.Exists(ConfigUtils.ConfigJsonPath))
            {
                try
                {
                    string configJson = File.ReadAllText(ConfigUtils.ConfigJsonPath);
                    config = JsonConvert.DeserializeObject<Config>(configJson);

                    MainTab.ItemsSource = ConfigUtils.ConvertTabsFromConfigToUI(config);

                    AddTextToEventsList("Config loaded from file: " + ConfigUtils.ConfigJsonPath, false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    AddTextToEventsList("Error occured while loading file: " + ex.Message, false);
                }
            }
            else
            {
                MessageBox.Show("File " + ConfigUtils.ConfigJsonPath + " does not exist.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

19 View Source File : DataService.cs
License : MIT License
Project Creator : Aleksbgbg

public T Load<T>(string dataName, Func<string> emptyData)
        {
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(_appDataService.GetFile($"Data/{dataName}.json", emptyData)));
        }

19 View Source File : DataService.cs
License : MIT License
Project Creator : Aleksbgbg

public T LoadAndWipe<T>(string dataName, string emptyData = "")
        {
            string dataFile = _appDataService.GetFile($"Data/{dataName}.json", emptyData);

            string fileData = File.ReadAllText(dataFile);

            if (fileData != emptyData)
            {
                File.WriteAllText(dataFile, emptyData); // Prevent duplicate loading of file if not cleared correctly
            }

            return JsonConvert.DeserializeObject<T>(fileData);
        }

19 View Source File : AutoComputeShaderNodeView.cs
License : MIT License
Project Creator : alelievr

void UpdateComputeShaderData(ComputeShader shader)
		{
			if (ShaderUtil.GetComputeShaderMessages(shader).Any(m => m.severity == ShaderCompilerMessageSeverity.Error))
			{
				Debug.LogError("Compute Shader " + shader + " has errors");
				return;
			}

			var path = replacedetDatabase.GetreplacedetPath(shader);
			string fileContent = File.ReadAllText(path);

			// First remove all the functions from the text
			int functionMarkLocation = fileContent.IndexOf("{");
			fileContent = fileContent.Substring(0, functionMarkLocation).Trim();

			// Fill kernel names
			computeShaderNode.kernelNames.Clear();
			foreach (Match match in kernelRegex.Matches(fileContent))
				computeShaderNode.kernelNames.Add(match.Groups[1].Value);
			
			// Fill output properties name
			computeShaderNode.computeOutputs.Clear();
			foreach (Match match in readWriteObjects.Matches(fileContent))
			{
				if (match.Groups[4].Value.StartsWith("__"))
					continue;
				
				if (match.Groups[4].Value == computeShaderNode.previewTexturePropertyName)
					continue;

				computeShaderNode.computeOutputs.Add(new AutoComputeShaderNode.ComputeParameter{
					displayName = ObjectNames.NicifyVariableName(match.Groups[4].Value),
					propertyName = match.Groups[4].Value,
					specificType = match.Groups[3].Value,
					sType = new SerializableType(ComputeShaderTypeToCSharp(match.Groups[2].Value)),
				});
			}

			// We can then select input properties
			computeShaderNode.computeInputs.Clear();
			foreach (Match match in readOnlyObjects.Matches(fileContent))
			{
				var propertyName = match.Groups[4].Value;

				if (propertyName.StartsWith("__"))
					continue;

				if (propertyName == computeShaderNode.previewTexturePropertyName)
					continue;

				// If the resource is allocated by this node, we don't display it as input
				if (computeShaderNode.managedResources.Any(r => r.propertyName == propertyName && r.autoAlloc))
					continue;

				computeShaderNode.computeInputs.Add(new AutoComputeShaderNode.ComputeParameter{
					displayName = ObjectNames.NicifyVariableName(match.Groups[4].Value),
					propertyName = match.Groups[4].Value,
					specificType = match.Groups[3].Value,
					sType = new SerializableType(ComputeShaderTypeToCSharp(match.Groups[2].Value)),
				});
			}

			UpdateAllocUI();

			computeShaderNode.UpdateComputeShader();
		}

19 View Source File : ApnsClient.cs
License : Apache License 2.0
Project Creator : alexalok

public static ApnsClient CreateUsingJwt([NotNull] HttpClient http, [NotNull] ApnsJwtOptions options)
        {
            if (http == null) throw new ArgumentNullException(nameof(http));
            if (options == null) throw new ArgumentNullException(nameof(options));

            string certContent;
            if (options.CertFilePath != null)
            {
                Debug.replacedert(options.CertContent == null);
                certContent = File.ReadAllText(options.CertFilePath);
            }
            else if (options.CertContent != null)
            {
                Debug.replacedert(options.CertFilePath == null);
                certContent = options.CertContent;
            }
            else
            {
                throw new ArgumentException("Either certificate file path or certificate contents must be provided.", nameof(options));
            }

            certContent = certContent.Replace("\r", "").Replace("\n", "")
                .Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "");

#if !NET46
            certContent = $"-----BEGIN PRIVATE KEY-----\n{certContent}\n-----END PRIVATE KEY-----";
            var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(new StringReader(certContent)).ReadObject();
            // See https://github.com/dotnet/core/issues/2037#issuecomment-436340605 as to why we calculate q ourselves
            // TL;DR: we don't have Q coords in ecPrivateKeyParameters, only G ones. They won't work.
            var q = ecPrivateKeyParameters.Parameters.G.Multiply(ecPrivateKeyParameters.D).Normalize();
            var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
            var msEcp = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                Q = { X = q.AffineXCoord.GetEncoded(), Y = q.AffineYCoord.GetEncoded() }, 
                D = d
            };
            var key = ECDsa.Create(msEcp);
#else
            var key = CngKey.Import(Convert.FromBase64String(certContent), CngKeyBlobFormat.Pkcs8PrivateBlob);
#endif
            return new ApnsClient(http, key, options.KeyId, options.TeamId, options.BundleId);
        }

19 View Source File : ViewManager.cs
License : MIT License
Project Creator : AlexanderPro

public bool LoadSettings()
        {
            var settingsFileName = Path.GetFileNameWithoutExtension(replacedemblyUtils.replacedemblyLocation) + ".xml";
            settingsFileName = Path.Combine(replacedemblyUtils.replacedemblyDirectoryName, settingsFileName);
            if (File.Exists(settingsFileName))
            {
                try
                {
                    var xml = File.ReadAllText(settingsFileName, Encoding.UTF8);
                    Settings = SerializeUtils.Deserialize<ProgramSettings>(xml);
                    return true;
                }
                catch (Exception e)
                {
                    MessageBox.Show($"Failed to load settings from the file {settingsFileName}{Environment.NewLine}{e.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            else
            {
                Settings.VideoFileExtensions = new List<string> { "*.mp4", "*.mp3", "*.mpg", "*.mpeg", "*.avi" };
                Settings.GalleryFileExtensions = new List<string> { "*.bmp", "*.jpg", "*.jpeg", "*.png", "*.gif", "*.tiff" };
                return true;
            }
        }

19 View Source File : PythonScriptsImporter.cs
License : MIT License
Project Creator : AlexLemminG

public override void OnImportreplacedet(replacedetImportContext ctx){
		var existedPythonScriptreplacedet = UnityEditor.replacedetDatabase.LoadMainreplacedetAtPath (ctx.replacedetPath) as PythonScript;
		//script text
		var text = File.ReadAllText (ctx.replacedetPath);
		int updateCount = existedPythonScriptreplacedet == null ? 0 : existedPythonScriptreplacedet.updateCount;
		var pythonScriptreplacedet = PythonScript.CreateFromString (text, updateCount);

		//script name
		var fileName = Path.GetFileNameWithoutExtension (ctx.replacedetPath);
		pythonScriptreplacedet.name = fileName;

		//script replacedet
		#if UNITY_2017_3_OR_NEWER
		ctx.AddObjectToreplacedet ("script", pythonScriptreplacedet);
		ctx.SetMainObject (pythonScriptreplacedet);
		#else
		ctx.SetMainreplacedet("script", pythonScriptreplacedet);
		#endif

	}

19 View Source File : AliceControllerTests.cs
License : MIT License
Project Creator : alexvolchetsky

[Fact]
        public async Task TestImageUpload()
        {
            string json = File.ReadAllText(TestsConstants.AliceRequestResourcesFilePath);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var response = await _client.PostAsync("alice", content).ConfigureAwait(false);
            string responseContent = await response.Content.ReadreplacedtringAsync().ConfigureAwait(false);
            replacedert.True(response.StatusCode == HttpStatusCode.OK, responseContent);
            replacedert.Contains(Yandex_Alice_Sdk_Demo_Resources.Image_Upload_Success, responseContent);

            _testOutputHelper.WriteLine(responseContent);

            await _cleanService.CleanResourcesAsync().ConfigureAwait(false);
        }

See More Examples