private static void WriteDiagnosticResults(ImmutableArray <Tuple <ProjectId, Diagnostic> > diagnostics, string fileName)
        {
            var orderedDiagnostics =
                diagnostics
                .OrderBy(i => i.Item2.Id)
                .ThenBy(i => i.Item2.Location.SourceTree?.FilePath, StringComparer.OrdinalIgnoreCase)
                .ThenBy(i => i.Item2.Location.SourceSpan.Start)
                .ThenBy(i => i.Item2.Location.SourceSpan.End);

            var           uniqueLines    = new HashSet <string>();
            StringBuilder completeOutput = new StringBuilder();
            StringBuilder uniqueOutput   = new StringBuilder();

            foreach (var diagnostic in orderedDiagnostics)
            {
                string message       = diagnostic.Item2.ToString();
                string uniqueMessage = $"{diagnostic.Item1}: {diagnostic.Item2}";
                completeOutput.AppendLine(message);
                if (uniqueLines.Add(uniqueMessage))
                {
                    uniqueOutput.AppendLine(message);
                }
            }

            string directoryName            = Path.GetDirectoryName(fileName);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            string extension      = Path.GetExtension(fileName);
            string uniqueFileName = Path.Combine(directoryName, $"{fileNameWithoutExtension}-Unique{extension}");

            File.WriteAllText(fileName, completeOutput.ToString(), Encoding.UTF8);
            File.WriteAllText(uniqueFileName, uniqueOutput.ToString(), Encoding.UTF8);
        }
示例#2
0
 public MainWindow()
 {
     InitializeComponent();
     Closing       += OnClosing;
     timer          = new DispatcherTimer();
     timer.Interval = TimeSpan.FromSeconds(1);
     timer.Tick    += TimerOnTick;
     try
     {
         string   alltext   = File.ReadAllText("settings.txt");
         string[] keyAndSql = alltext.Split('|');
         KeyText.Text = keyAndSql[0];
         constr       = keyAndSql[1];
     }
     catch (Exception ex)
     {
         MessageBox.Show("Settings file not found or file is corrupted", "Alert", MessageBoxButton.OK,
                         MessageBoxImage.Error);
         File.WriteAllText(DateTime.Now.ToString("dd.MM.yy hh.mm.ss") + " errorlog.txt", DateTime.Now + " -- " + "Settings file not found or file is corrupted");
         Application.Current.Shutdown();
     }
     bw         = new BackgroundWorker();
     bw.DoWork += bw_DoWork;
     if (KeyText.Text != "")
     {
         var text = @KeyText.Text;
         if (text != "" && bw.IsBusy != true)
         {
             bw.RunWorkerAsync(text);
             timer.Start();
             autostart = true;
         }
     }
 }
示例#3
0
        public void TestCheckShouldntExist()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath  = Path.Join(input.FullName, "SomeProgram.cs");
            string outputPath = Path.Join(output.FullName, "DocTestSomeProgram.cs");

            File.WriteAllText(inputPath, "no code");

            File.WriteAllText(outputPath, "unexpected content");

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(
                new[] { "--input", input.FullName, "--output", output.FullName, "--check" });

            string nl = Environment.NewLine;

            Assert.AreEqual(1, exitCode);
            Assert.AreEqual(
                $"No doctests found in: {inputPath}; the output should not exist: {outputPath}{nl}",
                consoleCapture.Output());
        }
示例#4
0
 private void savetofilelog()
 {
     if (LogBox.Text != "")
     {
         bool   newfile = true;
         string textlog = "";
         if (File.Exists("log.txt"))
         {
             newfile = false;
             textlog = File.ReadAllText("log.txt");
             File.WriteAllText("log.txt", "");
         }
         else
         {
             newfile = true;
             File.WriteAllText("log.txt", "");
         }
         using (var stream = File.CreateText("log.txt"))
         {
             stream.Write(LogBox.Text);
             LogBox.Clear();
             if (!newfile)
             {
                 stream.Write(textlog);
             }
         }
     }
 }
示例#5
0
        public void TestCheckDoesntExist()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath  = Path.Join(input.FullName, "SomeProgram.cs");
            string outputPath = Path.Join(output.FullName, "DocTestSomeProgram.cs");

            File.WriteAllText(
                inputPath,
                @"/// <code doctest=""true"">
/// var x = 1;
/// </code>
");

            // Test pre-condition
            Assert.IsFalse(File.Exists(outputPath));

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(
                new[] { "--input", input.FullName, "--output", output.FullName, "--check" });

            string nl = Environment.NewLine;

            Assert.AreEqual(1, exitCode);
            Assert.AreEqual($"Output file does not exist: {inputPath} -> {outputPath}{nl}", consoleCapture.Output());
        }
示例#6
0
        public void TestExtractionError()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath = Path.Join(input.FullName, "SomeProgram.cs");

            File.WriteAllText(
                inputPath,
                @"/// <code doctest=""true"">
/// var a = 0;
/// // ---
/// var x = 1;
/// </code>
");

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(new[] { "--input", input.FullName, "--output", output.FullName });

            string nl = Environment.NewLine;

            Assert.AreEqual(1, exitCode);
            Assert.AreEqual(
                $"Failed to extract doctest(s) from: {inputPath}{nl}" +
                $"* Line 1, column 1: Expected only using directives in the header, but got: FieldDeclaration{nl}",
                consoleCapture.Output());
        }
示例#7
0
        private static async Task AuthorizeAsync(MisskeyClient mi, Logger logger)
        {
            var app = await mi.App.CreateAsync("RealXelticaBot", "Xeltica Imitation", ((Permission[])Enum.GetValues(typeof(Permission))).Select(p => p.ToStr()).ToArray(), "http://xeltica.work");

            var session = await mi.Auth.Session.GenerateAsync();

            try
            {
                Server.OpenUrl(session.Url);
            }
            catch (NotSupportedException)
            {
                logger.Error("ユーザー認証のためのURLを開くことができませんでした。以下のURLにアクセスして認証を進めてください。");
                logger.Error("> " + session.Url);
            }

            logger.Info("ユーザー認証を行います。ウェブブラウザ上で認証が終わったら、コンソールで何かキーを押してください。");
            Console.Write("> ");
            ReadLine();

            await mi.Auth.Session.UserKeyAsync(session.Token);

            var credential = JsonConvert.SerializeObject(mi.Credential);

            File.WriteAllText("./token", credential);
        }
        /// <summary>
        /// Force load of storage file from telegram.
        /// Carefully, you can loose your unsaved data.
        /// </summary>
        public async Task ForceLoad()
        {
            using (await _saveLock.LockAsync())
            {
                var chat = await _botClient.GetChatAsync(_saveResChatId);

                if (chat.PinnedMessage?.Caption?.Trim() != FileResName)
                {
                    //Can't find storage.
                    File.WriteAllText(_storageFilePath, "{}");
                }
                else
                {
                    var fileId = chat.PinnedMessage.Document.FileId;
                    if (File.Exists(_storageFilePath))
                    {
                        File.Delete(_storageFilePath);
                    }
                    using (var stream = File.OpenWrite(_storageFilePath))
                    {
                        await _botClient.GetInfoAndDownloadFileAsync(fileId, stream);
                    }
                }

                LoadStorageStateFromFile();
            }
        }
示例#9
0
        public async Task <IActionResult> OnPost()
        {
            if (ModelState.IsValid)
            {
                var settings = _serviceProvider.GetService <ISynologyConnectionSettings>();

                settings.BaseHost = SynologyHost;
                settings.Password = SynologyPass;
                settings.Port     = SynologyPort;
                settings.Ssl      = UseSsl;
                settings.SslPort  = SynologyPort;
                settings.Username = SynologyUser;

                using (var syno = _serviceProvider.GetService <ISynologyConnection>())
                {
                    var result = await syno.Api().Auth().LoginAsync();

                    if (!result.Success && result.Error.Code != 403)
                    {
                        ModelState.AddModelError("", "Invalid connection settings.");
                    }
                    else
                    {
                        var json = JsonConvert.SerializeObject(settings, Formatting.Indented);

                        IOFile.WriteAllText("synosettings.json", json);

                        return(RedirectToPage("Index"));
                    }
                }
            }

            return(Page());
        }
示例#10
0
        public void TestDoctest()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath  = Path.Join(input.FullName, "SomeProgram.cs");
            string outputPath = Path.Join(output.FullName, "DocTestSomeProgram.cs");

            File.WriteAllText(
                inputPath,
                @"/// <code doctest=""true"">
/// var x = 1;
/// </code>
");

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(new[] { "--input", input.FullName, "--output", output.FullName });

            string nl = Environment.NewLine;

            Assert.AreEqual(0, exitCode);
            Assert.AreEqual(
                $"Generated doctest(s) for: {inputPath} -> {outputPath}{nl}",
                consoleCapture.Output());
        }
示例#11
0
        public void TestReportToStdout()
        {
            using var tmpdir = new TemporaryDirectory();

            using var consoleCapture = new ConsoleCapture();

            string nl = Environment.NewLine;

            string path = Path.Join(tmpdir.Path, "SomeProgram.cs");

            File.WriteAllText(path, $"// TODO (mristin, 2020-07-20): Do something!{nl}");

            int exitCode = Program.MainWithCode(new[] { "--inputs", path, "--report-path", "-" });

            Assert.AreEqual("", consoleCapture.Error());
            Assert.AreEqual(
                $@"[
  {{
    ""path"": ""{path.Replace(@"\", @"\\")}"",
    ""records"": [
      {{
        ""prefix"": ""TODO"",
        ""suffix"": "" (mristin, 2020-07-20): Do something!"",
        ""line"": 0,
        ""column"": 0,
        ""status"": ""ok""
      }}
    ]
  }}
]
",
                consoleCapture.Output());
            Assert.AreEqual(0, exitCode);
        }
示例#12
0
        public void TestRuleArgumentsConsidered()
        {
            using var tmpdir = new TemporaryDirectory();

            using var consoleCapture = new ConsoleCapture();

            string nl = Environment.NewLine;

            string pathNotOk = Path.Join(tmpdir.Path, "NotOk.cs");

            File.WriteAllText(pathNotOk, $"// AAA: Do something!{nl}");

            int exitCode = Program.MainWithCode(
                new[]
            {
                "--inputs", pathNotOk, "--prefixes", "^AAA", "--disallowed-prefixes", "^BBB", "--suffixes", "^CCC"
            });

            Assert.AreEqual(
                $"FAILED: {pathNotOk}{nl}" +
                $" * Line 1, column 1: invalid suffix (see --suffixes): : Do something!{nl}" +
                $"One or more TODOs were invalid. Please see above.{nl}" +
                $"--prefixes was set to: ^AAA{nl}" +
                $"--disallowed-prefixes was set to: ^BBB{nl}" +
                @"--suffixes was set to: ^CCC" + nl,
                consoleCapture.Error());
            Assert.AreEqual(1, exitCode);
        }
示例#13
0
        public void TestWithInvalidAndValidTodoAndVerbose()
        {
            using var tmpdir = new TemporaryDirectory();

            using var consoleCapture = new ConsoleCapture();

            string nl = Environment.NewLine;

            string pathNotOk = Path.Join(tmpdir.Path, "NotOk.cs");

            File.WriteAllText(pathNotOk, $"// TODO (mristin): Do something!{nl}");

            string pathOk = Path.Join(tmpdir.Path, "Ok.cs");

            File.WriteAllText(pathOk, "// TODO (mristin, 2020-07-20): Do something else!");

            int exitCode = Program.MainWithCode(new[] { "--inputs", pathNotOk, pathOk, "--verbose" });

            Assert.AreEqual(
                $"FAILED: {pathNotOk}{nl}" +
                $" * Line 1, column 1: invalid suffix (see --suffixes):  (mristin): Do something!{nl}" +
                $"One or more TODOs were invalid. Please see above.{nl}" +
                $"--prefixes was set to: ^TODO ^BUG ^HACK{nl}" +
                $"--disallowed-prefixes was set to: ^DONT-CHECK-IN ^Todo ^todo ^ToDo ^Bug ^bug ^Hack ^hack{nl}" +
                @"--suffixes was set to: ^ \([^)]+, [0-9]{4}-[0-9]{2}-[0-9]{2}\): ." + nl,
                consoleCapture.Error());
            Assert.AreEqual($"OK, 1 todo(s): {pathOk}{nl}", consoleCapture.Output());
            Assert.AreEqual(1, exitCode);
        }
示例#14
0
        public void TestNoDoctest()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath  = Path.Join(input.FullName, "SomeProgram.cs");
            string outputPath = Path.Join(output.FullName, "DocTestSomeProgram.cs");

            File.WriteAllText(inputPath, "no doctests");

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(
                new[]
            {
                "--input-output", $"{input.FullName}{Path.PathSeparator}{output.FullName}",
                "--verbose"
            });

            string nl = Environment.NewLine;

            Assert.AreEqual(0, exitCode);
            Assert.AreEqual(
                $"No doctests found in: {inputPath}{nl}",
                consoleCapture.Output());

            Assert.IsFalse(File.Exists(outputPath));
        }
        public void Test_plugin_paths_from_default_JSON_options()
        {
            using (var tmpDir = new TemporaryDirectory())
            {
                var exePath     = Path.Combine(tmpDir.Path, "NonexistingAasxPackageExplorer.exe");
                var optionsPath = Path.Combine(tmpDir.Path, "NonexistingAasxPackageExplorer.options.json");

                var text = @"{
    ""PluginDir"": "".\\AcmePlugins"",
    ""PluginDll"": [ { ""Path"": ""AasxPluginBomStructure.dll"", ""Args"": [] } ];
}";
                File.WriteAllText(optionsPath, text);

                var optionsInformation = App.InferOptions(
                    exePath, new string[] { });

                Assert.AreEqual(".\\AcmePlugins", optionsInformation.PluginDir);

                Assert.AreEqual(1, optionsInformation.PluginDll.Count);
                Assert.IsEmpty(optionsInformation.PluginDll[0].Args);
                Assert.AreEqual(null, optionsInformation.PluginDll[0].Options);
                Assert.AreEqual(null, optionsInformation.PluginDll[0].DefaultOptions);
                Assert.AreEqual("AasxPluginBomStructure.dll", optionsInformation.PluginDll[0].Path);
            }
        }
        public void ChangeAccessUser(string username, bool access)
        {
            TelegramBotDataUsers[username].Lock = access;

            var telegramBotDataUsersJson = JsonConvert.SerializeObject(TelegramBotDataUsers, Formatting.Indented);

            File.WriteAllText(FilePath, telegramBotDataUsersJson);
        }
示例#17
0
 public void AddAdmin(string text)
 {
     if (!_savedAdmins.Contains(text))
     {
         _savedAdmins.Add(text);
         File.WriteAllText("/data/admins.bot", string.Join("\n", _savedAdmins));
     }
 }
示例#18
0
 public void AddChat(long id)
 {
     if (!_savedChatIds.Contains(id))
     {
         _savedChatIds.Add(id);
         File.WriteAllText("/data/chats.bot", string.Join(" ", _savedChatIds));
     }
 }
        public void AddUser(TelegramBotUser telegramBotUser)
        {
            TelegramBotDataUsers.Add(telegramBotUser.UserName, telegramBotUser);

            var telegramBotDataUsersJson = JsonConvert.SerializeObject(TelegramBotDataUsers, Formatting.Indented);

            File.WriteAllText(FilePath, telegramBotDataUsersJson);
        }
        public void UpdateUserState(string username, TelegramBotStateEnum state)
        {
            TelegramBotDataUsers[username].CurrentState = state;

            var telegramBotDataUsersJson = JsonConvert.SerializeObject(TelegramBotDataUsers, Formatting.Indented);

            File.WriteAllText(FilePath, telegramBotDataUsersJson);
        }
        public void Test_plugin_paths_from_JSON_options()
        {
            string exePath = Common.AasxPackageExplorerExe();

            using (var tmpDir = new TemporaryDirectory())
            {
                var jsonOptionsPath = Path.Combine(tmpDir.Path, "options-test.json");

                var text = @"{
    ""PluginDll"": [
        {
          ""Path"": ""AasxIntegrationEmptySample.dll"",
          ""Args"": [],
          ""Options"": null
        },
        {
          ""Path"": ""AasxPluginUaNetServer.dll"",
          ""Args"": [
            ""-single-nodeids"",
            ""-single-keys"",
            ""-ns"",
            ""2"",
            ""-ns"",
            ""3""
          ],
          ""Options"": null
        },
        {
          ""Path"": ""AasxPluginBomStructure.dll"",
          ""Args"": []
        }
    ];
}";
                File.WriteAllText(jsonOptionsPath, text);

                var optionsInformation = App.InferOptions(
                    exePath, new[] { "-read-json", jsonOptionsPath });

                Assert.AreEqual(3, optionsInformation.PluginDll.Count);

                // TODO (mristin, 2020-11-13): @MIHO please check -- Options should be null, not empty?
                Assert.IsEmpty(optionsInformation.PluginDll[0].Args);
                Assert.IsEmpty(optionsInformation.PluginDll[0].Options);
                Assert.AreEqual(null, optionsInformation.PluginDll[0].DefaultOptions);
                Assert.AreEqual("AasxIntegrationEmptySample.dll", optionsInformation.PluginDll[0].Path);

                Assert.That(optionsInformation.PluginDll[1].Args,
                            Is.EquivalentTo(new[] { "-single-nodeids", "-single-keys", "-ns", "2", "-ns", "3" }));
                Assert.IsEmpty(optionsInformation.PluginDll[1].Options);
                Assert.AreEqual(null, optionsInformation.PluginDll[1].DefaultOptions);
                Assert.AreEqual("AasxPluginUaNetServer.dll", optionsInformation.PluginDll[1].Path);

                Assert.IsEmpty(optionsInformation.PluginDll[2].Args);
                Assert.AreEqual(null, optionsInformation.PluginDll[2].Options);
                Assert.AreEqual(null, optionsInformation.PluginDll[2].DefaultOptions);
                Assert.AreEqual("AasxPluginBomStructure.dll", optionsInformation.PluginDll[2].Path);
            }
        }
示例#22
0
        // save the current state of the inventory
        public void SaveInventory()
        {
            string path = Application.dataPath + gameDataProjectFilePath;
            // list save
            string json = JsonUtility.ToJson(this, true);

            File.WriteAllText(path, json);
            Debug.Log(json);
        }
 private void GenerateDefaultConnectionString()
 {
     if (!File.Exists("./connectionstrings.json"))
     {
         var defaultConnectionString = new ConnectionStrings();
         defaultConnectionString.LibraryConnection = "Host=localhost;Database=library;Username=postgres;Password=your_password";
         File.WriteAllText("./connectionstrings.json", JsonConvert.SerializeObject(defaultConnectionString));
     }
 }
示例#24
0
        public void TestCheckDifferent()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath  = Path.Join(input.FullName, "SomeProgram.cs");
            string outputPath = Path.Join(output.FullName, "DocTestSomeProgram.cs");

            File.WriteAllText(
                inputPath,
                @"/// <code doctest=""true"">
/// var x = 1;
/// </code>
");

            File.WriteAllText(outputPath, "different content");

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(
                new[]
            {
                "--input-output", $"{input.FullName}{Path.PathSeparator}{output.FullName}",
                "--check",
                "--verbose"
            });

            string nl = Environment.NewLine;

            Assert.AreEqual(1, exitCode);
            Assert.AreEqual(
                $"Expected different content: {inputPath} -> {outputPath}{nl}" +
                $"Here is the diff between the expected content and the actual content:{nl}" +
                $"- // This file was automatically generated by doctest-csharp.{nl}" +
                $"+ different content{nl}" +
                $"- // !!! DO NOT EDIT OR APPEND !!!{nl}" +
                $"- {nl}" +
                $"- using NUnit.Framework;{nl}" +
                $"- {nl}" +
                $"- namespace Tests{nl}" +
                $"- {{{nl}" +
                $"-     public class DocTest_SomeProgram_cs{nl}" +
                $"-     {{{nl}" +
                $"-         [Test]{nl}" +
                $"-         public void AtLine0AndColumn4(){nl}" +
                $"-         {{{nl}" +
                $"-             var x = 1;{nl}" +
                $"-         }}{nl}" +
                $"-     }}{nl}" +
                $"- }}{nl}" +
                $"- {nl}" +
                $"- // This file was automatically generated by doctest-csharp.{nl}" +
                $"- // !!! DO NOT EDIT OR APPEND !!!{nl}" +
                $"- {nl}",
                consoleCapture.Output());
        }
 private void SaveSubscriptions( )
 {
     Logger.Debug($"Saving subscriptions to {SubscriptionFileName}");
     lock ( subscriptionLock )
     {
         var json = JsonConvert.SerializeObject(subscriptions, Formatting.Indented);
         File.WriteAllText(SubscriptionFileName, json);
     }
 }
示例#26
0
        public void Save()
        {
            if (_IsLoaded)
            {
                DirectoryIO.CreateDirectory(DataSavePath);

                String HostListAsText = JsEncoder.EncoderStream.EncodeTable(UserHostList.ToTable(HostList));
                String ConfigAsText; // This won't be null after the region below

                #region ConfigFileSaving
                {
                    JsEncoder.TableValue ConfigTable = new JsEncoder.TableValue();
                    ConfigTable[new JsEncoder.StringValue("UserName")]    = new JsEncoder.StringValue(UserName);
                    ConfigTable[new JsEncoder.StringValue("WorkingPort")] = new JsEncoder.IntValue(WorkingPort);

                    ConfigAsText = JsEncoder.EncoderStream.EncodeTable(ConfigTable);
                }
                #endregion

                String VersionFileBackupPath  = String.Concat(VersionFilePath, ".bak");
                String ConfigFileBackupPath   = String.Concat(ConfigFilePath, ".bak");
                String HostListFileBackupPath = String.Concat(HostListFilePath, ".bak");

                if (FileIO.Exists(VersionFileBackupPath))
                {
                    FileIO.Delete(VersionFileBackupPath);
                }
                if (FileIO.Exists(ConfigFileBackupPath))
                {
                    FileIO.Delete(ConfigFileBackupPath);
                }
                if (FileIO.Exists(HostListFileBackupPath))
                {
                    FileIO.Delete(HostListFileBackupPath);
                }

                if (FileIO.Exists(VersionFilePath))
                {
                    FileIO.Move(VersionFilePath, VersionFileBackupPath);
                }
                if (FileIO.Exists(ConfigFilePath))
                {
                    FileIO.Move(ConfigFilePath, ConfigFileBackupPath);
                }
                if (FileIO.Exists(HostListFilePath))
                {
                    FileIO.Move(HostListFilePath, HostListFileBackupPath);
                }

                FileIO.WriteAllText(VersionFilePath, NetworkConfig.VersionString, System.Text.Encoding.Unicode);
                FileIO.WriteAllText(ConfigFilePath, ConfigAsText, System.Text.Encoding.Unicode);
                FileIO.WriteAllText(HostListFilePath, HostListAsText, System.Text.Encoding.Unicode);
            }
        }
示例#27
0
        public void TestCheckOk()
        {
            using var tmpdir = new TemporaryDirectory();
            DirectoryInfo input  = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject"));
            DirectoryInfo output = Directory.CreateDirectory(Path.Join(tmpdir.Path, "SomeProject.Test/doctests"));

            string inputPath  = Path.Join(input.FullName, "SomeProgram.cs");
            string outputPath = Path.Join(output.FullName, "DocTestSomeProgram.cs");

            File.WriteAllText(
                inputPath,
                @"/// <code doctest=""true"">
/// var x = 1;
/// </code>
");

            File.WriteAllText(
                outputPath,
                @"// This file was automatically generated by doctest-csharp.
// !!! DO NOT EDIT OR APPEND !!!

using NUnit.Framework;

namespace Tests
{
    public class DocTest_SomeProgram_cs
    {
        [Test]
        public void AtLine0AndColumn4()
        {
            var x = 1;
        }
    }
}

// This file was automatically generated by doctest-csharp.
// !!! DO NOT EDIT OR APPEND !!!
");

            using var consoleCapture = new ConsoleCapture();

            int exitCode = Program.MainWithCode(
                new[]
            {
                "--input-output", $"{input.FullName}{Path.PathSeparator}{output.FullName}",
                "--check",
                "--verbose"
            });

            string nl = Environment.NewLine;

            Assert.AreEqual(0, exitCode);
            Assert.AreEqual($"OK: {inputPath} -> {outputPath}{nl}", consoleCapture.Output());
        }
示例#28
0
        /// <summary>
        ///     Serializes an object to a json file.
        /// </summary>
        /// <param name="clazz">The class instance to serialize</param>
        /// <param name="filename">The target filename (including .json)</param>
        public static void SerializeObject <T>(T clazz, string filename) where T : SerializableDataClass
        {
            var options = new JsonSerializerOptions {
                WriteIndented = true,
                MaxDepth      = 200
            };

            var jsonString = JsonSerializer.Serialize(clazz, options);

            File.WriteAllText(filename, jsonString);
        }
示例#29
0
        private void CacheCurrentPlalist()
        {
            var path      = App.MakePathTo(PlaylistCachePath);
            var toSaveObj = new Playlist
            {
                Posision = _musicService.Current,
                Songs    = _musicService.Playlist.Select(song => song.Path.AbsolutePath).ToList()
            };
            var toSave = JsonConvert.SerializeObject(toSaveObj);

            File.WriteAllText(path, toSave);
        }
示例#30
0
        /**
         * Convert an object of type T to JSON representation, and output to a file.
         * If filename is not an absolute path, it will be relative to the
         * Application's dataPath.
         */
        public void Persist(string filename, T settings)
        {
            string dstFilePath = filename;

            if (!Path.IsPathRooted(dstFilePath)) // If relative path, base at dataPath.
            {
                dstFilePath = Path.Combine(Application.dataPath, dstFilePath);
            }
            if (!Directory.Exists(Path.GetDirectoryName(dstFilePath))) // If directory doesnt exist create it.
            {
                Directory.CreateDirectory(Path.GetDirectoryName(dstFilePath));
            }
            File.WriteAllText(dstFilePath, JsonUtility.ToJson(settings));
        }