WriteAllText() private méthode

private WriteAllText ( String path, String contents ) : void
path String
contents String
Résultat void
        public void Compile()
        {
            Console.WriteLine("start compile");
            var projectPath = Directory.GetCurrentDirectory();

            //load files
            var files = Directory.GetFiles(Path.Combine(projectPath, sourceFolder));

            var sourceFiles = files
                .Where(y => Path.GetExtension(y) == sourceFileExtension)
                .Select(x => new HDL.Parser.File()
                {
                    Name = Path.GetFileNameWithoutExtension(x),
                    Value = File.ReadAllText(x)
                })
                .ToList();

            Console.WriteLine($"Load {sourceFiles.Count} files");

            new ParserController(sourceFiles, x =>
            {
                Console.WriteLine($"{x.Count} tokens found");
                var compiler = new CompilerController(x, result =>
                {
                    new VHDLGeneratorController().GenerateCode(result, code =>
                    {
                        Console.WriteLine("Result");
                        Console.WriteLine("_______________________");
                        Console.WriteLine(code);
                        File.WriteAllText(Path.Combine(projectPath, outputFolder, outputFileName), code);
                    });
                });
            });
        }
Exemple #2
0
        public void SaveResults()
        {
            var singleRun  = _runFlags.SingleRun;
            var hasFailure = false;
            var xml        = "";

            Response.ContentType = "text/plain";
            try
            {
                var json = new StreamReader(Request.Body).ReadToEnd();
                ValidateResultsJson(json);

                var results = Runner.Models.Results.TestResults.LoadFromJson(json);
                hasFailure = results.failures > 0;
                xml        = results.ToXmlText();

                if (singleRun)
                {
                    ConsoleHelper.WriteLine();
                    results.PrintTextReport();
                }
            }
            catch (Exception x)
            {
                LogMiscErrorCore("Failed to save results. " + x);
                hasFailure = true;
            }

            IOFile.WriteAllText(ResultXmlPath(), xml);

            if (singleRun)
            {
                Environment.Exit(hasFailure ? 1 : 0);
            }
        }
        private void RemoveScriptsPreModsTechDCS(string path)
        {
            Logger.Info($"Removing SRS Pre Mods Scripts at {path}");
            //does it contain an export.lua?
            if (File.Exists(path + "\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Export.lua");

                if (contents.Contains("SimpleRadioStandalone.lua"))
                {
                    Logger.Info($"Removed SRS from Export.lua");
                    contents = contents.Replace("dofile(lfs.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])",
                                                "");
                    contents =
                        contents.Replace(
                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])",
                            "");
                    contents = contents.Trim();

                    File.WriteAllText(path + "\\Export.lua", contents);
                }
            }

            DeleteFileIfExists(path + "\\DCS-SimpleRadioStandalone.lua");
            DeleteFileIfExists(path + "\\DCS-SRSGameGUI.lua");
            DeleteFileIfExists(path + "\\DCS-SRS-AutoConnectGameGUI.lua");
            DeleteFileIfExists(path + "\\DCS-SRS-Overlay.dlg");
            DeleteFileIfExists(path + "\\DCS-SRS-OverlayGameGUI.lua");
            DeleteFileIfExists(path + "\\Hooks\\DCS-SRS-Hook.lua");

            Logger.Info($"Removed all SRS Scripts at {path}");
        }
        protected override void ExecuteCmdlet()
        {
            if (!string.IsNullOrEmpty(Out))
            {
                if (!Path.IsPathRooted(Out))
                {
                    Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
                }
                if (File.Exists(Out))
                {
                    if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Out), Resources.Confirm))
                    {
                        var xml = GetProvisioningTemplateXML();

                        File.WriteAllText(Out, xml, Encoding);
                    }
                }
                else
                {
                    var xml = GetProvisioningTemplateXML();

                    File.WriteAllText(Out, xml, Encoding);
                }
            }
            else
            {
                var xml = GetProvisioningTemplateXML();

                WriteObject(xml);
            }
        }
        public static void ClassInitialize(TestContext testContext)
        {
            if (!GlobalTestSettings.RunNetworkTests)
            {
                return;
            }

            accountInfoFilePath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
                "SyncProTesting",
                "BackblazeB2AccountInfo.json");

            if (File.Exists(accountInfoFilePath))
            {
                string fileContent = File.ReadAllText(accountInfoFilePath);
                accountInfo = JsonConvert.DeserializeObject <BackblazeB2AccountInfo>(fileContent);

                return;
            }

            CredentialResult credentials;

            try
            {
                credentials = CredentialHelper.PromptForCredentials(
                    "Enter your Backblaze AccountID (username) and Application Key (password)");
            }
            catch (Win32Exception win32Exception)
                when(win32Exception.NativeErrorCode ==
                     (int)NativeMethods.CredUI.CredUIReturnCodes.ERROR_CANCELLED)
                {
                    Assert.Inconclusive("Backblaze B2 credentials are required to run tests");

                    // ReSharper disable once HeuristicUnreachableCode
                    return;
                }

            accountInfo = new BackblazeB2AccountInfo
            {
                AccountId      = credentials.Username,
                ApplicationKey = credentials.Password
            };

            using (BackblazeB2Client client = CreateClient())
            {
                IList <Bucket> allBuckets = client.ListBucketsAsync().Result;
                Bucket         bucket     = allBuckets.FirstOrDefault(b => b.BucketName == DefaultBucketName);

                if (bucket == null)
                {
                    bucket = client.CreateBucket(DefaultBucketName, Constants.BucketTypes.Private).Result;
                }

                accountInfo.BucketId = bucket.BucketId;
            }

            string serializedInfo = JsonConvert.SerializeObject(accountInfo, Formatting.Indented);

            File.WriteAllText(accountInfoFilePath, serializedInfo);
        }
Exemple #6
0
        /// <summary>
        /// Saves all the metadata that fits in XMP to a file.
        /// </summary>
        /// <example>SaveXmplFile("c:\dir\metadata.xmp")</example>
        public void SaveXmpFile(string path)
        {
            var tag = new XmpTag();

            SaveInImageTag(tag);
            File.WriteAllText(path, tag.Render(), Encoding.UTF8);
        }
Exemple #7
0
        public void Test_that_error_report_doesnt_break_the_app()
        {
            using var tmpDir = new TemporaryDirectory();
            var path = Path.Combine(tmpDir.Path, "invalid.aasx");

            File.WriteAllText(path, "totally invalid");

            Common.RunWithMainWindow((application, automation, mainWindow) =>
            {
                Common.AssertLoadAasx(application, mainWindow, path);

                var numberErrors = Retry.Find(
                    () => (application.HasExited)
                        ? null
                        : mainWindow.FindFirstChild(cf => cf.ByAutomationId("LabelNumberErrors")),
                    new RetrySettings {
                    ThrowOnTimeout = true, Timeout = TimeSpan.FromSeconds(5)
                });

                Assert.AreEqual("Errors: 1", numberErrors.AsLabel().Text);

                var buttonReport = Retry.Find(
                    () => mainWindow.FindFirstChild(cf => cf.ByAutomationId("ButtonReport")),
                    new RetrySettings
                {
                    ThrowOnTimeout = true,
                    Timeout        = TimeSpan.FromSeconds(5),
                    TimeoutMessage = "Could not find the report button"
                }).AsButton();

                buttonReport.Click();

                Common.RequireTopLevelWindowByTitle(application, automation, "Message Report");
            });
        }
Exemple #8
0
 private void parseIPFSObjects()
 {
     try
     {
         if (File.Exists(jsonFilePath))
         {
             File.SetAttributes(jsonFilePath, FileAttributes.Normal);
             string json = File.ReadAllText(jsonFilePath);
             File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
             List <IPFSElement> tempElements = JsonConvert.DeserializeObject <List <IPFSElement> >(json);
             if (lastElementCount != tempElements.Count)
             {
                 elements = new ArrayList(tempElements);
                 this.objectListView1.SetObjects(elements);
                 lastElementCount = elements.Count;
             }
         }
         else
         {
             new DirectoryInfo(Path.GetDirectoryName(jsonFilePath)).Create();
             File.SetAttributes(jsonFilePath, FileAttributes.Normal);
             File.WriteAllText(jsonFilePath, "[]");
             File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
        public static void WriteMap(ARealmReversed realm, TerritoryType teriType, SaintCoinach.Graphics.Territory teri = null)
        {
            string name = teri != null ? teri.Name : teriType.Name;

            //Plot.Ward ward = Plot.StringToWard(teriType.Name);
            string outdir  = Path.Combine(FFXIVHSPaths.GetRootDirectory(), name + "\\");
            string outpath = Path.Combine(outdir, name + ".json");

            //string outpath = FFXIVHSPaths.GetWardJson(ward);

            if (!Directory.Exists(outdir))
            {
                Directory.CreateDirectory(outdir);
            }

            if (File.Exists(outpath))
            {
                WriteMapModels(realm, teriType, teri);
                return;
            }

            Map map = ReadTerritory(teriType, teri);

            string json = JsonConvert.SerializeObject(map, Formatting.Indented);

            File.WriteAllText(outpath, json);
        }
Exemple #10
0
 private void handleLinkOnlyElements()
 {
     try
     {
         for (int i = 0; i < elements.Count; i++)
         {
             IPFSElement el = ((IPFSElement)elements[i]);
             if (el.IsLinkOnly && !el.Active)
             {
                 new Thread(delegate()
                 {
                     el.Active     = true;
                     string output = ExecuteCommand("pin add " + el.Hash, true);
                     if (output.Equals("pinned " + el.Hash + " recursively\n"))
                     {
                         ShowNotification("File Pinned!", System.Drawing.SystemIcons.Information, System.Windows.Forms.ToolTipIcon.Info, 5000);
                     }
                     if (File.Exists(jsonFilePath))
                     {
                         string json = JsonConvert.SerializeObject(elements);
                         File.SetAttributes(jsonFilePath, FileAttributes.Normal);
                         File.WriteAllText(jsonFilePath, json);
                         File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
                     }
                 }).Start();
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
Exemple #11
0
        public void ToggleActiveState(int index)
        {
            if (index < elements.Count)
            {
                IPFSElement el = (IPFSElement)elements[index];
                el.Active = !el.Active;
                if (File.Exists(jsonFilePath))
                {
                    string json = JsonConvert.SerializeObject(elements);
                    File.SetAttributes(jsonFilePath, FileAttributes.Normal);
                    File.WriteAllText(jsonFilePath, json);
                    File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
                }
                this.objectListView1.RefreshObjects(elements);

                if (el.Active)
                {
                    AddElement(el.Path);
                }
                else
                {
                    UnpinElement(el);
                }
            }
        }
Exemple #12
0
        private void CreateFiles()
        {
            if (Directory.Exists("test"))
            {
                Directory.Delete("test", true);
            }
            var root = Directory.CreateDirectory("test");
            var dir1 = root.CreateSubdirectory("dir1");

            IOFile.WriteAllText(Path.Combine(dir1.FullName, "º½ÅÄ-1.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir1.FullName, "º½ÅÄ-2.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir1.FullName, "Æû³µ-1.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir1.FullName, "Æû³µ-2.mp4"), "");

            var dir2 = dir1.CreateSubdirectory("dir2");

            IOFile.WriteAllText(Path.Combine(dir2.FullName, "·É»ú-1.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir2.FullName, "Æû³µ-2.txt"), "");

            var dir3 = root.CreateSubdirectory("º½ÅÄ");

            IOFile.WriteAllText(Path.Combine(dir3.FullName, "1.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir3.FullName, "2.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir3.FullName, "1.jpg"), "");
            IOFile.WriteAllText(Path.Combine(dir3.FullName, "2.jpg"), "");

            var dir4 = root.CreateSubdirectory("Æû³µ");

            IOFile.WriteAllText(Path.Combine(dir4.FullName, "1.mp4"), "");
            IOFile.WriteAllText(Path.Combine(dir4.FullName, "2.jpg"), "");
            IOFile.WriteAllText(Path.Combine(dir4.FullName, "3.jpg"), "");
            IOFile.WriteAllText(Path.Combine(dir4.FullName, "4.mp4"), "");
        }
Exemple #13
0
        private string CreateImportManifestContent(string provider, string name, string version, string fileName, long fileSize, string fileHash, Tuple <string, string>[] compatibilityIds)
        {
            var aduContent = new
            {
                updateId          = new { provider, name, version },
                updateType        = "microsoft/swupdate:1",
                installedCriteria = "1.2.3.4",
                compatibility     = compatibilityIds.Select(c => new
                {
                    deviceManufacturer = c.Item1,
                    deviceModel        = c.Item2
                }).ToArray(),
                createdDateTime = DateTime.UtcNow,
                manifestVersion = new Version(2, 0),
                files           = new[]
                {
                    new
                    {
                        fileName    = fileName,
                        sizeInBytes = fileSize,
                        hashes      = new Dictionary <string, string>()
                        {
                            { "Sha256", fileHash }
                        }
                    }
                }
            };

            string filePath = Path.GetTempFileName();

            File.WriteAllText(filePath, JsonConvert.SerializeObject(aduContent, Formatting.Indented));

            return(filePath);
        }
Exemple #14
0
        private static bool AddStartupTask(string filePath)
        {
            try
            {
                string taskXml     = Properties.Resources.StartGestureSignTask.Replace("GestureSignFilePath", filePath);
                string xmlFilePath = Path.Combine(AppConfig.LocalApplicationDataPath, "StartGestureSignTask.xml");
                File.WriteAllText(xmlFilePath, taskXml, System.Text.Encoding.Unicode);

                using (Process schtasks = new Process())
                {
                    string arguments = string.Format(" /create /tn StartGestureSign /f /xml \"{0}\"", xmlFilePath);
                    schtasks.StartInfo = new ProcessStartInfo("schtasks.exe", arguments)
                    {
                        CreateNoWindow  = true,
                        WindowStyle     = ProcessWindowStyle.Hidden,
                        UseShellExecute = true,
                        Verb            = "runas",
                    };
                    schtasks.Start();
                    schtasks.WaitForExit();
                }
                if (File.Exists(xmlFilePath))
                {
                    File.Delete(xmlFilePath);
                }
            }
            catch (Exception exception)
            {
                GestureSign.Common.Log.Logging.LogAndNotice(exception);
                return(false);
            }

            return(true);
        }
Exemple #15
0
        public static void Main(string[] args)
        {
            if (File.Exists(NLogConfig))
            {
                NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(NLogConfig);
            }
            MainLog.Trace("Started");
            if (!File.Exists(ConfigPath))
            {
                Save(new Config());
                MainLog.Trace("Config saved");
                return;
            }
            if (!File.Exists(DatabasePath))
            {
                File.WriteAllText(DatabasePath, JsonConvert.SerializeObject(Data.Generatator.Generate()), Encoding.UTF8);
            }
            DB     = JsonConvert.DeserializeObject <Data.Database>(File.ReadAllText(DatabasePath, Encoding.UTF8));
            Config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(ConfigPath, Encoding.UTF8));

            TelegramBot = new TelegramBotClient(Config.TelegramToken);
            MLang       = MachineLang.MLang.Load(Config.LangBase);
            AirBot      = new AirBotWorker(MLang, TelegramBot, Config, DB);

            AirBot.Start();
            new Thread(() =>
            {
                while (true)
                {
                    File.WriteAllText(DatabasePath, JsonConvert.SerializeObject(DB), Encoding.UTF8);
                    Thread.Sleep(10000);
                }
            }).Start();
            Task.Delay(Timeout.Infinite).Wait();
        }
Exemple #16
0
        public void CreateNewPostOnDisk(string title, string weblogName)
        {
            // strip path of invalid characters
            var    invalids = Path.GetInvalidFileNameChars();
            string filename = null;

            foreach (char c in invalids)
            {
                filename = title.Replace(c, '-');
            }

            var folder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder, DateTime.Now.Year + "-" + DateTime.Now.Month.ToString("00"), filename);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var outputFile = Path.Combine(folder, filename + ".md");

            // Create the new post by creating a file with title preset
            string newPostMarkdown = NewWeblogPost(new WeblogPostMetadata()
            {
                Title      = title,
                WeblogName = weblogName
            });

            File.WriteAllText(outputFile, newPostMarkdown);
            Model.Window.OpenTab(outputFile);

            mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile);
        }
Exemple #17
0
        private static void WriteDiagnosticResults(ImmutableArray <Tuple <ProjectId, Diagnostic> > diagnostics, string fileName)
        {
            var orderedDiagnostics =
                diagnostics
                .OrderBy(tuple => tuple.Item2.Id)
                .ThenBy(tuple => tuple.Item2.Location.SourceTree?.FilePath, StringComparer.OrdinalIgnoreCase)
                .ThenBy(tuple => tuple.Item2.Location.SourceSpan.Start)
                .ThenBy(tuple => tuple.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);
        }
Exemple #18
0
        private static void CorrectingFiles(string path)
        {
            var csFilesPath  = Path.Combine(path, "Files", "cs");
            var resourcePath = Path.Combine(path, "Resources");
            var schemasPath  = Path.Combine(path, "Schemas");
            var names        = new List <string>();
            var csFilesDir   = new DirectoryInfo(csFilesPath);

            foreach (var file in csFilesDir.GetFiles("*.cs"))
            {
                var name = file.Name.Split('.')[0];
                names.Add(name);
                var currentResourcesDirectory = new DirectoryInfo(Path.Combine(resourcePath, name + ".SourceCode"));
                if (!currentResourcesDirectory.Exists)
                {
                    break;
                }
                var countLines = 0;
                foreach (var resourceFile in currentResourcesDirectory.GetFiles("*.xml"))
                {
                    var currentCount = File.ReadAllLines(resourceFile.FullName).Length;
                    countLines = countLines > currentCount ? countLines : currentCount;
                }
                if (countLines < 9)
                {
                    currentResourcesDirectory.Delete(true);
                    Directory.Delete(Path.Combine(schemasPath, name), true);
                }
                else
                {
                    File.WriteAllText(Path.Combine(schemasPath, name, file.Name), string.Empty);
                }
            }
        }
        public void Can_Read_Compiled_Package_Warnings()
        {
            //copy a file to the same path that the package will install so we can detect file conflicts
            var path = IOHelper.MapPath("~/" + _testBaseFolder);

            Console.WriteLine(path);

            var filePath = Path.Combine(path, "bin", "Auros.DocumentTypePicker.dll");

            Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            File.WriteAllText(filePath, "test");

            //this is where our test zip file is
            var packageFile = Path.Combine(IOHelper.MapPath("~/Packaging/packages"), DocumentTypePickerPackage);

            Console.WriteLine(packageFile);

            var package            = PackageInstallation.ReadPackage(new FileInfo(packageFile));
            var preInstallWarnings = package.Warnings;

            Assert.IsNotNull(preInstallWarnings);

            Assert.AreEqual(1, preInstallWarnings.FilesReplaced.Count());
            Assert.AreEqual("bin\\Auros.DocumentTypePicker.dll", preInstallWarnings.FilesReplaced.First());

            // TODO: More Asserts
        }
Exemple #20
0
        private string CreateImportManifestContent(string provider, string name, string version, string fileName, long fileSize, string fileHash, Tuple <string, string>[] compatibilityIds)
        {
            var aduContent = new ImportManifest(
                new UpdateId(provider, name, version),
                "microsoft/swupdate:1", "1.2.3.4",
                new List <ImportManifestCompatibilityInfo>(
                    compatibilityIds.Select(c => new ImportManifestCompatibilityInfo(c.Item1, c.Item2))),
                DateTime.UtcNow, new Version(2, 0), new List <ImportManifestFile>()
            {
                new ImportManifestFile(
                    fileName,
                    fileSize,
                    new Dictionary <HashType, string>()
                {
                    {
                        HashType.Sha256, fileHash
                    }
                })
            });

            string filePath = Path.GetTempFileName();

            File.WriteAllText(filePath, JsonConvert.SerializeObject(aduContent, Formatting.Indented));

            return(filePath);
        }
        public void writeString(Java.Lang.String str, bool append, Java.Lang.String encoding)
        {
            if (_isDirectory)
            {
                IOException exception = new IOException();
                exception._init_("Can't write string to a directory");
                throw exception;
            }

            if (type() == FileType.INTERNAL_)
            {
                IOException exception = new IOException();
                exception._init_("Can't write in an INTERNAL file");
                throw exception;
            }

            if (append)
            {
                File.AppendAllText(pathWithPrefix(), str, Encoding.GetEncoding((string)encoding));
            }
            else
            {
                File.WriteAllText(pathWithPrefix(), str, Encoding.GetEncoding((string)encoding));
            }
        }
Exemple #22
0
        private void RemoveAnnotationFromExcelFile(string outPath, string zipOutFolder)
        {
            var wb = new Workbook(Opts.WorkingFileName);

            var sb = new StringBuilder();

            foreach (var ws in wb.Worksheets)
            {
                foreach (var cm in ws.Comments)
                {
                    var cellName = CellsHelper.CellIndexToName(cm.Row, cm.Column);

                    var str = $"Sheet Name: \"{ws.Name}\", Cell Name: {cellName}, Comment Note: \r\n\"{cm.Note}\"";

                    sb.AppendLine(str);
                    sb.AppendLine();
                }
            }

            File.WriteAllText(zipOutFolder + "\\comments.txt", sb.ToString());


            foreach (var ws in wb.Worksheets)
            {
                ws.Comments.Clear();
            }

            wb.Save(outPath);
        }
Exemple #23
0
        public IActionResult EditTypeChart(IDictionary <int, Matchup> Matchups)
        {
            ViewBag.User = context.GetOneUser(HttpContext.Session.GetInt32("UserId"));
            if (ViewBag.User == null)
            {
                return(RedirectToAction("Index", "Home", new { area = "Account" }));
            }
            foreach (KeyValuePair <int, Matchup> matchup in Matchups)
            {
                Matchup ExistingMatchup = context.GetOneMatchup(matchup.Key);
                if (ExistingMatchup == null)
                {
                    TempData["ErrorMessage"] = "One of the types couldn't be found anymore - perhaps it was deleted?";
                    return(RedirectToAction("EditTypeChart"));
                }
                ExistingMatchup.EffectivenessId = matchup.Value.EffectivenessId;
            }
            context.SaveChanges();
            TempData["SuccessMessage"] = "Type chart successfully updated!";
            TypeChart NewTypeChart = new TypeChart(Matchups, context);
            string    filelocation = Path.Combine(_env.WebRootPath + "\\jsondata\\typechart.json");

            FileIO.WriteAllText(filelocation, JsonConvert.SerializeObject(NewTypeChart));
            return(RedirectToAction("EditTypeChart"));
        }
Exemple #24
0
    /// <summary>
    ///     Writes text to a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <param name="contents">The contents to write.</param>
    /// <param name="encoding">The encoding to use.</param>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
    ///     Visual Basic).
    /// </exception>
    /// <remarks>
    ///     This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
    ///     <see langword="null" />, an implementation-specific
    ///     encoding will be used.
    /// </remarks>
    public void WriteAllText(
        string path,
        string contents,
        Encoding?encoding = null)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        _ = Requires.NotNullOrWhiteSpace(
            contents,
            nameof(contents));

        if (encoding == null)
        {
            FSFile.WriteAllText(
                path,
                contents);
        }
        else
        {
            FSFile.WriteAllText(
                path,
                contents,
                encoding);
        }
    }
Exemple #25
0
        public void NotifySuiteFinalized(string name, bool passed)
        {
            Response.ContentType = "text/plain";
            lock (IO_SYNC)
            {
                Console.Write("[");
                if (passed)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" OK ");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("FAIL");
                }
                Console.ResetColor();
                Console.WriteLine("] " + name);

                if (_runFlags.IsContinuousIntegration)
                {
                    IOFile.WriteAllText(Path.Combine(_env.ContentRootPath, "testing/LastSuiteTime.txt"), DateTime.Now.ToString("s"));
                }
            }
        }
Exemple #26
0
    /// <summary>
    ///     Asynchronously writes text to a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <param name="contents">The contents to write.</param>
    /// <param name="encoding">The encoding to use.</param>
    /// <param name="cancellationToken">The cancellation token to stop this operation.</param>
    /// <returns>A task representing the current operation.</returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
    ///     Visual Basic).
    /// </exception>
    /// <remarks>
    ///     This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
    ///     <see langword="null" />, an implementation-specific
    ///     encoding will be used.
    /// </remarks>
    public Task WriteAllTextAsync(
        string path,
        string contents,
        Encoding?encoding = null,
        CancellationToken cancellationToken = default)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        _ = Requires.NotNullOrWhiteSpace(
            contents,
            nameof(contents));

        return(encoding == null
            ? Work.OnThreadPoolAsync(
                   state => FSFile.WriteAllText(
                       state.Path,
                       state.Contents),
                   (Path : path, Contents : contents),
                   cancellationToken)
               : Work.OnThreadPoolAsync(
                   state => FSFile.WriteAllText(
                       state.Path,
                       state.Contents,
                       state.Encoding),
                   (Path : path, Contents : contents, Encoding : encoding),
                   cancellationToken));
    }
Exemple #27
0
        public void CreateNewPostOnDisk(string title, string postFilename, string weblogName)
        {
            string filename      = SafeFilename(postFilename);
            string titleFilename = SafeFilename(title);

            var folder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder, DateTime.Now.Year + "-" + DateTime.Now.Month.ToString("00"), titleFilename);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var outputFile = Path.Combine(folder, filename);

            // Create the new post by creating a file with title preset
            string newPostMarkdown = NewWeblogPost(new WeblogPostMetadata()
            {
                Title      = title,
                WeblogName = weblogName
            });

            File.WriteAllText(outputFile, newPostMarkdown);
            Model.Window.OpenTab(outputFile);

            mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile);
        }
        public static void WriteTextToFile(string path, string content)
        {
            var fileInfo = new FileInfo(path);

            fileInfo.Directory.Create();
            File.WriteAllText(path, content);
        }
    void OnValidate()
    {
        if (!import)
        {
            return;
        }
        import = false;

        var liveRemotePath = RemotePath + @"\lives\" + liveName;
        var liveLocalPath  = LocalPath + @"\lives\" + liveName + ".json";

        string liveJson = File.ReadAllText(liveRemotePath);

        Debug.Log(liveJson);
        File.WriteAllText(liveLocalPath, liveJson);

        var live = JsonUtility.FromJson <ApiLiveResponse>(liveJson).content;

        Debug.Log(live.live_name);

        var    mapRemotePath = RemotePath + @"\maps\" + live.map_path;
        var    mapLocalPath  = LocalPath + @"\maps\" + live.map_path;
        string mapJson       = ApiLiveMap.Transform(File.ReadAllText(mapRemotePath));

        File.WriteAllText(mapLocalPath, mapJson);

        var bgmRemotePath = RemotePath + @"\bgms\" + live.bgm_path;
        var bgmLocalPath  = LocalPath + @"\bgms\" + live.bgm_path;

        byte[] bgmBytes = File.ReadAllBytes(bgmRemotePath);
        File.WriteAllBytes(bgmLocalPath, bgmBytes);
    }
Exemple #30
0
        /// <summary>
        ///     将视图写入html文件
        /// </summary>
        private async Task WriteViewToFileAsync(ResultExecutingContext context)
        {
            try {
                var html = await RenderToStringAsync(context);

                if (string.IsNullOrWhiteSpace(html))
                {
                    return;
                }

                var path      = Common.GetPhysicalPath(string.IsNullOrWhiteSpace(Path) ? GetPath(context) : Path);
                var directory = System.IO.Path.GetDirectoryName(path);
                if (string.IsNullOrWhiteSpace(directory))
                {
                    return;
                }

                if (Directory.Exists(directory) == false)
                {
                    Directory.CreateDirectory(directory);
                }

                File.WriteAllText(path, html);
            } catch (Exception ex) {
                ex.Log(Log.GetLog().Caption("生成html静态文件失败"));
            }
        }