예제 #1
0
        /// <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);
            }
        }
예제 #2
0
    /// <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));
        }
    }
예제 #3
0
        /// <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));
                    }));
                }
예제 #4
0
        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);
        }
예제 #5
0
        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);
        }
예제 #6
0
        /// <inheritdoc/>
        public Selections Solve(Requirements requirements)
        {
            #region Sanity checks
            if (requirements == null)
            {
                throw new ArgumentNullException("requirements");
            }
            if (requirements.InterfaceUri == null)
            {
                throw new ArgumentException(Resources.MissingInterfaceUri, "requirements");
            }
            #endregion

            Log.Info("Running Python Solver for: " + requirements);

            // Execute the external solver
            ISolverControl control;
            if (WindowsUtils.IsWindows)
            {
                control = new SolverControlBundled(_handler);                         // Use bundled Python on Windows
            }
            else
            {
                control = new SolverControlNative(_handler);  // Use native Python everywhere else
            }
            string arguments = GetSolverArguments(requirements);

            string result = null;
            _handler.RunTask(new SimpleTask(Resources.ExternalSolverRunning, () => { result = control.ExecuteSolver(arguments); }));

            // Flush in-memory cache in case external solver updated something on-disk
            _feedManager.Flush();

            // Detect when feeds get out-of-date
            _feedManager.Stale = result.Contains("<!-- STALE_FEEDS -->");

            // Parse StandardOutput data as XML
            _handler.CancellationToken.ThrowIfCancellationRequested();
            try
            {
                var selections = XmlStorage.FromXmlString <Selections>(result);
                selections.Normalize();
                return(selections);
            }
            #region Error handling
            catch (InvalidDataException ex)
            {
                Log.Warn("Solver result:" + Environment.NewLine + result);
                throw new SolverException(Resources.ExternalSolverOutputErrror, ex);
            }
            #endregion
        }
예제 #7
0
        private static IDictionary <FeedUri, Feed> ParseFeeds(IEnumerable <KeyValuePair <string, string> > feeds)
        {
            var feedsParsed = new Dictionary <FeedUri, Feed>();

            foreach (var feedXml in feeds)
            {
                var feed = XmlStorage.FromXmlString <Feed>(string.Format(
                                                               "<?xml version='1.0'?><interface xmlns='http://zero-install.sourceforge.net/2004/injector/interface' uri='{0}'>{1}</interface>",
                                                               feedXml.Key, feedXml.Value));
                feed.Normalize(new FeedUri(feedXml.Key));
                feedsParsed.Add(new FeedUri(feedXml.Key), feed);
            }
            return(feedsParsed);
        }
예제 #8
0
        /// <inheritdoc/>
        public override ExitCode Execute()
        {
            string input = Console.ReadLine();

            if (string.IsNullOrEmpty(input))
            {
                return(ExitCode.InvalidData);
            }

            var feedFragment = XmlStorage.FromXmlString <Feed>(input);

            Fetcher.Fetch(feedFragment.Elements.OfType <Implementation>());

            return(ExitCode.OK);
        }
예제 #9
0
        /// <inheritdoc/>
        public Selections Solve(Requirements requirements)
        {
            #region Sanity checks
            if (requirements == null)
            {
                throw new ArgumentNullException(nameof(requirements));
            }
            if (requirements.InterfaceUri == null)
            {
                throw new ArgumentException(Resources.MissingInterfaceUri, nameof(requirements));
            }
            #endregion

            Selections?selections = null;
            _handler.RunTask(new SimpleTask(Resources.ExternalSolverRunning, () =>
            {
                using var control = new ExternalSolverSession(GetStartInfo())
                      {
                          { "confirm", args => DoConfirm((string)args[0]) },
                          { "confirm-keys", args => DoConfirmKeys(new FeedUri((string)args[0]), args[1].ReparseAsJson <Dictionary <string, string[][]> >()) },
                          { "update-key-info", args => null }
                      };
                control.Invoke(args =>
                {
                    if ((string)args[0] == "ok")
                    {
                        _feedManager.Stale = args[1].ReparseAsJson(new { stale = false }).stale;
                        selections         = XmlStorage.FromXmlString <Selections>((string)args[2]);
                    }
                    else
                    {
                        throw new SolverException(((string)args[1]).Replace("\n", Environment.NewLine));
                    }
                }, "select", GetEffectiveRequirements(requirements), false /*_feedManager.Refresh*/); // Pretend refresh is always false to avoid downloading feeds in external process (could cause problems with HTTPS and GPG validation)
                while (selections == null)
                {
                    control.HandleStderr();
                    control.HandleNextChunk();
                }
                control.HandleStderr();
            }));
            Debug.Assert(selections != null);

            // Invalidate in-memory feed cache, because external solver may have modified on-disk feed cache
            _feedManager.Clear();

            return(selections);
        }
예제 #10
0
        public void TestSaveLoad()
        {
            var dictionary1 = new XmlDictionary
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };

            // Serialize and deserialize data
            string data        = dictionary1.ToXmlString();
            var    dictionary2 = XmlStorage.FromXmlString <XmlDictionary>(data);

            // Ensure data stayed the same
            dictionary2.Should().Equal(dictionary1, because: "Serialized objects should be equal.");
            ReferenceEquals(dictionary1, dictionary2).Should().BeFalse(because: "Serialized objects should not return the same reference.");
        }
예제 #11
0
    public void Equality()
    {
        var dataBase              = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");
        var dataAttribSwap        = XmlStorage.FromXmlString <XmlUnknownStub>("<root key2=\"value2\" key1=\"value1\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");
        var dataChildSwap         = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">text<child2 key=\"value\" /><child1 key=\"value\" /></element></root>");
        var dataAttribChange      = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"valueX\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");
        var dataChildAttribChange = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"valueX\" /></element></root>");
        var dataTextChange        = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">new text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");

        dataBase.Should().Be(dataBase);
        dataAttribSwap.Should().Be(dataBase);
        dataAttribSwap.GetHashCode().Should().Be(dataBase.GetHashCode());
        dataChildSwap.Should().NotBe(dataBase);
        dataAttribChange.Should().NotBe(dataBase);
        dataChildAttribChange.Should().NotBe(dataBase);
        dataTextChange.Should().NotBe(dataBase);
    }
예제 #12
0
        /// <summary>
        /// Imports the XML data
        /// </summary>
        protected override void OnFirstExecute()
        {
            // Backup current state for undo
            _undoUniverse = _getUniverse();

            // Create new universe from XML and partially restore old data
            var newUniverse = XmlStorage.FromXmlString <TUniverse>(_xmlData);

            newUniverse.SourceFile = _undoUniverse.SourceFile;
            TransferNonXmlData(_undoUniverse, newUniverse);

            // Apply new data
            _setUniverse(newUniverse);

            // Update rendering
            _refreshHandler();
        }
예제 #13
0
    /// <inheritdoc/>
    public override ExitCode Execute()
    {
        string?input = Console.ReadLine();

        if (string.IsNullOrEmpty(input))
        {
            return(ExitCode.InvalidData);
        }

        var feedFragment = XmlStorage.FromXmlString <Feed>(input);

        feedFragment.Name = "dummy";
        feedFragment.Normalize();
        FetchAll(feedFragment.Implementations);

        return(ExitCode.OK);
    }
예제 #14
0
        /// <inheritdoc/>
        public Selections Solve(Requirements requirements)
        {
            #region Sanity checks
            if (requirements == null)
            {
                throw new ArgumentNullException(nameof(requirements));
            }
            if (requirements.InterfaceUri == null)
            {
                throw new ArgumentException(Resources.MissingInterfaceUri, nameof(requirements));
            }
            #endregion

            Selections selections = null;
            _handler.RunTask(new SimpleTask(Resources.ExternalSolverRunning, () =>
            {
                using (var control = new JsonControl(GetStartInfo())
                {
                    { "confirm", args => DoConfirm((string)args[0]) },
                    { "confirm-keys", args => DoConfirmKeys(new FeedUri((string)args[0]), args[1].ReparseAsJson <Dictionary <string, string[][]> >()) },
                    { "update-key-info", args => null }
                })
                {
                    control.Invoke(args =>
                    {
                        if ((string)args[0] == "ok")
                        {
                            _feedManager.Stale = args[1].ReparseAsJson(new { stale = false }).stale;
                            selections         = XmlStorage.FromXmlString <Selections>((string)args[2]);
                        }
                        else
                        {
                            throw new SolverException(((string)args[1]).Replace("\n", Environment.NewLine));
                        }
                    }, "select", GetEffectiveRequirements(requirements), _feedManager.Refresh);
                    while (selections == null)
                    {
                        control.HandleStderr();
                        control.HandleNextChunk();
                    }
                    control.HandleStderr();
                }
            }));

            return(selections);
        }
예제 #15
0
        public void TestEquals()
        {
            var dataBase             = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");
            var dataAttribSwap       = XmlStorage.FromXmlString <XmlUnknownStub>("<root key2=\"value2\" key1=\"value1\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");
            var dataChildSwap        = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">text<child2 key=\"value\" /><child1 key=\"value\" /></element></root>");
            var dataAttibChange      = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"valueX\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");
            var dataChildAttibChange = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">text<child1 key=\"value\" /><child2 key=\"valueX\" /></element></root>");
            var dataTextChange       = XmlStorage.FromXmlString <XmlUnknownStub>("<root key1=\"value1\" key2=\"value2\"><element key=\"value\">new text<child1 key=\"value\" /><child2 key=\"value\" /></element></root>");

            Assert.AreEqual(dataBase, dataBase);
            Assert.AreEqual(dataBase, dataAttribSwap);
            Assert.AreEqual(dataBase.GetHashCode(), dataAttribSwap.GetHashCode());
            Assert.AreNotEqual(dataBase, dataChildSwap);
            Assert.AreNotEqual(dataBase, dataAttibChange);
            Assert.AreNotEqual(dataBase, dataChildAttibChange);
            Assert.AreNotEqual(dataBase, dataTextChange);
        }
        public void TestSaveLoad()
        {
            var collection1 = new LocalizableStringCollection
            {
                "neutralValue",
                { "en-US", "americaValue" },
                { "en-GB", "gbValue" },
                { "de", "germanValue" },
                { "de-DE", "germanyValue" }
            };

            // Serialize and deserialize data
            string data        = collection1.ToXmlString();
            var    collection2 = XmlStorage.FromXmlString <LocalizableStringCollection>(data);

            // Ensure data stayed the same
            collection2.Should().Equal(collection1, because: "Serialized objects should be equal.");
            collection2.GetSequencedHashCode().Should().Be(collection1.GetSequencedHashCode(), because: "Serialized objects' hashes should be equal.");
            ReferenceEquals(collection1, collection2).Should().BeFalse(because: "Serialized objects should not return the same reference.");
        }
예제 #17
0
    /// <inheritdoc/>
    public async Task <Selections> SelectAsync(Requirements requirements, bool refresh = false, bool offline = false)
    {
        var args = new List <string> {
            "select", "--batch", "--xml"
        };

        if (refresh)
        {
            args.Add("--refresh");
        }
        if (offline)
        {
            args.Add("--offline");
        }
        args.Add(requirements.ToCommandLineArgs());

        string output = await Task.Run(() => _launcher.RunAndCapture(args.ToArray()));

        return(XmlStorage.FromXmlString <Selections>(output));
    }
예제 #18
0
            public override IEnumerable <EntryInfo> GetEntriesIn(TContainer container)
            {
                var pointer = _getPointer(container);

                if (pointer.Value != null)
                {
                    var description = AttributeUtils.GetAttributes <DescriptionAttribute, TProperty>().FirstOrDefault();
                    yield return(new EntryInfo(
                                     name: _name,
                                     description: description?.Description,
                                     target: pointer.Value,
                                     getEditorControl: executor => CreateEditor(container, pointer.Value, executor),
                                     toXmlString: () => pointer.Value.ToXmlString(),
                                     fromXmlString: xmlString =>
                    {
                        var newValue = XmlStorage.FromXmlString <TProperty>(xmlString);
                        return newValue.Equals(pointer.Value) ? null : new SetValueCommand <TProperty>(pointer, newValue);
                    },
                                     removeCommand: new SetValueCommand <TProperty>(pointer, null)));
                }
            }
예제 #19
0
                public EntryInfo TryGetEntry(TContainer container, IList <TList> list, TList candidate)
                {
                    if (!(candidate is TElement element))
                    {
                        return(null);
                    }

                    var description = AttributeUtils.GetAttributes <DescriptionAttribute, TElement>().FirstOrDefault();

                    return(new EntryInfo(
                               name: _name,
                               description: description?.Description,
                               target: element,
                               getEditorControl: executor => CreateEditor(container, element, executor),
                               toXmlString: () => element.ToXmlString(),
                               fromXmlString: xmlString =>
                    {
                        var newValue = XmlStorage.FromXmlString <TElement>(xmlString);
                        return newValue.Equals(element) ? null : new ReplaceInList <TList>(list, element, newValue);
                    },
                               removeCommand: new RemoveFromCollection <TList>(list, element)));
                }
예제 #20
0
 public void TestFromXmlString()
 => XmlStorage.FromXmlString <TestData>("<?xml version=\"1.0\"?><TestData><Data>Hello</Data></TestData>").Data.Should().Be("Hello");
예제 #21
0
        /// <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));
                        }));
                    }
                }
                #region Error handling
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (IOException ex)
                {
                    Msg.Inform(this, ex.Message, MsgSeverity.Error);
                    return;
                }
                catch (InvalidDataException ex)
                {
                    Msg.Inform(this, ex.Message, MsgSeverity.Error);
                    return;
                }
                catch (WebException ex)
                {
                    Msg.Inform(this, ex.Message, MsgSeverity.Error);
                    return;
                }
                catch (UnauthorizedAccessException ex)
                {
                    Msg.Inform(this, ex.Message, MsgSeverity.Error);
                    return;
                }
                #endregion

                // Ensure a matching <feed-for> is present for online feeds
                if (feed.FeedFor.All(entry => entry.Target != _interfaceUri))
                {
                    if (!Msg.YesNo(this, Resources.IgnoreMissingFeedFor, MsgSeverity.Warn))
                    {
                        return;
                    }
                }
            }

            var reference = new FeedReference {
                Source = feedUri
            };
            if (_interfacePreferences.Feeds.Contains(reference))
            {
                return;
            }
            _interfacePreferences.Feeds.Add(reference);
            listBoxFeeds.Items.Add(reference);
        }