예제 #1
0
 public WildcardPattern (string pattern, WildcardOptions options = WildcardOptions.DefaultFileSystem)
 {
     if (pattern == null)
         throw new ArgumentNullException("pattern");
     Pattern = pattern;
     Options = options;
 }
예제 #2
0
 public WildcardPattern(string pattern, WildcardOptions options)
 {
     if (pattern == null)
     {
         throw PSTraceSource.NewArgumentNullException("pattern");
     }
     this.pattern = pattern;
     this.options = options;
 }
        /// <summary>
        /// If regular expressions are used for pattern matching,
        /// then build an array of compiled regular expressions
        /// at startup.This increases performance during scanning
        /// operations when simple matching is not used.
        /// </summary>
        protected override void BeginProcessing()
        {
            WriteDebug("Validating patterns.");

            WriteVerbose("Search pattern(s) are valid.");

            // If it's not a simple match, then
            // compile the regular expressions once.
            if (!simpleMatch)
            {
                WriteDebug("Compiling search regular expressions.");

                RegexOptions regexOptions = RegexOptions.Compiled;

                if (!caseSensitive)
                {
                    regexOptions |= RegexOptions.IgnoreCase;
                }

                regexPattern = new Regex[patterns.Length];

                for (int i = 0; i < patterns.Length; i++)
                {
                    try
                    {
                        regexPattern[i] =
                            new Regex(patterns[i], regexOptions);
                    }
                    catch (ArgumentException ex)
                    {
                        ThrowTerminatingError(new ErrorRecord(
                                                  ex,
                                                  "InvalidRegularExpression",
                                                  ErrorCategory.InvalidArgument,
                                                  patterns[i]
                                                  ));
                    }
                } //loop through patterns to create RegEx objects

                WriteVerbose("Pattern(s) compiled into regular expressions.");
            }// if not a simple match
            // If it's a simple match, then compile the
            // wildcard patterns once
            else
            {
                WriteDebug("Compiling search wildcards.");

                WildcardOptions wildcardOptions = WildcardOptions.Compiled;

                if (!caseSensitive)
                {
                    wildcardOptions |= WildcardOptions.IgnoreCase;
                }

                wildcardPattern = new WildcardPattern[patterns.Length];
                for (int i = 0; i < patterns.Length; i++)
                {
                    wildcardPattern[i] =
                        new WildcardPattern(patterns[i], wildcardOptions);
                }

                WriteVerbose("Pattern(s) compiled into wildcard expressions.");
            } // if match is a simple match
        }     // end of function BeginProcessing()
예제 #4
0
파일: regex.cs 프로젝트: 40a/PowerShell
        internal static RegexOptions TranslateWildcardOptionsIntoRegexOptions(WildcardOptions options)
        {
            RegexOptions regexOptions = RegexOptions.Singleline;

#if !CORECLR // RegexOptions.Compiled is not in CoreCLR
            if ((options & WildcardOptions.Compiled) != 0)
            {
                regexOptions |= RegexOptions.Compiled;
            }
#endif
            if ((options & WildcardOptions.IgnoreCase) != 0)
            {
                regexOptions |= RegexOptions.IgnoreCase;
            }
            if ((options & WildcardOptions.CultureInvariant) == WildcardOptions.CultureInvariant)
            {
                regexOptions |= RegexOptions.CultureInvariant;
            }

            return regexOptions;
        }
예제 #5
0
파일: regex.cs 프로젝트: 40a/PowerShell
 public CharacterNormalizer(WildcardOptions options)
 {
     _caseInsensitive = 0 != (options & WildcardOptions.IgnoreCase);
     if (_caseInsensitive)
     {
         _cultureInfo = 0 != (options & WildcardOptions.CultureInvariant)
             ? CultureInfo.InvariantCulture
             : CultureInfo.CurrentCulture;
     }
     else
     {
         // Don't bother saving the culture if we won't use it
         _cultureInfo = null;
     }
 }
        /// <summary>
        /// list blobs by blob name and container name
        /// </summary>
        /// <param name="containerName">container name</param>
        /// <param name="blobName">blob name pattern</param>
        /// <returns>An enumerable collection of IListBlobItem</returns>
        internal async Task ListBlobsByName(long taskId, IStorageBlobManagement localChannel, string containerName, string blobName, bool includeDeleted = false, bool includeVersion = false)
        {
            CloudBlobContainer container       = null;
            BlobRequestOptions requestOptions  = RequestOptions;
            AccessCondition    accessCondition = null;

            string prefix = string.Empty;

            if (String.IsNullOrEmpty(blobName) || WildcardPattern.ContainsWildcardCharacters(blobName) || includeDeleted)
            {
                container = await GetCloudBlobContainerByName(localChannel, containerName).ConfigureAwait(false);

                prefix = NameUtil.GetNonWildcardPrefix(blobName);
                WildcardOptions options  = WildcardOptions.IgnoreCase | WildcardOptions.Compiled;
                WildcardPattern wildcard = null;

                if (!String.IsNullOrEmpty(blobName))
                {
                    wildcard = new WildcardPattern(blobName, options);
                }

                Func <string, bool> blobFilter = (blobNameToFilte) => wildcard == null || wildcard.IsMatch(blobNameToFilte);
                await ListBlobsByPrefix(taskId, localChannel, containerName, prefix, blobFilter, includeDeleted, IncludeVersion).ConfigureAwait(false);
            }
            else
            {
                container = await GetCloudBlobContainerByName(localChannel, containerName, true).ConfigureAwait(false);

                BlobContainerClient track2container = AzureStorageContainer.GetTrack2BlobContainerClient(container, localChannel.StorageContext, ClientOptions);

                if (!NameUtil.IsValidBlobName(blobName))
                {
                    throw new ArgumentException(String.Format(Resources.InvalidBlobName, blobName));
                }

                BlobBaseClient blobClient = null;
                if (UseTrack2Sdk()) // User Track2 SDK
                {
                    blobClient = Util.GetTrack2BlobClient(track2container, blobName, localChannel.StorageContext, this.VersionId, false, this.SnapshotTime is null ? null : this.SnapshotTime.Value.ToString("o"), ClientOptions);
                    global::Azure.Storage.Blobs.Models.BlobProperties blobProperties;
                    try
                    {
                        blobProperties = blobClient.GetProperties(BlobRequestConditions, cancellationToken: CmdletCancellationToken);
                    }
                    catch (global::Azure.RequestFailedException e) when(e.Status == 404)
                    {
                        throw new ResourceNotFoundException(String.Format(Resources.BlobNotFound, blobName, containerName));
                    }
                    blobClient = Util.GetTrack2BlobClient(track2container, blobName, localChannel.StorageContext, this.VersionId, blobProperties.IsLatestVersion, this.SnapshotTime is null ? null : this.SnapshotTime.Value.ToString("o"), ClientOptions, blobProperties.BlobType);

                    AzureStorageBlob outputBlob = new AzureStorageBlob(blobClient, localChannel.StorageContext, blobProperties, ClientOptions);
                    OutputStream.WriteObject(taskId, outputBlob);
                }
                else // Use Track1 SDK
                {
                    CloudBlob blob = await localChannel.GetBlobReferenceFromServerAsync(container, blobName, this.SnapshotTime, accessCondition, requestOptions, OperationContext, CmdletCancellationToken).ConfigureAwait(false);

                    if (null == blob)
                    {
                        throw new ResourceNotFoundException(String.Format(Resources.BlobNotFound, blobName, containerName));
                    }
                    else
                    {
                        OutputStream.WriteObject(taskId, new AzureStorageBlob(blob, localChannel.StorageContext, ClientOptions));
                    }
                }
            }
        }
 public CharacterNormalizer (WildcardOptions options)
 {
     _cultureInfo = WildcardOptions.CultureInvariant == (options & WildcardOptions.CultureInvariant)
         ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
     _caseInsensitive = WildcardOptions.IgnoreCase == (options & WildcardOptions.IgnoreCase);
 }
예제 #8
0
        internal static bool TestControlByPropertiesFromDictionary(
            this IUiElement element,
            Dictionary <string, object> dict)
        {
            bool result = false;

            if (null == dict || 0 == dict.Keys.Count())
            {
                return(result);
            }

            foreach (string key in dict.Keys)
            {
                string keyValue = dict[key].ToString();

                const WildcardOptions options = WildcardOptions.IgnoreCase |
                                                WildcardOptions.Compiled;

                switch (key)
                {
                case "ACCELERATORKEY":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().AcceleratorKey)))
                    {
                        return(result);
                    }
                    break;

                case "ACCESSKEY":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().AccessKey)))
                    {
                        return(result);
                    }
                    break;

                case "AUTOMATIONID":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().AutomationId)))
                    {
                        return(result);
                    }
                    break;

                case "CLASS":
                case "CLASSNAME":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().ClassName)))
                    {
                        return(result);
                    }
                    break;

                case "CONTROLTYPE":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().ControlType.ProgrammaticName.Substring(12))))
                    {
                        return(result);
                    }
                    break;

                case "FRAMEWORKID":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().FrameworkId)))
                    {
                        return(result);
                    }
                    break;

                case "HASKEYBOARDFOCUS":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().HasKeyboardFocus.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "HELPTEXT":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().HelpText)))
                    {
                        return(result);
                    }
                    break;

                case "ISCONTENTELEMENT":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsContentElement.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ISCONTROLELEMENT":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsControlElement.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ISENABLED":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsEnabled.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ISKEYBOARDFOCUSABLE":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsKeyboardFocusable.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ISOFFSCREEN":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsOffscreen.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ISPASSWORD":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsPassword.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ISREQUIREDFORFORM":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().IsRequiredForForm.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ITEMSTATUS":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().ItemStatus)))
                    {
                        return(result);
                    }
                    break;

                case "ITEMTYPE":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().ItemType)))
                    {
                        return(result);
                    }
                    break;

                case "LABELEDBY":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().LabeledBy.Current.Name)))
                    {
                        return(result);
                    }
                    break;

                case "LOCALIZEDCONTROLTYPE":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().LocalizedControlType)))
                    {
                        return(result);
                    }
                    break;

                case "NAME":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().Name)))
                    {
                        return(result);
                    }
                    break;

                case "NATIVEWINDOWHANDLE":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().NativeWindowHandle.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "ORIENTATION":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().Orientation.ToString())))
                    {
                        return(result);
                    }
                    break;

                case "PROCESSID":
                    if (!(new WildcardPattern(
                              keyValue,
                              options).IsMatch(element.GetCurrent().ProcessId.ToString())))
                    {
                        return(result);
                    }
                    break;

                default:
                    (new CommonCmdletBase()).WriteError(
                        // this,
                        new CommonCmdletBase(),
                        "Wrong AutomationElement parameter is provided: " + key,
                        "WrongParameter",
                        ErrorCategory.InvalidArgument,
                        true);
                    break;
                }
            }

            result = true;
            return(result);
        }
예제 #9
0
 /// <summary>
 /// Initializes an instance of the WildcardPattern class for
 /// the specified wildcard pattern expression, with options
 /// that modify the pattern.
 /// </summary>
 /// <param name="pattern">The wildcard pattern to match.</param>
 /// <param name="options">Wildcard options</param>
 /// <returns>The constructed WildcardPattern object</returns>
 /// <remarks> if wildCardType == None, the pattern does not have wild cards  </remarks>
 public WildcardPattern(string pattern, WildcardOptions options)
 {
     Pattern = pattern ?? throw new ArgumentNullException(nameof(pattern));
     Options = options;
 }
예제 #10
0
 public static bool IsMatch(string input, string pattern, WildcardOptions options = WildcardOptions.DefaultFileSystem)
 {
     return(new WildcardPattern(pattern, options).IsMatch(input));
 }
예제 #11
0
 public CharacterNormalizer(WildcardOptions options)
 {
     if (WildcardOptions.CultureInvariant == (options & WildcardOptions.CultureInvariant))
     {
         this._cultureInfo = CultureInfo.InvariantCulture;
     }
     else
     {
         this._cultureInfo = CultureInfo.CurrentCulture;
     }
     this._caseInsensitive = WildcardOptions.IgnoreCase == (options & WildcardOptions.IgnoreCase);
 }
예제 #12
0
 internal static Collection <WildcardPattern> CreateWildcardsFromStrings(
     string[] globPatterns,
     WildcardOptions options)
 {
     return(SessionStateUtilities.CreateWildcardsFromStrings(SessionStateUtilities.ConvertArrayToCollection <string>(globPatterns), options));
 }
예제 #13
0
 public ExtendedWildcardPattern(string includePattern, string excludePattern, WildcardOptions options)
 {
     includeFilter = new WildcardPattern(includePattern, options);
     excludeFilter = new WildcardPattern(excludePattern, options);
 }
예제 #14
0
        /// <summary>
        /// Searches package sources given name and version information
        ///
        /// Package information must be returned using <c>request.YieldPackage(...)</c> function.
        /// </summary>
        /// <param name="name">a name or partial name of the package(s) requested</param>
        /// <param name="requiredVersion">A specific version of the package. Null or empty if the user did not specify</param>
        /// <param name="minimumVersion">A minimum version of the package. Null or empty if the user did not specify</param>
        /// <param name="maximumVersion">A maximum version of the package. Null or empty if the user did not specify</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="request">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
        public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, Request request)
        {
            request.Debug("Calling '{0}::FindPackage' '{1}','{2}','{3}','{4}'", PackageProviderName, requiredVersion, minimumVersion, maximumVersion, id);

            List <PackageSource> sources;
            var providerPackageSources = ProviderStorage.GetPackageSources(request);

            if (request.PackageSources != null && request.PackageSources.Any())
            {
                sources = new List <PackageSource>();

                foreach (var userRequestedSource in request.PackageSources)
                {
                    if (providerPackageSources.ContainsKey(userRequestedSource))
                    {
                        sources.Add(providerPackageSources[userRequestedSource]);
                    }
                }
            }
            else
            {
                sources = providerPackageSources.Select(i => i.Value).ToList();
            }

            var searchTerm = ReplacePowerShellWildcards(name);

            // Wildcard pattern matching configuration.
            const WildcardOptions wildcardOptions = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
            var wildcardPattern = new WildcardPattern(String.IsNullOrEmpty(name) ? "*" : name, wildcardOptions);

            if (request.IsCanceled)
            {
                return;
            }

            foreach (var packageSource in sources.AsNotNull())
            {
                var repo   = RepositoryFactory.CreateV3(packageSource.Location);
                var search = repo.GetResource <UISearchResource>();

                for (int i = 0; true; i += SearchPageSize)
                {
                    List <UISearchMetadata> results;

                    try
                    {
                        var task = search.Search(searchTerm, new SearchFilter(), i, SearchPageSize, CancellationToken.None);
                        task.Wait();
                        results = task.Result.ToList();
                    }
                    catch (NullReferenceException)
                    {
                        // usually means the source was incorrect, skip to the next source
                        break;
                    }

                    foreach (var result in results.AsNotNull())
                    {
                        if (!wildcardPattern.IsMatch(result.Identity.Id))
                        {
                            continue;
                        }

                        var package = new DataServicePackage()
                        {
                            Id = result.Identity.Id, Version = result.Identity.Version.ToString(), Summary = result.Summary, Authors = result.LatestPackageMetadata.Authors, Title = result.Title, IconUrl = result.IconUrl, Owners = result.LatestPackageMetadata.Owners, Description = result.LatestPackageMetadata.Description, Tags = result.LatestPackageMetadata.Tags, LicenseUrl = result.LatestPackageMetadata.LicenseUrl, ProjectUrl = result.LatestPackageMetadata.ProjectUrl, Published = result.LatestPackageMetadata.Published, ReportAbuseUrl = result.LatestPackageMetadata.ReportAbuseUrl
                        };
                        var fastPath = packageSource.MakeFastPath(result.Identity.Id, result.Identity.Version.ToString());

                        var packageItem = new PackageItem()
                        {
                            Id = result.Identity.Id, Version = result.Identity.Version.ToString(), FastPath = fastPath, Package = package, IsPackageFile = false, PackageSource = packageSource, FullPath = String.Empty
                        };

                        // YieldPackage returns false when operation was cancelled
                        if (!request.YieldPackage(packageItem, name))
                        {
                            return;
                        }
                    }

                    if (!results.Any())
                    {
                        break;
                    }
                }
            }
        }
예제 #15
0
 public CharacterNormalizer(WildcardOptions options)
 {
     _cultureInfo = WildcardOptions.CultureInvariant == (options & WildcardOptions.CultureInvariant)
         ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
     _caseInsensitive = WildcardOptions.IgnoreCase == (options & WildcardOptions.IgnoreCase);
 }
예제 #16
0
 public static bool IsMatch (string input, string pattern, WildcardOptions options = WildcardOptions.DefaultFileSystem)
 {
     return new WildcardPattern(pattern, options).IsMatch(input);
 }
예제 #17
0
파일: Compiler.cs 프로젝트: 40a/PowerShell
        private static Expression GetLikeRHSOperand(WildcardOptions options, Expression expr)
        {
            var constExpr = expr as ConstantExpression;
            if (constExpr == null)
                return expr;

            var val = constExpr.Value as string;
            if (val == null)
                return expr;

            return Expression.Constant(WildcardPattern.Get(val, options));
        }
예제 #18
0
        private IEnumerable <PackageItem> SearchSourceForPackages(PackageSource source, string name, string requiredVersion, string minimumVersion, string maximumVersion)
        {
            try {
                if (!String.IsNullOrEmpty(name) && WildcardPattern.ContainsWildcardCharacters(name))
                {
                    // NuGet does not support PowerShell/POSIX style wildcards and supports only '*' in searchTerm with NuGet.exe
                    // Replace the range from '[' - to ']' with * and ? with * then wildcard pattern is applied on the results from NuGet.exe
                    var tempName             = name;
                    var squareBracketPattern = Regex.Escape("[") + "(.*?)]";
                    foreach (Match match in Regex.Matches(tempName, squareBracketPattern))
                    {
                        tempName = tempName.Replace(match.Value, "*");
                    }
                    var searchTerm = tempName.Replace("?", "*");

                    // Wildcard pattern matching configuration.
                    const WildcardOptions wildcardOptions = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
                    var wildcardPattern = new WildcardPattern(searchTerm, wildcardOptions);

                    IEnumerable <string> packageIds = null;
                    using (var p = AsyncProcess.Start(NuGetExePath, String.Format(@"list ""{0}"" -Source ""{1}"" ", searchTerm, source.Location))) {
                        packageIds = p.StandardOutput.Where(each => !String.IsNullOrEmpty(each)).Select(l => {
                            Verbose("NuGet: {0}", l);
                            if (l.Contains("No packages found."))
                            {
                                return(null);
                            }
                            // ComicRack 0.9.162
                            var packageDetails = l.Split();

                            if (wildcardPattern.IsMatch(packageDetails[0]))
                            {
                                return(packageDetails[0]);
                            }
                            return(null);
                        }).Where(each => each != null).ToArray();

                        foreach (var l in p.StandardError.Where(l => !String.IsNullOrEmpty(l)))
                        {
                            Warning("NuGet: {0}", l);
                        }
                    }
                    return(packageIds.SelectMany(packageId => GetPackageById(source, packageId, requiredVersion, minimumVersion, maximumVersion)));
                    // return packageIds.SelectMany(packageId => SearchSourceForPackages(source, packageId, requiredVersion, minimumVersion, maximumVersion));
                    // return packageIds.SelectMany(packageId => FindPackageByNameFirst(source, packageId, requiredVersion, minimumVersion, maximumVersion));
                    // return SearchSourceForPackages(source.Location, requiredVersion, minimumVersion, maximumVersion);

                    /* return FilterOnVersion(source.Repository.FindPackages(packageIds), requiredVersion, minimumVersion, maximumVersion)
                     *  .Select(pkg => new PackageItem {
                     *      Package = pkg,
                     *      PackageSource = source,
                     *      FastPath = MakeFastPath(source, pkg.Id, pkg.Version.ToString())
                     *  });*/
                }
            } catch (Exception e) {
                e.Dump(this);
                return(Enumerable.Empty <PackageItem>());
            }

            try {
                var criteria = Contains.Value;
                if (String.IsNullOrEmpty(criteria))
                {
                    criteria = name;
                }

                if (FilterOnTag != null)
                {
                    criteria = FilterOnTag.Value.Where(tag => !string.IsNullOrEmpty(tag)).Aggregate(criteria, (current, tag) => current + " tag:" + tag);
                }
                Debug("Searching repository '{0}' for '{1}'", source.Repository.Source, criteria);
                // var src = PackageRepositoryFactory.Default.CreateRepository(source.Repository.Source);
                //  var src = new AggregateRepository(new IPackageRepository[] {source.Repository});
                var src = source.Repository;

                /*
                 * IQueryable<IPackage> packages;
                 * if (src is IServiceBasedRepository) {
                 *  packages = (src as IServiceBasedRepository).Search(criteria, new string[0], AllowPrereleaseVersions);
                 * } else {
                 *  packages = src.Search(criteria, AllowPrereleaseVersions);
                 * }
                 */

                var packages = src.Search(criteria, AllowPrereleaseVersions);



                /*
                 * foreach (var p in pp) {
                 *  Console.WriteLine(p.GetFullName());
                 * }
                 */

                // packages = packages.OrderBy(p => p.Id);

                // query filtering:
                if (!AllVersions && (String.IsNullOrEmpty(requiredVersion) && String.IsNullOrEmpty(minimumVersion) && String.IsNullOrEmpty(maximumVersion)))
                {
                    packages = packages.FindLatestVersion();
                }

                IEnumerable <IPackage> pkgs = new PackagesEnumerable(packages);

                // if they passed a name, restrict the search things that actually contain the name in the FullName.
                if (!String.IsNullOrEmpty(name))
                {
                    pkgs = FilterOnName(pkgs, name);
                }

                pkgs = FilterOnTags(pkgs);

                pkgs = FilterOnContains(pkgs);

                return(FilterOnVersion(pkgs, requiredVersion, minimumVersion, maximumVersion)
                       .Select(pkg => new PackageItem {
                    Package = pkg,
                    PackageSource = source,
                    FastPath = MakeFastPath(source, pkg.Id, pkg.Version.ToString())
                }));
            } catch (Exception e) {
                e.Dump(this);
                return(Enumerable.Empty <PackageItem>());
            }
        }
예제 #19
0
        private IEnumerable <WildcardPattern> CreateKeyPatternList(string pattern)
        {
            WildcardOptions options = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;

            return(SessionStateUtilities.CreateWildcardsFromStrings(new string[] { pattern }, options));
        }
예제 #20
0
        private void TestParametersAgainstCollection(
            ControlType controlType,
            string name,
            string automationId,
            string className,
            string txtValue,
            IEnumerable <IUiElement> collection,
            UsualWildcardRegex selector,
            int expectedNumberOfElements)
        {
            // Arrange
            ControlType[] controlTypes =
                new[] { controlType };

            GetControlCmdletBase cmdlet =
                FakeFactory.Get_GetControlCmdletBase(controlTypes, name, automationId, className, txtValue);

            var data =
                new ControlSearcherData {
                ControlType  = controlTypes.ConvertControlTypeToStringArray(),
                Name         = name,
                AutomationId = automationId,
                Class        = className,
                Value        = txtValue
            };

            Condition condition;
            bool      useWildcardOrRegex = true;

            switch (selector)
            {
            case UsualWildcardRegex.Wildcard:
                condition =
                    ControlSearcher.GetWildcardSearchCondition(
                        data);
                useWildcardOrRegex = true;
                break;

            case UsualWildcardRegex.Regex:
                condition =
                    ControlSearcher.GetWildcardSearchCondition(
                        data);
                useWildcardOrRegex = false;
                break;
            }

            // Act
            var resultList = RealCodeCaller.GetResultList_ReturnOnlyRightElements(collection.ToArray(), data, useWildcardOrRegex);

            // Assert
            MbUnit.Framework.Assert.Count(expectedNumberOfElements, resultList);
            Assert.Equal(expectedNumberOfElements, resultList.Count);
            string[] controlTypeNames;
            switch (selector)
            {
            case UsualWildcardRegex.Wildcard:
                const WildcardOptions options = WildcardOptions.IgnoreCase;
                // 20140312
//                    WildcardPattern namePattern = new WildcardPattern(name, options);
//                    WildcardPattern automationIdPattern = new WildcardPattern(automationId, options);
//                    WildcardPattern classNamePattern = new WildcardPattern(className, options);
//                    WildcardPattern txtValuePattern = new WildcardPattern(txtValue, options);
                var namePattern         = new WildcardPattern(name, options);
                var automationIdPattern = new WildcardPattern(automationId, options);
                var classNamePattern    = new WildcardPattern(className, options);
                var txtValuePattern     = new WildcardPattern(txtValue, options);

                // 20140312
//                    if (!string.IsNullOrEmpty(name)) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => namePattern.IsMatch(x.Current.Name));
//                        resultList.All(x => namePattern.IsMatch(x.Current.Name));
//                    }
//                    if (!string.IsNullOrEmpty(automationId)) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => automationIdPattern.IsMatch(x.Current.AutomationId));
//                        resultList.All(x => automationIdPattern.IsMatch(x.Current.AutomationId));
//                    }
//                    if (!string.IsNullOrEmpty(className)) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => classNamePattern.IsMatch(x.Current.ClassName));
//                        resultList.All(x => classNamePattern.IsMatch(x.Current.ClassName));
//                    }
//                    controlTypeNames =
//                        controlTypes.Select(ct => null != ct ? ct.ProgrammaticName.Substring(12) : string.Empty).ToArray();
//                    if (null != controlType) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => controlTypeNames.Contains(x.Current.ControlType.ProgrammaticName.Substring(12)));
//                        resultList.All(x => controlTypeNames.Contains(x.Current.ControlType.ProgrammaticName.Substring(12)));
//                    }
                if (!string.IsNullOrEmpty(name))
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => namePattern.IsMatch(x.GetCurrent().Name));
                    resultList.All(x => namePattern.IsMatch(x.GetCurrent().Name));
                }
                if (!string.IsNullOrEmpty(automationId))
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => automationIdPattern.IsMatch(x.GetCurrent().AutomationId));
                    resultList.All(x => automationIdPattern.IsMatch(x.GetCurrent().AutomationId));
                }
                if (!string.IsNullOrEmpty(className))
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => classNamePattern.IsMatch(x.GetCurrent().ClassName));
                    resultList.All(x => classNamePattern.IsMatch(x.GetCurrent().ClassName));
                }
                controlTypeNames =
                    controlTypes.Select(ct => null != ct ? ct.ProgrammaticName.Substring(12) : string.Empty).ToArray();
                if (null != controlType)
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => controlTypeNames.Contains(x.GetCurrent().ControlType.ProgrammaticName.Substring(12)));
                    resultList.All(x => controlTypeNames.Contains(x.GetCurrent().ControlType.ProgrammaticName.Substring(12)));
                }

                if (!string.IsNullOrEmpty(txtValue))
                {
                    MbUnit.Framework.Assert.ForAll(
                        resultList
                        .Cast <IUiElement>()
                        .ToList <IUiElement>(), x =>
                    {
                        IValuePattern valuePattern = x.GetCurrentPattern <IValuePattern>(ValuePattern.Pattern) as IValuePattern;
                        return(valuePattern != null && txtValuePattern.IsMatch(valuePattern.Current.Value));
                    });

                    resultList.All(
                        x => {
                        IValuePattern valuePattern = x.GetCurrentPattern <IValuePattern>(ValuePattern.Pattern) as IValuePattern;
                        return(valuePattern != null && txtValuePattern.IsMatch(valuePattern.Current.Value));
                    });
                }
                break;

            case UsualWildcardRegex.Regex:
                // 20140312
//                    if (!string.IsNullOrEmpty(name)) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => Regex.IsMatch(x.Current.Name, name));
//                        resultList.All(x => Regex.IsMatch(x.Current.Name, name));
//                    }
//                    if (!string.IsNullOrEmpty(automationId)) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => Regex.IsMatch(x.Current.AutomationId, automationId));
//                        resultList.All(x => Regex.IsMatch(x.Current.AutomationId, automationId));
//                    }
//                    if (!string.IsNullOrEmpty(className)) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => Regex.IsMatch(x.Current.ClassName, className));
//                        resultList.All(x => Regex.IsMatch(x.Current.ClassName, className));
//                    }
//                    controlTypeNames =
//                        controlTypes.Select(ct => null != ct ? ct.ProgrammaticName.Substring(12) : string.Empty).ToArray();
//                    if (null != controlType) {
//                        MbUnit.Framework.Assert.ForAll(resultList.Cast<IUiElement>().ToList<IUiElement>(), x => controlTypeNames.Contains(x.Current.ControlType.ProgrammaticName.Substring(12)));
//                        resultList.All(x => controlTypeNames.Contains(x.Current.ControlType.ProgrammaticName.Substring(12)));
//                    }
                if (!string.IsNullOrEmpty(name))
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => Regex.IsMatch(x.GetCurrent().Name, name));
                    resultList.All(x => Regex.IsMatch(x.GetCurrent().Name, name));
                }
                if (!string.IsNullOrEmpty(automationId))
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => Regex.IsMatch(x.GetCurrent().AutomationId, automationId));
                    resultList.All(x => Regex.IsMatch(x.GetCurrent().AutomationId, automationId));
                }
                if (!string.IsNullOrEmpty(className))
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => Regex.IsMatch(x.GetCurrent().ClassName, className));
                    resultList.All(x => Regex.IsMatch(x.GetCurrent().ClassName, className));
                }
                controlTypeNames =
                    controlTypes.Select(ct => null != ct ? ct.ProgrammaticName.Substring(12) : string.Empty).ToArray();
                if (null != controlType)
                {
                    MbUnit.Framework.Assert.ForAll(resultList.Cast <IUiElement>().ToList <IUiElement>(), x => controlTypeNames.Contains(x.GetCurrent().ControlType.ProgrammaticName.Substring(12)));
                    resultList.All(x => controlTypeNames.Contains(x.GetCurrent().ControlType.ProgrammaticName.Substring(12)));
                }

                if (!string.IsNullOrEmpty(txtValue))
                {
                    MbUnit.Framework.Assert.ForAll(
                        resultList
                        .Cast <IUiElement>()
                        .ToList <IUiElement>(), x =>
                    {
                        IValuePattern valuePattern = x.GetCurrentPattern <IValuePattern>(ValuePattern.Pattern) as IValuePattern;
                        return(valuePattern != null && Regex.IsMatch(valuePattern.Current.Value, txtValue));
                    });
                    Assert.True(
                        resultList.All(
                            x => {
                        IValuePattern valuePattern = x.GetCurrentPattern <IValuePattern>(ValuePattern.Pattern) as IValuePattern;
                        return(valuePattern != null && Regex.IsMatch(valuePattern.Current.Value, txtValue));
                    })
                        );
                }
                break;
            }
        }
예제 #21
0
        private static IEnumerable <CimModule> GetCimModules(
            CimSession cimSession,
            Uri resourceUri,
            string cimNamespace,
            string moduleNamePattern,
            bool onlyManifests,
            Cmdlet cmdlet,
            CancellationToken cancellationToken)
        {
            Dbg.Assert(cimSession != null, "Caller should verify cimSession != null");
            Dbg.Assert(moduleNamePattern != null, "Caller should verify that moduleNamePattern != null");

            const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
            var    wildcardPattern = WildcardPattern.Get(moduleNamePattern, wildcardOptions);
            string dosWildcard     = WildcardPatternToDosWildcardParser.Parse(wildcardPattern);

            var options = new CimOperationOptions {
                CancellationToken = cancellationToken
            };

            options.SetCustomOption("PS_ModuleNamePattern", dosWildcard, mustComply: false);
            if (resourceUri != null)
            {
                options.ResourceUri = resourceUri;
            }

            if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null))
            {
                cimNamespace = DiscoveryProviderNamespace;
            }

            // TODO/FIXME: ETW for method invocation
            IEnumerable <CimInstance> syncResults = cimSession.EnumerateInstances(
                cimNamespace,
                DiscoveryProviderModuleClass,
                options);
            // TODO/FIXME: ETW for method results
            IEnumerable <CimModule> cimModules = syncResults
                                                 .Select(cimInstance => new CimModule(cimInstance))
                                                 .Where(cimModule => wildcardPattern.IsMatch(cimModule.ModuleName));

            if (!onlyManifests)
            {
                cimModules = cimModules.Select(
                    delegate(CimModule cimModule)
                {
                    cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options);
                    return(cimModule);
                });
            }

            return(EnumerateWithCatch(
                       cimModules,
                       delegate(Exception exception)
            {
                ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception);
                if (!cmdlet.MyInvocation.ExpectingInput)
                {
                    if (((-1) != errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase)) ||
                        (cancellationToken.IsCancellationRequested || (exception is OperationCanceledException)) ||
                        (!cimSession.TestConnection()))
                    {
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                cmdlet.WriteError(errorRecord);
            }));
        }
 internal static RegexOptions TranslateWildcardOptionsIntoRegexOptions (WildcardOptions options)
 {
     var singleline = RegexOptions.Singleline;
     if ((options & WildcardOptions.Compiled) != WildcardOptions.None)
         singleline |= RegexOptions.Compiled;
     if ((options & WildcardOptions.IgnoreCase) != WildcardOptions.None)
         singleline |= RegexOptions.IgnoreCase;
     if ((options & WildcardOptions.CultureInvariant) == WildcardOptions.CultureInvariant)
         singleline |= RegexOptions.CultureInvariant;
     return singleline;
 }
예제 #23
0
        private Dictionary <string, UpdatableHelpModuleInfo> GetModuleInfo(System.Management.Automation.ExecutionContext context, string pattern, bool loaded, bool noErrors)
        {
            List <PSModuleInfo> modules = context.Modules.GetModules(new string[] { pattern }, false);
            Dictionary <string, UpdatableHelpModuleInfo> dictionary = new Dictionary <string, UpdatableHelpModuleInfo>();

            if (modules.Count != 0)
            {
                base.WriteDebug(StringUtil.Format("Found {0} loaded modules.", modules.Count));
                foreach (PSModuleInfo info in modules)
                {
                    if (InitialSessionState.IsEngineModule(info.Name) && !InitialSessionState.IsNestedEngineModule(info.Name))
                    {
                        base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info.Name, info.Guid));
                        if (!dictionary.ContainsKey(info.Name))
                        {
                            dictionary.Add(info.Name, new UpdatableHelpModuleInfo(info.Name, info.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info.Name]));
                        }
                    }
                    else if (!InitialSessionState.IsNestedEngineModule(info.Name))
                    {
                        if (string.IsNullOrEmpty(info.HelpInfoUri))
                        {
                            if (!noErrors)
                            {
                                this.ProcessException(info.Name, null, new UpdatableHelpSystemException("HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound, new object[0]), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                            }
                        }
                        else if (!info.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                        {
                            if (!noErrors)
                            {
                                this.ProcessException(info.Name, null, new UpdatableHelpSystemException("InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, info.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                            }
                        }
                        else if (!dictionary.ContainsKey(info.Name))
                        {
                            dictionary.Add(info.Name, new UpdatableHelpModuleInfo(info.Name, info.Guid, info.ModuleBase, info.HelpInfoUri));
                        }
                    }
                }
            }
            WildcardOptions options = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
            IEnumerable <WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(new string[] { pattern }, options);

            if (!loaded)
            {
                Collection <PSObject>     collection  = base.InvokeCommand.InvokeScript("Get-Module -ListAvailable");
                Collection <PSModuleInfo> collection2 = new Collection <PSModuleInfo>();
                if (collection != null)
                {
                    foreach (PSObject obj2 in collection)
                    {
                        try
                        {
                            collection2.Add((PSModuleInfo)LanguagePrimitives.ConvertTo(obj2, typeof(PSModuleInfo), CultureInfo.InvariantCulture));
                        }
                        catch (PSInvalidCastException)
                        {
                        }
                    }
                }
                base.WriteDebug(StringUtil.Format("Found {0} available (Get-Module -ListAvailable) modules.", collection2.Count));
                foreach (PSModuleInfo info2 in collection2)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(info2.Name, patterns, true))
                    {
                        if (InitialSessionState.IsEngineModule(info2.Name) && !InitialSessionState.IsNestedEngineModule(info2.Name))
                        {
                            base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info2.Name, info2.Guid));
                            if (!dictionary.ContainsKey(info2.Name))
                            {
                                dictionary.Add(info2.Name, new UpdatableHelpModuleInfo(info2.Name, info2.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info2.Name]));
                            }
                        }
                        else if (!InitialSessionState.IsNestedEngineModule(info2.Name))
                        {
                            if (string.IsNullOrEmpty(info2.HelpInfoUri))
                            {
                                if (!noErrors)
                                {
                                    this.ProcessException(info2.Name, null, new UpdatableHelpSystemException("HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound, new object[0]), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                                }
                            }
                            else if (!info2.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!noErrors)
                                {
                                    this.ProcessException(info2.Name, null, new UpdatableHelpSystemException("InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, info2.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                                }
                            }
                            else if (!dictionary.ContainsKey(info2.Name))
                            {
                                dictionary.Add(info2.Name, new UpdatableHelpModuleInfo(info2.Name, info2.Guid, info2.ModuleBase, info2.HelpInfoUri));
                            }
                        }
                    }
                }
            }
            foreach (KeyValuePair <string, string> pair in metadataCache)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, patterns, true))
                {
                    if (!pair.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
                    {
                        Collection <PSObject>     collection3 = base.InvokeCommand.InvokeScript(StringUtil.Format("Get-Module {0} -ListAvailable", pair.Key));
                        Collection <PSModuleInfo> collection4 = new Collection <PSModuleInfo>();
                        if (collection3 != null)
                        {
                            foreach (PSObject obj3 in collection3)
                            {
                                try
                                {
                                    collection4.Add((PSModuleInfo)LanguagePrimitives.ConvertTo(obj3, typeof(PSModuleInfo), CultureInfo.InvariantCulture));
                                }
                                catch (PSInvalidCastException)
                                {
                                }
                            }
                        }
                        foreach (PSModuleInfo info3 in collection4)
                        {
                            if (!dictionary.ContainsKey(info3.Name))
                            {
                                base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info3.Name, info3.Guid));
                                dictionary.Add(pair.Key, new UpdatableHelpModuleInfo(info3.Name, info3.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info3.Name]));
                            }
                        }
                    }
                    else if (!dictionary.ContainsKey(pair.Key))
                    {
                        dictionary.Add(pair.Key, new UpdatableHelpModuleInfo(pair.Key, Guid.Empty, Utils.GetApplicationBase(context.ShellID), pair.Value));
                    }
                }
            }
            return(dictionary);
        }
예제 #24
0
        /// <summary>
        /// The ProcessRecord method does the following for each of the
        /// requested process names:
        /// 1) Check that the process is not a critical process.
        /// 2) Attempt to stop that process.
        /// If no process is requested then nothing occurs.
        /// </summary>
        protected override void ProcessRecord()
        {
            Process[] processes = null;

            try
            {
                processes = Process.GetProcesses();
            }
            catch (InvalidOperationException ioe)
            {
                base.ThrowTerminatingError(new ErrorRecord(ioe,
                                                           "UnableToAcessProcessList",
                                                           ErrorCategory.InvalidOperation,
                                                           null));
            }


            // For every process name passed to the cmdlet, get the associated
            // processes.
            // Write a nonterminating error for failure to retrieve
            // a process.
            foreach (string name in processNames)
            {
                // Write a user-friendly verbose message to the pipeline. These
                // messages are intended to give the user detailed information
                // on the operations performed by the cmdlet. These messages will
                // appear with the -Verbose option.
                string message = String.Format(CultureInfo.CurrentCulture,
                                               "Attempting to stop process \"{0}\".", name);
                WriteVerbose(message);

                // Validate the process name against a wildcard pattern.
                // If the name does not contain any wildcard patterns, it
                // will be treated as an exact match.
                WildcardOptions options = WildcardOptions.IgnoreCase |
                                          WildcardOptions.Compiled;
                WildcardPattern wildcard = new WildcardPattern(name, options);

                foreach (Process process in processes)
                {
                    string processName;

                    try
                    {
                        processName = process.ProcessName;
                    }
                    catch (Win32Exception e)
                    {
                        WriteError(new ErrorRecord(
                                       e, "ProcessNameNotFound",
                                       ErrorCategory.ObjectNotFound,
                                       process)
                                   );
                        continue;
                    }

                    // Write a debug message to the host that can be used when
                    // troubleshooting a problem. All debug messages will appear
                    // with the -Debug option.
                    message = String.Format(CultureInfo.CurrentCulture,
                                            "Acquired name for pid {0} : \"{1}\"",
                                            process.Id, processName);
                    WriteDebug(message);

                    // Check to see if this process matches the current process
                    // name pattern. Skip this process if it does not.
                    if (!wildcard.IsMatch(processName))
                    {
                        continue;
                    }

                    // Stop the process.
                    SafeStopProcess(process);
                } // foreach (Process...
            }     // foreach (string...
        }         // ProcessRecord
예제 #25
0
파일: regex.cs 프로젝트: 40a/PowerShell
        /// <summary>
        /// Create a new WildcardPattern, or return an already created one.
        /// </summary>
        /// <param name="pattern">The pattern</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static WildcardPattern Get(string pattern, WildcardOptions options)
        {
            if (pattern == null)
                throw PSTraceSource.NewArgumentNullException("pattern");

            if (pattern.Length == 1 && pattern[0] == '*')
                return s_matchAllIgnoreCasePattern;

            return new WildcardPattern(pattern, options);
        }
예제 #26
0
 public WildcardPattern(string pattern, WildcardOptions options)
 {
     _pattern = pattern;
     _options = options;
 }
예제 #27
0
        /// <summary>
        /// Gets a list of modules from the given pattern.
        /// </summary>
        /// <param name="context">Execution context.</param>
        /// <param name="pattern">Pattern to search.</param>
        /// <param name="fullyQualifiedName">Module Specification.</param>
        /// <param name="noErrors">Do not generate errors for modules without HelpInfoUri.</param>
        /// <returns>A list of modules.</returns>
        private Dictionary <Tuple <string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(ExecutionContext context, string pattern, ModuleSpecification fullyQualifiedName, bool noErrors)
        {
            List <PSModuleInfo> modules = null;
            string moduleNamePattern    = null;

            if (pattern != null)
            {
                moduleNamePattern = pattern;
                modules           = Utils.GetModules(pattern, context);
            }
            else if (fullyQualifiedName != null)
            {
                moduleNamePattern = fullyQualifiedName.Name;
                modules           = Utils.GetModules(fullyQualifiedName, context);
            }

            var helpModules = new Dictionary <Tuple <string, Version>, UpdatableHelpModuleInfo>();

            if (modules != null)
            {
                foreach (PSModuleInfo module in modules)
                {
                    ProcessSingleModuleObject(module, context, helpModules, noErrors);
                }
            }

            // Match wildcards
            WildcardOptions wildcardOptions           = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
            IEnumerable <WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] {
                moduleNamePattern
            }, wildcardOptions);

            foreach (KeyValuePair <string, string> name in s_metadataCache)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(name.Key, patternList, true))
                {
                    // For core snapin, there are no GUIDs. So, we need to construct the HelpInfo slightly differently
                    if (!name.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
                    {
                        var keyTuple = new Tuple <string, Version>(name.Key, new Version("1.0"));
                        if (!helpModules.ContainsKey(keyTuple))
                        {
                            List <PSModuleInfo> availableModules = Utils.GetModules(name.Key, context);
                            if (availableModules != null)
                            {
                                foreach (PSModuleInfo module in availableModules)
                                {
                                    keyTuple = new Tuple <string, Version>(module.Name, module.Version);
                                    if (!helpModules.ContainsKey(keyTuple))
                                    {
                                        WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));

                                        helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name,
                                                                                              module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name]));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        var keyTuple2 = new Tuple <string, Version>(name.Key, new Version("1.0"));
                        if (!helpModules.ContainsKey(keyTuple2))
                        {
                            helpModules.Add(keyTuple2,
                                            new UpdatableHelpModuleInfo(name.Key, Guid.Empty,
                                                                        Utils.GetApplicationBase(context.ShellID),
                                                                        name.Value));
                        }
                    }
                }
            }

            return(helpModules);
        }
예제 #28
0
        /// <summary>
        /// For each of the requested processnames:
        /// 1) check it's not a critical process
        /// 2) attempt to stop that process.
        /// If no process requested, then nothing occurs.
        /// </summary>
        protected override void ProcessRecord()
        {
            Process[] processes = null;

            try
            {
                processes = Process.GetProcesses();
            }
            catch (InvalidOperationException ioe)
            {
                base.ThrowTerminatingError(new ErrorRecord(ioe,
                                                           "UnableToAcessProcessList",
                                                           ErrorCategory.InvalidOperation,
                                                           null));
            }

            // If a name parameter is passed to cmdlet, get associated
            // process(es).
            // Write a non-terminating error for failure to retrieve
            // a process
            foreach (string name in processNames)
            {
                // Write a user-level message to the pipeline. These are
                // intended to give the user detailed information on the
                // operations performed by the Cmdlet. These messages will
                // appear with the -Verbose option.
                string message = String.Format(CultureInfo.CurrentCulture,
                                               "Attempting to stop process \"{0}\".", name);
                WriteVerbose(message);

                // Use this process name argument as a wildcard pattern.
                // If it does not contain wildcard patterns it will behave
                // as an exact match.
                WildcardOptions options = WildcardOptions.IgnoreCase |
                                          WildcardOptions.Compiled;
                WildcardPattern wildcard = new WildcardPattern(name, options);

                foreach (Process process in processes)
                {
                    string processName;

                    try
                    {
                        processName = process.ProcessName;
                    }
                    catch (Win32Exception e)
                    {
                        WriteError(new ErrorRecord(
                                       e, "ProcessNameNotFound",
                                       ErrorCategory.ObjectNotFound,
                                       process)
                                   );
                        continue;
                    }

                    // Write a debug message to the host which will be helpful
                    // in troubleshooting a problem. All debug messages
                    // will appear with the -Debug option
                    message = String.Format(CultureInfo.CurrentCulture,
                                            "Acquired name for pid {0} : \"{1}\"",
                                            process.Id, processName);
                    WriteDebug(message);

                    // Does this process match the current process name pattern?
                    // Skip this process if not.
                    if (!wildcard.IsMatch(processName))
                    {
                        continue;
                    }

                    // Stop the process.
                    SafeStopProcess(process);
                } // foreach (Process...
            }     // foreach (string...
        }         // ProcessRecord
예제 #29
0
 public WildcardPattern(string pattern, WildcardOptions options)
 {
     _pattern = pattern;
     _options = options;
 }
예제 #30
0
        internal static Collection <WildcardPattern> CreateWildcardsFromStrings(Collection <string> globPatterns, WildcardOptions options)
        {
            Collection <WildcardPattern> collection = new Collection <WildcardPattern>();

            if ((globPatterns != null) && (globPatterns.Count > 0))
            {
                foreach (string str in globPatterns)
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        collection.Add(new WildcardPattern(str, options));
                    }
                }
            }
            return(collection);
        }