示例#1
0
        private static TSettings deserialize <TSettings>(string filename, SettingsSerializer serializer) where TSettings : SettingsBase, new()
        {
            return(Ut.WaitSharingVio(maximum: TimeSpan.FromSeconds(5), func: () =>
            {
                switch (serializer)
                {
                case SettingsSerializer.ClassifyXml:
                    return ClassifyXml.DeserializeFile <TSettings>(filename);

                case SettingsSerializer.ClassifyJson:
                    return ClassifyJson.DeserializeFile <TSettings>(filename);

                case SettingsSerializer.ClassifyBinary:
                    return ClassifyBinary.DeserializeFile <TSettings>(filename);

                case SettingsSerializer.DotNetBinary:
                    var bf = new BinaryFormatter();
                    using (var fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        return (TSettings)bf.Deserialize(fs);

                default:
                    throw new InternalErrorException("6843184");
                }
            }));
        }
示例#2
0
 /// <summary>See base.</summary>
 protected override bool getUser(ref string username, out string passwordHash, out bool canCreateUsers)
 {
     passwordHash   = null;
     canCreateUsers = false;
     if (File.Exists(_usersPath))
     {
         AuthUsers users;
         lock (_lock)
             users = ClassifyXml.DeserializeFile <AuthUsers>(_usersPath);
         var un   = username; // ref parameter can’t be used in a lambda :(
         var user = users.Users.FirstOrDefault(u => u.Username == un);
         if (user == null)
         {
             return(false);
         }
         username       = user.Username;
         passwordHash   = user.PasswordHash;
         canCreateUsers = user.CanCreateUsers;
         return(true);
     }
     else
     {
         lock (_lock)
             ClassifyXml.SerializeToFile <AuthUsers>(new AuthUsers(), _usersPath);
     }
     return(false);
 }
示例#3
0
        public static GncFileWrapper LoadFromFile(string filename)
        {
            var wrapper = ClassifyXml.DeserializeFile <GncFileWrapper>(filename);

            wrapper.LoadedFromFile = filename;
            return(wrapper);
        }
示例#4
0
文件: Lingo.cs 项目: biorpg/RT.Util
        /// <summary>Loads and returns the translation for the specified module and language. The translation must exist in the application
        /// executable directory under a subdirectory called "Translations". If the translation cannot be loaded successfully, an exception is thrown.</summary>
        /// <param name="translationType">The type of the translation class to load the translation into.</param>
        /// <param name="module">The name of the module whose translation to load.</param>
        /// <param name="language">The language code of the language to load.</param>
        /// <returns>The loaded translation.</returns>
        public static TranslationBase LoadTranslation(Type translationType, string module, Language language)
        {
            string path  = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Translations", module + "." + language.GetIsoLanguageCode() + ".xml");
            var    trans = (TranslationBase)ClassifyXml.DeserializeFile(translationType, path);

            trans.Language = language;
            return(trans);
        }
示例#5
0
        /// <summary>Saves this instance to the file system.</summary>
        protected override sealed void SaveSession()
        {
            var sessionPath = SessionPath;

            // Directory.CreateDirectory() does nothing if the directory already exists.
            Directory.CreateDirectory(sessionPath);
            lock (_lock)
                ClassifyXml.SerializeToFile(this, Path.Combine(sessionPath, SessionID));
        }
示例#6
0
文件: Lingo.cs 项目: biorpg/RT.Util
 /// <summary>Writes the specified translation for the specified module to an XML file in the application directory.</summary>
 /// <param name="translationType">Translation class to write.</param>
 /// <param name="moduleName">Name of the module for which this is a translation.</param>
 /// <param name="translation">The translation to save.</param>
 public static void SaveTranslation(Type translationType, string moduleName, TranslationBase translation)
 {
     ClassifyXml.SerializeToFile(translationType, translation, Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Translations", moduleName + "." + translation.Language.GetIsoLanguageCode() + ".xml"));
     if (AlsoSaveTranslationsTo != null && Directory.Exists(AlsoSaveTranslationsTo))
     {
         try
         {
             var filename = Path.Combine(AlsoSaveTranslationsTo, moduleName + "." + translation.Language.GetIsoLanguageCode() + ".xml");
             File.SetAttributes(filename, File.GetAttributes(filename) & ~FileAttributes.ReadOnly);
             ClassifyXml.SerializeToFile(translationType, translation, filename);
         }
         catch { }
     }
 }
示例#7
0
        /// <summary>Retrieves an existing session from the file system and initialises this instance with the relevant data.</summary>
        protected override sealed bool ReadSession()
        {
            var file = Path.Combine(SessionPath, SessionID);

            lock (_lock)
            {
                if (!File.Exists(file))
                {
                    return(false);
                }
                ClassifyXml.DeserializeFileIntoObject(file, this);
            }
            return(true);
        }
示例#8
0
        }                          // for Classify

        /// <summary>
        ///     Constructs a new instance by loading an existing summoner data file.</summary>
        /// <param name="filename">
        ///     File to load the summoner data from. This filename is also used to save summoner data and to infer the
        ///     directory name for API response cache.</param>
        public SummonerInfo(string filename)
        {
            if (filename == null)
            {
                throw new ArgumentNullException(nameof(filename));
            }
            _filename = filename;
            if (!File.Exists(_filename))
            {
                throw new ArgumentException($"Summoner data file not found: \"{filename}\".", nameof(filename));
            }
            ClassifyXml.DeserializeFileIntoObject(filename, this);
            if (Region == null || AccountId == 0 || SummonerId == 0)
            {
                throw new InvalidOperationException($"Summoner data file does not contain the minimum required data.");
            }
            Region = Region.ToUpper();
        }
示例#9
0
        static int Main(string[] args)
        {
            if (args.Length == 2 && args[0] == "--post-build-check")
            {
                return(Ut.RunPostBuildChecks(args[1], Assembly.GetExecutingAssembly()));
            }

            var settingsFile = PathUtil.AppPathCombine("MySrvMon.xml");

            if (!File.Exists(settingsFile))
            {
                var sample = new Settings();
                sample.Modules.Add(new SmartModule());
                ClassifyXml.SerializeToFile(sample, settingsFile + ".sample");
                Console.WriteLine("Sample settings file saved: " + settingsFile + ".sample");
                Console.WriteLine("Edit and rename to " + settingsFile);
                return(1);
            }
            var settings = ClassifyXml.DeserializeFile <Settings>(settingsFile);

            ClassifyXml.SerializeToFile(settings, settingsFile + ".rewrite"); // for SMTP password encryption

            foreach (var module in settings.Modules)
            {
                module.Execute();
            }

            foreach (var module in settings.Modules.OrderByDescending(m => m.Status))
            {
                ConsoleColoredString report =
                    "===========================\r\n" +
                    "=== " + module.Name + "\r\n" +
                    "===========================\r\n\r\n";
                report  = report.Color(module.Status.GetConsoleColor());
                report += module.ConsoleReport + "\r\n";
                ConsoleUtil.Write(report);
            }

            var worstStatus = settings.Modules.Max(v => v.Status);

            return((int)worstStatus);
        }
示例#10
0
        static void Main(string[] args)
        {
            Console.WriteLine($"Loading settings from {args[0]}...");
            var settings = ClassifyXml.DeserializeFile <Settings>(args[0]);

            ClassifyXml.SerializeToFile(settings, args[0]);

            Console.Write("Loading static data...");
            LeagueStaticData.Load(Path.Combine(settings.DataPath, "Static"));
            Console.WriteLine(" done");

            Console.Write("Initialising global data...");
            DataStore.Initialise(settings.DataPath, "", autoRewrites: false);
            Console.WriteLine(" done");

            if (settings.ItemsOutputPath != null)
            {
                ItemSheet.Generate(settings.ItemsOutputPath);
            }

            if (settings.ItemSetsSettings != null && settings.LeagueInstallPath != null)
            {
                ItemSets.Generate(settings.DataPath, settings.LeagueInstallPath, settings.ItemSetsSettings);
            }

            if (settings.PersonalOutputPathTemplate != null)
            {
                PersonalStats.Generate(settings.DataPath, settings.PersonalOutputPathTemplate, settings.Humans);
            }

            if (settings.EventStatsSettings != null && settings.EventStatsSettings.OutputPath != null)
            {
                new EventStats(settings.EventStatsSettings).Generate();
            }

            if (settings.SummonerRift5v5StatsSettings != null)
            {
                new SummonerRift5v5Stats(settings.SummonerRift5v5StatsSettings).Generate();
            }
        }
示例#11
0
        /// <summary>See base.</summary>
        protected override bool changePassword(string username, string newPasswordHash, Func <string, bool> verifyOldPasswordHash)
        {
            lock (_lock)
            {
                AuthUsers users;
                try { users = ClassifyXml.DeserializeFile <AuthUsers>(_usersPath); }
                catch { users = null; }
                if (users == null)
                {
                    users = new AuthUsers();
                }

                var user = users.Users.FirstOrDefault(u => u.Username == username);
                if (user == null || (verifyOldPasswordHash != null && !verifyOldPasswordHash(user.PasswordHash)))
                {
                    return(false);
                }

                user.PasswordHash = newPasswordHash;
                ClassifyXml.SerializeToFile <AuthUsers>(users, _usersPath);
                return(true);
            }
        }
示例#12
0
        internal static void serialize(object settings, Type settingsType, string filename, SettingsSerializer serializer)
        {
            var tempname = filename + ".~tmp";

            Ut.WaitSharingVio(() =>
            {
                switch (serializer)
                {
                case SettingsSerializer.ClassifyXml:
                    // SerializeToFile automatically creates the folder if necessary
                    ClassifyXml.SerializeToFile(settingsType, settings, tempname, format: ClassifyXmlFormat.Create("Settings"));
                    break;

                case SettingsSerializer.ClassifyJson:
                    // SerializeToFile automatically creates the folder if necessary
                    ClassifyJson.SerializeToFile(settingsType, settings, tempname);
                    break;

                case SettingsSerializer.ClassifyBinary:
                    // SerializeToFile automatically creates the folder if necessary
                    ClassifyBinary.SerializeToFile(settingsType, settings, tempname);
                    break;

                case SettingsSerializer.DotNetBinary:
                    PathUtil.CreatePathToFile(tempname);
                    var bf = new BinaryFormatter();
                    using (var fs = File.Open(tempname, FileMode.Create, FileAccess.Write, FileShare.Read))
                        bf.Serialize(fs, settings);
                    break;

                default:
                    throw new InternalErrorException("4968453");
                }
                File.Delete(filename);
                File.Move(tempname, filename);
            }, TimeSpan.FromSeconds(5));
        }
示例#13
0
        /// <summary>See base.</summary>
        protected override bool createUser(string username, string passwordHash, bool canCreateUsers)
        {
            lock (_lock)
            {
                AuthUsers users;
                try { users = ClassifyXml.DeserializeFile <AuthUsers>(_usersPath); }
                catch { users = null; }
                if (users == null)
                {
                    users = new AuthUsers();
                }

                if (users.Users.Any(u => u.Username == username))
                {
                    return(false);
                }

                users.Users.Add(new AuthUser {
                    Username = username, PasswordHash = passwordHash, CanCreateUsers = canCreateUsers
                });
                ClassifyXml.SerializeToFile <AuthUsers>(users, _usersPath);
                return(true);
            }
        }
示例#14
0
        /// <summary>Presents the user with a dialog to select a language from, and (if they click "OK") creates a new XML file for the new translation.</summary>
        /// <typeparam name="TTranslation">Class containing the translatable strings.</typeparam>
        /// <param name="moduleName">Name of the module being translated (forms part of the translation's XML file).</param>
        /// <param name="fontName">Specifies the name of the font to use in this dialog, or null for the default font.</param>
        /// <param name="fontSize">Specifies the size of the font to use in this dialog. Ignored if <paramref name="fontName"/> is null.</param>
        /// <returns>If the user clicked OK, creates a new XML file and returns the translation. If the user clicked Cancel, returns null.</returns>
        public static TTranslation CreateTranslation <TTranslation>(string moduleName, string fontName, float fontSize) where TTranslation : TranslationBase, new()
        {
            using (TranslationCreateForm tcf = new TranslationCreateForm())
            {
                tcf.Font = fontName != null ? new Font(fontName, fontSize, FontStyle.Regular) : SystemFonts.MessageBoxFont;
                if (tcf.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }

                if (tcf.SelectedLanguage == new TTranslation().Language)
                {
                    DlgMessage.Show("This is the native language of the application. This translation cannot be edited, and you cannot create a new translation for this language.",
                                    "Error creating translation", DlgType.Error, "OK");
                    return(null);
                }

                var trans = new TTranslation {
                    Language = tcf.SelectedLanguage
                };
                string iso     = trans.Language.GetIsoLanguageCode();
                string xmlFile = PathUtil.AppPathCombine("Translations", moduleName + "." + iso + ".xml");
                if (File.Exists(xmlFile))
                {
                    int result = DlgMessage.Show("A translation into the selected language already exists. If you wish to start this translation afresh, please delete the translation file first.\n\nThe translation file is: " + xmlFile,
                                                 "Error creating translation", DlgType.Error, "&Go to containing folder", "Cancel");
                    if (result == 0)
                    {
                        Process.Start(Path.GetDirectoryName(xmlFile));
                    }
                    return(null);
                }
                ClassifyXml.SerializeToFile(trans, xmlFile);
                return(trans);
            }
        }
示例#15
0
 private void save()
 {
     Directory.CreateDirectory(Path.GetDirectoryName(_filename));
     ClassifyXml.SerializeToFile(this, _filename);
 }
示例#16
0
 public void SaveToFile(string filename)
 {
     LoadedFromFile = filename;
     ClassifyXml.SerializeToFile(this, filename);
 }