CreateText() public static méthode

public static CreateText ( String path ) : StreamWriter
path String
Résultat StreamWriter
Exemple #1
0
 private static void CopySupportFile(string outputDirectory, string fileName, string contents)
 {
     using (var writer = File.CreateText(Path.Combine(outputDirectory, fileName)))
     {
         writer.Write(contents);
     }
 }
Exemple #2
0
        public static void GenerateSimulink(TestBench selectedTestBench, string outputDirectory, string projectDirectory)
        {
            // Reset block name cache (interpreters don't necessarily get reloaded between executions, so
            // we need to reset any static variables ourselves that need to be reset between executions)
            SimulinkBlock.ResetBlockNameCache();

            var model = new SimulinkModel(selectedTestBench);

            // Copy support files
            CopySupportFile(outputDirectory, "CreateOrOverwriteModel.m", Resources.CreateOrOverwriteModel);
            CopySupportFile(outputDirectory, "PopulateTestBenchParams.py", Resources.PopulateTestBenchParams);

            CopyCopyFiles(selectedTestBench, projectDirectory, outputDirectory);

            var postProcessScripts = GetAndCopyPostProcessScripts(selectedTestBench, projectDirectory, outputDirectory);

            using (var writer = File.CreateText(Path.Combine(outputDirectory, "build_simulink.m.in")))
            {
                model.GenerateSimulinkModelCode(writer);
            }

            using (var writer = File.CreateText(Path.Combine(outputDirectory, "run_simulink.m")))
            {
                model.GenerateSimulinkExecutionCode(writer);
            }

            using (var writer = File.CreateText(Path.Combine(outputDirectory, "run.cmd")))
            {
                GenerateRunCmd(writer, postProcessScripts);
            }
        }
Exemple #3
0
        public void SetUp()
        {
            directory = TestContext.CurrentContext.TestDirectory.Combine("subdir");
            Directory.CreateDirectory(directory);

            try {
                uncDirectory = UncHelper.GetUncFromPath(directory);
                filePath     = new StringBuilder(directory).Append(@"\").Append(Filename).ToString();
                uncFilePath  = UncHelper.GetUncFromPath(filePath);

                using (var writer = File.CreateText(filePath)) {
                    writer.WriteLine("test");
                }

                Debug.Assert(Pri.LongPath.File.Exists(uncFilePath));
            }
            catch (Exception) {
                if (Directory.Exists(directory))
                {
                    Directory.Delete(directory, true);
                }

                throw;
            }
        }
Exemple #4
0
        public void Export_Zip()
        {
            var mt = MediaTypeBuilder.CreateImageMediaType("testImage");

            MediaTypeService.Save(mt);
            var m1 = MediaBuilder.CreateMediaFile(mt, -1);

            MediaService.Save(m1);

            //Ensure a file exist
            var fullPath = HostingEnvironment.MapPathWebRoot(m1.Properties[Constants.Conventions.Media.File].GetValue().ToString());

            using (StreamWriter file1 = File.CreateText(fullPath))
            {
                file1.WriteLine("hello");
            }

            var def = new PackageDefinition
            {
                Name      = "test",
                MediaUdis = new List <GuidUdi>()
                {
                    m1.GetUdi()
                }
            };

            bool result = PackageBuilder.SavePackage(def);

            Assert.IsTrue(result);
            Assert.IsTrue(def.PackagePath.IsNullOrWhiteSpace());

            string packageXmlPath = PackageBuilder.ExportPackage(def);

            def = PackageBuilder.GetById(def.Id); // re-get
            Assert.IsNotNull(def.PackagePath);

            using (FileStream packageZipStream = File.OpenRead(packageXmlPath))
                using (ZipArchive zipArchive = PackageMigrationResource.GetPackageDataManifest(packageZipStream, out XDocument packageXml))
                {
                    string test = "test-file.txt";
                    Assert.Multiple(() =>
                    {
                        var mediaEntry = zipArchive.GetEntry("media/media/test-file.txt");
                        Assert.AreEqual("umbPackage", packageXml.Root.Name.ToString());
                        Assert.IsNotNull(mediaEntry);
                        Assert.AreEqual(test, mediaEntry.Name);
                        Assert.IsNotNull(zipArchive.GetEntry("package.xml"));
                        Assert.AreEqual(
                            $"<MediaItems><MediaSet><testImage id=\"{m1.Id}\" key=\"{m1.Key}\" parentID=\"-1\" level=\"1\" creatorID=\"-1\" sortOrder=\"0\" createDate=\"{m1.CreateDate.ToString("s")}\" updateDate=\"{m1.UpdateDate.ToString("s")}\" nodeName=\"Test File\" urlName=\"test-file\" path=\"{m1.Path}\" isDoc=\"\" nodeType=\"{mt.Id}\" nodeTypeAlias=\"testImage\" writerName=\"\" writerID=\"0\" udi=\"{m1.GetUdi()}\" mediaFilePath=\"/media/test-file.txt\"><umbracoFile><![CDATA[/media/test-file.txt]]></umbracoFile><umbracoBytes><![CDATA[100]]></umbracoBytes><umbracoExtension><![CDATA[png]]></umbracoExtension></testImage></MediaSet></MediaItems>",
                            packageXml.Element("umbPackage").Element("MediaItems").ToString(SaveOptions.DisableFormatting));
                        Assert.AreEqual(2, zipArchive.Entries.Count());
                        Assert.AreEqual(ZipArchiveMode.Read, zipArchive.Mode);
                        Assert.IsNull(packageXml.DocumentType);
                        Assert.IsNull(packageXml.NextNode);
                        Assert.IsNull(packageXml.Parent);
                        Assert.IsNull(packageXml.PreviousNode);
                    });
                }
        }
    /// <summary>
    ///     Opens a <see cref="StreamWriter" /> to write text to a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <returns>
    ///     A <see cref="StreamWriter" /> that can write to a file.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
    /// </exception>
    public StreamWriter CreateText(string path)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));

        return(FSFile.CreateText(path));
    }
 /// <summary>
 /// Serialize data to JSON file.
 /// </summary>
 private void SaveAsJson <T>(T data, string fileName)
 {
     using (StreamWriter file = File.CreateText(fileName))
     {
         var serializer = new JsonSerializer();
         //serialize object directly into file stream
         serializer.Serialize(file, data);
     }
 }
        public void MakeLauncher(string command, string args, string launcherPath)
        {
            string filePath = Path.ChangeExtension(
                launcherPath, batchFileExtension);
            string cmdLine = string.Format("\"{0}\" {1}", command, args);

            using (StreamWriter s = File.CreateText(filePath))
            {
                s.WriteLine(cmdLine);
            }
        }
        public static AutoFlushedTextFile Create(string textFilePath, string firstLile)
        {
            var stream = File.CreateText(textFilePath);

            stream.AutoFlush = true;
            stream.WriteLine(firstLile);
            if (ShowTxtFile && File.Exists(SublimePath))
            {
                Process.Start(SublimePath, textFilePath);
            }
            return(new AutoFlushedTextFile(stream, textFilePath));
        }
        private void checkLocalResources()
        {
            if (!Directory.Exists(localResourcesDir))
            {
                Directory.CreateDirectory(localResourcesDir);
            }

            if (!File.Exists(localResourcesData))
            {
                File.CreateText(localResourcesData);
            }
        }
Exemple #10
0
    void loadFile(string filename)
    {
        if (!File.Exists(filename))
        {
            File.CreateText(filename);
            return;
        }

        try
        {
            string       line;
            StreamReader sReader = new StreamReader(filename, Encoding.Default);
            do
            {
                line = sReader.ReadLine();
                if (line != null)
                {
                    // Lines with # are for comments
                    if (!line.Contains("#"))
                    {
                        // Value property identified by string before the colon.
                        string[] data = line.Split(':');
                        if (data.Length == 2)
                        {
                            switch (data[0])
                            {
                            case "IP Address":
                                Debug.Log("IP Address: " + data[1]);
                                ipAddress = data[1].Trim();
                                break;

                            case "Port":
                                Debug.Log("Port: " + data[1]);
                                port = data[1].Trim();
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
            }while (line != null);
            sReader.Close();
            return;
        }
        catch (Exception e)
        {
        }
    }
Exemple #11
0
        public static void Generate()
        {
            string reflectionPath = Path.Combine(Bootstrap.Source, @"Kernel\Runtime\Reflection\Reflection.Generated.cpp");

            using (StreamWriter output = CFile.CreateText(reflectionPath))
            {
                output.WriteLine("#include <System/System.h>");
                output.WriteLine("#include <Kernel/Runtime/Reflection/Reflection.h>");
                output.WriteLine();

                //Type[] types = Program.Parser.Types.Where(t => t.Modifiers.HasFlag(Modifiers.Shared))
                //                                   .Where(t => !t.Name.Contains("RTTI"))
                //                                   .ToArray();
                //List<Method> methods = types.SelectMany(t => t.Methods).ToList();

                //foreach (var file in Program.Parser.Files)
                //	output.WriteLine("#include <{0}>", file.Path.Replace(context.Path + "\\", "").Replace("\\", "/"));
                //output.WriteLine();

                output.WriteLine("using namespace System::Runtime;");
                output.WriteLine();

                foreach (Namespace ns in Program.Parser.Namespaces)
                {
                    output.WriteLine("using namespace {0};", ns.ToIdentifier(cppGenerator));
                }
                output.WriteLine();

                output.WriteLine("void Reflection::Initialize()");
                output.WriteLine("{");

                Type[] types = Program.Parser.Types.Where(t => !(t.Parent is Namespace) && !(t is Type.Alias) && !t.Templates.Any())
                               .Where(t => !t.Name.Contains("RTTI"))
                               .Where(t => t.Name != "type_info" && t.Name != "initializer_list")
                               .ToArray();
                foreach (Type t in types)
                {
                    output.WriteLine(string.Join(Environment.NewLine, GenerateType(t).Select(l => "    " + l)));
                }



                //foreach (Namespace ns in Program.Parser.Namespaces.Where(n => !(n.Parent is Namespace)))
                //	output.WriteLine(string.Join(Environment.NewLine, GenerateNamespace(ns).Select(l => "    " + l)));

                output.WriteLine("}");
            }
        }
Exemple #12
0
    private static void saveBuildingsData(string path)
    {
        string fileName = Path.Combine(path, "Buildings.data");

        if (File.Exists(fileName))
        {
            File.Delete(fileName);
        }
        BuildingsDataModel data = new BuildingsDataModel();

        data.GetValues();
        string json = JsonConvert.SerializeObject(data);

        using (StreamWriter sw = File.CreateText(fileName))
        {
            sw.Write(json);
        }
    }
 /// <summary>
 /// Запись ошибок в лог.
 /// </summary>
 /// <param name="_NameOperations">Имя операции.</param>
 /// <param name="_NameError">Имя ошибки.</param>
 public void LogForOperations(string _NameOperations, string _NameError)
 {
     try
     {
         if (!SDirectory.Exists(@"C:\\FileManagerLog"))
         {
             SDirectory.CreateDirectory(@"C:\\FileManagerLog");//создаем каталог для лога
             SFile.CreateText(@"c:\FileManagerLog\log.txt");
         }
         System.IO.StreamWriter writer = new System.IO.StreamWriter(@"c:\FileManagerLog\log.txt");                                           //создаем поток
         writer.WriteLine("Время операции:" + System.DateTime.Now + ". " + _NameOperations + "'" + dname + "'. Ошибка: " + _NameError + ""); //запись в лог
         writer.Close();                                                                                                                     //закрываем поток
     }
     catch (Exception e)                                                                                                                     //обработка исключений для лога
     {
         throw e;
     }
 }
Exemple #14
0
        public static void ConverttotoXML(string path)
        {
            string pathXML = Path.GetDirectoryName(path); //sto prendendo il path del file originale e prendo anche il nome
            string title   = Path.GetFileNameWithoutExtension(path).ToLower();
            string line;

            string[] titles  = new string[] { };
            int      counter = 0;

            using (StreamReader file = File.OpenText(path))
            {
                using (StreamWriter filewriter = File.CreateText(pathXML + "/" + title + ".xml"))
                {
                    filewriter.WriteLine("<" + title + ">");

                    while ((line = file.ReadLine()) != null)
                    {
                        if (counter == 0) //caso prima riga, con i titoli
                        {
                            line   = line.ToLower();
                            titles = line.Split(",");
                            counter++; //aggiorno il contatore per andare all'altra riga
                        }
                        else //sono in una riga con i dati
                        {
                            string[] data = new string[] { };
                            data = line.Split(",");
                            string titleSingle = title.Substring(0, title.Length - 1); // in titlesingle ho employee (senza la s)
                            filewriter.WriteLine("\t<" + titleSingle + ">");


                            for (int i = 0; i < title.Length - 1; i++)
                            {
                                filewriter.WriteLine("\t\t<" + titles[i] + ">" + data[i] + "</" + titles[i] + ">");
                            }
                            filewriter.WriteLine("\t</" + titleSingle + ">");
                            counter++;
                        }
                    }
                    filewriter.WriteLine("</" + title + ">");
                }
            }
        }
Exemple #15
0
        public void Example()
        {
            #region Usage
            Movie movie = new Movie
            {
                Name = "Bad Boys",
                Year = 1995
            };

            // serialize JSON to a string and then write string to a file
            File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));

            // serialize JSON directly to a file
            using (StreamWriter file = File.CreateText(@"c:\movie.json"))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, movie);
            }
            #endregion
        }
Exemple #16
0
        private void imprimirTicket()
        {
            //CAMBIAR RUTA



            // Create a file to write to.
            try
            {
                string path = @"C:\\Users\\pao_q\\OneDrive\\Escritorio\\Punto_Venta\\Punto_Venta\\ticket.txt";
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine("\t\t\tAbarrotes Covid\n\t\t\t\tTicket\n");
                    sw.WriteLine(DateTime.Now.ToLongDateString() + "\t\t\t\t\t" + DateTime.Now.ToLongTimeString() + "\n");
                    sw.WriteLine("\tPrecio\t\tNombre\t\t\tCantidad\tTotal");


                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        for (int j = 0; j < dataGridView1.Columns.Count; j++)
                        {
                            sw.Write("\t" + dataGridView1.Rows[i].Cells[j].Value + "\t" + "|");
                        }
                        sw.WriteLine("");
                        sw.WriteLine("--------------------------------------------------------------------------\n");
                    }
                    sw.WriteLine("\t\t\t\t" + label3.Text);
                }


                MessageBox.Show("Ticket Impreso", "Abarrotes Covid");
            }


            catch (System.Exception e)
            {
                e.Message.ToString();
            }

            limpiar(); //limpia gridview & total
        }
Exemple #17
0
    private static void saveConfig(string path, string name)
    {
        string fileName = Path.Combine(path, "ollopa.save");

        if (File.Exists(fileName))
        {
            File.Delete(fileName);
        }
        ConfigDataModel data = new ConfigDataModel();

        data.GetValues();
        using (StreamWriter sw = File.CreateText(fileName))
        {
            sw.Write(name);
        }
        string json = JsonConvert.SerializeObject(data);

        using (StreamWriter sw = File.CreateText(fileName))
        {
            sw.Write(json);
        }
    }
Exemple #18
0
        /// <summary>Caches current log messages within the Zip archive</summary>
        /// <param name="logger">The logging object</param>
        /// <param name="archive">The destination archive object</param>
        /// <param name="system">The system object used to prep the log file for export</param>
        private static void ArchiveCurrentLog(Logger logger, SharpZipArchive archive, IFileSystem system)
        {
            // Only run if logging is enabled
            if (logger.LoggingOptions["output_buffer_enabled"] == "true")
            {
                string logfileTempPath = String.Format("CyLR_Collection_Log_{0}.log", DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss"));
                // Cache log messages to File object
                using (StreamWriter sw = File.CreateText(logfileTempPath))
                {
                    sw.Write(logger.logMessages);
                }

                // Add cached file to archive
                List <string> paths = new List <string> {
                    logfileTempPath
                };
                var fileHandles = OpenFiles(system, paths, logger);
                archive.CollectFilesToArchive(fileHandles);

                // Removed cached log file
                File.Delete(logfileTempPath);
            }
        }
        private void DumpPlayers()
        {
            var players      = _db.GetAllPlayers();
            var dumpTxt      = "";
            var dumpFileName = $"database_players_dump_{DateTime.Now.Day}{DateTime.Now.Month}{DateTime.Now.Year}_{DateTime.Now.Hour}.txt";

            foreach (var player in players)
            {
                dumpTxt += $"{player.Number};{player.Surname};{player.Name};{player.SecondName};{player.Birthday};{player.Position};{player.Status};{player.TelegramUserid}\n";
            }

            try
            {
                using (var stream = File.CreateText(Path.Combine(Config.DbDirPath, dumpFileName)))
                {
                    stream.Write(dumpTxt);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemple #20
0
        private static void Main()
        {
            var sw = default(StreamWriter);

            try
            {
                var fileDir = new DirectoryInfo(ConfigurationManager.AppSettings["DirLocation"] + @"\Log\");
                if (!fileDir.Exists)
                {
                    fileDir.Create();
                }

                sw = File.Exists(fileDir.FullName + "TrackLog.txt")
                    ? File.AppendText(fileDir.FullName + "TrackLog.txt")
                    : File.CreateText(fileDir.FullName + "TrackLog.txt");
                sw.WriteLine("======================= Schedular Started, Dated : " + DateTime.Now + " ==========================");

                ReadDownloadedFile(sw);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.WriteLine("Main - " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    sw.WriteLine(ex.InnerException?.Message ?? ex.Message + " - " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                }
            }
            finally
            {
                if (sw != null)
                {
                    sw.WriteLine("======================= SchedularEnded, Dated : " + DateTime.Now + " ==========================");
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
        public void CreateProject(string name)
        {
            var config = new Config()
            {
                Name = name
            };

            var projectPath = Path.Combine(Directory.GetCurrentDirectory(), name);

            Directory.CreateDirectory(projectPath);
            Directory.CreateDirectory(Path.Combine(projectPath, sourceFolder));
            Directory.CreateDirectory(Path.Combine(projectPath, outputFolder));
            Directory.CreateDirectory(Path.Combine(projectPath, packageFolder));

            using (var file = File.CreateText(Path.Combine(projectPath, configFile)))
            {
                file.Write(JsonSerializer.Serialize(config));
            }

            using (var file = File.CreateText(Path.Combine(projectPath, sourceFolder, mainSourceFile + sourceFileExtension)))
            {
                file.Write("module Main()(){}");
            }
        }
        private async Task SaveFilesOnDisk(FileStructureDTO fileStructure, IDictionary <string, FileDTO> allFileInFileStructure, string path)
        {
            foreach (var node in fileStructure.NestedFiles)
            {
                if (node.Type == TreeNodeType.File)
                {
                    var hasFile = allFileInFileStructure.TryGetValue(node.Id, out var file);
                    if (!hasFile)
                    {
                        continue;
                    }

                    Directory.CreateDirectory(path);
                    using (StreamWriter streamWriter = File.CreateText(Path.Combine(path, file.Name)))
                    {
                        await streamWriter.WriteAsync(file.Content).ConfigureAwait(false);
                    }
                }
                else
                {
                    await SaveFilesOnDisk(node, allFileInFileStructure, Path.Combine(path, node.Name)).ConfigureAwait(false);
                }
            }
        }
        private void InstallScripts(string path)
        {
            Logger.Info($"Installing Scripts to {path}");
            _progressBarDialog.UpdateProgress(false, $"Creating Script folders @ {path}");
            //Scripts Path
            CreateDirectory(path + "\\Scripts");
            CreateDirectory(path + "\\Scripts\\Hooks");

            //Make Tech Path
            CreateDirectory(path + "\\Mods");
            CreateDirectory(path + "\\Mods\\Tech");
            CreateDirectory(path + "\\Mods\\Tech\\DCS-SRS");

            Task.Delay(TimeSpan.FromMilliseconds(100)).Wait();

            _progressBarDialog.UpdateProgress(false, $"Updating / Creating Export.lua @ {path}");
            Logger.Info($"Handling Export.lua");
            //does it contain an export.lua?
            if (File.Exists(path + "\\Scripts\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Scripts\\Export.lua");

                contents.Split('\n');

                if (contents.Contains("SimpleRadioStandalone.lua") && !contents.Contains("Mods\\Tech\\DCS-SRS\\Scripts\\DCS-SimpleRadioStandalone.lua"))
                {
                    Logger.Info($"Updating existing Export.lua with existing SRS install");
                    var lines = contents.Split('\n');

                    StringBuilder sb = new StringBuilder();

                    foreach (var line in lines)
                    {
                        if (line.Contains("SimpleRadioStandalone.lua"))
                        {
                            sb.Append("\n");
                            sb.Append(EXPORT_SRS_LUA);
                            sb.Append("\n");
                        }
                        else if (line.Trim().Length > 0)
                        {
                            sb.Append(line);
                            sb.Append("\n");
                        }
                    }
                    File.WriteAllText(path + "\\Scripts\\Export.lua", sb.ToString());
                }
                else
                {
                    Logger.Info($"Appending to existing Export.lua");
                    var writer = File.AppendText(path + "\\Scripts\\Export.lua");

                    writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n");
                    writer.Close();
                }
            }
            else
            {
                Logger.Info($"Creating new Export.lua");
                var writer = File.CreateText(path + "\\Scripts\\Export.lua");

                writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n");
                writer.Close();
            }


            //Now sort out Scripts//Hooks folder contents
            Logger.Info($"Creating / installing Hooks & Mods");
            _progressBarDialog.UpdateProgress(false, $"Creating / installing Hooks & Mods @ {path}");
            try
            {
                File.Copy(_currentDirectory + "\\Scripts\\Hooks\\DCS-SRS-hook.lua", path + "\\Scripts\\Hooks\\DCS-SRS-hook.lua",
                          true);
                DirectoryCopy(_currentDirectory + "\\Scripts\\DCS-SRS", path + "\\Mods\\Tech\\DCS-SRS");
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(
                    "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer",
                    "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }
            Logger.Info($"Scripts installed to {path}");

            _progressBarDialog.UpdateProgress(false, $"Installed Hooks & Mods @ {path}");
        }
Exemple #24
0
        private void InstallScripts(string path)
        {
            //if scripts folder doesnt exist, create it
            Directory.CreateDirectory(path);
            Directory.CreateDirectory(path + "\\Hooks");
            Thread.Sleep(100);

            var write = true;

            //does it contain an export.lua?
            if (File.Exists(path + "\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Export.lua");

                if (contents.Contains("SimpleRadioStandalone.lua"))
                {
//                    contents =
//                        contents.Replace(
//                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])",
//                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])");
//                    contents = contents.Trim();
//
//                    File.WriteAllText(path + "\\Export.lua", contents);

                    // do nothing
                }
                else
                {
                    var writer = File.AppendText(path + "\\Export.lua");

                    writer.WriteLine(
                        "\n  local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])\n");
                    writer.Close();
                }
            }
            else
            {
                var writer = File.CreateText(path + "\\Export.lua");

                writer.WriteLine(
                    "\n  local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])\n");
                writer.Close();
            }

            try
            {
                File.Copy(currentDirectory + "\\DCS-SimpleRadioStandalone.lua",
                          path + "\\DCS-SimpleRadioStandalone.lua", true);

                File.Copy(currentDirectory + "\\DCS-SRSGameGUI.lua",
                          path + "\\DCS-SRSGameGUI.lua", true);

                File.Copy(currentDirectory + "\\DCS-SRS-OverlayGameGUI.lua", path + "\\DCS-SRS-OverlayGameGUI.lua",
                          true);

                File.Copy(currentDirectory + "\\DCS-SRS-Overlay.dlg", path + "\\DCS-SRS-Overlay.dlg",
                          true);

                File.Copy(currentDirectory + "\\DCS-SRS-hook.lua", path + "\\Hooks\\DCS-SRS-hook.lua",
                          true);
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(
                    "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer",
                    "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }
        }
        public static async Task <int> Main(string[] args)
        {
            // check for GMaster or PlasticSCM or SemanticMerge arguments (to allow debugging without the tools)
            if (args.Length == 2)
            {
                var shell    = args[0]; // reserved for future usage
                var flagFile = args[1];

                SystemFile.WriteAllBytes(flagFile, new byte[] { 0x42 });
            }

            var watch   = Stopwatch.StartNew();
            var gcWatch = Stopwatch.StartNew();

            while (true)
            {
                var inputFile = await Console.In.ReadLineAsync();

                if (inputFile == null || "end".Equals(inputFile, StringComparison.OrdinalIgnoreCase))
                {
                    // session is done
                    Tracer.Trace($"Terminating as session was ended (instance {InstanceId:B})");
                    return(0);
                }

                var encodingToUse = await Console.In.ReadLineAsync();

                var outputFile = await Console.In.ReadLineAsync();

                try
                {
                    try
                    {
                        watch.Restart();

                        var file = Parser.Parse(inputFile, encodingToUse);

                        using (var writer = SystemFile.CreateText(outputFile))
                        {
                            YamlWriter.Write(writer, file);
                        }

                        var parseErrors = file.ParsingErrorsDetected == true;
                        if (parseErrors)
                        {
                            var parsingError = file.ParsingErrors[0];
                            Tracer.Trace(parsingError.ErrorMessage);
                            Tracer.Trace(parsingError.Location);
                        }

                        // clean-up after big files
                        if (IsBigFile(inputFile))
                        {
                            gcWatch.Restart();

                            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, false, true);

                            Tracer.Trace($"Garbage collection took {gcWatch.Elapsed:s\\.fff} secs  (instance {InstanceId:B})");
                        }

                        Console.WriteLine(parseErrors ? "KO" : "OK");
                    }
                    finally
                    {
                        Tracer.Trace($"Parsing took {watch.Elapsed:s\\.fff} secs  (instance {InstanceId:B})");
                    }
                }
                catch (Exception ex)
                {
                    Tracer.Trace($"Exception: {ex}");

                    var stackTraceLines = ex.StackTrace?.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) ?? Enumerable.Empty <string>();
                    foreach (var stackTraceLine in stackTraceLines)
                    {
                        Tracer.Trace(stackTraceLine);
                    }

                    Console.WriteLine("KO");

                    throw;
                }
            }
        }
Exemple #26
0
        private void Installer1_Committed(object sender, InstallEventArgs e)
        {
            try
            {
                var path = new DirectoryInfo(Context.Parameters["assemblypath"]).Parent;

                if (Directory.Exists(path.FullName + @"\gin-cli\"))
                {
                    var dInfo = new DirectoryInfo(path.FullName + @"\gin-cli\");
                    dInfo.Empty();
                    Directory.Delete(path.FullName + @"\gin-cli\", true);
                }
                Directory.CreateDirectory(path.FullName + @"\dokan\");

                //Give the client the ability to register a URL to communicate with the service
                var everyone = new System.Security.Principal.SecurityIdentifier(
                    "S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                var procStartInfo = new ProcessStartInfo("cmd.exe",
                                                         "/C netsh http add urlacl url=http://+:8738/GinService/ user=\\" + everyone + " delegate=yes")
                {
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true
                };

                var process = new Process {
                    StartInfo = procStartInfo
                };
                var Output = new StringBuilder();
                process.OutputDataReceived += (o, args) =>
                {
                    if (!string.IsNullOrEmpty(args.Data))
                    {
                        Output.AppendLine(args.Data);
                    }
                };
                Output.Clear();
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();

                //Give the user the ability to register the service URL
                procStartInfo = new ProcessStartInfo("cmd.exe",
                                                     "/C netsh http add urlacl url=http://+:8733/GinService/ user=\\" + everyone + " delegate=yes")
                {
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true
                };

                process = new Process {
                    StartInfo = procStartInfo
                };
                Output = new StringBuilder();
                process.OutputDataReceived += (o, args) =>
                {
                    if (!string.IsNullOrEmpty(args.Data))
                    {
                        Output.AppendLine(args.Data);
                    }
                };
                Output.Clear();
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();

                Output.Clear();

                //Create shortcuts in the Startup and Start Menu folders
                var wsh      = new WshShell();
                var shortcut = wsh.CreateShortcut(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup) + @"\GinClientApp.lnk") as
                               IWshShortcut;
                shortcut.Arguments        = "";
                shortcut.TargetPath       = path.FullName + @"\GinClientApp.exe";
                shortcut.WindowStyle      = 1;
                shortcut.Description      = "Gin Client for Windows";
                shortcut.WorkingDirectory = path.FullName;
                shortcut.IconLocation     = path.FullName + @"\gin_icon.ico";
                shortcut.Save();

                if (!Directory.Exists(
                        Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu) + @"\G-Node\"))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu) +
                                              @"\G-Node\");
                }

                wsh      = new WshShell();
                shortcut = wsh.CreateShortcut(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu) +
                    @"\G-Node\GinClientApp.lnk") as
                           IWshShortcut;
                shortcut.Arguments        = "";
                shortcut.TargetPath       = path.FullName + @"\GinClientApp.exe";
                shortcut.WindowStyle      = 1;
                shortcut.Description      = "Gin Client for Windows";
                shortcut.WorkingDirectory = path.FullName;
                shortcut.IconLocation     = path.FullName + @"\gin_icon.ico";
                shortcut.Save();
            }
            catch (Exception exc)
            {
                ///print error into json in appdata folder
                var fs = File.CreateText(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\g-node\WinGIN\InstallError.json");
                fs.Write(JsonConvert.SerializeObject(exc));
                fs.Flush();
                fs.Close();
                throw new InstallException("Installation failed. Please check your internet connection and try it later.");
            }
        }
        public static async Task <int> Main(string[] args)
        {
            // check for GMaster or PlasticSCM or SemanticMerge arguments (to allow debugging without the tools)
            if (args.Length == 2)
            {
                var shell    = args[0]; // reserved for future usage
                var flagFile = args[1];

                SystemFile.WriteAllBytes(flagFile, new byte[] { 0x42 });
            }

            var watch   = Stopwatch.StartNew();
            var gcWatch = Stopwatch.StartNew();

            while (true)
            {
                var inputFile = await Console.In.ReadLineAsync();

                if (inputFile == null || "end".Equals(inputFile, StringComparison.OrdinalIgnoreCase))
                {
                    // session is done
                    Tracer.Trace($"Terminating as session was ended (instance {InstanceId:B})");
                    return(0);
                }

                var encodingToUse = await Console.In.ReadLineAsync();

                var outputFile = await Console.In.ReadLineAsync();

                try
                {
                    var parseErrors = false;
                    try
                    {
                        watch.Restart();

                        // we find a flavor here, as we want to support different main methods, based on file ending
                        var flavor = XmlFlavorFinder.Find(inputFile);

                        var file = Parser.Parse(inputFile, encodingToUse, flavor);

                        using (var writer = SystemFile.CreateText(outputFile))
                        {
                            YamlWriter.Write(writer, file);
                        }

                        parseErrors = file.ParsingErrorsDetected == true;
                        if (parseErrors)
                        {
                            var parsingError = file.ParsingErrors[0];
                            Tracer.Trace(parsingError.ErrorMessage);
                            Tracer.Trace(parsingError.Location);
                        }

                        // clean-up after big files
                        if (IsBigFile(inputFile))
                        {
                            gcWatch.Restart();

                            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, false, true);

                            Tracer.Trace($"Garbage collection took {gcWatch.Elapsed:s\\.fff} secs  (instance {InstanceId:B})");
                        }

                        Console.WriteLine(parseErrors ? "KO" : "OK");
                    }
                    finally
                    {
                        Tracer.Trace($"Parsing took {watch.Elapsed:s\\.fff} secs  (instance {InstanceId:B}), errors found: {parseErrors}");
                    }
                }
                catch (Exception ex)
                {
                    Tracer.Trace($"Exception: {ex}", ex);

                    Console.WriteLine("KO");

                    return(0);
                }
            }
        }
Exemple #28
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                string packageResourceName      = "ASTRA.EMSG.Mobile.Installer.InstallerPackage.Application.pkg";
                string packageName              = "Application.pkg";
                string applicationDirectoryName = "EMSG.Mobile";
                string applicationName          = "ASTRA.EMSG.Mobile.exe";

                string installDirectory = System.IO.Path.Combine(userDirectory, applicationDirectoryName);
                if (!Directory.Exists(installDirectory))
                {
                    Directory.CreateDirectory(installDirectory);
                }

                string packageFilePath = Path.Combine(installDirectory, packageName);

                string applicationPath = Path.Combine(installDirectory, applicationName);

                using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(packageResourceName))
                {
                    using (var fw = new FileStream(packageFilePath, FileMode.Create))
                    {
                        byte[] bytes = ReadAllByte(resourceStream);
                        fw.Write(bytes, 0, bytes.Length);
                    }
                }

                var packaging = new Packaging.Packaging();

                var worker = new BackgroundWorker();
                worker.DoWork +=
                    (s, a) =>
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        InstallStep.Visibility  = Visibility.Collapsed;
                        ProgressStep.Visibility = Visibility.Visible;
                    }));
                    ReturnResult returnResult = packaging.UncompressFile(installDirectory, packageFilePath, true);
                    if (returnResult.Success)
                    {
                        CreateIcon("EMSG Mobile", applicationPath);
                        SetLanguageInConfig(applicationPath);
                    }
                };
                worker.RunWorkerCompleted += (s, a) =>
                {
                    Dispatcher.Invoke(new Action(() =>
                    {
                        ProgressStep.Visibility =
                            Visibility.Collapsed;
                        SuccessStep.Visibility =
                            Visibility.Visible;
                    }));
                };
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                using (var file = File.CreateText("errorlog.txt"))
                {
                    file.WriteLine(string.Format("{0} - {1}", DateTime.Now, ex));
                }
            }
        }
Exemple #29
0
        public async static Task LetturaScritturaFileAsync2()
        {
            //piu step:
            //creo cartella + sottocarte con file


            DirectoryInfo directory = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "ProvaLetturascrittura"));

            try
            {
                //creazione cartelle
                directory.Create();
                Console.WriteLine(" cartella creata");
                directory.CreateSubdirectory("ProvaScrittura");
                Console.WriteLine("Subdirectory creata correttamente");

                //creazionefile
                string path = Path.Combine(directory.FullName, "ProvaScrittura/SequenzaNumeri.txt"); //parti da directory
                using (StreamWriter file = File.CreateText(path))                                    //uso stramwriter per scrivere nel file
                {
                    for (int i = 0; i <= 10; i++)
                    {
                        await file.WriteAsync(i.ToString() + "\n");// conversione in stringa
                    }
                }
                using (StreamWriter file = File.AppendText(path))// se avessi lascito create avrebbe sovrascritto, in questo modo aggiungo
                {
                    for (int i = 10; i <= 20; i++)
                    {
                        await file.WriteAsync(i.ToString() + "\n");// conversione in stringa
                    }
                }

                // letturafile
                string line;
                int    counter = 0; //mi dice a che riga sono

                using (StreamReader fileReader = File.OpenText(path))
                {
                    while ((line = fileReader.ReadLine()) != null) // mostro a schermo la riga
                    {
                        Console.WriteLine(line);
                        counter++;
                    }
                    line = ""; //resetto la riga
                    fileReader.BaseStream.Position = 0;

                    //lettura totale del test
                    line = fileReader.ReadToEnd();
                    Console.WriteLine(line);  // mi mette tutto in una riga


                    //split
                    string[] linesplit = line.Split("\n"); //divide in base ad una separatore

                    foreach (string el in linesplit)
                    {
                        Console.Write(el + " ");
                    }
                }
            }
            catch (Exception e)
            { Console.WriteLine(e.Message); }
        }
Exemple #30
0
        public static void ConvertJSON(string path)
        {
            if (File.Exists(path))
            {
                try
                {
                    int    totalLines = File.ReadLines(path).Count();
                    string jsonPath   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Employees.json");
                    using (StreamReader fileReader = File.OpenText(path))
                    {
                        string   title = Path.GetFileNameWithoutExtension(path).ToLower();
                        string   line;
                        string[] titles  = new string[] { };
                        int      counter = 0;

                        //using (StreamWriter fileWriter = File.CreateText(jsonPath))
                        using (StreamWriter fileWriter = File.CreateText(jsonPath + "/" + title + ".json"))
                        {
                            //apriamo le parentesi
                            fileWriter.WriteLine("{");
                            fileWriter.WriteLine("\"" + title + "\":[");

                            while ((line = fileReader.ReadLine()) != null)
                            {
                                if (counter == 0)
                                {
                                    line   = line.ToLower();
                                    titles = line.Split(",");
                                    counter++;
                                }

                                else
                                {
                                    string[] data = new string[] { };
                                    data = line.Split(",");

                                    fileWriter.Write("{");
                                    for (int i = 0; i < titles.Length; i++)
                                    {
                                        if (i == title.Length - 1) // se è l'ultimo
                                        {
                                            fileWriter.Write("\"" + titles[i] + "\":\"" + data[i] + "\"");
                                        }
                                        else
                                        {
                                            fileWriter.Write("\"" + titles[i] + "\":\"" + data[i] + "\",");
                                        }
                                    }

                                    if (counter != totalLines - 1) // se non è l'ultima riga
                                    {
                                        fileWriter.Write("},\n");
                                    }
                                    else
                                    {
                                        fileWriter.Write("}\n");
                                    }
                                }
                            }

                            fileWriter.WriteLine("]}");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }