示例#1
0
        public IAsyncEnumerable <SoftwareIdentity> InstallPackage(SoftwareIdentity softwareIdentity, IRequestObject requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            if (softwareIdentity == null)
            {
                throw new ArgumentNullException("softwareIdentity");
            }
            var hostApi = requestObject.As <IHostApi>();

            // if the provider didn't say this was trusted, we should ask the user if it's ok.
            if (!softwareIdentity.FromTrustedSource)
            {
                try {
                    if (!hostApi.ShouldContinueWithUntrustedPackageSource(softwareIdentity.Name, softwareIdentity.Source))
                    {
                        hostApi.Warning(hostApi.FormatMessageString(Constants.Messages.UserDeclinedUntrustedPackageInstall, softwareIdentity.Name));
                        return(new EmptyAsyncEnumerable <SoftwareIdentity>());
                    }
                } catch {
                    return(new EmptyAsyncEnumerable <SoftwareIdentity>());
                }
            }

            return(new SoftwareIdentityRequestObject(this, requestObject.As <IHostApi>(), request => Provider.InstallPackage(softwareIdentity.FastPackageReference, request), Constants.PackageStatus.Installed));
        }
示例#2
0
        public void GetDynamicOptions(string category, IRequestObject requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            using (var request = requestObject.As <BootstrapRequest>()) {
                try {
                    request.Debug("Calling 'Bootstrap::GetDynamicOptions ({0})'", category);

                    switch ((category ?? string.Empty).ToLowerInvariant())
                    {
                    case "package":
                        // request.YieldDynamicOption( "ForceCheck", OptionType.Switch, false);

                        break;

                    case "source":
                        break;

                    case "install":
                        request.YieldDynamicOption("DestinationPath", OptionType.Folder.ToString(), true);
                        break;
                    }
                } catch {
                    // this makes it ignore new OptionCategories that it doesn't know about.
                }
            }
        }
示例#3
0
        /// <summary>
        /// Returns a collection of strings to the client advertizing features this provider supports.
        /// </summary>
        /// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
        public void GetFeatures(IRequestObject requestObject)
        {
            try {
                // create a strongly-typed request object.
                using (var request = requestObject.As <T>()) {
                    // Nice-to-have put a debug message in that tells what's going on.
                    request.Debug("Calling '{0}::GetFeatures' ", ProviderName);

                    // Check to see if we're ok to proceed.
                    if (!request.IsReady(false))
                    {
                        return;
                    }

                    foreach (var feature in _features)
                    {
                        request.Yield(feature);
                    }
                }
            }
            catch (Exception e) {
                // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
                // Really this is just here as a precautionary to behave correctly.
                // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
                Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::GetFeatures' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
            }
        }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
        public void InstallPackage(string fastPackageReference, IRequestObject requestObject)
        {
            try {
                // create a strongly-typed request object.
                using (var request = requestObject.As <T>()) {
                    // Nice-to-have put a debug message in that tells what's going on.
                    request.Debug("Calling '{0}::InstallPackage' '{1}'", ProviderName, fastPackageReference);

                    // Check to see if we're ok to proceed.
                    if (!request.IsReady(true))
                    {
                        return;
                    }

                    var pkgRef = request.GetPackageByFastpath(fastPackageReference);
                    if (pkgRef == null)
                    {
                        request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
                        return;
                    }

                    var dependencies = request.GetUninstalledPackageDependencies(pkgRef).Reverse().ToArray();
                    int progressId   = 0;

                    if (dependencies.Length > 0)
                    {
                        progressId = request.StartProgress(0, "Installing package '{0}'", pkgRef.GetCanonicalId(request));
                    }
                    var n = 0;
                    foreach (var d in dependencies)
                    {
                        request.Progress(progressId, (n * 100 / (dependencies.Length + 1)) + 1, "Installing dependent package '{0}'", d.GetCanonicalId(request));
                        if (!request.InstallSinglePackage(d))
                        {
                            request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.DependentPackageFailedInstall, d.GetCanonicalId(request));
                            return;
                        }
                        n++;
                        request.Progress(progressId, (n * 100 / (dependencies.Length + 1)), "Installed dependent package '{0}'", d.GetCanonicalId(request));
                    }

                    // got this far, let's install the package we came here for.
                    if (!request.InstallSinglePackage(pkgRef))
                    {
                        // package itself didn't install.
                        // roll that back out everything we did install.
                        // and get out of here.
                        request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.PackageFailedInstall, pkgRef.GetCanonicalId(request));
                        request.CompleteProgress(progressId, false);
                    }
                    request.CompleteProgress(progressId, true);
                }
            }
            catch (Exception e) {
                // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
                // Really this is just here as a precautionary to behave correctly.
                // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
                Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::InstallPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
            }
        }
示例#5
0
        /// <summary>
        /// Removes/Unregisters a package source
        /// </summary>
        /// <param name="name">The name or location of a package source to remove.</param>
        /// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
        public void RemovePackageSource(string name, IRequestObject requestObject)
        {
            try {
                // create a strongly-typed request object.
                using (var request = requestObject.As <T>()) {
                    // Nice-to-have put a debug message in that tells what's going on.
                    request.Debug("Calling '{0}::RemovePackageSource' '{1}'", ProviderName, name);

                    var src = request.FindRegisteredSource(name);
                    if (src == null)
                    {
                        request.Warning(Constants.Messages.UnableToResolveSource, name);
                        return;
                    }

                    request.RemovePackageSource(src.Name);
                    request.YieldPackageSource(src.Name, src.Location, src.Trusted, false, src.IsValidated);
                }
            }
            catch (Exception e) {
                // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
                // Really this is just here as a precautionary to behave correctly.
                // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
                Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::RemovePackageSource' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
            }
        }
示例#6
0
        public void InitializeProvider(RequestImpl requestImpl)
        {
            if (requestImpl == null)
            {
                throw new ArgumentNullException("requestImpl");
            }

            var req = requestImpl.As <Request>();

            req.Debug("Initializing PowerShell MetaProvider");

            // to do : get modules to load (from configuration ?)
            var modules = ScanForModules(req).ToArray();

            req.Debug("Scanned for PowerShell Provider Modules ");

            // try to create each module at least once.
            Parallel.ForEach(modules, modulePath => {
                var provider = Create(modulePath);
                if (provider != null)
                {
                    if (provider.GetPackageProviderName() != null)
                    {
                        // looks good to me, let's add this to the list of moduels this meta provider can create.
                        _packageProviders.AddOrSet(provider.GetPackageProviderName(), provider);
                    }
                    else
                    {
                        provider.Dispose();
                        provider = null;
                    }
                }
            });
            req.Debug("Loaded PowerShell Provider Modules ");
        }
示例#7
0
        public void DownloadFile(Uri remoteLocation, string localFilename, IRequestObject requestObject)
        {
            Activity();

            // check the Uri type, see if we have anyone who can handle that
            // if so, call that provider's download file
            if (remoteLocation == null)
            {
                throw new ArgumentNullException("remoteLocation");
            }
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            using (var request = requestObject.As <Request>()) {
                foreach (var downloader in PackageManager._instance.Downloaders.Values)
                {
                    if (downloader.SupportedUriSchemes.Contains(remoteLocation.Scheme, StringComparer.OrdinalIgnoreCase))
                    {
                        downloader.DownloadFile(remoteLocation, localFilename, request);
                        return;
                    }
                }
                request.Error(ErrorCategory.NotImplemented, Constants.Messages.ProtocolNotSupported, remoteLocation.Scheme, Constants.Messages.ProtocolNotSupported, remoteLocation.Scheme);
            }
        }
示例#8
0
        public override void GetDynamicOptions(string category, IRequestObject requestObject)
        {
            using (var request = requestObject.As <ChocolateyRequest>()) {
                try {
                    request.Debug("Calling '{0}::GetDynamicOptions' '{1}'", ProviderName, category);

                    switch ((category ?? string.Empty).ToLowerInvariant())
                    {
                    case "package":
                        request.YieldDynamicOption("FilterOnTag", global::OneGet.ProviderSDK.Constants.OptionType.StringArray, false);
                        request.YieldDynamicOption("Contains", global::OneGet.ProviderSDK.Constants.OptionType.String, false);
                        request.YieldDynamicOption("AllowPrereleaseVersions", global::OneGet.ProviderSDK.Constants.OptionType.Switch, false);
                        break;

                    case "source":
                        request.YieldDynamicOption("ConfigFile", global::OneGet.ProviderSDK.Constants.OptionType.String, false);
                        request.YieldDynamicOption("SkipValidate", global::OneGet.ProviderSDK.Constants.OptionType.Switch, false);
                        break;

                    case "install":
                        request.YieldDynamicOption("SkipDependencies", global::OneGet.ProviderSDK.Constants.OptionType.Switch, false);
                        request.YieldDynamicOption("ContinueOnFailure", global::OneGet.ProviderSDK.Constants.OptionType.Switch, false);
                        request.YieldDynamicOption("ExcludeVersion", global::OneGet.ProviderSDK.Constants.OptionType.Switch, false);
                        request.YieldDynamicOption("PackageSaveMode", global::OneGet.ProviderSDK.Constants.OptionType.String, false, new[] {
                            "nuspec", "nupkg", "nuspec;nupkg"
                        });
                        break;
                    }
                }
                catch {
                    // this makes it ignore new OptionCategories that it doesn't know about.
                }
            }
        }
示例#9
0
        /*
         * private IEnumerable<SoftwareIdentity> FindPackagesByUrisImpl(CancellationTokenSource cancellationTokenSource, Uri[] uris, IRequestObject requestObject) {
         *  var id = StartFind(requestObject);
         *  foreach (var uri in uris) {
         *      foreach (var pkg in FindPackageByUri(uri, id.Value, requestObject).TakeWhile(pkg => !cancellationTokenSource.IsCancellationRequested)) {
         *          yield return pkg;
         *      }
         *      foreach (var pkg in CompleteFind(id.Value, requestObject).TakeWhile(pkg => !cancellationTokenSource.IsCancellationRequested)) {
         *          yield return pkg;
         *      }
         *  }
         * }
         */

        public IAsyncEnumerable <SoftwareIdentity> FindPackagesByFiles(string[] filenames, IRequestObject requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

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

            if (filenames.Length == 0)
            {
                return(new EmptyAsyncEnumerable <SoftwareIdentity>());
            }

            if (filenames.Length == 1)
            {
                return(FindPackageByFile(filenames[0], 0, requestObject));
            }

            return(new SoftwareIdentityRequestObject(this, requestObject.As <IHostApi>(), request => {
                var id = StartFind(request);
                foreach (var file in filenames)
                {
                    Provider.FindPackageByFile(file, id.Value, request);
                }
                Provider.CompleteFind(id.Value, request);
            }, Constants.PackageStatus.Available));
        }
示例#10
0
        public string GetKnownFolder(string knownFolder, RequestImpl requestImpl)
        {
            if (requestImpl == null)
            {
                throw new ArgumentNullException("requestImpl");
            }

            using (var request = requestImpl.As <Request>()) {
                request.Debug("Calling 'CommonServiceProvider::GetKnownFolder'");
                if (!string.IsNullOrEmpty(knownFolder))
                {
                    if (knownFolder.Equals("tmp", StringComparison.OrdinalIgnoreCase) || knownFolder.Equals("temp", StringComparison.OrdinalIgnoreCase))
                    {
                        return(FilesystemExtensions.TempPath);
                    }
                    KnownFolder folder;
                    if (Enum.TryParse(knownFolder, true, out folder))
                    {
                        return(KnownFolders.GetFolderPath(folder));
                    }
                }

                request.Error(ErrorCategory.InvalidArgument, knownFolder, Constants.UnknownFolderId, knownFolder);
            }
            return(null);
        }
示例#11
0
 /// <summary>
 ///     Finds packages given a locally-accessible filename
 ///     Package information must be returned using <c>request.YieldPackage(...)</c> function.
 /// </summary>
 /// <param name="file">the full path to the file to determine if it is a package</param>
 /// <param name="id">
 ///     if this is greater than zero (and the number should have been generated using <c>StartFind(...)</c>,
 ///     the core is calling this multiple times to do a batch search request. The operation can be delayed until
 ///     <c>CompleteFind(...)</c> is called
 /// </param>
 /// <param name="requestImpl">
 ///     An object passed in from the CORE that contains functions that can be used to interact with
 ///     the CORE and HOST
 /// </param>
 public void FindPackageByFile(string file, int id, RequestImpl requestImpl)
 {
     try {
         // create a strongly-typed request object.
         using (var request = requestImpl.As <Request>()) {
             // Nice-to-have put a debug message in that tells what's going on.
             request.Debug("Calling '{0}::FindPackageByFile' '{1}','{2}'", ProviderName, file, id);
             if (!file.FileExists())
             {
                 request.Error(ErrorCategory.ObjectNotFound, file, Constants.Messages.UnableToResolvePackage, file);
                 return;
             }
             try {
                 var package = new InstallPackage(file, DatabaseOpenMode.ReadOnly);
                 YieldPackage(package, file, request);
                 package.Close();
             } catch (Exception e) {
                 e.Dump();
                 // any exception at this point really just means that
                 request.Error(ErrorCategory.OpenError, file, Constants.Messages.UnableToResolvePackage, file);
             }
         }
     } catch (Exception e) {
         // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
         // Really this is just here as a precautionary to behave correctly.
         // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
         Debug.WriteLine("Unexpected Exception thrown in '{0}::FindPackageByFile' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace);
     }
 }
示例#12
0
        public void SetEnvironmentVariable(string variable, string value, int context, RequestImpl requestImpl)
        {
            if (requestImpl == null)
            {
                throw new ArgumentNullException("requestImpl");
            }

            using (var request = requestImpl.As <Request>()) {
                request.Debug("Calling 'CommonServiceProvider::SetEnvironmentVariable'");
                if (string.IsNullOrEmpty(value))
                {
                    RemoveEnvironmentVariable(variable, context, requestImpl);
                }

                switch ((EnvironmentContext)context)
                {
                case EnvironmentContext.System:
                    if (!IsElevated(requestImpl))
                    {
                        request.Warning("SetEnvironmentVariable Failed - Admin Elevation required to set variable '{0}' in machine context", variable);
                        return;
                    }
                    request.Verbose("SetEnvironmentVariable (machine) '{0}' = '{1}'", variable, value);
                    Environment.SetEnvironmentVariable(variable, value, EnvironmentVariableTarget.Machine);
                    break;

                default:
                    request.Verbose("SetEnvironmentVariable (user) '{0}' = '{1}'", variable, value);
                    Environment.SetEnvironmentVariable(variable, value, EnvironmentVariableTarget.User);
                    break;
                }
                Environment.SetEnvironmentVariable(variable, null, EnvironmentVariableTarget.Process);
            }
        }
示例#13
0
 public void InitializeProvider(RequestImpl requestImpl)
 {
     using (var request = requestImpl.As <Request>()) {
         // use the request object to interact with the OneGet core:
         request.Debug("Calling 'InitializeProvider'");
     }
 }
示例#14
0
        public IEnumerable <PackageProvider> SelectProviders(string providerName, RequestImpl requestImpl)
        {
            if (providerName.Is())
            {
                // strict name match for now.
                if (_packageProviders.ContainsKey(providerName))
                {
                    return(_packageProviders[providerName].SingleItemAsEnumerable().ByRef());
                }

                if (requestImpl != null)
                {
                    // if the end user requested a provider that's not there. perhaps the bootstrap provider can find it.
                    if (RequirePackageProvider(null, providerName, Constants.MinVersion, requestImpl))
                    {
                        // seems to think we found it.
                        if (_packageProviders.ContainsKey(providerName))
                        {
                            return(_packageProviders[providerName].SingleItemAsEnumerable().ByRef());
                        }
                    }
                    var hostApi = requestImpl.As <IHostApi>();

                    // warn the user that that provider wasn't found.
                    hostApi.Warning(hostApi.FormatMessageString(Constants.UnknownProvider, providerName));
                }
                return(Enumerable.Empty <PackageProvider>().ByRef());
            }

            return(PackageProviders.ByRef());
        }
示例#15
0
文件: As.cs 项目: ColinZeb/Snippets
        /// <summary>
        /// Determines whether [is] [the specified object].
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The object.</param>
        /// <returns><c>true</c> if [is] [the specified object]; otherwise, <c>false</c>.</returns>
        /// <exception cref="System.NullReferenceException">obj</exception>
        public static bool Is <T>(this Object obj)
        {
            if (obj == null)
            {
                throw new NullReferenceException("obj");
            }

            if (typeof(T) == typeof(string))
            {
                return(true);
            }

            if (obj.GetType() == typeof(string) && typeof(T).IsValueType)
            {
                try
                {
                    obj.As <T>();
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(typeof(T).IsAssignableFrom(obj.GetType()));
        }
示例#16
0
        public void CopyFile(string sourcePath, string destinationPath, IRequestObject requestObject)
        {
            Activity();

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

            using (var request = requestObject.As <Request>()) {
                request.Debug("Calling 'ProviderService::CopyFile'");
                if (sourcePath == null)
                {
                    throw new ArgumentNullException("sourcePath");
                }
                if (destinationPath == null)
                {
                    throw new ArgumentNullException("destinationPath");
                }
                if (File.Exists(destinationPath))
                {
                    destinationPath.TryHardToDelete();
                    if (File.Exists(destinationPath))
                    {
                        request.Error(ErrorCategory.OpenError, destinationPath, Constants.Messages.UnableToOverwriteExistingFile, destinationPath);
                    }
                }
                File.Copy(sourcePath, destinationPath);
                if (!File.Exists(destinationPath))
                {
                    request.Error(ErrorCategory.InvalidResult, destinationPath, Constants.Messages.UnableToCopyFileTo, destinationPath);
                }
            }
        }
        public IEnumerable <PackageProvider> SelectProviders(string providerName, IRequestObject requestObject)
        {
            if (providerName.Is())
            {
                // match with wildcards
                var results = _packageProviders.Values.Where(each => each.ProviderName.IsWildcardMatch(providerName)).ReEnumerable();
                if (results.Any())
                {
                    return(results.ByRef());
                }
                if (requestObject != null && !providerName.ContainsWildcards())
                {
                    // if the end user requested a provider that's not there. perhaps the bootstrap provider can find it.
                    if (RequirePackageProvider(null, providerName, Constants.MinVersion, requestObject))
                    {
                        // seems to think we found it.
                        if (_packageProviders.ContainsKey(providerName))
                        {
                            return(_packageProviders[providerName].SingleItemAsEnumerable().ByRef());
                        }
                    }
                    var hostApi = requestObject.As <IHostApi>();

                    // warn the user that that provider wasn't found.
                    hostApi.Warning(hostApi.FormatMessageString(Constants.Messages.UnknownProvider, providerName));
                }
                return(Enumerable.Empty <PackageProvider>().ByRef());
            }

            return(PackageProviders.ByRef());
        }
示例#18
0
        /// <summary>
        ///     Returns dynamic option definitions to the HOST
        /// </summary>
        /// <param name="category">The category of dynamic options that the HOST is interested in</param>
        /// <param name="requestObject">
        ///     An object passed in from the CORE that contains functions that can be used to interact with
        ///     the CORE and HOST
        /// </param>
        public void GetDynamicOptions(string category, IRequestObject requestObject)
        {
            try {
                // create a strongly-typed request object.
                using (var request = requestObject.As <Request>()) {
                    // Nice-to-have put a debug message in that tells what's going on.
                    request.Debug("Calling '{0}::GetDynamicOptions' '{1}'", ProviderName, category);

                    switch ((category ?? string.Empty).ToLowerInvariant())
                    {
                    case "install":
                        // options required for install/uninstall/getinstalledpackages
                        break;

                    case "provider":
                        // options used with this provider. Not currently used.
                        break;

                    case "source":
                        // options for package sources
                        break;

                    case "package":
                        // options used when searching for packages
                        break;
                    }
                }
            } catch (Exception e) {
                // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
                // Really this is just here as a precautionary to behave correctly.
                // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
                Debug.WriteLine("Unexpected Exception thrown in '{0}::GetDynamicOptions' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace);
            }
        }
示例#19
0
        /*
         * private IEnumerable<SoftwareIdentity> FindPackagesImpl(CancellationTokenSource cancellationTokenSource, string[] names, string requiredVersion, string minimumVersion, string maximumVersion, IRequestObject requestObject) {
         *  var id = StartFind(requestObject);
         *  foreach (var name in names) {
         *      foreach (var pkg in FindPackage(name, requiredVersion, minimumVersion, maximumVersion, id, requestObject).TakeWhile(pkg => !cancellationTokenSource.IsCancellationRequested)) {
         *          yield return pkg;
         *      }
         *      foreach (var pkg in CompleteFind(id, requestObject).TakeWhile(pkg => !cancellationTokenSource.IsCancellationRequested)) {
         *          yield return pkg;
         *      }
         *  }
         * }
         */

        public IAsyncEnumerable <SoftwareIdentity> FindPackagesByUris(Uri[] uris, IRequestObject requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

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

            if (uris.Length == 0)
            {
                return(new EmptyAsyncEnumerable <SoftwareIdentity>());
            }

            if (uris.Length == 1)
            {
                return(FindPackageByUri(uris[0], 0, requestObject));
            }

            return(new SoftwareIdentityRequestObject(this, requestObject.As <IHostApi>(), request => {
                var id = StartFind(request);
                foreach (var uri in uris)
                {
                    Provider.FindPackageByUri(uri, id.Value, request);
                }
                Provider.CompleteFind(id.Value, request);
            }, Constants.PackageStatus.Available));
        }
示例#20
0
        public IAsyncEnumerable <SoftwareIdentity> FindPackages(string[] names, string requiredVersion, string minimumVersion, string maximumVersion, IRequestObject requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

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

            if (names.Length == 0)
            {
                return(FindPackage(null, requiredVersion, minimumVersion, maximumVersion, 0, requestObject));
            }

            if (names.Length == 1)
            {
                return(FindPackage(names[0], requiredVersion, minimumVersion, maximumVersion, 0, requestObject));
            }

            return(new SoftwareIdentityRequestObject(this, requestObject.As <IHostApi>(), request => {
                var id = StartFind(request);
                foreach (var name in names)
                {
                    Provider.FindPackage(name, requiredVersion, minimumVersion, maximumVersion, id.Value, request);
                }
                Provider.CompleteFind(id.Value, request);
            }, Constants.PackageStatus.Available));
        }
示例#21
0
        public void CreateFolder(string folder, IRequestObject requestObject)
        {
            Activity();

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

            using (var request = requestObject.As <Request>()) {
                request.Debug("Calling 'ProviderService::CreateFolder'");

                if (!Directory.Exists(folder))
                {
                    try {
                        Directory.CreateDirectory(folder);
                        request.Verbose("CreateFolder Success {0}", folder);
                        return;
                    } catch (Exception e) {
                        request.Error(ErrorCategory.InvalidResult, folder, Constants.Messages.CreatefolderFailed, folder, e.Message);
                        return;
                    }
                }
                request.Verbose("CreateFolder -- Already Exists {0}", folder);
            }
        }
示例#22
0
        public bool ExecuteElevatedAction(string provider, string payload, IRequestObject requestObject)
        {
            Activity();

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

            // launches a new elevated host that
            // talks back to this (unelevated) host for everything in HostApi
            // everything else should be handled in the new process.
            var guid = Guid.NewGuid();

            var properties = new Hashtable();

            properties.Add("portName", "OneGet_" + guid);
            properties.Add("authorizedGroup", "Administrators");
            properties.Add("secure", "true");
            properties.Add("exclusiveAddressUse", "true");
            properties.Add("strictBinding", "false");
            properties.Add("name", "OneGetHost");

            // set up the server IPC channel
            var serverChannel = new IpcServerChannel(properties, new BinaryServerFormatterSinkProvider(properties, null));

            ChannelServices.RegisterChannel(serverChannel, true);

            var instance = new RemotableHostApi(requestObject.As <IHostApi>());

            var objRef     = RemotingServices.Marshal(instance, "Host", typeof(IHostApi));
            var remoteUris = serverChannel.GetUrlsForUri("Host");
            var uri        = remoteUris[0];

            // Create the client elevated
            try {
                var process = AsyncProcess.Start(new ProcessStartInfo {
                    FileName  = Assembly.GetExecutingAssembly().Location,
                    Arguments = "{0} {1} {2}".format(uri, provider, (string.IsNullOrWhiteSpace(payload) ? "null" : payload).ToBase64()),
#if !DEBUG
                    WindowStyle = ProcessWindowStyle.Hidden,
#endif
                    Verb = "runas",
                });

                process.WaitForExit();
                if (process.ExitCode != 0)
                {
                    return(false);
                }
            } catch (Exception e) {
                e.Dump();
                return(false);
            } finally {
                RemotingServices.Disconnect(instance);
                ChannelServices.UnregisterChannel(serverChannel);
            }
            return(true);
        }
示例#23
0
 public int StartFind(RequestImpl requestImpl)
 {
     if (requestImpl == null)
     {
         throw new ArgumentNullException("requestImpl");
     }
     return(Provider.StartFind(requestImpl.As <IRequest>()));
 }
示例#24
0
        public IAsyncValue <int> StartFind(IRequestObject requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException("requestObject");
            }

            return(new FuncRequestObject <int>(this, requestObject.As <IHostApi>(), request => Provider.StartFind(request)));
        }
示例#25
0
        public void InitializeProvider(object dynamicInterface, RequestImpl requestImpl)
        {
            RequestExtensions.RemoteDynamicInterface = dynamicInterface;

            using (var request = requestImpl.As <Request>()) {
                // use the request object to interact with the OneGet core:
                request.Debug("Information", "Calling 'InitializeProvider'");
            }
        }
示例#26
0
文件: Console.cs 项目: retsimx/Bridge
        public static void Write(Object value)
        {
            var con = Script.ToDynamic().Bridge.global.console;

            if (con && con.log)
            {
                con.log(value.As <dynamic>());
            }
        }
示例#27
0
        internal IRequest ExtendRequest(RequestImpl requestImpl, params object[] objects)
        {
            var baseGetMessageString = requestImpl.As <GetMessageString>();

            return(requestImpl.Extend <IRequest>(new {
                // check the caller's resource manager first, then fall back to this resource manager
                GetMessageString = new Func <string, string>((s) => baseGetMessageString(s) ?? Messages.ResourceManager.GetString(s)),
            }, objects, AdditionalImplementedFunctions));
        }
示例#28
0
 public void InitializeProvider(IRequestObject requestObject)
 {
     // we should go find out what's available once here just to make sure that
     // we have a list
     try {
         PackageManager._instance.BootstrappableProviderNames = GetProviders(requestObject.As <BootstrapRequest>()).Select(provider => provider.Attributes["name"]).ToArray();
     } catch {
     }
 }
示例#29
0
 public void DownloadFile(Uri remoteLocation, string localFilename, RequestImpl requestImpl)
 {
     // TODO: Fill in implementation
     // Delete this method if you do not need to implement it
     // Please don't throw an not implemented exception, it's not optimal.
     using (var request = requestImpl.As <Request>()) {
         // use the request object to interact with the OneGet core:
         request.Debug("Information", "Calling 'DownloadFile'");
     }
 }
示例#30
0
 public void UnpackArchive(string localFilename, string destinationFolder, RequestImpl requestImpl)
 {
     // TODO: Fill in implementation
     // Delete this method if you do not need to implement it
     // Please don't throw an not implemented exception, it's not optimal.
     using (var request = requestImpl.As <Request>()) {
         // use the request object to interact with the OneGet core:
         request.Debug("Information", "Calling 'UnpackArchive'");
     }
 }
示例#31
0
文件: Request.cs 项目: 40a/PowerShell
        internal static PsRequest New(Object requestObject, PowerShellProviderBase provider, string methodName) {
            if (requestObject is IAsyncAction) {
                ((IAsyncAction)(requestObject)).OnCancel += provider.CancelRequest;
                ((IAsyncAction)(requestObject)).OnAbort += provider.CancelRequest;
            }
            var req = requestObject.As<PsRequest>();

            req.CommandInfo = provider.GetMethod(methodName);
            if (req.CommandInfo == null) {
                req.Debug("METHOD_NOT_IMPLEMENTED", methodName);
            }
            req._provider = provider;

            if (req.Options == null) {
                req.Debug("req.Options is null");
                
            } else {

                req.Debug("Calling New() : MethodName = '{0}'", methodName);

                foreach(string key in req.Options.Keys)
                {
                    req.Debug(String.Format(CultureInfo.CurrentCulture, "{0}: {1}", key, req.Options[key]));                   
                }
            }
                      
            return req;
        }
示例#32
0
        internal static PsRequest New(Object requestObject, PowerShellProviderBase provider, string methodName)
        {
            if (requestObject is IAsyncAction) {
                ((IAsyncAction)(requestObject)).OnCancel += provider.CancelRequest;
                ((IAsyncAction)(requestObject)).OnAbort += provider.CancelRequest;
            }
            var req = requestObject.As<PsRequest>();

            req.CommandInfo = provider.GetMethod(methodName);
            if (req.CommandInfo == null) {
                req.Debug("METHOD_NOT_IMPLEMENTED", methodName);
            }
            req._provider = provider;
            return req;
        }