Exemplo n.º 1
0
        /// <inheritdoc/>
        public string GetIcon(Uri iconUrl, ITaskHandler handler)
        {
            #region Sanity checks
            if (iconUrl == null) throw new ArgumentNullException(nameof(iconUrl));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            string path = Path.Combine(DirectoryPath, new FeedUri(iconUrl).Escape());

            // Prevent file-exists race conditions
            lock (_lock)
            {
                // Download missing icons
                if (!File.Exists(path))
                {
                    using (var atomic = new AtomicWrite(path))
                    {
                        handler.RunTask(new DownloadFile(iconUrl, atomic.WritePath));
                        atomic.Commit();
                    }
                }
            }

            return path;
        }
Exemplo n.º 2
0
        internal WorkflowManagement(ConnectionMultiplexer mux, ITaskHandler taskHandler, WorkflowHandler workflowHandler, string identifier, IEnumerable<string> typesProcessed, ILua lua, EventHandler<Exception> exceptionHandler = null, Behaviours behaviours = Behaviours.All)
        {
            _taskHandler = taskHandler;

            _workflowHandler = workflowHandler;

            if (exceptionHandler != null)
            {
                ExceptionThrown += exceptionHandler;
            }

            _typesProcessed = typesProcessed;

            _db = mux.GetDatabase();

            _sub = mux.GetSubscriber();

            if (_typesProcessed == null || _typesProcessed.Count() == 0)
            {
                _sub.Subscribe("submittedTask", (c, v) =>
                {
                    ProcessNextTask();
                });
            }
            else
            {
                foreach(var t in _typesProcessed)
                {
                    _sub.Subscribe("submittedTask:" + t, (c, v) =>
                    {
                        ProcessNextTask(t);
                    });
                }
            }

            _sub.Subscribe("workflowFailed", (c, v) =>
            {
                ProcessNextFailedWorkflow();
            });

            _sub.Subscribe("workflowComplete", (c, v) =>
            {
                ProcessNextCompleteWorkflow();
            });

            _lua = lua;
            _lua.LoadScripts(_db, mux.GetServer("localhost:6379"));

            _identifier = identifier;

            if (behaviours.HasFlag(Behaviours.AutoRestart))
            {
                var resubmittedTasks = ResubmitTasks();

                foreach (var item in resubmittedTasks)
                {
                    Console.WriteLine("Resubmitted {0}", item);
                }
            }
        }
        /// <summary>
        /// Creates an integration manager base.
        /// </summary>
        /// <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>
        protected IntegrationManagerBase([NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            Handler = handler;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a new manager.
        /// </summary>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        /// <param name="machineWide">Apply operations machine-wide instead of just for the current user.</param>
        protected ManagerBase([NotNull] ITaskHandler handler, bool machineWide = false)
        {
            #region Sanity checks
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            Handler = handler;
            MachineWide = machineWide;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creates a new catalog manager.
        /// </summary>
        /// <param name="trustManager">Methods for verifying signatures and user trust.</param>
        /// <param name="handler">A callback object used when the the user needs to be informed about progress.</param>
        public CatalogManager([NotNull] ITrustManager trustManager, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (trustManager == null) throw new ArgumentNullException("trustManager");
            #endregion

            _trustManager = trustManager;
            _handler = handler;
        }
        /// <summary>
        /// Creates a new Windows shortcut in the quick launch bar.
        /// </summary>
        /// <param name="quickLaunch">Information about the shortcut to be created.</param>
        /// <param name="target">The target the shortcut shall point to.</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>
        public static void Create(QuickLaunch quickLaunch, FeedTarget target, ITaskHandler handler)
        {
            #region Sanity checks
            if (quickLaunch == null) throw new ArgumentNullException("quickLaunch");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            string filePath = GetQuickLaunchPath(quickLaunch.Name);
            Create(filePath, target, quickLaunch.Command, handler, machineWide: false);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new Windows shortcut in the "Send to" menu.
        /// </summary>
        /// <param name="sendTo">Information about the shortcut to be created.</param>
        /// <param name="target">The target the shortcut shall point to.</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>
        public static void Create(SendTo sendTo, FeedTarget target, ITaskHandler handler)
        {
            #region Sanity checks
            if (sendTo == null) throw new ArgumentNullException(nameof(sendTo));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            string filePath = GetSendToPath(sendTo.Name);
            Create(filePath, target, sendTo.Command, handler, machineWide: false);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a new download fetcher.
        /// </summary>
        /// <param name="store">The location to store the downloaded and unpacked <see cref="ZeroInstall.Store.Model.Implementation"/>s in.</param>
        /// <param name="handler">A callback object used when the the user needs to be informed about progress.</param>
        protected FetcherBase([NotNull] IStore store, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (store == null) throw new ArgumentNullException("store");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            _store = store;
            Handler = handler;
        }
        /// <summary>
        /// Creates a new Windows shortcut in the "Startup" menu.
        /// </summary>
        /// <param name="autoStart">Information about the shortcut to be created.</param>
        /// <param name="target">The target the shortcut shall point to.</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">Create the shortcut machine-wide instead of just for the current user.</param>
        public static void Create(AutoStart autoStart, FeedTarget target, ITaskHandler handler, bool machineWide)
        {
            #region Sanity checks
            if (autoStart == null) throw new ArgumentNullException("autoStart");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            string filePath = GetStartupPath(autoStart.Name, machineWide);
            Create(filePath, target.GetRunStub(autoStart.Command, handler));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Deletes this temporary directory from the <see cref="IStore"/> it is located in.
        /// </summary>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about IO tasks.</param>
        /// <exception cref="DirectoryNotFoundException">The directory could be found in the store.</exception>
        /// <exception cref="IOException">The directory could not be deleted.</exception>
        /// <exception cref="UnauthorizedAccessException">Write access to the store is not permitted.</exception>
        public override void Delete(ITaskHandler handler)
        {
            #region Sanity checks
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            handler.RunTask(new SimpleTask(string.Format(Resources.DeletingDirectory, _path), () =>
            {
                DirectoryStore.DisableWriteProtection(_path);
                Directory.Delete(_path, recursive: true);
            }));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Adds a context menu entry to the current system.
        /// </summary>
        /// <param name="target">The application being integrated.</param>
        /// <param name="contextMenu">The context menu entry to add.</param>
        /// <param name="machineWide">Add the context menu entry machine-wide instead of just for the current user.</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>
        /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
        /// <exception cref="IOException">A problem occurs while writing to the filesystem.</exception>
        /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception>
        /// <exception cref="UnauthorizedAccessException">Write access to the filesystem is not permitted.</exception>
        /// <exception cref="InvalidDataException">The data in <paramref name="contextMenu"/> is invalid.</exception>
        public static void Apply(FeedTarget target, Store.Model.Capabilities.ContextMenu contextMenu, bool machineWide, ITaskHandler handler)
        {
            #region Sanity checks
            if (contextMenu == null) throw new ArgumentNullException("contextMenu");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            if (contextMenu.Verb == null) throw new InvalidDataException("Missing verb");
            if (string.IsNullOrEmpty(contextMenu.Verb.Name)) throw new InvalidDataException("Missing verb name");

            // TODO: Implement
        }
Exemplo n.º 12
0
 /// <summary>
 /// Deletes this implementation from the <see cref="IStore"/> it is located in.
 /// </summary>
 /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about IO tasks.</param>
 /// <exception cref="KeyNotFoundException">No matching implementation could be found in the <see cref="IStore"/>.</exception>
 /// <exception cref="IOException">The implementation could not be deleted.</exception>
 /// <exception cref="UnauthorizedAccessException">Write access to the store is not permitted.</exception>
 public override void Delete(ITaskHandler handler)
 {
     try
     {
         Store.Remove(_digest, handler);
     }
         #region Error handling
     catch (ImplementationNotFoundException ex)
     {
         throw new KeyNotFoundException(ex.Message, ex);
     }
     #endregion
 }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a new Python solver.
        /// </summary>
        /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
        /// <param name="feedCache">The underlying cache backing the <paramref name="feedManager"/>.</param>
        /// <param name="feedManager">Provides access to remote and local <see cref="Feed"/>s. Handles downloading, signature verification and caching.</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        public PythonSolver([NotNull] Config config, [NotNull] IFeedManager feedManager, [NotNull] IFeedCache feedCache, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (config == null) throw new ArgumentNullException("config");
            if (feedManager == null) throw new ArgumentNullException("feedManager");
            if (feedCache == null) throw new ArgumentNullException("feedCache");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            _config = config;
            _feedManager = feedManager;
            _feedCache = feedCache;
            _handler = handler;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Removes all applications from the <see cref="AppList"/> and undoes any desktop environment integration.
        /// </summary>
        /// <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 the operation machine-wide instead of just for the current user.</param>
        public static void RemoveAllApps(ITaskHandler handler, bool machineWide)
        {
            #region Sanity checks
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            using (var integrationManager = new IntegrationManager(handler, machineWide))
            {
                handler.RunTask(ForEachTask.Create(Resources.RemovingApplications, integrationManager.AppList.Entries.ToList(), integrationManager.RemoveApp));

                // Purge sync status, otherwise next sync would remove everything from server as well instead of restoring from there
                File.Delete(AppList.GetDefaultPath(machineWide) + SyncIntegrationManager.AppListLastSyncSuffix);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates a new manifest directory task.
        /// </summary>
        /// <param name="path">The path of the directory to operate on.</param>
        /// <param name="manifest">The contents of a <see cref="Implementations.Manifest"/> file describing the directory.</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about IO tasks.</param>
        protected DirectoryOperation([NotNull] string path, [NotNull] Manifest manifest, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
            if (manifest == null) throw new ArgumentNullException(nameof(manifest));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            Path = path;
            Manifest = manifest;
            Handler = handler;

            ElementPaths = Manifest.ListPaths();
        }
Exemplo n.º 16
0
        public CaptureCommand(IEnumerable<string> args, ITaskHandler handler)
        {
            _handler = handler;

            var options = new OptionSet
            {
                {
                    "V|version", _ =>
                    {
                        var assembly = Assembly.GetEntryAssembly().GetName();
                        Console.WriteLine(@"Zero Install Capture CLI v{0}", assembly.Version);
                        throw new OperationCanceledException();
                    }
                },
                {"f|force", _ => _force = true},
                {
                    "installation-dir=", value =>
                    {
                        try
                        {
                            _installationDirectory = Path.GetFullPath(value);
                        }
                            #region Error handling
                        catch (ArgumentException ex)
                        {
                            // Wrap exception since only certain exception types are allowed
                            throw new OptionException(ex.Message, "installation-dir");
                        }
                        catch (NotSupportedException ex)
                        {
                            // Wrap exception since only certain exception types are allowed
                            throw new OptionException(ex.Message, "installation-dir");
                        }
                        #endregion
                    }
                },
                {"main-exe=", value => _mainExe = value},
                {"collect-files=", value => _zipFile = value},
                {
                    "h|help|?", _ =>
                    {
                        PrintHelp();
                        throw new OperationCanceledException();
                    }
                }
            };
            _additionalArgs = options.Parse(args);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Creates a new trust manager.
        /// </summary>
        /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
        /// <param name="openPgp">The OpenPGP-compatible system used to validate the signatures.</param>
        /// <param name="trustDB">A database of OpenPGP signature fingerprints the users trusts to sign <see cref="Feed"/>s coming from specific domains.</param>
        /// <param name="feedCache">Provides access to a cache of <see cref="Feed"/>s that were downloaded via HTTP(S).</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions.</param>
        public TrustManager([NotNull] Config config, [NotNull] IOpenPgp openPgp, [NotNull] TrustDB trustDB, [NotNull] IFeedCache feedCache, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (config == null) throw new ArgumentNullException("config");
            if (openPgp == null) throw new ArgumentNullException("openPgp");
            if (trustDB == null) throw new ArgumentNullException("trustDB");
            if (feedCache == null) throw new ArgumentNullException("feedCache");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            _config = config;
            _openPgp = openPgp;
            _trustDB = trustDB;
            _feedCache = feedCache;
            _handler = handler;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a new simple solver.
        /// </summary>
        /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
        /// <param name="store">Used to check which <see cref="Implementation"/>s are already cached.</param>
        /// <param name="feedManager">Provides access to remote and local <see cref="Feed"/>s. Handles downloading, signature verification and caching.</param>
        /// <param name="packageManager">An external package manager that can install <see cref="PackageImplementation"/>s.</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        public BacktrackingSolver([NotNull] Config config, [NotNull] IFeedManager feedManager, [NotNull] IStore store, [NotNull] IPackageManager packageManager, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (config == null) throw new ArgumentNullException(nameof(config));
            if (feedManager == null) throw new ArgumentNullException(nameof(feedManager));
            if (store == null) throw new ArgumentNullException(nameof(store));
            if (packageManager == null) throw new ArgumentNullException(nameof(packageManager));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            _config = config;
            _store = store;
            _packageManager = packageManager;
            _feedManager = feedManager;
            _handler = handler;
        }
Exemplo n.º 19
0
 /// <inheritdoc/>
 public string AddArchives(IEnumerable<ArchiveFileInfo> archiveInfos, ManifestDigest manifestDigest, ITaskHandler handler)
 {
     try
     {
         string result = GetServiceProxy().AddArchives(archiveInfos, manifestDigest, handler);
         Log.Info("Sent implementation to Store Service: " + manifestDigest.AvailableDigests.First());
         return result;
     }
         #region Error handling
     catch (RemotingException ex)
     {
         // Wrap exception since only certain exception types are allowed
         throw new IOException(ex.Message, ex);
     }
     #endregion
 }
Exemplo n.º 20
0
        /// <summary>
        /// Hooks into the creation of new processes on the current thread to inject API hooks.
        /// </summary>
        /// <param name="selections">The implementations chosen for launch.</param>
        /// <param name="executor">The executor used to launch the new process.</param>
        /// <param name="feedManager">Provides access to remote and local <see cref="Feed"/>s. Handles downloading, signature verification and caching.</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        /// <exception cref="ImplementationNotFoundException">The main implementation is not cached (possibly because it is installed natively).</exception>
        public RunHook(Selections selections, IExecutor executor, IFeedManager feedManager, ITaskHandler handler)
        {
            var feed = feedManager[selections.InterfaceUri];
            _target = new FeedTarget(selections.InterfaceUri, feed);

            var mainImplementation = selections.MainImplementation;
            _implementationDir = executor.GetImplementationPath(mainImplementation);
            _mainImplementation = feed[mainImplementation.ID];

            _handler = handler;
            _registryFilter = GetRegistryFilter();
            _relaunchControl = GetRelaunchControl();

            Log.Info("Activating API hooking");
            _hookW = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateProcessW"), new UnsafeNativeMethods.DCreateProcessW(CreateProcessWCallback), null);
            _hookW.ThreadACL.SetInclusiveACL(new[] {Thread.CurrentThread.ManagedThreadId});
            _hookA = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateProcessA"), new UnsafeNativeMethods.DCreateProcessA(CreateProcessACallback), null);
            _hookA.ThreadACL.SetInclusiveACL(new[] {Thread.CurrentThread.ManagedThreadId});
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates a new external JSON solver.
        /// </summary>
        /// <param name="backingSolver">An internal solver used to find an implementation of the external solver.</param>
        /// <param name="selectionsManager">Used to check whether the external solver is already in the cache.</param>
        /// <param name="fetcher">Used to download implementations of the external solver.</param>
        /// <param name="executor">Used to launch the external solver.</param>
        /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
        /// <param name="feedManager">Provides access to remote and local <see cref="Feed"/>s. Handles downloading, signature verification and caching.</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        public ExternalSolver([NotNull] ISolver backingSolver, [NotNull] ISelectionsManager selectionsManager, [NotNull] IFetcher fetcher, [NotNull] IExecutor executor, [NotNull] Config config, [NotNull] IFeedManager feedManager, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (backingSolver == null) throw new ArgumentNullException(nameof(backingSolver));
            if (selectionsManager == null) throw new ArgumentNullException(nameof(selectionsManager));
            if (fetcher == null) throw new ArgumentNullException(nameof(fetcher));
            if (executor == null) throw new ArgumentNullException(nameof(executor));
            if (config == null) throw new ArgumentNullException(nameof(config));
            if (feedManager == null) throw new ArgumentNullException(nameof(feedManager));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            #endregion

            _backingSolver = backingSolver;
            _selectionsManager = selectionsManager;
            _fetcher = fetcher;
            _executor = executor;
            _feedManager = feedManager;
            _handler = handler;

            _solverRequirements = new Requirements(config.ExternalSolverUri);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Adds a context menu entry to the current system.
        /// </summary>
        /// <param name="target">The application being integrated.</param>
        /// <param name="contextMenu">The context menu entry to add.</param>
        /// <param name="machineWide">Add the context menu entry machine-wide instead of just for the current user.</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>
        /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
        /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception>
        /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception>
        /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception>
        /// <exception cref="InvalidDataException">The data in <paramref name="contextMenu"/> is invalid.</exception>
        public static void Apply(FeedTarget target, Store.Model.Capabilities.ContextMenu contextMenu, bool machineWide, ITaskHandler handler)
        {
            #region Sanity checks
            if (contextMenu == null) throw new ArgumentNullException("contextMenu");
            if (handler == null) throw new ArgumentNullException("handler");
            #endregion

            if (contextMenu.Verb == null) throw new InvalidDataException("Missing verb");
            if (string.IsNullOrEmpty(contextMenu.Verb.Name)) throw new InvalidDataException("Missing verb name");

            var hive = machineWide ? Registry.LocalMachine : Registry.CurrentUser;
            foreach (string keyName in GetKeyName(contextMenu.Target))
            {
                using (var verbKey = hive.CreateSubKeyChecked(FileType.RegKeyClasses + @"\" + keyName + @"\shell\" + RegKeyPrefix + contextMenu.Verb.Name))
                {
                    string description = contextMenu.Verb.Descriptions.GetBestLanguage(CultureInfo.CurrentUICulture);
                    if (description != null) verbKey.SetValue("", description);
                    if (contextMenu.Verb.Extended) verbKey.SetValue(FileType.RegValueExtended, "");

                    using (var commandKey = verbKey.CreateSubKeyChecked("command"))
                        commandKey.SetValue("", FileType.GetLaunchCommandLine(target, contextMenu.Verb, machineWide, handler));
                }
            }
        }
Exemplo n.º 23
0
 public UserRemindResponseGenerator(ITaskHandler taskHandler) => this.taskHandler = taskHandler;
Exemplo n.º 24
0
 /// <summary>
 /// Creates a new integration manager.
 /// </summary>
 /// <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 occurred 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 another desktop integration class is currently active.</exception>
 /// <exception cref="InvalidDataException">A problem occurred while deserializing the XML data.</exception>
 protected IntegrationManagerBase(ITaskHandler handler, bool machineWide = false)
     : base(handler, machineWide)
 {
 }
Exemplo n.º 25
0
        /// <summary>
        /// Creates a new Python solver.
        /// </summary>
        /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
        /// <param name="feedManager">Provides access to remote and local <see cref="Feed"/>s. Handles downloading, signature verification and caching.</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        public PythonSolver([NotNull] Config config, [NotNull] IFeedManager feedManager, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (feedManager == null)
            {
                throw new ArgumentNullException("feedManager");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            _config      = config;
            _feedManager = feedManager;
            _handler     = handler;
        }
Exemplo n.º 26
0
        public static TemporaryDirectory DownloadAndApply([NotNull] this RetrievalMethod retrievalMethod, [NotNull] ITaskHandler handler, [CanBeNull] ICommandExecutor executor = null)
        {
            #region Sanity checks
            if (retrievalMethod == null)
            {
                throw new ArgumentNullException("retrievalMethod");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            var download = retrievalMethod as DownloadRetrievalMethod;
            if (download != null)
            {
                return(download.DownloadAndApply(handler, executor));
            }

            var recipe = retrievalMethod as Recipe;
            if (recipe != null)
            {
                return(recipe.DownloadAndApply(handler, executor));
            }

            throw new NotSupportedException(Resources.UnknownRetrievalMethodType);
        }
Exemplo n.º 27
0
        public static TemporaryFile Download([NotNull] this DownloadRetrievalMethod retrievalMethod, [NotNull] ITaskHandler handler, [CanBeNull] ICommandExecutor executor = null)
        {
            #region Sanity checks
            if (retrievalMethod == null)
            {
                throw new ArgumentNullException("retrievalMethod");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            if (executor == null)
            {
                executor = new SimpleCommandExecutor();
            }
            if (retrievalMethod.Href == null)
            {
                throw new ArgumentException(Resources.HrefMissing, "retrievalMethod");
            }
            new PerTypeDispatcher <DownloadRetrievalMethod>(ignoreMissing: false)
            {
                // ReSharper disable AccessToDisposedClosure
                (Archive archive) =>
                {
                    // Guess MIME types now because the file ending is not known later
                    if (string.IsNullOrEmpty(archive.MimeType))
                    {
                        string mimeType = Archive.GuessMimeType(archive.Href.OriginalString);
                        executor.Execute(new SetValueCommand <string>(() => archive.MimeType, value => archive.MimeType = value, mimeType));
                    }
                },
                (SingleFile file) =>
                {
                    // Guess file name based on URL
                    if (string.IsNullOrEmpty(file.Destination))
                    {
                        string destination = file.Href.OriginalString.GetRightPartAtLastOccurrence('/').StripCharacters(Path.GetInvalidFileNameChars());
                        executor.Execute(new SetValueCommand <string>(() => file.Destination, value => file.Destination = value, destination));
                    }
                }
                // ReSharper restore AccessToDisposedClosure
            }.Dispatch(retrievalMethod);

            // Download the file
            var href           = ModelUtils.GetAbsoluteHref(retrievalMethod.Href, string.IsNullOrEmpty(executor.Path) ? null : new FeedUri(executor.Path));
            var downloadedFile = new TemporaryFile("0publish");
            handler.RunTask(new DownloadFile(href, downloadedFile)); // Defer task to handler

            // Set downloaded file size
            long newSize = new FileInfo(downloadedFile).Length;
            if (retrievalMethod.Size != newSize)
            {
                executor.Execute(new SetValueCommand <long>(() => retrievalMethod.Size, value => retrievalMethod.Size = value, newSize));
            }

            return(downloadedFile);
        }
Exemplo n.º 28
0
        public void Init()
        {
            var fixture = new Fixture().Customize(new AutoMoqCustomization());

            mockDeck = fixture.Create<Mock<IDeck>>();
            mockDice = fixture.Create<Mock<Dice>>();
            mockDeckFactory = fixture.Create<Mock<IDeckFactory>>();
            mockPlayer = fixture.Create<Mock<IPlayer>>();

            ninject = new StandardKernel(new BindingsModule());

            ninject.Rebind<IDice>().ToConstant(mockDice.Object).InSingletonScope();
            ninject.Rebind<IDeckFactory>().ToConstant(mockDeckFactory.Object).InSingletonScope();
            ninject.Rebind<ITaskHandler>().To<TaskHandler>().WithConstructorArgument(PlayerFactory.BuildPlayers(6)); // register six OTHER players

            mockDeckFactory.Setup(x => x.BuildChanceDeck()).Returns(mockDeck.Object);
            mockDeckFactory.Setup(x => x.BuildCommunitiyChestDeck()).Returns(mockDeck.Object);

            turnHandler = ninject.Get<ITurnHandler>();
            player = ninject.Get<IPlayer>();
            realtor = ninject.Get<IRealtor>();

            jailer = ninject.Get<IJailer>();
            taskHandler = ninject.Get<ITaskHandler>();
        }
 public CollectFromBankerTask(int amount, ITaskHandler taskHandler)
 {
     this.taskHandler = taskHandler;
     this.amount = amount;
 }
Exemplo n.º 30
0
 public GetOutOfJailTask(ITaskHandler taskHandler)
 {
     this.taskHandler = taskHandler;
 }
Exemplo n.º 31
0
 /// <summary>
 /// Does nothing. Should be handled by an <see cref="DirectoryStore"/> directly instead of using the service.
 /// </summary>
 public void Verify(ManifestDigest manifestDigest, ITaskHandler handler)
 {}
Exemplo n.º 32
0
 /// <summary>
 /// Does nothing. Should be handled by an <see cref="DirectoryStore"/> directly instead of using the service.
 /// </summary>
 public long Optimise(ITaskHandler handler)
 {
     return 0;
 }
Exemplo n.º 33
0
 /// <summary>
 /// Does nothing. Should be handled by an <see cref="DirectoryStore"/> directly instead of using the service.
 /// </summary>
 public bool Remove(ManifestDigest manifestDigest, ITaskHandler handler)
 {
     return false;
 }
Exemplo n.º 34
0
 /// <inheritdoc/>
 public string AddDirectory(string path, ManifestDigest manifestDigest, ITaskHandler handler)
 {
     try
     {
         string result = GetServiceProxy().AddDirectory(path, manifestDigest, handler);
         Log.Info("Sent implementation to Store Service: " + manifestDigest.Best);
         return result;
     }
         #region Error handling
     catch (RemotingException ex)
     {
         // Wrap exception since only certain exception types are allowed
         throw new IOException(ex.Message, ex);
     }
     catch (SerializationException ex)
     {
         // Wrap exception since only certain exception types are allowed
         throw new IOException(ex.Message, ex);
     }
     #endregion
 }
Exemplo n.º 35
0
        /// <summary>
        /// Registers an application as a candidate for a default program for some service in the current system. This can only be applied machine-wide, not per user.
        /// </summary>
        /// <param name="target">The application being integrated.</param>
        /// <param name="defaultProgram">The default program information to be registered.</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="accessPoint">Indicates that the program should be set as the current default for the service it provides.</param>
        /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
        /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception>
        /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception>
        /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception>
        /// <exception cref="InvalidDataException">The data in <paramref name="defaultProgram"/> is invalid.</exception>
        public static void Register(FeedTarget target, [NotNull] Store.Model.Capabilities.DefaultProgram defaultProgram, [NotNull] ITaskHandler handler, bool accessPoint = false)
        {
            #region Sanity checks
            if (defaultProgram == null)
            {
                throw new ArgumentNullException("defaultProgram");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            if (string.IsNullOrEmpty(defaultProgram.ID))
            {
                throw new InvalidDataException("Missing ID");
            }
            if (string.IsNullOrEmpty(defaultProgram.Service))
            {
                throw new InvalidDataException("Missing Service");
            }

            using (var serviceKey = Registry.LocalMachine.CreateSubKeyChecked(RegKeyMachineClients + @"\" + defaultProgram.Service))
            {
                using (var appKey = serviceKey.CreateSubKeyChecked(defaultProgram.ID))
                {
                    // Add flag to remember whether created for capability or access point
                    appKey.SetValue(accessPoint ? FileType.PurposeFlagAccessPoint : FileType.PurposeFlagCapability, "");

                    appKey.SetValue("", target.Feed.Name);

                    FileType.RegisterVerbCapability(appKey, target, defaultProgram, true, handler);

                    // Set callbacks for Windows SPAD
                    using (var installInfoKey = appKey.CreateSubKeyChecked(RegSubKeyInstallInfo))
                    {
                        string exePath = Path.Combine(Locations.InstallBase, "0install-win.exe").EscapeArgument();
                        installInfoKey.SetValue(RegValueReinstallCommand, exePath + " integrate-app --machine --batch --add=defaults " + target.Uri.ToStringRfc().EscapeArgument());
                        installInfoKey.SetValue(RegValueShowIconsCommand, exePath + " integrate-app --machine --batch --add=icons " + target.Uri.ToStringRfc().EscapeArgument());
                        installInfoKey.SetValue(RegValueHideIconsCommand, exePath + " integrate-app --machine --batch --remove=icons " + target.Uri.ToStringRfc().EscapeArgument());
                        installInfoKey.SetValue(RegValueIconsVisible, 0, RegistryValueKind.DWord);
                    }

                    if (defaultProgram.Service == Store.Model.Capabilities.DefaultProgram.ServiceMail)
                    {
                        var mailToProtocol = new Store.Model.Capabilities.UrlProtocol {
                            Verbs = { new Verb {
                                          Name = Verb.NameOpen
                                      } }
                        };
                        using (var mailToKey = appKey.CreateSubKeyChecked(@"Protocols\mailto"))
                            FileType.RegisterVerbCapability(mailToKey, target, mailToProtocol, true, handler);
                    }
                }

                if (accessPoint)
                {
                    serviceKey.SetValue("", defaultProgram.ID);
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Creates a new bootstrap process.
        /// </summary>
        /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
        /// <param name="gui"><c>true</c> if the application was launched in GUI mode; <c>false</c> if it was launched in command-line mode.</param>
        public BootstrapProcess(ITaskHandler handler, bool gui)
            : base(handler)
        {
            _gui = gui;

            _options = new OptionSet
            {
                {
                    "?|h|help", () => "Show the built-in help text.", _ =>
                    {
                        Handler.Output("Help", HelpText);
                        throw new OperationCanceledException(); // Don't handle any of the other arguments
                    }
                },
                {
                    "batch", () => "Automatically answer questions with defaults when possible. Avoid unnecessary console output (e.g. progress bars).", _ =>
                    {
                        if (Handler.Verbosity >= Verbosity.Verbose)
                        {
                            throw new OptionException("Cannot combine --batch and --verbose", "verbose");
                        }
                        Handler.Verbosity = Verbosity.Batch;
                    }
                },
                {
                    "v|verbose", () => "More verbose output. Use twice for even more verbose output.", _ =>
                    {
                        if (Handler.Verbosity == Verbosity.Batch)
                        {
                            throw new OptionException("Cannot combine --batch and --verbose", "batch");
                        }
                        Handler.Verbosity++;
                    }
                },
                {
                    "no-existing", () => "Do not detect and use existing Zero Install instances. Always use downloaded and cached instance.", _ => _noExisting = true
                },
                {
                    "version=", () => "Select a specific {VERSION} of Zero Install. Implies --no-existing.", (VersionRange range) =>
                    {
                        _version    = range;
                        _noExisting = true;
                    }
                },
                {
                    "feed=", () => "Specify an alternative {FEED} for Zero Install. Must be an absolute URI. Implies --no-existing.", feed =>
                    {
                        Config.SelfUpdateUri = new FeedUri(feed);
                        _noExisting          = true;
                    }
                },
                {
                    "content-dir=", () => "Specifies a {DIRECTORY} to search for feeds and archives to import. The default is a directory called 'content'.", path =>
                    {
                        if (!Directory.Exists(path))
                        {
                            throw new DirectoryNotFoundException($"Directory '{path}' not found.");
                        }
                        _contentDir = path;
                    }
                },
                {
                    "o|offline", () => "Run in off-line mode, not downloading anything.", _ => Config.NetworkUse = NetworkLevel.Offline
                },

                // Disable interspersed arguments (needed for passing arguments through to target)
                {
                    "<>", value =>
                    {
                        _targetArgs.Add(value);

                        // Stop using options parser, treat everything from here on as unknown
                        _options.Clear();
                    }
                }
            };
        }
Exemplo n.º 37
0
 /// <summary>
 /// Creates a new Windows command-line credential provider.
 /// </summary>
 /// <param name="handler">Used to determine whether and how to ask the user for input.</param>
 public WindowsCliCredentialProvider([NotNull] ITaskHandler handler) : base(handler)
 {
 }
Exemplo n.º 38
0
        private async Task CreateVirtualEnvironmentAsync(ITaskHandler taskHandler)
        {
            IPythonInterpreterFactory factory = null;

            bool failed     = true;
            var  baseInterp = _registry.FindInterpreter(_baseInterpreter);

            try {
                factory = await VirtualEnv.CreateAndAddFactory(
                    _site,
                    _registry,
                    _options,
                    _project,
                    _workspace,
                    _virtualEnvPath,
                    baseInterp,
                    _registerAsCustomEnv,
                    _customEnvName,
                    _useVEnv
                    );

                if (factory != null)
                {
                    if (_installReqs && File.Exists(_reqsPath))
                    {
                        await InstallPackagesAsync(taskHandler, factory);
                    }

                    await _site.GetUIThread().InvokeTask(async() => {
                        // Note that for a workspace, VirtualEnv.CreateAndAddFactory
                        // takes care of updating PythonSettings.json, as that is
                        // required in order to obtain the factory. So no need to do
                        // anything here for workspace.
                        if (_project != null)
                        {
                            _project.AddInterpreter(factory.Configuration.Id);
                            if (_setAsCurrent)
                            {
                                _project.SetInterpreterFactory(factory);
                            }
                        }

                        if (_setAsDefault && _options != null)
                        {
                            _options.DefaultInterpreter = factory;
                        }

                        if (_viewInEnvWindow)
                        {
                            await InterpreterListToolWindow.OpenAtAsync(_site, factory);
                        }
                    });
                }

                failed = false;
            } finally {
                _logger?.LogEvent(PythonLogEvent.CreateVirtualEnv, new CreateVirtualEnvInfo()
                {
                    Failed = failed,
                    InstallRequirements = _installReqs,
                    UseVEnv             = _useVEnv,
                    Global                 = _registerAsCustomEnv,
                    LanguageVersion        = baseInterp?.Configuration?.Version.ToString() ?? "",
                    Architecture           = baseInterp?.Configuration?.ArchitectureString ?? "",
                    SetAsDefault           = _setAsDefault,
                    SetAsCurrent           = _setAsCurrent,
                    OpenEnvironmentsWindow = _viewInEnvWindow,
                });
            }

            taskHandler?.Progress.Report(new TaskProgressData()
            {
                CanBeCanceled   = false,
                ProgressText    = Strings.VirtualEnvStatusCenterCreateProgressCompleted,
                PercentComplete = 100,
            });
        }
        /// <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);
            }
        }
 public ImageRetriever(IImageProvider provider, ITaskHandler taskHandler)
 {
     this.provider    = provider;
     this.taskHandler = taskHandler;
 }
Exemplo n.º 41
0
        public static TemporaryDirectory DownloadAndApply([NotNull] this Recipe recipe, [NotNull] ITaskHandler handler, [CanBeNull] ICommandExecutor executor = null)
        {
            #region Sanity checks
            if (recipe == null)
            {
                throw new ArgumentNullException("recipe");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            var downloadedFiles = new List <TemporaryFile>();
            try
            {
                foreach (var step in recipe.Steps.OfType <DownloadRetrievalMethod>())
                {
                    downloadedFiles.Add(step.Download(handler, executor));
                }

                // Apply the recipe
                return(recipe.Apply(downloadedFiles, handler));
            }
            finally
            {
                // Clean up temporary archive files
                foreach (var downloadedFile in downloadedFiles)
                {
                    downloadedFile.Dispose();
                }
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// Adds an AutoPlay handler registration to the current system.
        /// </summary>
        /// <param name="target">The application being integrated.</param>
        /// <param name="autoPlay">The AutoPlay handler information to be applied.</param>
        /// <param name="machineWide">Register the handler machine-wide instead of just for the current user.</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="accessPoint">Indicates that the handler should become the default handler for all <see cref="Store.Model.Capabilities.AutoPlay.Events"/>.</param>
        /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
        /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception>
        /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception>
        /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception>
        /// <exception cref="InvalidDataException">The data in <paramref name="autoPlay"/> is invalid.</exception>
        public static void Register(FeedTarget target, [NotNull] Store.Model.Capabilities.AutoPlay autoPlay, bool machineWide, [NotNull] ITaskHandler handler, bool accessPoint = false)
        {
            #region Sanity checks
            if (autoPlay == null)
            {
                throw new ArgumentNullException(nameof(autoPlay));
            }
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }
            #endregion

            if (string.IsNullOrEmpty(autoPlay.ID))
            {
                throw new InvalidDataException("Missing ID");
            }
            if (autoPlay.Verb == null)
            {
                throw new InvalidDataException("Missing verb");
            }
            if (string.IsNullOrEmpty(autoPlay.Verb.Name))
            {
                throw new InvalidDataException("Missing verb name");
            }
            if (string.IsNullOrEmpty(autoPlay.Provider))
            {
                throw new InvalidDataException("Missing provider");
            }

            var hive = machineWide ? Registry.LocalMachine : Registry.CurrentUser;

            using (var commandKey = hive.CreateSubKeyChecked(FileType.RegKeyClasses + @"\" + FileType.RegKeyPrefix + ".AutoPlay" + autoPlay.ID + @"\shell\" + autoPlay.Verb.Name + @"\command"))
                commandKey.SetValue("", FileType.GetLaunchCommandLine(target, autoPlay.Verb, machineWide, handler));

            using (var handlerKey = hive.CreateSubKeyChecked(RegKeyHandlers + @"\" + FileType.RegKeyPrefix + autoPlay.ID))
            {
                // Add flag to remember whether created for capability or access point
                handlerKey.SetValue(accessPoint ? FileType.PurposeFlagAccessPoint : FileType.PurposeFlagCapability, "");

                handlerKey.SetValue(RegValueProgID, FileType.RegKeyPrefix + ".AutoPlay" + autoPlay.ID);
                handlerKey.SetValue(RegValueVerb, autoPlay.Verb.Name);
                handlerKey.SetValue(RegValueProvider, autoPlay.Provider);
                handlerKey.SetValue(RegValueDescription, autoPlay.Descriptions.GetBestLanguage(CultureInfo.CurrentUICulture) ?? autoPlay.Verb.Name);

                var icon = autoPlay.GetIcon(Icon.MimeTypeIco) ?? target.Feed.GetIcon(Icon.MimeTypeIco, autoPlay.Verb.Command);
                if (icon != null)
                {
                    handlerKey.SetValue(RegValueIcon, IconProvider.GetIconPath(icon, handler, machineWide) + ",0");
                }
            }

            foreach (var autoPlayEvent in autoPlay.Events.Except(x => string.IsNullOrEmpty(x.Name)))
            {
                using (var eventKey = hive.CreateSubKeyChecked(RegKeyAssocs + @"\" + autoPlayEvent.Name))
                    eventKey.SetValue(FileType.RegKeyPrefix + autoPlay.ID, "");

                if (accessPoint)
                {
                    using (var chosenEventKey = hive.CreateSubKeyChecked(RegKeyChosenAssocs + @"\" + autoPlayEvent.Name))
                        chosenEventKey.SetValue("", FileType.RegKeyPrefix + autoPlay.ID);
                }
            }
        }
Exemplo n.º 43
0
        public static TemporaryDirectory LocalApply([NotNull] this DownloadRetrievalMethod retrievalMethod, string localPath, [NotNull] ITaskHandler handler, [CanBeNull] ICommandExecutor executor = null)
        {
            #region Sanity checks
            if (retrievalMethod == null)
            {
                throw new ArgumentNullException("retrievalMethod");
            }
            if (string.IsNullOrEmpty(localPath))
            {
                throw new ArgumentNullException("localPath");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            if (executor == null)
            {
                executor = new SimpleCommandExecutor();
            }

            // Set local file size
            long newSize = new FileInfo(localPath).Length;
            if (retrievalMethod.Size != newSize)
            {
                executor.Execute(new SetValueCommand <long>(() => retrievalMethod.Size, value => retrievalMethod.Size = value, newSize));
            }

            var extractionDir = new TemporaryDirectory("0publish");
            try
            {
                new PerTypeDispatcher <DownloadRetrievalMethod>(ignoreMissing: true)
                {
                    // ReSharper disable AccessToDisposedClosure
                    (Archive archive) =>
                    {
                        // Guess MIME types now because the file ending is not known later
                        if (string.IsNullOrEmpty(archive.MimeType))
                        {
                            string mimeType = Archive.GuessMimeType(localPath);
                            executor.Execute(new SetValueCommand <string>(() => archive.MimeType, value => archive.MimeType = value, mimeType));
                        }

                        archive.Apply(localPath, extractionDir, handler);
                    },
                    (SingleFile file) =>
                    {
                        // Guess file name based on local path
                        if (string.IsNullOrEmpty(file.Destination))
                        {
                            string destination = Path.GetFileName(localPath);
                            executor.Execute(new SetValueCommand <string>(() => file.Destination, value => file.Destination = value, destination));
                        }

                        file.Apply(localPath, extractionDir, handler);
                    }
                    // ReSharper restore AccessToDisposedClosure
                }.Dispatch(retrievalMethod);
            }
            #region Error handling
            catch
            {
                extractionDir.Dispose();
                throw;
            }
            #endregion

            return(extractionDir);
        }
Exemplo n.º 44
0
 /// <inheritdoc/>
 public string AddArchives(IEnumerable <ArchiveFileInfo> archiveInfos, ManifestDigest manifestDigest, ITaskHandler handler)
 {
     try
     {
         string result = GetProxy().AddArchives(archiveInfos, manifestDigest, handler);
         Log.Info("Sent implementation to Store Service: " + manifestDigest.Best);
         return(result);
     }
     #region Error handling
     catch (RemotingException ex)
     {
         // Wrap exception since only certain exception types are allowed
         throw new IOException(ex.Message, ex);
     }
     catch (SerializationException ex)
     {
         // Wrap exception since only certain exception types are allowed
         throw new IOException(ex.Message, ex);
     }
     #endregion
 }
Exemplo n.º 45
0
        public static TemporaryDirectory DownloadAndApply([NotNull] this DownloadRetrievalMethod retrievalMethod, [NotNull] ITaskHandler handler, [CanBeNull] ICommandExecutor executor = null)
        {
            #region Sanity checks
            if (retrievalMethod == null)
            {
                throw new ArgumentNullException("retrievalMethod");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            using (var downloadedFile = retrievalMethod.Download(handler, executor))
            {
                var extractionDir = new TemporaryDirectory("0publish");
                try
                {
                    new PerTypeDispatcher <DownloadRetrievalMethod>(ignoreMissing: false)
                    {
                        // ReSharper disable AccessToDisposedClosure
                        (Archive archive) => archive.Apply(downloadedFile, extractionDir, handler),
                        (SingleFile file) => file.Apply(downloadedFile, extractionDir, handler)
                        // ReSharper restore AccessToDisposedClosure
                    }.Dispatch(retrievalMethod);
                }
                #region Error handling
                catch
                {
                    extractionDir.Dispose();
                    throw;
                }
                #endregion

                return(extractionDir);
            }
        }
Exemplo n.º 46
0
 /// <summary>
 /// Does nothing. Should be handled by an <see cref="DiskImplementationStore"/> directly instead of using the service.
 /// </summary>
 public bool Remove(ManifestDigest manifestDigest, ITaskHandler handler) => false;
Exemplo n.º 47
0
        /// <summary>
        /// Creates a new trust manager.
        /// </summary>
        /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
        /// <param name="openPgp">The OpenPGP-compatible system used to validate the signatures.</param>
        /// <param name="trustDB">A database of OpenPGP signature fingerprints the users trusts to sign <see cref="Feed"/>s coming from specific domains.</param>
        /// <param name="feedCache">Provides access to a cache of <see cref="Feed"/>s that were downloaded via HTTP(S).</param>
        /// <param name="handler">A callback object used when the the user needs to be asked questions.</param>
        public TrustManager([NotNull] Config config, [NotNull] IOpenPgp openPgp, [NotNull] TrustDB trustDB, [NotNull] IFeedCache feedCache, [NotNull] ITaskHandler handler)
        {
            #region Sanity checks
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (openPgp == null)
            {
                throw new ArgumentNullException(nameof(openPgp));
            }
            if (trustDB == null)
            {
                throw new ArgumentNullException(nameof(trustDB));
            }
            if (feedCache == null)
            {
                throw new ArgumentNullException(nameof(feedCache));
            }
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }
            #endregion

            _config    = config;
            _openPgp   = openPgp;
            _trustDB   = trustDB;
            _feedCache = feedCache;
            _handler   = handler;
        }
Exemplo n.º 48
0
 /// <summary>
 /// Does nothing. Should be handled by an <see cref="DiskImplementationStore"/> directly instead of using the service.
 /// </summary>
 public long Optimise(ITaskHandler handler) => 0;
Exemplo n.º 49
0
        /// <summary>
        /// Registers a file type in the current system.
        /// </summary>
        /// <param name="target">The application being integrated.</param>
        /// <param name="fileType">The file type to register.</param>
        /// <param name="machineWide">Register the file type machine-wide instead of just for the current user.</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="accessPoint">Indicates that the file associations shall become default handlers for their respective types.</param>
        /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
        /// <exception cref="IOException">A problem occurs while writing to the filesystem.</exception>
        /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception>
        /// <exception cref="UnauthorizedAccessException">Write access to the filesystem is not permitted.</exception>
        /// <exception cref="InvalidDataException">The data in <paramref name="fileType"/> is invalid.</exception>
        public static void Register(FeedTarget target, [NotNull] Store.Model.Capabilities.FileType fileType, bool machineWide, [NotNull] ITaskHandler handler, bool accessPoint = false)
        {
            #region Sanity checks
            if (fileType == null)
            {
                throw new ArgumentNullException("fileType");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            if (string.IsNullOrEmpty(fileType.ID))
            {
                throw new InvalidDataException("Missing ID");
            }

            // TODO: Implement
        }
Exemplo n.º 50
0
 /// <summary>
 /// Creates a new feed manager.
 /// </summary>
 /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
 /// <param name="feedCache">The disk-based cache to store downloaded <see cref="Feed"/>s.</param>
 /// <param name="trustManager">Methods for verifying signatures and user trust.</param>
 /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
 public FeedManager(Config config, IFeedCache feedCache, ITrustManager trustManager, ITaskHandler handler)
 {
     _config       = config ?? throw new ArgumentNullException(nameof(config));
     _feedCache    = feedCache ?? throw new ArgumentNullException(nameof(feedCache));
     _trustManager = trustManager ?? throw new ArgumentNullException(nameof(trustManager));
     _handler      = handler ?? throw new ArgumentNullException(nameof(handler));
 }
Exemplo n.º 51
0
        /// <inheritdoc/>
        public string AddArchives(IEnumerable <ArchiveFileInfo> archiveInfos, ManifestDigest manifestDigest, ITaskHandler handler)
        {
            #region Sanity checks
            if (archiveInfos == null)
            {
                throw new ArgumentNullException(nameof(archiveInfos));
            }
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }
            #endregion

            Flush();

            if (Contains(manifestDigest))
            {
                throw new ImplementationAlreadyInStoreException(manifestDigest);
            }

            // Find the last store the implementation can be added to (some might be write-protected)
            Exception innerException = null;
            foreach (var store in _stores.Reverse())
            {
                try
                {
                    // Try to add implementation to this store
                    return(store.AddArchives(archiveInfos, manifestDigest, handler));
                }
                #region Error handling
                catch (IOException ex)
                {
                    innerException = ex; // Remember the last error
                }
                catch (UnauthorizedAccessException ex)
                {
                    innerException = ex; // Remember the last error
                }
                catch (RemotingException ex)
                {
                    innerException = ex; // Remember the last error
                }
                #endregion
            }

            // If we reach this, the implementation couldn't be added to any store
            throw innerException?.PreserveStack()
                  ?? new InvalidOperationException();
        }
Exemplo n.º 52
0
 /// <summary>
 /// Creates a new catalog manager.
 /// </summary>
 /// <param name="trustManager">Methods for verifying signatures and user trust.</param>
 /// <param name="handler">A callback object used when the the user needs to be informed about progress.</param>
 public CatalogManager(ITrustManager trustManager, ITaskHandler handler)
 {
     _trustManager = trustManager ?? throw new ArgumentNullException(nameof(trustManager));
     _handler      = handler ?? throw new ArgumentNullException(nameof(handler));
 }
Exemplo n.º 53
0
        /// <summary>
        /// Creates a new Windows shortcut on the desktop.
        /// </summary>
        /// <param name="desktopIcon">Information about the shortcut to be created.</param>
        /// <param name="target">The target the shortcut shall point to.</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">Create the shortcut machine-wide instead of just for the current user.</param>
        public static void Create([NotNull] DesktopIcon desktopIcon, FeedTarget target, [NotNull] ITaskHandler handler, bool machineWide = false)
        {
            #region Sanity checks
            if (desktopIcon == null)
            {
                throw new ArgumentNullException("desktopIcon");
            }
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            #endregion

            string filePath = GetDesktopPath(desktopIcon.Name, machineWide);
            Create(filePath, target, desktopIcon.Command, handler, machineWide);
        }
Exemplo n.º 54
0
 /// <summary>
 /// Does nothing. Should be handled by an administrator directly instead of using the service.
 /// </summary>
 public override void Verify(ManifestDigest manifestDigest, ITaskHandler handler)
 {
 }
Exemplo n.º 55
0
 /// <summary>
 /// Verify this implementation is undamaged.
 /// </summary>
 /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about IO tasks.</param>
 /// <exception cref="OperationCanceledException">The user canceled the task.</exception>
 /// <exception cref="IOException">The entry's directory could not be processed.</exception>
 /// <exception cref="UnauthorizedAccessException">Read access to the entry's directory is not permitted.</exception>
 public void Verify([NotNull] ITaskHandler handler)
 {
     Store.Verify(_digest, handler);
 }
Exemplo n.º 56
0
 public SqlStatusReporter(ILocalConfiguration configuration, ITaskHandler taskHandler)
 {
     LocalConfiguration = configuration;
     WindowTaskHandler  = taskHandler;
 }
Exemplo n.º 57
0
        /// <inheritdoc/>
        protected override string VerifyAndAdd(string tempID, ManifestDigest expectedDigest, ITaskHandler handler)
        {
            #region Sanity checks
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }
            #endregion

            var callingIdentity = WindowsIdentity.GetCurrent();
            Debug.Assert(callingIdentity != null);

            using (_serviceIdentity.Impersonate()) // Use system rights instead of calling user
            {
                try
                {
                    var tempDirectory = new DirectoryInfo(System.IO.Path.Combine(Path, tempID));
                    try
                    {
                        handler.RunTask(new SimpleTask($"{Resources.SettingFilePermissions} ({expectedDigest.Best})", tempDirectory.ResetAcl)
                        {
                            Tag = expectedDigest.Best
                        });
                    }
                    catch (IndexOutOfRangeException)
                    {
                        // Workaround for .NET 2.0 bug
                    }

                    string result = base.VerifyAndAdd(tempID, expectedDigest, handler);
                    Log.Info(string.Format(Resources.SuccessfullyAddedImplementation, callingIdentity.Name, expectedDigest.AvailableDigests.FirstOrDefault(), Path));
                    return(result);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format(Resources.FailedToAddImplementation, callingIdentity.Name, expectedDigest.AvailableDigests.FirstOrDefault(), Path) + Environment.NewLine + ex.Message);
                    throw;
                }
            }
        }
Exemplo n.º 58
0
 /// <summary>
 /// Creates a new trust manager.
 /// </summary>
 /// <param name="config">User settings controlling network behaviour, solving, etc.</param>
 /// <param name="openPgp">The OpenPGP-compatible system used to validate the signatures.</param>
 /// <param name="trustDB">A database of OpenPGP signature fingerprints the users trusts to sign <see cref="Feed"/>s coming from specific domains.</param>
 /// <param name="feedCache">Provides access to a cache of <see cref="Feed"/>s that were downloaded via HTTP(S).</param>
 /// <param name="handler">A callback object used when the the user needs to be asked questions.</param>
 public TrustManager(Config config, IOpenPgp openPgp, TrustDB trustDB, IFeedCache feedCache, ITaskHandler handler)
 {
     _config    = config ?? throw new ArgumentNullException(nameof(config));
     _openPgp   = openPgp ?? throw new ArgumentNullException(nameof(openPgp));
     _trustDB   = trustDB ?? throw new ArgumentNullException(nameof(trustDB));
     _feedCache = feedCache ?? throw new ArgumentNullException(nameof(feedCache));
     _handler   = handler ?? throw new ArgumentNullException(nameof(handler));
 }
Exemplo n.º 59
0
 /// <summary>
 /// Creates a new command base.
 /// </summary>
 /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
 protected ScopedOperation(ITaskHandler handler)
     : base(handler)
 {
 }
Exemplo n.º 60
0
 public TasksController(ITaskHandler taskHandler, IInterpreter interpreter)
 {
     this.taskHandler = taskHandler;
     this.interpreter = interpreter;
 }