Ejemplo n.º 1
0
        /// <summary>
        /// Fetch a file.
        /// </summary>
        /// <typeparam name="T">The type of file to fetch.</typeparam>
        /// <param name="filePath">The path to the file to fetch.</param>
        /// <returns>The file.</returns>
        public override IOFile FetchFile <T>(string filePath)
        {
            IOFile f = (IOFile)Activator.CreateInstance(typeof(T));

            f.Read(Files[filePath]);
            return(f);
        }
Ejemplo n.º 2
0
    public int OnExecute()
    {
        var sess = _main.GetSession();

        using var client = sess.GetClient();

        var vault = _main.GetVault(client, Vault !);

        if (vault == null)
        {
            return(1);
        }

        var output = new GetVaultOutput
        {
            Id    = vault.Id !.Value,
            Label = vault.Summary !.Label,
            Type  = vault.Summary !.Type,
        };

        var outputSer = JsonSerializer.Serialize(output,
                                                 Indented ? Common.IndentedJsonOutput : Common.DefaultJsonOutput);

        if (File == null)
        {
            _console.WriteLine(outputSer);
        }
        else
        {
            IOFile.WriteAllText(File, outputSer);
        }

        return(0);
    }
Ejemplo n.º 3
0
    public bool SaveBoard(Cell[,] cells, float time, int score)
    {
        BoardData save = new BoardData(cells, score, time);

        IOFile.WriteCacheJson <BoardData>(save, SAVE_FILE);
        return(false);
    }
Ejemplo n.º 4
0
        public async Task <IActionResult> Settings(SettingsViewModel model)
        {
            if (ModelState.IsValid)
            {
                var settings = _serviceProvider.GetService <ISynologyConnectionSettings>();

                settings.BaseHost = model.SynologyHost;
                settings.Password = model.SynologyPass;
                settings.Port     = model.SynologyPort;
                settings.Ssl      = model.UseSsl;
                settings.SslPort  = model.SynologyPort;
                settings.Username = model.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(model, Formatting.Indented);

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

                        return(RedirectToAction("Index"));
                    }
                }
            }

            return(View(model));
        }
        private void OpenFile(object param)
        {
            var dialog = new OpenFileDialog
            {
                CheckFileExists = true,
                Title           = "Open File",
                ValidateNames   = true,
            };

            if (dialog.ShowDialog(Application.Current.MainWindow) == true)
            {
                OpenFileText = Resources.ChangeFile;
                using (var stream = dialog.OpenFile())
                {
                    _file = new IOFile();
                    var data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);

                    _file.Data      = Convert.ToBase64String(data);
                    _file.Alias     = Name;
                    _file.FileName  = dialog.SafeFileName;
                    _file.Extension = Path.GetExtension(dialog.FileName);
                }
            }
        }
Ejemplo n.º 6
0
        public Pack(PackCollection collection, DirectoryInfo dataDirectory, PackIdentifier id)
        {
            if (dataDirectory == null)
            {
                throw new ArgumentNullException("dataDirectory");
            }
            if (!dataDirectory.Exists)
            {
                throw new DirectoryNotFoundException();
            }

            Collection    = collection;
            DataDirectory = dataDirectory;
            this.Id       = id;

            var indexPath  = Path.Combine(DataDirectory.FullName, id.Expansion, string.Format(IndexFileFormat, Id.TypeKey, Id.ExpansionKey, Id.Number));
            var index2Path = Path.Combine(DataDirectory.FullName, id.Expansion, string.Format(Index2FileFormat, Id.TypeKey, Id.ExpansionKey, Id.Number));

            if (IOFile.Exists(indexPath))
            {
                Source = new IndexSource(this, new Index(id, indexPath));
            }
            else if (IOFile.Exists(index2Path))
            {
                Source = new Index2Source(this, new Index2(id, index2Path));
            }
            else
            {
                throw new FileNotFoundException();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Fetch the file contained in the pack.
        /// </summary>
        /// <typeparam name="T">Type of IOFile.</typeparam>
        /// <returns>The file contained in the pack.</returns>
        public IOFile FetchFile <T>()
        {
            IOFile f = (IOFile)Activator.CreateInstance(typeof(T));

            FileReader.Position = 0;
            f.Read(FileReader);
            return(f);
        }
Ejemplo n.º 8
0
        public Index(PackIdentifier packId, string path)
        {
            PackId = packId;

            using (var file = IOFile.OpenRead(path)) {
                using (var reader = new BinaryReader(file))
                    Build(reader);
            }
        }
Ejemplo n.º 9
0
    public int OnExecute()
    {
        var sess = _main.GetSession();

        using var client = sess.GetClient();

        var vault = Vault == null
            ? null
            : _main.GetVault(client, Vault !);

        if (vault == null && Vault != null)
        {
            return(1);
        }

        var record = _main.GetRecord(client, ref vault, Record !);

        if (record == null)
        {
            return(1);
        }

        client.UnlockRecord(vault !, record);

        var output = new GetRecordOutput
        {
            Id       = record.Id !.Value,
            Label    = record.Summary !.Label,
            Type     = record.Summary !.Type,
            Address  = record.Summary !.Address,
            Username = record.Summary !.Username,
            Tags     = record.Summary !.Tags,
            Memo     = record.Content !.Memo,
            Password = record.Content !.Password,
            Fields   = record.Content.Fields?.Select(x =>
                                                     new NewCommands.NewRecordCommand.NewRecordInput.Field()
            {
                Name  = x.Name,
                Type  = x.Type,
                Value = x.Value,
            }).ToArray(),
        };

        var outputSer = JsonSerializer.Serialize(output,
                                                 Indented ? Common.IndentedJsonOutput : Common.DefaultJsonOutput);

        if (File == null)
        {
            _console.WriteLine(outputSer);
        }
        else
        {
            IOFile.WriteAllText(File, outputSer);
        }

        return(0);
    }
Ejemplo n.º 10
0
        public void CorrrectInputWithLetters_ReturnFalse()
        {
            var input  = "1 2 3 a b";
            var stream = new IOFile();

            input = stream.CorrectInput(input);

            Assert.AreNotEqual(input, "");
        }
Ejemplo n.º 11
0
        public Index2(PackIdentifier packId, string path)
        {
            this.PackId = packId;

            using (FileStream file = IOFile.OpenRead(path)) {
                using (BinaryReader reader = new BinaryReader(file))
                    Build(reader);
            }
        }
Ejemplo n.º 12
0
        public void CorrrectInputOnlyNumbers_ReturnFalse()
        {
            var input  = "1 2 3 11 22";
            var stream = new IOFile();

            input = stream.CorrectInput(input);

            Assert.AreNotEqual(input, "");
        }
Ejemplo n.º 13
0
        public void CorrrectInput_ReturnTrue()
        {
            var input  = "10 9 8 7 6 5 4 3 2 1";
            var stream = new IOFile();

            input = stream.CorrectInput(input);

            Assert.AreEqual(input, "");
        }
Ejemplo n.º 14
0
        private void MenuItemOpenInFoder_Click(object sender, RoutedEventArgs e)
        {
            if (fileView.SelectedItem == null)
            {
                return;
            }
            ItemNodeBase file = fileView.SelectedItem as ItemNodeBase;

            IOFile.OpenInFolder(Config.GamePath + "\\" + file.FileFullName);
        }
Ejemplo n.º 15
0
        public IActionResult Index()
        {
            if (!IOFile.Exists("synosettings.json"))
            {
                return(RedirectToAction(nameof(Settings)));
            }

            var settings = JsonConvert.DeserializeObject <SettingsViewModel>(IOFile.ReadAllText("synosettings.json"));

            return(View());
        }
Ejemplo n.º 16
0
        private static void CreateOptionsFile(string file)
        {
            string dir = file.Substring(0, file.LastIndexOf('\\'));

            Directory.CreateDirectory(dir);
            FileStream f = File.Create(file);

            f.Close();
            IOFile.WriteLine(file, 1, "Version;1.2", true);
            IOFile.WriteLine(file, 2, "ReleaseDate;2011-07-04", true);
        }
Ejemplo n.º 17
0
    public bool LoadBoardSave(Cell[,] cells)
    {
        BoardData save = IOFile.ReadCacheJson <BoardData>(SAVE_FILE);

        if (cells.Length == 0 || save == null)
        {
            return(false);
        }
        save.MapSaveToBoard(cells);
        return(true);
    }
Ejemplo n.º 18
0
        public IActionResult GetYamlFile()
        {
            if (!OptionsSnapshot.Value.RemoteConfiguration)
            {
                return(Forbid());
            }

            var yaml = IOFile.ReadAllText(Program.ConfigurationFile);

            return(Ok(yaml));
        }
Ejemplo n.º 19
0
        public IActionResult Settings()
        {
            SettingsViewModel model = null;

            if (IOFile.Exists("synosettings.json"))
            {
                model = JsonConvert.DeserializeObject <SettingsViewModel>(IOFile.ReadAllText("synosettings.json"));
            }

            return(View(model));
        }
Ejemplo n.º 20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = "", action, style, skey, h;

        action = Request.QueryString["action"];
        style  = Request.QueryString["style"];
        skey   = Request.QueryString["skey"];
        h      = Request.QueryString["h"];
        str    = IOFile.ReadFile("~/eWebEditor/aspx/ajs/" + style + ".js");
        Response.Write(str);
    }
Ejemplo n.º 21
0
        private static void GenerateX509Certificate(string password, string filename)
        {
            Log.Information("Generating X509 certificate...");
            filename = Path.Combine(AppContext.BaseDirectory, filename);

            var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable);

            IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password));

            Log.Information($"Password: {password}");
            Log.Information($"Certificate exported to {filename}");
        }
Ejemplo n.º 22
0
        private void button1_Click(object sender, EventArgs e)
        {
            IOFile counter  = new IOFile();
            string filmName = textBox1.Text;
            string genre    = textBox2.Text;
            int    year     = Convert.ToInt32(textBox3.Text);
            string date     = textBox4.Text;
            int    price    = Convert.ToInt32(textBox5.Text);
            string id       = textBox6.Text;

            counter.WriteFilmToFile(filmName, genre, year, date, price, id);
        }
Ejemplo n.º 23
0
        public Stream GetDataStream(byte datFile = 0)
        {
            var thread = Thread.CurrentThread;

            var key = Tuple.Create(thread, datFile);
            WeakReference <Stream> streamRef;
            Stream stream;

            lock (_DataStreams)
                _DataStreams.TryGetValue(key, out streamRef);

            if (streamRef == null || !streamRef.TryGetTarget(out stream))
            {
                stream = null;
            }

            if (stream != null)
            {
                return(stream);
            }

            var baseName = String.Format(DatFileFormat, Id.TypeKey, Id.ExpansionKey, Id.Number, datFile);
            var fullPath = Path.Combine(DataDirectory.FullName, Id.Expansion, baseName);


            if (KeepInMemory)
            {
                if (!_Buffers.ContainsKey(datFile))
                {
                    _Buffers.Add(datFile, IOFile.ReadAllBytes(fullPath));
                }
                stream = new MemoryStream(_Buffers[datFile], false);
            }
            else
            {
                stream = IOFile.OpenRead(fullPath);
            }

            lock (_DataStreams) {
                if (_DataStreams.ContainsKey(key))
                {
                    _DataStreams[key].SetTarget(stream);
                }
                else
                {
                    _DataStreams.Add(key, new WeakReference <Stream>(stream));
                }
            }

            return(stream);
        }
Ejemplo n.º 24
0
    /// <summary>
    /// 处理后台左边菜单
    /// </summary>
    /// <returns></returns>
    private string leftall()
    {
        string str = string.Empty, mer = Request.QueryString["mer"];

        str = IOFile.ReadFile("~/admin/Apply/lefthtml/left" + mer + ".html");
        if (str.IndexOf("{div|") > -1)
        {
            str = ask.Web.left.divClass(str);
        }
        if (str.IndexOf("{p|") > -1)
        {
            str = ask.Web.left.pClass(str);
        }
        return(str);
    }
Ejemplo n.º 25
0
 /// <summary>
 /// Fetch an IO file.
 /// </summary>
 /// <typeparam name="T">The type of file.</typeparam>
 /// <param name="filePath">Path to the file.</param>
 /// <returns>The file fetched.</returns>
 public virtual IOFile FetchFile <T>(string filePath)
 {
     FileReader.Position = FileListing[filePath].Offset;
     if (FileListing[filePath].IsPacked)
     {
         using (Pack p = new Pack()) {
             p.Read(FileReader.ReadBytes(FileListing[filePath].Size));
             return(p.FetchFile <T>());
         }
     }
     else
     {
         IOFile f = (IOFile)Activator.CreateInstance(typeof(T));
         f.Read(FileReader.ReadBytes(FileListing[filePath].Size));
         return(f);
     }
 }
Ejemplo n.º 26
0
 private static void RecreateConfigurationFileIfMissing(string configurationFile)
 {
     if (!IOFile.Exists(configurationFile))
     {
         try
         {
             Log.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", configurationFile);
             var source      = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml");
             var destination = configurationFile;
             IOFile.Copy(source, destination);
         }
         catch (Exception ex)
         {
             Log.Error("Failed to create configuration file {ConfigurationFile}: {Message}", configurationFile, ex.Message);
         }
     }
 }
Ejemplo n.º 27
0
        public ActionResult ObtenirPublication(int?id)
        {
            PUBLICATION pub = null;

            try
            {
                if (id == null)
                {
                    throw new ArgumentNullException("id");
                }

                pub = db.GetPublication(id).First();
            }
            catch
            {
                TempData[Constantes.CLE_MSG_RETOUR] = new Message(Message.TYPE_MESSAGE.ERREUR, Resources.Publication.idPublicationInvalide);
            }

            if (pub != null)
            {
                if (User.IsInRole("admin") || ((List <SECTEUR>)Session["lstSect"]).Any(s => s.ID == pub.IDSECTEUR))
                {
                    var cd = new ContentDisposition {
                        FileName = pub.NOMFICHIERORIGINAL, Inline = false
                    };
                    Response.AppendHeader("Content-Disposition", cd.ToString());

                    try
                    {
                        return(File(IOFile.ReadAllBytes(Fichiers.CheminEnvois(pub.NOMFICHIERSERVEUR)), pub.NOMFICHIERORIGINAL));
                    }
                    catch (IOException)
                    {
                        TempData[Constantes.CLE_MSG_RETOUR] = new Message(Message.TYPE_MESSAGE.ERREUR, Resources.Publication.publicationErreurFichier);
                    }
                }
                else
                {
                    TempData[Constantes.CLE_MSG_RETOUR] = new Message(Message.TYPE_MESSAGE.ERREUR, Resources.Publication.accesRefuse);
                }
            }

            return(RedirectToAction("Publications", "Sectoriel"));
        }
Ejemplo n.º 28
0
        public async Task <IOFile> RequestFileDownload(LockerObject fileInfo, string password = "")
        {
            IOFile res = null;
            var    msg = new FileDownloadRequestMessage {
                filename = fileInfo.name
            };

            await SendMessage(msg);

            var resp = await WaitForRequestResponse <FileDownloadResponseMessage>(60000,
                                                                                  MessageType.FileDownloadResponse);

            if (resp != null && resp.success)
            {
                var fileJson = fileInfo.encrypted? Encryption.Decrypt(resp.data, password): resp.data;
                res = JsonConvert.DeserializeObject <IOFile>(fileJson);
            }
            return(res);
        }
Ejemplo n.º 29
0
        public static NearEarthObject GetAsteroids()
        {
            string path = "../Asteroids.json";

            if (!File.Exists(path))
            {
                ApiConfig.AddUrl = @"neo/rest/v1/feed";
                //string start = $"{DateTime.Now.AddDays(-1).Year}-{DateTime.Now.AddDays(-1).Month}-{DateTime.Now.AddDays(-1).Day}";
                //string end = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}";
                ApiConfig.Start_Date = "2019-12-03";
                ApiConfig.End_Date   = "2019-12-04";
                string query = $"{ApiConfig.BaseUrl}/{ApiConfig.AddUrl}?start_date={ApiConfig.Start_Date}&end_date={ApiConfig.End_Date}&api_key={ApiConfig.Api_Key}";
                IOFile.SaveToFile(query, path);
            }
            string          desJson         = IOFile.ReadFromFile(path);
            Asteroids_NeoWs asteroids_NeoWs = JsonConvert.DeserializeObject <Asteroids_NeoWs>(desJson);

            return(asteroids_NeoWs.NearObjects);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Open a file from a file path.
 /// </summary>
 /// <typeparam name="T">The type of IOFile.</typeparam>
 /// <param name="filePath">Path of the file.</param>
 /// <returns>The file openend.</returns>
 public static IOFile OpenFile <T>(string filePath)
 {
     if (FileListing.Contains(filePath))
     {
         return(FileMap[filePath].FetchFile <T>(filePath));
     }
     else if (GameHelper.GameAssemby.GetManifestResourceNames().Contains(GetEmbeddedResourceName(filePath)))
     {
         IOFile f = (IOFile)Activator.CreateInstance(typeof(T));
         f.Read(GameHelper.GameAssemby.GetManifestResourceStream(GetEmbeddedResourceName(filePath)));
         return(f);
     }
     else
     {
         IOFile f = (IOFile)Activator.CreateInstance(typeof(T));
         f.Read(filePath);
         return(f);
     }
 }