private void GetDataFromXmlStorage() { Debug.Log(XmlStorage.GetInt("integer", 0)); Debug.Log(XmlStorage.GetFloat("float", 0f)); Debug.Log(XmlStorage.Get <ExampleController.Test>("TestClass", null)); Debug.Log(XmlStorage.Get <ExampleController.Test>("TestClass", null).str); Debug.Log(XmlStorage.Get <ExampleController.Test>("TestClass", null).list1.First()); Debug.Log(XmlStorage.Get <ExampleController.Test>("TestClass", null).list1.Last()); Debug.Log(""); Debug.Log(XmlStorage.GetInt("del_tes1")); Debug.Log(XmlStorage.GetString("del_tes1")); Debug.Log(""); Debug.Log(XmlStorage.GetInt("del_tes2")); Debug.Log(XmlStorage.GetString("del_tes2")); Debug.Log(""); Debug.Log(XmlStorage.Get <string>("address")); Debug.Log(""); Debug.Log(XmlStorage.Get("vec2", Vector2.zero)); Debug.Log(XmlStorage.Get("vec3", Vector3.zero)); Debug.Log(XmlStorage.Get("qua", Quaternion.identity).eulerAngles); Debug.Log(""); Debug.Log(""); }
private static void DmCmnBackupSave(bool is_first, bool is_new, bool is_del) { AppMain.GSS_MAIN_SYS_INFO mainSysInfo = AppMain.GsGetMainSysInfo(); var save = SSave.CreateInstance().GetSave(); if (save == null) { SSave.CreateInstance().SetSave((save = new gs.Sonic4Save())); } if (is_first) { XmlStorage.Save(save, true, false); //mainSysInfo.cmp_backup.setData(mainSysInfo.backup.getData()); } else if (is_new) { XmlStorage.Save(save, false, true); //mainSysInfo.cmp_backup.setData(mainSysInfo.backup.getData()); } else { if (mainSysInfo.is_save_run == 0U || !AppMain.dmCmnBackupIsCmpSaveData()) { return; } XmlStorage.Save(save, false, false); // mainSysInfo.cmp_backup.setData(mainSysInfo.backup.getData()); } }
public override object Load(XmlNode node) { if (node == null) { return(null); } var model = XmlStorage.GetObjectValue <IModel>(node, "Model"); var batchSize = XmlStorage.GetIntValue(node, "BatchSize"); var epoch = XmlStorage.GetIntValue(node, "Epoch"); var randomBatch = bool.Parse(XmlStorage.GetStringValue(node, "RandomBatch")); var result = (Trainer)Activator.CreateInstance(Type, model, batchSize, epoch, randomBatch); result.Mission = XmlStorage.GetStringValue(node, "Mission"); result.PrintSteps = XmlStorage.GetIntValue(node, "PrintSteps"); result.LastTrainLoss = XmlStorage.GetDoubleValue(node, "LastTrainLoss"); result.LastTrainAccuracy = XmlStorage.GetDoubleValue(node, "LastTrainAccuracy"); result.LastTestLoss = XmlStorage.GetDoubleValue(node, "LastTestLoss"); result.LastTestAccuracy = XmlStorage.GetDoubleValue(node, "LastTestAccuracy"); result.PreProcessor = XmlStorage.GetObjectValue <IPreProcessor>(node, "PreProcessor"); result.LabelCodec = XmlStorage.GetObjectValue <DiscreteCodec>(node, "LabelCodec"); result.Normalizer = XmlStorage.GetObjectValue <INormalizer>(node, "Normalizer"); return(result); }
public override XmlElement Save(XmlDocument doc, object o) { if (o == null) { return(null); } if (!(o is Trainer trainer)) { throw new Exception("Codec must be Trainer!"); } var el = GetRootElement(doc); XmlStorage.AddChild(el, "Mission", trainer.Mission); XmlStorage.AddChild(el, "BatchSize", trainer.BatchSize); XmlStorage.AddChild(el, "Epoch", trainer.Epoch); XmlStorage.AddChild(el, "RandomBatch", trainer.RandomBatch.ToString()); XmlStorage.AddChild(el, "PrintSteps", trainer.PrintSteps); XmlStorage.AddChild(el, "LastTrainLoss", trainer.LastTrainLoss); XmlStorage.AddChild(el, "LastTrainAccuracy", trainer.LastTrainAccuracy); XmlStorage.AddChild(el, "LastTestLoss", trainer.LastTestLoss); XmlStorage.AddChild(el, "LastTestAccuracy", trainer.LastTestAccuracy); XmlStorage.AddObjectChild(el, "PreProcessor", trainer.PreProcessor); XmlStorage.AddObjectChild(el, "LabelCodec", trainer.LabelCodec); XmlStorage.AddObjectChild(el, "Normalizer", trainer.Normalizer); XmlStorage.AddObjectChild(el, "Model", trainer.Model); return(el); }
public bool SaveProject(string filename) { var storage = new XmlStorage { Settings = new StoredSettings(_dataProvider.ProjectRepository.ProjectSettings), Objects = _dataProvider.ObjectsRepository.ViewModels .Select(viewModel => viewModel.ToStoredObject()) .ToList(), Variables = _dataProvider.VariablesRepository.Variables .Select(variable => variable.ToStoredObject()) .ToList(), Tabs = _dataProvider.TabsRepository.ToStoredObject() }; var settings = new XmlWriterSettings { Indent = true }; var serializer = new DataContractSerializer(typeof(XmlStorage), _knownTypes); using (var writer = XmlWriter.Create(filename, settings)) { serializer.WriteObject(writer, storage); } return(true); }
public GeneralSettingViewModel() { _xmlPluginKvSgsStorage = new XmlStorage <PluginKvSgs>(PathHelper.Combine(MessageToken.CONFIG_FOLDER, MessageToken.GENERAL_SETTING)); _xmlPluginKvSgsStorage.Load(); _pluginKvSgs = _xmlPluginKvSgsStorage.Storage; GeneralKvViewModels = new ObservableCollection <PluginKVViewModel> { new PluginKVViewModel( new PluginKV() { Key = MessageToken.SAVELOGDAYS, Value = "15", KvType = KvType.Int, }) }; foreach (var kvvm in GeneralKvViewModels) { var kv = _pluginKvSgs.PluginKvSgList.Find(o => o.Key == kvvm.Key); if (kv != null) { kvvm.Value = kv.Value; } else { _pluginKvSgs.PluginKvSgList.Add(new PluginKvSg() { Key = kvvm.Key, Value = kvvm.Value }); } kvvm.PropertyChanged += Kvvm_PropertyChanged; } }
public void PageRegistr(bool b) { if (b) { _password = _dateMas[1]; _name = _dateMas[2]; _mail = _dateMas[3]; _createTime = _dateMas[4] + " " + _dateMas[5]; _modifiedTime = _dateMas[7] + " " + _dateMas[8]; var storage = new XmlStorage("UserBase.xml"); var users = storage.Load(); users.Add(new User() { Login = _login, Name = _name, Password = _password, Mail = _mail, CreatedAt = _createTime, ModifiedAt = _modifiedTime }); storage.Save(users); Console.WriteLine($"Система: Данные пользователя при регистрации {_data} (Пользователь добавлен)"); string otvet = "0"; byte[] otvetRegistra = Encoding.Unicode.GetBytes(otvet); _stream.Write(otvetRegistra, 0, otvetRegistra.Length); } else { Console.WriteLine($"Система:\tДанные пользователя при регистрации {_data} (Уже существует)"); string otvet = "1"; byte[] otvetRegistra = Encoding.Unicode.GetBytes(otvet); _stream.Write(otvetRegistra, 0, otvetRegistra.Length); } }
public static AppList LoadSafe(bool machineWide = false) { try { return(XmlStorage.LoadXml <AppList>(GetDefaultPath(machineWide))); } #region Error handling catch (FileNotFoundException) { return(new AppList()); } catch (IOException ex) { Log.Warn(ex); return(new AppList()); } catch (UnauthorizedAccessException ex) { Log.Warn(ex); return(new AppList()); } catch (InvalidDataException ex) { Log.Warn(ex); return(new AppList()); } #endregion }
public void ReadFileNotIndexed() { var storage = new XmlStorage(_driver, new XmlStorageIndex(_driver)); Assert.DoesNotThrow(() => storage.Read <DataInfo>(TestFileName)); _driver.DidNotReceive().Read(Arg.Is(TestFileName)); }
/// <summary> /// Detects attacks such as feed substitution or replay attacks. /// </summary> /// <param name="data">The content of the feed file as a byte array.</param> /// <param name="uri">The URI the feed originally came from.</param> /// <param name="signature">The first trusted signature for the feed.</param> /// <exception cref="ReplayAttackException">A replay attack was detected.</exception> /// <exception cref="UriFormatException"><see cref="Feed.Uri"/> is missing or does not match <paramref name="uri"/>.</exception> private void DetectAttacks(byte[] data, FeedUri uri, ValidSignature signature) { // Detect feed substitution var feed = XmlStorage.LoadXml <Feed>(new MemoryStream(data)); if (feed.Uri == null) { throw new UriFormatException(string.Format(Resources.FeedUriMissing, uri)); } if (feed.Uri != uri) { throw new UriFormatException(string.Format(Resources.FeedUriMismatch, feed.Uri, uri)); } // Detect replay attacks try { var oldSignature = _feedCache.GetSignatures(uri).OfType <ValidSignature>().FirstOrDefault(); if (oldSignature != null && signature.Timestamp < oldSignature.Timestamp) { throw new ReplayAttackException(uri, oldSignature.Timestamp, signature.Timestamp); } } catch (KeyNotFoundException) { // No existing feed to be replaced } }
/// <summary> /// 传入项目所在目录名称 /// </summary> /// <param name="projectFolderName"></param> public App(string projectFolderName) : this() { if (string.IsNullOrWhiteSpace(projectFolderName)) { throw new ArgumentException("请输入Templates下的工程文件夹名称。"); } var projectMetaFile = $"{string.Format(TemplatesFolder, projectFolderName)}project.xml"; //生成项目文件示例 var projectFile = AppHelper.GetFileFullName(projectMetaFile); //DebugConsole.Error(projectFile); Project = XmlStorage.Load <ProjectMeta>(projectFile); //Debug.Green(p1.ToJsonByJc()); Project.TemplatesRootDirectory = $"~/Templates/{projectFolderName}/"; RootTemplateFullPath = FileHelper.GetFullPath(Project.TemplatesRootDirectory); var subs = FileHelper.GetSubFolderNames(RootTemplateFullPath).ToList(); //子模板目录 if (subs.Count == 0) { log.Error("子模板不存在,无法生成项目。"); } Models = new List <ModelMeta>(); foreach (var sub in subs) { Models.Add(new ModelMeta(sub, Project)); } }
private AppList LoadAppListSafe() { try { return(XmlStorage.LoadXml <AppList>(AppList.GetDefaultPath(_machineWide))); } #region Error handling catch (FileNotFoundException) { return(new AppList()); } catch (IOException ex) { Log.Warn(Resources.UnableToLoadAppList); Log.Warn(ex); return(new AppList()); } catch (UnauthorizedAccessException ex) { Log.Warn(Resources.UnableToLoadAppList); Log.Warn(ex); return(new AppList()); } catch (InvalidDataException ex) { Log.Warn(Resources.UnableToLoadAppList); Log.Warn(ex); return(new AppList()); } #endregion }
/// <summary> /// Tests the sync logic with custom <see cref="AppList"/>s. /// </summary> /// <param name="resetMode">The <see cref="SyncResetMode"/> to pass to <see cref="SyncIntegrationManager.Sync"/>.</param> /// <param name="appListLocal">The current local <see cref="AppList"/>.</param> /// <param name="appListLast">The state of the <see cref="AppList"/> after the last successful sync.</param> /// <param name="appListServer">The current server-side <see cref="AppList"/>.</param> private static void TestSync(SyncResetMode resetMode, AppList appListLocal, AppList?appListLast, AppList appListServer) { string appListLocalPath = AppList.GetDefaultPath(); appListLocal.SaveXml(appListLocalPath); appListLast?.SaveXml(appListLocalPath + SyncIntegrationManager.AppListLastSyncSuffix); using var appListServerPath = new TemporaryFile("0install-test-applist"); { using (var stream = File.Create(appListServerPath)) appListServer.SaveXmlZip(stream, CryptoKey); using (var appListServerFile = File.OpenRead(appListServerPath)) { using var syncServer = new MicroServer("app-list", appListServerFile); var config = new Config { SyncServer = new(syncServer.ServerUri), SyncServerUsername = "******", SyncServerPassword = "******", SyncCryptoKey = CryptoKey }; using (var integrationManager = new SyncIntegrationManager(config, _ => new Feed(), new SilentTaskHandler())) integrationManager.Sync(resetMode); appListServer = AppList.LoadXmlZip(syncServer.FileContent, CryptoKey); } } appListLocal = XmlStorage.LoadXml <AppList>(appListLocalPath); appListLast = XmlStorage.LoadXml <AppList>(appListLocalPath + SyncIntegrationManager.AppListLastSyncSuffix); appListServer.Should().Be(appListLocal, because: "Server and local data should be equal after sync"); appListLast.Should().Be(appListLocal, because: "Last sync snapshot and local data should be equal after sync"); }
/// <summary> /// Constructs an XmlStorage class /// </summary> /// <param name="fileName">Xml file to use</param> public XmlStorage(string fileName) { this.isRoot = true; this.root = this; this.fileName = fileName; this.name = "Root"; try { IO.FileStream stream = new IO.FileStream(fileName, IO.FileMode.Open, IO.FileAccess.Read); Xml.XmlTextReader reader = new Xml.XmlTextReader(stream); try { this.ReadElements(reader); } finally { reader.Close(); stream.Close(); } } catch (IO.FileNotFoundException) {} }
/// <summary> /// Adds a feed to the list of custom feeds. /// </summary> private void AddCustomFeed(string input) { FeedUri feedUri; try { feedUri = new FeedUri(input); } catch (UriFormatException ex) { Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } if (_interfaceUri.IsFile) { if (!File.Exists(_interfaceUri.LocalPath)) { Msg.Inform(this, string.Format(Resources.FileOrDirNotFound, _interfaceUri.LocalPath), MsgSeverity.Warn); return; } } else { Feed feed = null; try { using var handler = new DialogTaskHandler(this); handler.RunTask(new SimpleTask(Resources.CheckingFeed, delegate { using var webClient = new WebClientTimeout(); feed = XmlStorage.FromXmlString <Feed>(webClient.DownloadString(feedUri)); })); }
public PluginViewModel(IPlugin plugin) { this._plugin = plugin; var protocalSetting = plugin.GetProtocalSetting(); Title = protocalSetting.Title; Description = protocalSetting.Description; _log = TinyIoCContainer.Current.Resolve <ILogDog>(); PluginKVViewModels = new ObservableCollection <PluginKVViewModel>(); PluginMonitorViewModels = new ObservableCollection <PluginMonitorViewModel>(); _xmlPluginKvSgsStorage = new XmlStorage <PluginKvSgs>(PathHelper.Combine(MessageToken.CONFIG_FOLDER, MessageToken.SETTINGCONFIG_FOLDER)); _xmlPluginKvSgsStorage.Load(); _pluginKvSgs = _xmlPluginKvSgsStorage.Storage; var pluginKvs = protocalSetting.PluginKVs; var pluginMonitors = protocalSetting.PluginMonitors; foreach (var item in pluginKvs) { if (_pluginKvSgs.PluginKvSgList != null && _pluginKvSgs.PluginKvSgList.Exists(p => p.Key == item.Key)) { item.Value = _pluginKvSgs.PluginKvSgList.FirstOrDefault(p => p.Key == item.Key).Value; } var kvm = new PluginKVViewModel(item); PluginKVViewModels.Add(kvm); kvm.PropertyChanged += Kvm_PropertyChanged; } foreach (var item in plugin.GetProtocalSetting().PluginMonitors) { PluginMonitorViewModels.Add(new PluginMonitorViewModel(item)); } SelectedPluginMonitorVm = PluginMonitorViewModels.FirstOrDefault(); }
/// <summary> /// Tests the sync logic with custom <see cref="AppList"/>s. /// </summary> /// <param name="resetMode">The <see cref="SyncResetMode"/> to pass to <see cref="SyncIntegrationManager.Sync"/>.</param> /// <param name="appListLocal">The current local <see cref="AppList"/>.</param> /// <param name="appListLast">The state of the <see cref="AppList"/> after the last successful sync.</param> /// <param name="appListServer">The current server-side <see cref="AppList"/>.</param> private void TestSync(SyncResetMode resetMode, AppList appListLocal, AppList appListLast, AppList appListServer) { appListLocal.SaveXml(_appListPath); if (appListLast != null) { appListLast.SaveXml(_appListPath + SyncIntegrationManager.AppListLastSyncSuffix); } using (var stream = File.Create(_appListPath + ".zip")) appListServer.SaveXmlZip(stream); using (var appListServerFile = File.OpenRead(_appListPath + ".zip")) using (var syncServer = new MicroServer("app-list", appListServerFile)) { using (var integrationManager = new SyncIntegrationManager(_appListPath, new SyncServer { Uri = syncServer.ServerUri }, interfaceId => new Feed(), new SilentTaskHandler())) integrationManager.Sync(resetMode); appListServer = AppList.LoadXmlZip(syncServer.FileContent); } appListLocal = XmlStorage.LoadXml <AppList>(_appListPath); appListLast = XmlStorage.LoadXml <AppList>(_appListPath + SyncIntegrationManager.AppListLastSyncSuffix); Assert.AreEqual(appListLocal, appListServer, "Server and local data should be equal after sync"); Assert.AreEqual(appListLocal, appListLast, "Last sync snapshot and local data should be equal after sync"); }
public static void LoadCurrent() { try { string settingsPath = Locations.GetSaveConfigPath(GeneralSettings.AppName, true, "Settings.xml"); if (File.Exists(settingsPath)) { Current = XmlStorage.LoadXml <Settings>(settingsPath); Log.Info("Loaded settings from " + settingsPath); return; } } #region Error handling catch (IOException ex) { Log.Warn("Failed to load settings: " + ex.Message + "\nReverting to defaults"); } catch (UnauthorizedAccessException ex) { Log.Warn("Insufficient rights to load settings: " + ex.Message + "\nReverting to defaults"); } catch (InvalidDataException ex) { Log.Warn("Settings file damaged: " + ex.Message + "\nReverting to defaults"); } #endregion Log.Info("Loaded default settings"); Current = new Settings(); }
/// <summary> /// Creates a new integration manager using a custom <see cref="DesktopIntegration.AppList"/>. Do not use directly except for testing purposes! /// </summary> /// <param name="appListPath">The storage location of the <see cref="AppList"/> file.</param> /// <param name="handler">A callback object used when the the user is to be informed about the progress of long-running operations such as downloads.</param> /// <param name="machineWide">Apply operations machine-wide instead of just for the current user.</param> /// <exception cref="IOException">A problem occurs while accessing the <see cref="AppList"/> file.</exception> /// <exception cref="UnauthorizedAccessException">Read or write access to the <see cref="AppList"/> file is not permitted.</exception> /// <exception cref="InvalidDataException">A problem occurs while deserializing the XML data.</exception> public IntegrationManager([NotNull] string appListPath, [NotNull] ITaskHandler handler, bool machineWide = false) : base(handler) { #region Sanity checks if (appListPath == null) { throw new ArgumentNullException("appListPath"); } if (handler == null) { throw new ArgumentNullException("handler"); } #endregion MachineWide = machineWide; AppListPath = appListPath; if (File.Exists(AppListPath)) { Log.Debug("Loading AppList from: " + AppListPath); AppList = XmlStorage.LoadXml <AppList>(AppListPath); } else { Log.Debug("Creating new AppList: " + AppListPath); AppList = new AppList(); AppList.SaveXml(AppListPath); } }
public Sonic4Ep1() { Sonic4Ep1.pInstance = this; AppMain.storePath = System.IO.Directory.GetCurrentDirectory(); var config = XmlStorage.Load(); if (config == null) { config = new Sonic4Save(); } var backup = gs.backup.SSave.CreateInstance(); backup.SetSave(config); XmlStorage.Save(config, false, false); this.graphics = new GraphicsDeviceManager((Game)this); this.graphics.PreferredBackBufferWidth = 480 * 3; this.graphics.PreferredBackBufferHeight = 288 * 3; this.graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft; this.graphics.PreparingDeviceSettings += new EventHandler <PreparingDeviceSettingsEventArgs>(this.graphics_PreparingDeviceSettings); this.graphics.SynchronizeWithVerticalRetrace = true; this.graphics.IsFullScreen = false; this.IsMouseVisible = true; this.Content.RootDirectory = "Content"; this.TargetElapsedTime = TimeSpan.FromSeconds(1d / 60); this.Activated += new EventHandler <EventArgs>(OnActivated); this.Deactivated += new EventHandler <EventArgs>(OnDeactivated); }
public static AppList LoadXmlZip([NotNull] Stream stream, [CanBeNull] string password = null) { #region Sanity checks if (stream == null) { throw new ArgumentNullException("stream"); } #endregion using (var zipFile = new ZipFile(stream) { IsStreamOwner = false, Password = password }) { var zipEntry = zipFile.Cast <ZipEntry>().First(x => StringUtils.EqualsIgnoreCase(x.Name, "data.xml")); try { return(XmlStorage.LoadXml <AppList>(zipFile.GetInputStream(zipEntry))); } catch (InvalidOperationException) { throw new InvalidDataException(Resources.SyncServerDataDamaged); } } }
/// <summary> /// Creates a new sync manager for a custom <see cref="AppList"/> file. Used for testing. /// </summary> /// <param name="appListPath">The storage location of the <see cref="AppList"/> file.</param> /// <param name="server">Access information for the sync server.</param> /// <param name="feedRetriever">Callback method used to retrieve additional <see cref="Feed"/>s on demand.</param> /// <param name="handler">A callback object used when the the user is to be informed about the progress of long-running operations such as downloads.</param> /// <param name="machineWide">Apply operations machine-wide instead of just for the current user.</param> /// <exception cref="IOException">A problem occurs while accessing the <see cref="AppList"/> file.</exception> /// <exception cref="UnauthorizedAccessException">Read or write access to the <see cref="AppList"/> file is not permitted or if another desktop integration class is currently active.</exception> /// <exception cref="InvalidDataException">A problem occurs while deserializing the XML data.</exception> public SyncIntegrationManager([NotNull] string appListPath, SyncServer server, [NotNull] Converter <FeedUri, Feed> feedRetriever, [NotNull] ITaskHandler handler, bool machineWide = false) : base(appListPath, handler, machineWide) { #region Sanity checks if (server.Uri == null) { throw new ArgumentNullException("server"); } if (feedRetriever == null) { throw new ArgumentNullException("feedRetriever"); } #endregion _server = server; _feedRetriever = feedRetriever; if (File.Exists(AppListPath + AppListLastSyncSuffix)) { _appListLastSync = XmlStorage.LoadXml <AppList>(AppListPath + AppListLastSyncSuffix); } else { _appListLastSync = new AppList(); _appListLastSync.SaveXml(AppListPath + AppListLastSyncSuffix); } }
/// <inheritdoc/> public void Add(FeedUri feedUri, byte[] data) { #region Sanity checks if (feedUri == null) { throw new ArgumentNullException("feedUri"); } if (data == null) { throw new ArgumentNullException("data"); } #endregion // Add to underlying cache _backingCache.Add(feedUri, data); // Add to memory cache (replacing existing old versions) var feed = XmlStorage.LoadXml <Feed>(new MemoryStream(data)); feed.Normalize(feedUri); string key = feedUri.Escape(); lock (_feedDictionary) { _feedDictionary.Remove(key); _feedDictionary.Add(key, feed); } }
/// <summary> /// Performs a feed search query using the <see cref="Config.FeedMirror"/>. /// </summary> /// <param name="config">The current configuration determining which mirror server to query.</param> /// <param name="keywords">The keywords to search for.</param> public static SearchQuery Perform([NotNull] Config config, [CanBeNull] string keywords) { #region Sanity checks if (config == null) { throw new ArgumentNullException("config"); } #endregion if (string.IsNullOrEmpty(keywords)) { return(new SearchQuery()); } var url = new Uri( config.FeedMirror.EnsureTrailingSlash(), new Uri("search/?q=" + Uri.EscapeUriString(keywords), UriKind.Relative)); Log.Info("Performing search query: " + url.ToStringRfc()); using (var webClient = new WebClientTimeout()) { var result = XmlStorage.FromXmlString <SearchQuery>(webClient.DownloadString(url)); result.Keywords = keywords; return(result); } }
public void TestXml() { var requirements = new Requirements(FeedTest.Test1Uri, "command", new Architecture(OS.Windows, Cpu.I586)); string xml = requirements.ToXmlString(); XmlStorage.FromXmlString <Requirements>(xml).Should().Be(requirements); }
/// <inheritdoc/> public async Task <Selections> DownloadAsync(Requirements requirements, bool refresh = false) { var args = new List <string> { "download", "--batch" }; if (refresh) { args.Add("--refresh"); } args.Add(requirements.ToCommandLineArgs()); if (_guiLauncher == null) { args.Add("--xml"); string output = await Task.Run(() => _launcher.RunAndCapture(args.ToArray())); return(XmlStorage.FromXmlString <Selections>(output)); } else { args.Add("--background"); await Task.Run(() => _guiLauncher.Run(args.ToArray())); return(await SelectAsync(requirements, offline : true)); } }
private void TreeViewerOnImagedataRequred(object sender, ImageDataEventArgs args) { var metadata = _core.LoadMetadata(args.Path) ?? new ImageMetadata(); //var metadata = await _core.LoadMetadataAsync(args.Path, CancellationToken.None) ?? new ImageMetadata(); var criterion = new FilterCriterion() { Pattern = _txtTreeFilter.Text, OnlyImportant = _chkImportant.Checked, }; if (criterion.IsAllow(metadata)) { args.Metadata = metadata; } var resultFilename = Path.ChangeExtension(args.Path, "result.xml"); if (File.Exists(resultFilename)) { try { args.AlgorithmsMetadata = XmlStorage.LoadResult(resultFilename); } catch (Exception exc) when(!exc.IsCritical()) { Log.Warn($"Load result file fail: '{resultFilename}'."); } } }
static void Main(string[] args) { var storage = XmlStorage.GetStorage("iekru", "dwl"); var infos = storage.Enum().Select(u => new DataInfo(u, storage.ReadByUrl <string>(u))); var metric = new MaxContentNodes(infos); var nodes = metric.GetNodes(); }
/// <summary> /// Constructs an XmlStorage. /// This is used to create sub-sections /// </summary> /// <param name="root">Root XmlStorage instance</param> /// <param name="name">Name of subsection</param> /// <param name="reader">Xml reader to read elements from</param> private XmlStorage(XmlStorage root, string name, Xml.XmlTextReader reader) { this.isRoot = false; this.root = root; this.name = name; ReadElements(reader); }
private static Selections ParseExpectedSelections(string expectedSelections, Requirements requirements) { var expectedSelectionsParsed = XmlStorage.FromXmlString <Selections>(string.Format( "<?xml version='1.0'?><selections interface='{0}' command='{1}' xmlns='http://zero-install.sourceforge.net/2004/injector/interface'>{2}</selections>", requirements.InterfaceUri, requirements.Command, expectedSelections)); return(expectedSelectionsParsed); }
static int Main() { IStorage mainStorage = null; try { // create userdata directory if it does not exist System.IO.Directory.CreateDirectory(Config.Constants.UserDataPath); mainStorage = new XmlStorage(Config.Constants.UserDataPath + System.IO.Path.DirectorySeparatorChar + "settings.xml"); // load all our global settings NBM.Plugin.Settings.GlobalSettings.Instance(mainStorage); NBM.Plugin.Settings.GlobalSettings.Instance().Load(); // run main form WinForms.Application.Run(new MainForm(mainStorage)); } catch (Exception e) { BugReportForm form = new BugReportForm(e); form.ShowDialog(); } catch { BugReportForm form = new BugReportForm(); form.ShowDialog(); } finally { if (mainStorage != null) { NBM.Plugin.Settings.GlobalSettings.Instance().Save(); mainStorage.Close(); } } return 0; }
/// <summary> /// Constructs an XmlStorage. /// This is used to create sub-sections /// </summary> /// <param name="root">Root XmlStorage instance</param> /// <param name="name">Name of subsection</param> private XmlStorage(XmlStorage root, string name) { this.isRoot = false; this.root = root; this.name = name; }
public void Write() { if (!Directory.Exists (config_path)) Directory.CreateDirectory (config_path); XmlStorage storage = new XmlStorage (); storage.New (RECENT_TAG); foreach (RecentFile item in items) storage.Add <RecentFile> (item); storage.Save (filename); }
/// <summary> /// Creates an Xml subsection /// </summary> /// <param name="name">Name of subsection</param> /// <returns></returns> public XmlStorage CreateSubSection(string name) { if (this.subsectionTable.Contains(name)) return (XmlStorage)this.subsectionTable[name]; else { XmlStorage sub = new XmlStorage(this.root, name); this.subsectionTable.Add(name, sub); return sub; } }
public static void Load() { XmlStorage ps = new XmlStorage (); ps.Load (Path.Combine (Defines.DATA_DIR, Defines.THEMES_FILE)); ps.Get (ref themes); }
public static void Save() { XmlStorage ps = new XmlStorage (); ps.New ("ThemeConfiguration"); ps.Add (themes); ps.Save (Path.Combine (Defines.DATA_DIR, Defines.THEMES_FILE)); }
public void Save(string file) { XmlStorage ps = new XmlStorage (); ps.New ("project"); ps.Add (details, "details"); details.Filename = file; // // Save elements in separate arrays classified by type // List <VideoProjectElement> videos = new List <VideoProjectElement> (); List <SlideShowProjectElement> slides = new List <SlideShowProjectElement> (); List <ButtonProjectElement> bts = new List <ButtonProjectElement> (); for (int i = 0; i < Elements.Count; i++) { if (typeof (Video) == Elements[i].GetType ()) { videos.Add ((VideoProjectElement)Elements [i]); continue; } if (typeof (SlideShow) == Elements[i].GetType ()) { slides.Add ((SlideShowProjectElement) Elements [i]); continue; } Logger.Debug ("Project.Save. Skipping {0}", Elements[i].GetType ()); } foreach (Button button in Buttons) bts.Add (button); ps.Add (videos, "videos"); ps.Add (slides, "slides"); ps.Add (bts, "buttons"); Logger.Debug ("Project.Save. Saving {0}", Details.Filename); ps.Save (Details.Filename); for (int i = 0; i < Elements.Count; i++) Logger.Debug ("Project.Save. {0}", Elements[i]); }
public void Read() { if (File.Exists (filename) == false) return; XmlStorage ps = new XmlStorage (); XmlNode root; ps.Load (filename); if ((ps.xml_document.ChildNodes.Count > 0) == false) return; root = ps.xml_document.ChildNodes [1]; RecentFile item = new RecentFile (); foreach (XmlNode node in root.ChildNodes) { XmlSerializer serializer = new XmlSerializer (typeof (RecentFile)); StringReader reader = new StringReader (node.OuterXml); item = (RecentFile) serializer.Deserialize (reader); reader.Close (); items.Add (item); } }
public void Load(string file) { XmlStorage ps = new XmlStorage (); List <VideoProjectElement> videos = new List <VideoProjectElement> (); List <SlideShowProjectElement> slides = new List <SlideShowProjectElement> (); List <ButtonProjectElement> bts = new List <ButtonProjectElement> (); Logger.Debug ("Project.Load. Loading project {0}", file); ps.Load (file); Clear (); ps.Get <ProjectDetails> ("details", ref details); ps.Get <List <ButtonProjectElement>> ("buttons", ref bts); ps.Get <List <VideoProjectElement>> ("videos", ref videos); ps.Get <List <SlideShowProjectElement>> ("slides", ref slides); details.Filename = file; // After the details have been loaded foreach (Video video in videos) elements.Add (video); foreach (SlideShow slide in slides) elements.Add (slide); foreach (Button button in bts) buttons.Add (button); Logger.Debug ("Project.Load. Loaded {0} - {1} elements", Details.Filename, elements.Count); }