Esempio n. 1
0
 protected virtual System.Management.Automation.ProviderInfo Start(System.Management.Automation.ProviderInfo providerInfo)
 {
     using (PSTransactionManager.GetEngineProtectionScope())
     {
         return(providerInfo);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Starts the specified provider. This method is called by the Windows PowerShell runtime to initialize the
        /// provider when the provider is loaded into a session.
        /// </summary>
        /// <param name="providerInfo">
        /// A <see cref="ProviderInfo"/> object that describes the provider to be initialized.
        /// </param>
        /// <returns>A <see cref="ProviderInfo"/> object that contains information about the provider.</returns>
        protected override ProviderInfo Start(ProviderInfo providerInfo)
        {
            // Increase console window size
            this.IncreaseWindowSize(120, 50);

            return base.Start(providerInfo);
        }
        public static void ValidateDirectory(ProviderInfo provider, string directory)
        {
            validateFileSystemPath(provider, directory);

            if (!Directory.Exists(directory))
            {
                Exception exception;

                if (File.Exists(directory))
                {
                    exception = new InvalidOperationException($"{directory} is not a directory.");
                    ExceptionHelper.SetUpException(
                                                   ref exception,
                                                   ERR_NO_DIRECTORY,
                                                   ErrorCategory.InvalidOperation,
                                                   directory);
                }
                else
                {
                    exception =
                        new FileNotFoundException(
                            $"The directory {directory} could not be found.");
                    ExceptionHelper.SetUpException(
                                                   ref exception,
                                                   ERR_NO_DIRECTORY,
                                                   ErrorCategory.InvalidData,
                                                   directory);
                }

                throw exception;
            }
        }
Esempio n. 4
0
 internal PathInfo(PSDriveInfo drive, ProviderInfo provider, Path path, SessionState sessionState)
 {
     Drive = drive;
     Provider = provider;
     _path = path;
     _sessionState = sessionState;
 }
Esempio n. 5
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential)
 {
     this.credentials = PSCredential.Empty;
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     if (provider == null)
     {
         throw PSTraceSource.NewArgumentNullException("provider");
     }
     if (root == null)
     {
         throw PSTraceSource.NewArgumentNullException("root");
     }
     this.name = name;
     this.provider = provider;
     this.root = root;
     this.description = description;
     if (credential != null)
     {
         this.credentials = credential;
     }
     this.currentWorkingDirectory = string.Empty;
     this.Trace();
 }
Esempio n. 6
0
 internal void SetProviderInformation(System.Management.Automation.ProviderInfo providerInfoToSet)
 {
     if (providerInfoToSet == null)
     {
         throw PSTraceSource.NewArgumentNullException("providerInfoToSet");
     }
     this.providerInformation = providerInfoToSet;
 }
        protected UniversalProviderInfo(ProviderInfo providerInfo) : base(providerInfo) {
            try {
                PropertySheet = PropertySheet.Parse(@"@import ""pstab.properties"";", "default");
            } catch (Exception) {

                PropertySheet = new PropertySheet();
            }
            
        }
Esempio n. 8
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential)
 {
     Name = name;
     Provider = provider;
     Root = root;
     Description = description;
     Credential = credential;
     CurrentLocation = string.Empty;
 }
Esempio n. 9
0
 public AzureDriveInfo(Rule aliasRule, ProviderInfo providerInfo, PSCredential psCredential = null)
     : base(GetDriveInfo(aliasRule, providerInfo, psCredential))
 {
     Path = new Path {
         Account = aliasRule.HasProperty("key") ? aliasRule["key"].Value : aliasRule.Parameter,
         Container = aliasRule.HasProperty("container") ? aliasRule["container"].Value : "",
         SubPath = aliasRule.HasProperty("root") ? aliasRule["root"].Value.Replace('/', '\\').Replace("\\\\", "\\").Trim('\\') : "",
     };
     Path.Validate();
     Secret = aliasRule.HasProperty("secret") ? aliasRule["secret"].Value : psCredential != null ? psCredential.Password.ToString() : null;
 }
Esempio n. 10
0
 protected ProviderInfo(ProviderInfo providerInfo)
 {
     _sessionState = providerInfo._sessionState;
     PSSnapIn = providerInfo.PSSnapIn;
     Name = providerInfo.Name;
     Description = providerInfo.Description;
     Home = providerInfo.Home;
     ImplementingType = providerInfo.ImplementingType;
     Capabilities = providerInfo.Capabilities;
     HelpFile = providerInfo.HelpFile;
 }
Esempio n. 11
0
 internal DirectoryServiceDriveInfo
 (
     String name,
     ProviderInfo provider,
     String description,
     PSCredential credential,
     DirectoryRootInfo rootInfo
 )
     : base(name, provider, name + ':', description, credential)
 {
     _rootInfo = rootInfo;
 }
Esempio n. 12
0
 private static string GetProviderAssemblyPath(ProviderInfo providerInfo)
 {
     if (providerInfo == null)
     {
         return null;
     }
     if (providerInfo.ImplementingType == null)
     {
         return null;
     }
     return Path.GetDirectoryName(providerInfo.ImplementingType.Assembly.Location);
 }
 public static ILocationResolver GetLocationResolver(ProviderInfo providerInfo) {
     var result = providerInfo as ILocationResolver;
     if (result == null) {
         if (providerInfo.Name == "FileSystem") {
             return new FilesystemLocationProvider(providerInfo);
         }
     }
     if (result == null) {
         throw new ClrPlusException("Unable to create location resolver for {0}".format(providerInfo.Name));
     }
     return result;
 }
Esempio n. 14
0
 private static void validateFileSystemPath(ProviderInfo provider, string directory)
 {
     if (!isFileSystemPath(provider))
     {
         Exception exception = new ArgumentException("The syntax of the command is incorrect.");
         ExceptionHelper.SetUpException(
                                        ref exception,
                                        ERR_BAD_PROVIDER,
                                        ErrorCategory.InvalidArgument,
                                        directory);
         throw exception;
     }
 }
 protected override ProviderInfo Start(ProviderInfo sitecoreProviderInfo)
 {
     try
     {
         sitecoreProviderInfo.Description = "Sitcore Content Provider";
         providerInfo = sitecoreProviderInfo;
         LogInfo("Executing Start(string providerInfo='{0}')", sitecoreProviderInfo.Name);
         return sitecoreProviderInfo;
     }
     catch (Exception ex)
     {
         LogError(ex, "Error while executing Start(string providerInfo='{0}')", sitecoreProviderInfo.Name);
         throw;
     }
 }
Esempio n. 16
0
 protected ProviderInfo(ProviderInfo providerInfo)
 {
     this.helpFile = "";
     if (providerInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("providerInfo");
     }
     this.name = providerInfo.Name;
     this.implementingType = providerInfo.ImplementingType;
     this.capabilities = providerInfo.capabilities;
     this.description = providerInfo.description;
     this.hiddenDrive = providerInfo.hiddenDrive;
     this.home = providerInfo.home;
     this.helpFile = providerInfo.helpFile;
     this.pssnapin = providerInfo.pssnapin;
     this.sessionState = providerInfo.sessionState;
 }
Esempio n. 17
0
 protected PSDriveInfo(PSDriveInfo driveInfo)
 {
     this.credentials = PSCredential.Empty;
     if (driveInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("driveInfo");
     }
     this.name = driveInfo.Name;
     this.provider = driveInfo.Provider;
     this.credentials = driveInfo.Credential;
     this.currentWorkingDirectory = driveInfo.CurrentLocation;
     this.description = driveInfo.Description;
     this.driveBeingCreated = driveInfo.driveBeingCreated;
     this.hidden = driveInfo.hidden;
     this.isAutoMounted = driveInfo.isAutoMounted;
     this.root = driveInfo.root;
     this.persist = driveInfo.Persist;
     this.Trace();
 }
Esempio n. 18
0
 protected bool IsFileSystemPath(ProviderInfo provider, string path)
 {
     bool isFileSystem = true;
     // check that this provider is the filesystem
     if (provider.ImplementingType != typeof(FileSystemProvider))
     {
         // create a .NET exception wrapping our error text
         ArgumentException ex = new ArgumentException(path +
             " does not resolve to a path on the FileSystem provider.");
         // wrap this in a powershell errorrecord
         ErrorRecord error = new ErrorRecord(ex, "InvalidProvider",
             ErrorCategory.InvalidArgument, path);
         // write a non-terminating error to pipeline
         WriteError(error);
         // tell our caller that the item was not on the filesystem
         isFileSystem = false;
     }
     return isFileSystem;
 }
Esempio n. 19
0
 internal PathInfo(PSDriveInfo drive, ProviderInfo provider, string path, SessionState sessionState)
 {
     if (provider == null)
     {
         throw PSTraceSource.NewArgumentNullException("provider");
     }
     if (path == null)
     {
         throw PSTraceSource.NewArgumentNullException("path");
     }
     if (sessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("sessionState");
     }
     this.drive = drive;
     this.provider = provider;
     this.path = path;
     this.sessionState = sessionState;
 }
Esempio n. 20
0
        /// <summary>
        /// Constructs a ProviderInvocationException with provider information and an inner exception.
        /// </summary>
        /// 
        /// <param name="provider">
        /// Information about the provider to be used in formatting the message.
        /// </param>
        /// 
        /// <param name="innerException">
        /// The inner exception for this exception.
        /// </param>
        internal ProviderInvocationException(ProviderInfo provider, Exception innerException)
            : base(RuntimeException.RetrieveMessage(innerException), innerException)
        {
            _message = base.Message;
            _providerInfo = provider;

            IContainsErrorRecord icer = innerException as IContainsErrorRecord;
            if (null != icer && null != icer.ErrorRecord)
            {
                _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
            }
            else
            {
                _errorRecord = new ErrorRecord(
                    innerException,
                    "ErrorRecordNotSpecified",
                    ErrorCategory.InvalidOperation,
                    null);
            }
        }
Esempio n. 21
0
        internal string GetProviderSpecificPath(string path, ProviderRuntime runtime, out ProviderInfo providerInfo)
        {
            // differentiate between drive-qualified, provider-qualified, provider-internal, and provider-direct paths
            // then strip provider prefix, set provider, set drive is possible or get from Drive.Current
            PSDriveInfo drive;
            string resolvedPath = null;
            if (IsProviderQualifiedPath(path))
            {
                resolvedPath = GetProviderPathFromProviderQualifiedPath(path, out providerInfo);
                // in case there is no CurrentDrive, set a dummy drive to keep track of the used provider
                drive = providerInfo.CurrentDrive ?? providerInfo.DummyDrive;
            }
            else if (IsDriveQualifiedPath(path))
            {
                resolvedPath = GetProviderPathFromDriveQualifiedPath(path, runtime, out providerInfo, out drive);
            }
            // otherwise we first need to know about the provider/drive in use to properly resolve the path
            else if (runtime.PSDriveInfo != null)
            {
                drive = runtime.PSDriveInfo;
                providerInfo = drive.Provider;
            }
            else
            {
                drive = _sessionState.Path.CurrentLocation.Drive;
                providerInfo = _sessionState.Path.CurrentLocation.Provider;
            }
            // TODO: check for provider internal path beginning with \\ or //
            //       make sure to set the drive to a dummy drive then

            runtime.PSDriveInfo = drive;

            // if we had no success, yet, we deal with some kind of provider specific (maybe relative) path
            if (resolvedPath == null)
            {
                resolvedPath = ResolveHomePath(path, runtime, providerInfo);
                resolvedPath = ResolveRelativePath(resolvedPath, runtime, providerInfo);
            }

            return resolvedPath;
        }
        internal CmdletProvider Add(ProviderInfo providerInfo, ExecutionContext executionContext)
        {
            CmdletProvider provider = providerInfo.CreateInstance();

            var runtime = new ProviderRuntime(executionContext.SessionState);
            providerInfo = provider.Start(providerInfo, runtime);
            provider.SetProviderInfo(providerInfo);

            // Cache the Provider's Info and instance
            if (!_providers.ContainsKey(providerInfo.Name))
            {
                _providers.Add(providerInfo.Name, new List<ProviderInfo>());
            }
            _providers[providerInfo.Name].Add(providerInfo);
            _providerInstances[providerInfo] = provider;

            // provider is added, default drives can be added
            AddDefaultDrives(provider, runtime);

            return provider;
        }
Esempio n. 23
0
        public void createScopes()
        {
            TestHost testHost = new TestHost(new TestHostUserInterface());

            Runspace hostRunspace = TestHost.CreateRunspace(testHost);

            globalState = hostRunspace.ExecutionContext.SessionState;

            var dummyProviderInfo = new ProviderInfo(globalState, typeof(DummyProvider), "DummyProvider", "", null);
            globalState.Provider.Add(dummyProviderInfo, hostRunspace.ExecutionContext);
            dummyProvider = globalState.Provider.GetOne("DummyProvider");

            scriptState = new SessionState(globalState);
            scriptState.IsScriptScope = true;
            functionState = new SessionState(scriptState);
            localState = new SessionState(functionState);
            states = new Dictionary<AvailableStates, SessionState>();
            states.Add(AvailableStates.Global, globalState);
            states.Add(AvailableStates.Script, scriptState);
            states.Add(AvailableStates.Function, functionState);
            states.Add(AvailableStates.Local, localState);

            hostCommandManager = new CommandManager(hostRunspace as LocalRunspace);
        }
Esempio n. 24
0
 public string GetUnresolvedProviderPathFromPSPath(string path, out ProviderInfo provider, out PSDriveInfo drive)
 {
     throw new NotImplementedException();
 }
Esempio n. 25
0
 internal static bool CheckProviderCapabilities(ProviderCapabilities capability, ProviderInfo provider)
 {
     return((provider.Capabilities & capability) != ProviderCapabilities.None);
 }
Esempio n. 26
0
 public Collection <string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider)
 {
     throw new NotImplementedException();
 }
Esempio n. 27
0
        /// <summary>
        /// Loads providers from the PSSnapins on the Pash startup
        /// </summary>
        internal void LoadProviders()
        {
            // TODO: do it via RunspaceConfiguration
            /*foreach (ProviderConfigurationEntry entry in _executionContext.RunspaceConfiguration.Providers)
            {
                //AddProvider
            }*/

            CommandManager commandManager = this.CommandManager;
            foreach (var providerTypePair in commandManager._providers)
            {
                ProviderInfo providerInfo = new ProviderInfo(new SessionState(this), providerTypePair.providerType, providerTypePair.providerAttr.ProviderName, string.Empty, providerTypePair.snapinInfo);
                CmdletProvider provider = AddProvider(providerInfo);

                InitializeProvider(provider, providerInfo);

                // Cache the provider's instance
                if (!_providerInstances.ContainsKey(providerInfo.Name))
                {
                    _providerInstances.Add(providerInfo.Name, new List<CmdletProvider>());
                }
                List<CmdletProvider> instanceList = _providerInstances[providerInfo.Name];
                instanceList.Add(provider);
            }
        }
Esempio n. 28
0
        private void ResolveCurrentDirectoryInLookupPaths()
        {
            SortedList           sortedList         = new SortedList();
            int                  num1               = 0;
            string               fileSystem         = this._context.ProviderNames.FileSystem;
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            bool                 flag               = engineSessionState.CurrentDrive != (PSDriveInfo)null && engineSessionState.CurrentDrive.Provider.NameEquals(fileSystem) && engineSessionState.IsProviderLoaded(fileSystem);
            string               currentDirectory   = Environment.CurrentDirectory;
            LocationGlobber      locationGlobber    = this._context.LocationGlobber;

            foreach (int index in this.lookupPaths.IndexOfRelativePath())
            {
                string str1 = (string)null;
                string str2 = (string)null;
                CommandDiscovery.discoveryTracer.WriteLine("Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...", (object)this.lookupPaths[index]);
                if (flag)
                {
                    ProviderInfo provider = (ProviderInfo)null;
                    try
                    {
                        str2 = locationGlobber.GetProviderPath(this.lookupPaths[index], out provider);
                    }
                    catch (ProviderInvocationException ex)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'", (object)this.lookupPaths[index], (object)ex.Message);
                    }
                    catch (InvalidOperationException ex)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path '{0}', could not resolve a home directory for the provider", (object)this.lookupPaths[index]);
                    }
                    if (!string.IsNullOrEmpty(str2))
                    {
                        CommandDiscovery.discoveryTracer.TraceError("The relative path resolved to: {0}", (object)str2);
                        str1 = str2;
                    }
                    else
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path was not a file system path. {0}", (object)this.lookupPaths[index]);
                    }
                }
                else
                {
                    CommandDiscovery.discoveryTracer.TraceWarning("The current drive is not set, using the process current directory: {0}", (object)currentDirectory);
                    str1 = currentDirectory;
                }
                if (str1 != null)
                {
                    int num2 = this.lookupPaths.IndexOf(str1);
                    if (num2 != -1)
                    {
                        if (num2 > index)
                        {
                            sortedList.Add((object)num1++, (object)num2);
                            this.lookupPaths[index] = str1;
                        }
                        else
                        {
                            sortedList.Add((object)num1++, (object)index);
                        }
                    }
                    else
                    {
                        this.lookupPaths[index] = str1;
                    }
                }
                else
                {
                    sortedList.Add((object)num1++, (object)index);
                }
            }
            for (int count = sortedList.Count; count > 0; --count)
            {
                this.lookupPaths.RemoveAt((int)sortedList[(object)(count - 1)]);
            }
        }
Esempio n. 29
0
 internal string GetUnresolvedProviderPathFromPSPath(string path, CmdletProviderContext context, out ProviderInfo provider, out PSDriveInfo drive)
 {
     return(this.PathResolver.GetProviderPath(path, context, out provider, out drive));
 }
Esempio n. 30
0
 internal System.Management.Automation.ProviderInfo Start(System.Management.Automation.ProviderInfo providerInfo, CmdletProviderContext cmdletProviderContext)
 {
     this.Context = cmdletProviderContext;
     return(this.Start(providerInfo));
 }
Esempio n. 31
0
        } // SetLocation

        /// <summary>
        /// Determines if the specified path is the current working directory
        /// or a parent of the current working directory.
        /// </summary>
        ///
        /// <param name="path">
        /// A monad namespace absolute or relative path.
        /// </param>
        ///
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        ///
        /// <returns>
        /// true, if the path is the current working directory or a parent of the current
        /// working directory. false, otherwise.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        ///
        /// <exception cref="ProviderNotFoundException">
        /// If the path is a provider-qualified path for a provider that is
        /// not loaded into the system.
        /// </exception>
        ///
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        ///
        /// <exception cref="ProviderInvocationException">
        /// If the provider used to build the path threw an exception.
        /// </exception>
        ///
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> represents is not a NavigationCmdletProvider
        /// or ContainerCmdletProvider.
        /// </exception>
        ///
        /// <exception cref="InvalidOperationException">
        /// If the <paramref name="path"/> starts with "~" and the home location is not set for
        /// the provider.
        /// </exception>
        ///
        /// <exception cref="ProviderInvocationException">
        /// If the provider specified by <paramref name="providerId"/> threw an
        /// exception when its GetParentPath or MakePath was called while
        /// processing the <paramref name="path"/>.
        /// </exception>
        ///
        internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext context)
        {
            bool result = false;

            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            PSDriveInfo  drive    = null;
            ProviderInfo provider = null;

            string providerSpecificPath =
                Globber.GetProviderPath(
                    path,
                    context,
                    out provider,
                    out drive);

            if (drive != null)
            {
                s_tracer.WriteLine("Tracing drive");
                drive.Trace();
            }

            Dbg.Diagnostics.Assert(
                providerSpecificPath != null,
                "There should always be a way to generate a provider path for a " +
                "given path");

            if (drive != null)
            {
                context.Drive = drive;
            }

            // Check to see if the path that was specified is within the current
            // working drive

            if (drive == CurrentDrive)
            {
                // The path needs to be normalized to get rid of relative path tokens
                // so they don't interfere with our path comparisons below

                CmdletProviderContext normalizePathContext
                    = new CmdletProviderContext(context);

                try
                {
                    providerSpecificPath = NormalizeRelativePath(path, null, normalizePathContext);
                }
                catch (NotSupportedException)
                {
                    // Since the provider does not support normalizing the path, just
                    // use the path we currently have.
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                if (normalizePathContext.HasErrors())
                {
                    normalizePathContext.ThrowFirstErrorOrDoNothing();
                }

                s_tracer.WriteLine("Provider path = {0}", providerSpecificPath);

                // Get the current working directory provider specific path

                PSDriveInfo  currentWorkingDrive  = null;
                ProviderInfo currentDriveProvider = null;

                string currentWorkingPath =
                    Globber.GetProviderPath(
                        ".",
                        context,
                        out currentDriveProvider,
                        out currentWorkingDrive);

                Dbg.Diagnostics.Assert(
                    currentWorkingDrive == CurrentDrive,
                    "The current working drive should be the CurrentDrive.");

                s_tracer.WriteLine(
                    "Current working path = {0}",
                    currentWorkingPath);

                // See if the path is the current working directory or a parent
                // of the current working directory

                s_tracer.WriteLine(
                    "Comparing {0} to {1}",
                    providerSpecificPath,
                    currentWorkingPath);

                if (String.Compare(providerSpecificPath, currentWorkingPath, StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    // The path is the current working directory so
                    // return true

                    s_tracer.WriteLine("The path is the current working directory");

                    result = true;
                }
                else
                {
                    // Check to see if the specified path is a parent
                    // of the current working directory

                    string lockedDirectory = currentWorkingPath;

                    while (lockedDirectory.Length > 0)
                    {
                        // We need to allow the provider to go as far up the tree
                        // as it can even if that means it has to traverse higher
                        // than the mount point for this drive. That is
                        // why we are passing the empty string as the root here.

                        lockedDirectory =
                            GetParentPath(
                                drive.Provider,
                                lockedDirectory,
                                String.Empty,
                                context);

                        s_tracer.WriteLine(
                            "Comparing {0} to {1}",
                            lockedDirectory,
                            providerSpecificPath);

                        if (String.Compare(lockedDirectory, providerSpecificPath, StringComparison.CurrentCultureIgnoreCase) == 0)
                        {
                            // The path is a parent of the current working
                            // directory

                            s_tracer.WriteLine(
                                "The path is a parent of the current working directory: {0}",
                                lockedDirectory);

                            result = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                s_tracer.WriteLine("Drives are not the same");
            }

            return(result);
        } // IsCurrentLocationOrAncestor
Esempio n. 32
0
        internal Collection <string> GetResolvedProviderPathFromPSPath(string path, CmdletProviderContext context, out ProviderInfo provider)
        {
            CmdletProvider providerInstance = null;

            return(this.PathResolver.GetGlobbedProviderPathsFromMonadPath(path, false, context, out provider, out providerInstance));
        }
Esempio n. 33
0
        } // SetLocation

        /// <summary>
        /// Changes the current working directory to the path specified
        /// </summary>
        ///
        /// <param name="path">
        /// The path of the new current working directory
        /// </param>
        ///
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        ///
        /// <returns>
        /// The PathInfo object representing the path of the location
        /// that was set.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="path"/> does not exist, is not a container, or
        /// resolved to multiple containers.
        /// </exception>
        ///
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> refers to a provider that does not exist.
        /// </exception>
        ///
        /// <exception cref="DriveNotFoundException">
        /// If <paramref name="path"/> refers to a drive that does not exist.
        /// </exception>
        ///
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with <paramref name="path"/> threw an
        /// exception.
        /// </exception>
        ///
        /// <exception cref="ItemNotFoundException">
        /// If the <paramref name="path"/> could not be resolved.
        /// </exception>
        ///
        internal PathInfo SetLocation(string path, CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            string       originalPath = path;
            string       driveName    = null;
            ProviderInfo provider     = null;
            string       providerId   = null;

            PSDriveInfo previousWorkingDrive = CurrentDrive;

            // First check to see if the path is a home path

            if (LocationGlobber.IsHomePath(path))
            {
                path = Globber.GetHomeRelativePath(path);
            }

            if (LocationGlobber.IsProviderDirectPath(path))
            {
                // The path is a provider-direct path so use the current
                // provider and its hidden drive but don't modify the path
                // at all.

                provider     = CurrentLocation.Provider;
                CurrentDrive = provider.HiddenDrive;
            }
            else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId))
            {
                provider     = GetSingleProvider(providerId);
                CurrentDrive = provider.HiddenDrive;
            }
            else
            {
                // See if the path is a relative or absolute
                // path.

                if (Globber.IsAbsolutePath(path, out driveName))
                {
                    // Since the path is an absolute path
                    // we need to change the current working
                    // drive

                    PSDriveInfo newWorkingDrive = GetDrive(driveName);
                    CurrentDrive = newWorkingDrive;

                    // Now that the current working drive is set,
                    // process the rest of the path as a relative path.
                }
            }

            if (context == null)
            {
                context = new CmdletProviderContext(this.ExecutionContext);
            }

            if (CurrentDrive != null)
            {
                context.Drive = CurrentDrive;
            }

            CmdletProvider providerInstance = null;

            Collection <PathInfo> workingPath = null;

            try
            {
                workingPath =
                    Globber.GetGlobbedMonadPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out providerInstance);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception) // Catch-all OK, 3rd party callout
            {
                // Reset the drive to the previous drive and
                // then rethrow the error

                CurrentDrive = previousWorkingDrive;
                throw;
            }

            if (workingPath.Count == 0)
            {
                // Set the current working drive back to the previous
                // one in case it was changed.

                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // We allow globbing the location as long as it only resolves a single container.

            bool foundContainer                     = false;
            bool pathIsContainer                    = false;
            bool pathIsProviderQualifiedPath        = false;
            bool currentPathisProviderQualifiedPath = false;

            for (int index = 0; index < workingPath.Count; ++index)
            {
                CmdletProviderContext normalizePathContext =
                    new CmdletProviderContext(context);

                PathInfo resolvedPath = workingPath[index];
                string   currentPath  = path;
                try
                {
                    string providerName = null;
                    currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName);
                    if (currentPathisProviderQualifiedPath)
                    {
                        // The path should be the provider-qualified path without the provider ID
                        // or ::

                        string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path);

                        try
                        {
                            currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, String.Empty, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception) // Catch-all OK, 3rd party callout
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error

                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }
                    else
                    {
                        try
                        {
                            currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception) // Catch-all OK, 3rd party callout
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error

                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }

                    // Now see if there was errors while normalizing the path

                    if (normalizePathContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        normalizePathContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                // Check to see if the path is a container

                bool isContainer = false;

                CmdletProviderContext itemContainerContext =
                    new CmdletProviderContext(context);
                itemContainerContext.SuppressWildcardExpansion = true;

                try
                {
                    isContainer =
                        IsItemContainer(
                            resolvedPath.Path,
                            itemContainerContext);

                    if (itemContainerContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        itemContainerContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                catch (NotSupportedException)
                {
                    if (currentPath.Length == 0)
                    {
                        // Treat this as a container because providers that only
                        // support the ContainerCmdletProvider interface are really
                        // containers at their root.

                        isContainer = true;
                    }
                }
                finally
                {
                    itemContainerContext.RemoveStopReferral();
                }

                if (isContainer)
                {
                    if (foundContainer)
                    {
                        // The path resolved to more than one container

                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        throw
                            PSTraceSource.NewArgumentException(
                                "path",
                                SessionStateStrings.PathResolvedToMultiple,
                                originalPath);
                    }
                    else
                    {
                        // Set the path to use
                        path = currentPath;

                        // Mark it as a container
                        pathIsContainer = true;

                        // Mark whether or not it was provider-qualified
                        pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath;

                        // Mark that we have already found one container. Finding additional
                        // should be an error
                        foundContainer = true;
                    }
                }
            }

            if (pathIsContainer)
            {
                // Remove the root slash since it is implied that the
                // current working directory is relative to the root.

                if (!LocationGlobber.IsProviderDirectPath(path) &&
                    path.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.CurrentCulture) &&
                    !pathIsProviderQualifiedPath)
                {
                    path = path.Substring(1);
                }

                s_tracer.WriteLine(
                    "New working path = {0}",
                    path);

                CurrentDrive.CurrentLocation = path;
            }
            else
            {
                // Set the current working drive back to the previous
                // one in case it was changed.

                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        originalPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // Now make sure the current drive is set in the provider's
            // current working drive hashtable

            ProvidersCurrentWorkingDrive[CurrentDrive.Provider] =
                CurrentDrive;

            // Set the $PWD variable to the new location

            this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal);
            return(this.CurrentLocation);
        } // SetLocation
Esempio n. 34
0
 public Collection <string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider)
 {
     return(SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider));
 }
Esempio n. 35
0
        private void InitializeProvider(CmdletProvider providerInstance, ProviderInfo provider)
        {
            List<PSDriveInfo> drives = new List<PSDriveInfo>();
            DriveCmdletProvider driveProvider = providerInstance as DriveCmdletProvider;

            if (driveProvider != null)
            {
                Collection<PSDriveInfo> collection = driveProvider.DoInitializeDefaultDrives();
                if ((collection != null) && (collection.Count > 0))
                {
                    drives.AddRange(collection);
                    _providersCurrentDrive[provider] = collection[0];
                }
            }

            if (drives.Count > 0)
            {
                foreach (PSDriveInfo driveInfo in drives)
                {
                    if (driveInfo != null)
                    {
                        // TODO: need to set driveInfo.Root

                        driveProvider.DoNewDrive(driveInfo);

                        try
                        {
                            _drives.Add(driveInfo.Name, driveInfo);
                        }
                        catch
                        {
                            // TODO: What should we do if the drive name is not unique?
                        }
                    }
                }
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Constructor to make it easy to wrap a provider exception
        /// </summary>
        /// 
        /// <param name="errorId">
        /// This string will be used to construct the FullyQualifiedErrorId,
        /// which is a global identifier of the error condition.  Pass a
        /// non-empty string which is specific to this error condition in
        /// this context.
        /// </param>
        /// 
        /// <param name="resourceStr">
        /// This is the message template string
        /// </param>
        /// 
        /// <param name="provider">
        /// The provider information used to format into the message.
        /// </param>
        /// 
        /// <param name="path">
        /// The path that was being processed when the exception occurred.
        /// </param>
        /// 
        /// <param name="innerException">
        /// The exception that was thrown by the provider.
        /// </param>
        /// 
        /// <param name="useInnerExceptionMessage">
        /// If true, the message from the inner exception will be used if the exception contains
        /// an ErrorRecord. If false, the error message retrieved using the errorId will be used.
        /// </param>
        /// 
        internal ProviderInvocationException(
            string errorId,
            string resourceStr,
            ProviderInfo provider,
            string path,
            Exception innerException,
            bool useInnerExceptionMessage)
            : base(
                RetrieveMessage(errorId, resourceStr, provider, path, innerException),
                innerException)
        {
            _providerInfo = provider;

            _message = base.Message;

            Exception errorRecordException = null;
            if (useInnerExceptionMessage)
            {
                errorRecordException = innerException;
            }
            else
            {
                errorRecordException = new ParentContainsErrorRecordException(this);
            }

            IContainsErrorRecord icer = innerException as IContainsErrorRecord;
            if (null != icer && null != icer.ErrorRecord)
            {
                _errorRecord = new ErrorRecord(icer.ErrorRecord, errorRecordException);
            }
            else
            {
                _errorRecord = new ErrorRecord(
                    errorRecordException,
                    errorId,
                    ErrorCategory.InvalidOperation,
                    null);
            }
        }
Esempio n. 37
0
        /// <summary>
        /// Constructs a ProviderInvocationException with provider information and an
        /// ErrorRecord.
        /// </summary>
        /// 
        /// <param name="provider">
        /// Information about the provider to be used in formatting the message.
        /// </param>
        /// 
        /// <param name="errorRecord">
        /// Detailed error information
        /// </param>
        internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRecord)
            : base(RuntimeException.RetrieveMessage(errorRecord),
                    RuntimeException.RetrieveException(errorRecord))
        {
            if (null == errorRecord)
            {
                throw new ArgumentNullException("errorRecord");
            }

            _message = base.Message;
            _providerInfo = provider;
            _errorRecord = errorRecord;
        }
        /// <summary>
        /// Changes the current working directory to the path specified.
        /// </summary>
        /// <param name="path">
        /// The path of the new current working directory.
        /// </param>
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        /// <param name="literalPath">
        /// Indicate if the path is a literal path.
        /// </param>
        /// <returns>
        /// The PathInfo object representing the path of the location
        /// that was set.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="path"/> does not exist, is not a container, or
        /// resolved to multiple containers.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> refers to a provider that does not exist.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If <paramref name="path"/> refers to a drive that does not exist.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with <paramref name="path"/> threw an
        /// exception.
        /// </exception>
        /// <exception cref="ItemNotFoundException">
        /// If the <paramref name="path"/> could not be resolved.
        /// </exception>
        internal PathInfo SetLocation(string path, CmdletProviderContext context, bool literalPath)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            PathInfo     current      = CurrentLocation;
            string       originalPath = path;
            string       driveName    = null;
            ProviderInfo provider     = null;
            string       providerId   = null;

            switch (originalPath)
            {
            case string originalPathSwitch when !literalPath && originalPathSwitch.Equals("-", StringComparison.Ordinal):
                if (_setLocationHistory.UndoCount <= 0)
                {
                    throw new InvalidOperationException(SessionStateStrings.LocationUndoStackIsEmpty);
                }

                path = _setLocationHistory.Undo(this.CurrentLocation).Path;
                break;

            case string originalPathSwitch when !literalPath && originalPathSwitch.Equals("+", StringComparison.Ordinal):
                if (_setLocationHistory.RedoCount <= 0)
                {
                    throw new InvalidOperationException(SessionStateStrings.LocationRedoStackIsEmpty);
                }

                path = _setLocationHistory.Redo(this.CurrentLocation).Path;
                break;

            default:
                var pushPathInfo = GetNewPushPathInfo();
                _setLocationHistory.Push(pushPathInfo);
                break;
            }

            PSDriveInfo previousWorkingDrive = CurrentDrive;

            // First check to see if the path is a home path
            if (LocationGlobber.IsHomePath(path))
            {
                path = Globber.GetHomeRelativePath(path);
            }

            if (LocationGlobber.IsProviderDirectPath(path))
            {
                // The path is a provider-direct path so use the current
                // provider and its hidden drive but don't modify the path
                // at all.
                provider     = CurrentLocation.Provider;
                CurrentDrive = provider.HiddenDrive;
            }
            else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId))
            {
                provider     = GetSingleProvider(providerId);
                CurrentDrive = provider.HiddenDrive;
            }
            else
            {
                // See if the path is a relative or absolute
                // path.
                if (Globber.IsAbsolutePath(path, out driveName))
                {
                    // Since the path is an absolute path
                    // we need to change the current working
                    // drive
                    PSDriveInfo newWorkingDrive = GetDrive(driveName);
                    CurrentDrive = newWorkingDrive;

                    // If the path is simply a colon-terminated drive,
                    // not a slash-terminated path to the root of a drive,
                    // set the path to the current working directory of that drive.
                    string colonTerminatedVolume = CurrentDrive.Name + ':';
                    if (CurrentDrive.VolumeSeparatedByColon && (path.Length == colonTerminatedVolume.Length))
                    {
                        path = Path.Combine(colonTerminatedVolume + Path.DirectorySeparatorChar, CurrentDrive.CurrentLocation);
                    }

                    // Now that the current working drive is set,
                    // process the rest of the path as a relative path.
                }
            }

            if (context == null)
            {
                context = new CmdletProviderContext(this.ExecutionContext);
            }

            if (CurrentDrive != null)
            {
                context.Drive = CurrentDrive;
            }

            CmdletProvider providerInstance = null;

            Collection <PathInfo> workingPath = null;

            try
            {
                workingPath =
                    Globber.GetGlobbedMonadPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out providerInstance);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception)
            {
                // Reset the drive to the previous drive and
                // then rethrow the error
                CurrentDrive = previousWorkingDrive;
                throw;
            }

            if (workingPath.Count == 0)
            {
                // Set the current working drive back to the previous
                // one in case it was changed.
                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // We allow globbing the location as long as it only resolves a single container.
            bool foundContainer                     = false;
            bool pathIsContainer                    = false;
            bool pathIsProviderQualifiedPath        = false;
            bool currentPathisProviderQualifiedPath = false;

            for (int index = 0; index < workingPath.Count; ++index)
            {
                CmdletProviderContext normalizePathContext =
                    new CmdletProviderContext(context);

                PathInfo resolvedPath = workingPath[index];
                string   currentPath  = path;
                try
                {
                    string providerName = null;
                    currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName);
                    if (currentPathisProviderQualifiedPath)
                    {
                        // The path should be the provider-qualified path without the provider ID
                        // or ::
                        string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path);

                        try
                        {
                            currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, string.Empty, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception)
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error
                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }
                    else
                    {
                        try
                        {
                            currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception)
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error
                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }

                    // Now see if there was errors while normalizing the path
                    if (normalizePathContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        normalizePathContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                bool isContainer = false;

                CmdletProviderContext itemContainerContext =
                    new CmdletProviderContext(context);
                itemContainerContext.SuppressWildcardExpansion = true;

                try
                {
                    isContainer =
                        IsItemContainer(
                            resolvedPath.Path,
                            itemContainerContext);

                    if (itemContainerContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        itemContainerContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                catch (NotSupportedException)
                {
                    if (currentPath.Length == 0)
                    {
                        // Treat this as a container because providers that only
                        // support the ContainerCmdletProvider interface are really
                        // containers at their root.
                        isContainer = true;
                    }
                }
                finally
                {
                    itemContainerContext.RemoveStopReferral();
                }

                if (isContainer)
                {
                    if (foundContainer)
                    {
                        // The path resolved to more than one container
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        throw
                            PSTraceSource.NewArgumentException(
                                nameof(path),
                                SessionStateStrings.PathResolvedToMultiple,
                                originalPath);
                    }
                    else
                    {
                        // Set the path to use
                        path = currentPath;

                        // Mark it as a container
                        pathIsContainer = true;

                        // Mark whether or not it was provider-qualified
                        pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath;

                        // Mark that we have already found one container. Finding additional
                        // should be an error
                        foundContainer = true;
                    }
                }
            }

            if (pathIsContainer)
            {
                // Remove the root slash since it is implied that the
                // current working directory is relative to the root.
                if (!LocationGlobber.IsProviderDirectPath(path) &&
                    path.StartsWith(StringLiterals.DefaultPathSeparator) &&
                    !pathIsProviderQualifiedPath)
                {
                    path = path.Substring(1);
                }

                s_tracer.WriteLine(
                    "New working path = {0}",
                    path);

                CurrentDrive.CurrentLocation = path;
            }
            else
            {
                // Set the current working drive back to the previous
                // one in case it was changed.
                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        originalPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // Now make sure the current drive is set in the provider's
            // current working drive hashtable
            ProvidersCurrentWorkingDrive[CurrentDrive.Provider] =
                CurrentDrive;

            // Set the $PWD variable to the new location
            this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal);

            // If an action has been defined for location changes, invoke it now.
            if (PublicSessionState.InvokeCommand.LocationChangedAction != null)
            {
                var eventArgs = new LocationChangedEventArgs(PublicSessionState, current, CurrentLocation);
                PublicSessionState.InvokeCommand.LocationChangedAction.Invoke(ExecutionContext.CurrentRunspace, eventArgs);
                s_tracer.WriteLine("Invoked LocationChangedAction");
            }

            return(this.CurrentLocation);
        }
Esempio n. 39
0
        internal Collection <string> GetResolvedProviderPathFromPSPath(string path, bool allowNonexistingPaths, out ProviderInfo provider)
        {
            CmdletProvider providerInstance = null;

            return(this.PathResolver.GetGlobbedProviderPathsFromMonadPath(path, allowNonexistingPaths, out provider, out providerInstance));
        }
 /// <summary>
 /// Gives the provider the opportunity to initialize itself.
 /// </summary>
 /// 
 /// <param name="providerInfo">
 /// The information about the provider that is being started.
 /// </param>
 /// 
 /// <returns>
 /// Either the providerInfo that was passed or a derived class
 /// of ProviderInfo that was initialized with the provider information
 /// that was passed.
 /// </returns>
 /// 
 /// <remarks>
 /// The default implementation returns the ProviderInfo instance that
 /// was passed.To have session state maintain persisted data on behalf
 /// of the provider, the provider should derive from 
 /// <see cref="System.Management.Automation.ProviderInfo"/>
 /// and add any properties or methods for the data it wishes to persist.
 /// When Start gets called the provider should construct an instance of 
 /// its derived ProviderInfo using the providerInfo that is passed in 
 /// and return that new instance.
 /// </remarks>
 protected override ProviderInfo Start( ProviderInfo providerInfo )
 {
     return providerInfo;
 }
Esempio n. 41
0
        private static string RetrieveMessage(
            string errorId,
            string resourceStr,
            ProviderInfo provider,
            string path,
            Exception innerException)
        {
            if (innerException == null)
            {
                Diagnostics.Assert(false,
                                   "ProviderInvocationException.RetrieveMessage needs innerException");
                return(string.Empty);
            }

            if (string.IsNullOrEmpty(errorId))
            {
                Diagnostics.Assert(false,
                                   "ProviderInvocationException.RetrieveMessage needs errorId");
                return(RuntimeException.RetrieveMessage(innerException));
            }

            if (provider == null)
            {
                Diagnostics.Assert(false,
                                   "ProviderInvocationException.RetrieveMessage needs provider");
                return(RuntimeException.RetrieveMessage(innerException));
            }

            string format = resourceStr;

            if (string.IsNullOrEmpty(format))
            {
                Diagnostics.Assert(false,
                                   "ProviderInvocationException.RetrieveMessage bad errorId " + errorId);
                return(RuntimeException.RetrieveMessage(innerException));
            }

            string result = null;

            if (path == null)
            {
                result =
                    string.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        format,
                        provider.Name,
                        RuntimeException.RetrieveMessage(innerException));
            }
            else
            {
                result =
                    string.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        format,
                        provider.Name,
                        path,
                        RuntimeException.RetrieveMessage(innerException));
            }

            return(result);
        }
Esempio n. 42
0
        private CmdletProvider AddProvider(ProviderInfo providerInfo)
        {
            CmdletProvider provider = providerInfo.CreateInstance();

            provider.Start(providerInfo, new ProviderRuntime(_executionContext));
            provider.SetProviderInfo(providerInfo);

            // Cache the Provider's Info
            if (!_providers.ContainsKey(providerInfo.Name))
            {
                _providers.Add(providerInfo.Name, new List<ProviderInfo>());
            }
            _providers[providerInfo.Name].Add(providerInfo);

            return provider;
        }
Esempio n. 43
0
        /// <summary>
        /// On Windows, just append <paramref name="arg"/>.
        /// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>.
        /// </summary>
        /// <param name="arg">The argument that possibly needs expansion.</param>
        /// <param name="usedQuotes">True if the argument was a quoted string (single or double).</param>
        private void PossiblyGlobArg(string arg, bool usedQuotes)
        {
            var argExpanded = false;

#if UNIX
            // On UNIX systems, we expand arguments containing wildcard expressions against
            // the file system just like bash, etc.
            if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg))
            {
                // See if the current working directory is a filesystem provider location
                // We won't do the expansion if it isn't since native commands can only access the file system.
                var cwdinfo = Context.EngineSessionState.CurrentLocation;

                // If it's a filesystem location then expand the wildcards
                if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    // On UNIX, paths starting with ~ or absolute paths are not normalized
                    bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/');

                    // See if there are any matching paths otherwise just add the pattern as the argument
                    Collection <PSObject> paths = null;
                    try
                    {
                        paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false);
                    }
                    catch
                    {
                        // Fallthrough will append the pattern unchanged.
                    }

                    // Expand paths, but only from the file system.
                    if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo))
                    {
                        var sep = string.Empty;
                        foreach (var path in paths)
                        {
                            _arguments.Append(sep);
                            sep = " ";
                            var expandedPath = (path.BaseObject as FileSystemInfo).FullName;
                            if (normalizePath)
                            {
                                expandedPath =
                                    Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath);
                            }
                            // If the path contains spaces, then add quotes around it.
                            if (NeedQuotes(expandedPath))
                            {
                                _arguments.Append("\"");
                                _arguments.Append(expandedPath);
                                _arguments.Append("\"");
                            }
                            else
                            {
                                _arguments.Append(expandedPath);
                            }

                            argExpanded = true;
                        }
                    }
                }
            }
            else if (!usedQuotes)
            {
                // Even if there are no wildcards, we still need to possibly
                // expand ~ into the filesystem provider home directory path
                ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName);
                string       home = fileSystemProvider.Home;
                if (string.Equals(arg, "~"))
                {
                    _arguments.Append(home);
                    argExpanded = true;
                }
                else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
                {
                    var replacementString = home + arg.Substring(1);
                    _arguments.Append(replacementString);
                    argExpanded = true;
                }
            }
#endif // UNIX

            if (!argExpanded)
            {
                _arguments.Append(arg);
            }
        }
Esempio n. 44
0
        /// <summary>
        /// Get provider specific help info.
        /// </summary>
        internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName)
        {
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                // By returning null, we force get-help to return generic help
                // which includes a helpUri that points to the fwlink defined in the cmdlet code.
                return(null);
            }

            // Get the provider.
            ProviderInfo          providerInfo          = null;
            PSDriveInfo           driveInfo             = null;
            string                resolvedProviderPath  = null;
            CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(_executionContext);

            try
            {
                string psPath = _requestedPath;
                if (string.IsNullOrEmpty(_requestedPath))
                {
                    psPath = _pathIntrinsics.CurrentLocation.Path;
                }

                resolvedProviderPath = _executionContext.LocationGlobber.GetProviderPath(
                    psPath,
                    cmdletProviderContext,
                    out providerInfo,
                    out driveInfo);
            }
            // ignore exceptions caused by provider resolution
            catch (ArgumentNullException)
            {
            }
            catch (ProviderNotFoundException)
            {
            }
            catch (DriveNotFoundException)
            {
            }
            catch (ProviderInvocationException)
            {
            }
            catch (NotSupportedException)
            {
            }
            catch (InvalidOperationException)
            {
            }
            catch (ItemNotFoundException)
            {
            }

            if (providerInfo is null)
            {
                return(null);
            }

            // Does the provider know how to generate MAML.
            CmdletProvider cmdletProvider        = providerInfo.CreateInstance();
            ICmdletProviderSupportsHelp provider = cmdletProvider as ICmdletProviderSupportsHelp;

            // Under JEA sessions the resolvedProviderPath will be null, we should allow get-help to continue.
            if (provider is null)
            {
                return(null);
            }

            bool isJEASession = false;

            if (this._executionContext.InitialSessionState != null && this._executionContext.InitialSessionState.Providers != null && providerInfo != null)
            {
                foreach (
                    Runspaces.SessionStateProviderEntry sessionStateProvider in
                    this._executionContext.InitialSessionState.Providers[providerInfo.Name])
                {
                    if (sessionStateProvider.Visibility == SessionStateEntryVisibility.Private)
                    {
                        isJEASession = true;
                        break;
                    }
                }
            }

            if (resolvedProviderPath is null)
            {
                if (isJEASession)
                {
                    return(null);
                }
                else
                {
                    throw new ItemNotFoundException(_requestedPath, "PathNotFound", SessionStateStrings.PathNotFound);
                }
            }

            // ok we have path and valid provider that supplys content..initialize the provider
            // and get the help content for the path.
            cmdletProvider.Start(providerInfo, cmdletProviderContext);
            // There should be exactly one resolved path.
            string providerPath = resolvedProviderPath;
            // Get the MAML help info. Don't catch exceptions thrown by provider.
            string mamlXmlString = provider.GetHelpMaml(helpItemName, providerPath);

            if (string.IsNullOrEmpty(mamlXmlString))
            {
                return(null);
            }
            // process the MAML content only if it is non-empty.
            XmlDocument mamlDoc = InternalDeserializer.LoadUnsafeXmlDocument(
                mamlXmlString,
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */
            MamlCommandHelpInfo providerSpecificHelpInfo = MamlCommandHelpInfo.Load(mamlDoc.DocumentElement, HelpCategory.Provider);

            return(providerSpecificHelpInfo);
        }
Esempio n. 45
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential, bool persist) : this(name, provider, root, description, credential)
 {
     this.persist = persist;
 }
Esempio n. 46
0
 /// <summary>
 /// Constructs a ProviderInvocationException
 /// </summary>
 /// 
 /// <param name="errorId">
 /// This string will be used to construct the FullyQualifiedErrorId,
 /// which is a global identifier of the error condition.  Pass a
 /// non-empty string which is specific to this error condition in
 /// this context.
 /// </param>
 /// 
 /// <param name="resourceStr">
 /// This string is the message template string.
 /// </param>
 /// 
 /// <param name="provider">
 /// The provider information used to format into the message.
 /// </param>
 /// 
 /// <param name="path">
 /// The path that was being processed when the exception occurred.
 /// </param>
 /// 
 /// <param name="innerException">
 /// The exception that was thrown by the provider.
 /// </param>
 /// 
 internal ProviderInvocationException(
     string errorId,
     string resourceStr,
     ProviderInfo provider,
     string path,
     Exception innerException)
     : this(errorId, resourceStr, provider, path, innerException, true)
 {
 }
Esempio n. 47
0
 public PSDriveInfo(string name, ProviderInfo provider, string root, string description, PSCredential credential, string displayRoot) : this(name, provider, root, description, credential)
 {
     this.displayRoot = displayRoot;
 }
Esempio n. 48
0
        private static string RetrieveMessage(
            string errorId,
            string resourceStr,
            ProviderInfo provider,
            string path,
            Exception innerException)
        {
            if (null == innerException)
            {
                Diagnostics.Assert(false,
                "ProviderInvocationException.RetrieveMessage needs innerException");
                return "";
            }
            if (String.IsNullOrEmpty(errorId))
            {
                Diagnostics.Assert(false,
                "ProviderInvocationException.RetrieveMessage needs errorId");
                return RuntimeException.RetrieveMessage(innerException);
            }
            if (null == provider)
            {
                Diagnostics.Assert(false,
                "ProviderInvocationException.RetrieveMessage needs provider");
                return RuntimeException.RetrieveMessage(innerException);
            }

            string format = resourceStr;
            if (String.IsNullOrEmpty(format))
            {
                Diagnostics.Assert(false,
                "ProviderInvocationException.RetrieveMessage bad errorId " + errorId);
                return RuntimeException.RetrieveMessage(innerException);
            }
            string result = null;

            if (path == null)
            {
                result =
                    String.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        format,
                        provider.Name,
                        RuntimeException.RetrieveMessage(innerException));
            }
            else
            {
                result =
                    String.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        format,
                        provider.Name,
                        path,
                        RuntimeException.RetrieveMessage(innerException));
            }
            return result;
        }
        /// <summary>
        /// Load help file provided.
        /// </summary>
        /// <remarks>
        /// This will load providerHelpInfo from help file into help cache.
        /// </remarks>
        /// <param name="providerInfo">providerInfo for which to locate help.</param>
        private void LoadHelpFile(ProviderInfo providerInfo)
        {
            if (providerInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("providerInfo");
            }

            string helpFile = providerInfo.HelpFile;

            if (String.IsNullOrEmpty(helpFile) || _helpFiles.Contains(helpFile))
            {
                return;
            }

            string helpFileToLoad = helpFile;

            // Get the mshsnapinfo object for this cmdlet.
            PSSnapInInfo mshSnapInInfo = providerInfo.PSSnapIn;

            // Search fallback
            // 1. If PSSnapInInfo exists, then always look in the application base
            //    of the mshsnapin
            // Otherwise,
            //    Look in the default search path and cmdlet assembly path
            Collection <String> searchPaths = new Collection <String>();

            if (mshSnapInInfo != null)
            {
                Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase),
                                   "Application Base is null or empty.");
                // not minishell case..
                // we have to search only in the application base for a mshsnapin...
                // if you create an absolute path for helpfile, then MUIFileSearcher
                // will look only in that path.
                helpFileToLoad = Path.Combine(mshSnapInInfo.ApplicationBase, helpFile);
            }
            else if ((providerInfo.Module != null) && (!string.IsNullOrEmpty(providerInfo.Module.Path)))
            {
                helpFileToLoad = Path.Combine(providerInfo.Module.ModuleBase, helpFile);
            }
            else
            {
                searchPaths.Add(GetDefaultShellSearchPath());
                searchPaths.Add(GetProviderAssemblyPath(providerInfo));
            }

            string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths);

            if (String.IsNullOrEmpty(location))
            {
                throw new FileNotFoundException(helpFile);
            }

            XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                new FileInfo(location),
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */

            // Add this file into _helpFiles hashtable to prevent it to be loaded again.
            _helpFiles[helpFile] = 0;

            XmlNode helpItemsNode = null;

            if (doc.HasChildNodes)
            {
                for (int i = 0; i < doc.ChildNodes.Count; i++)
                {
                    XmlNode node = doc.ChildNodes[i];
                    if (node.NodeType == XmlNodeType.Element && String.Compare(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        helpItemsNode = node;
                        break;
                    }
                }
            }

            if (helpItemsNode == null)
            {
                return;
            }

            using (this.HelpSystem.Trace(location))
            {
                if (helpItemsNode.HasChildNodes)
                {
                    for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
                    {
                        XmlNode node = helpItemsNode.ChildNodes[i];
                        if (node.NodeType == XmlNodeType.Element && String.Compare(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            HelpInfo helpInfo = ProviderHelpInfo.Load(node);

                            if (helpInfo != null)
                            {
                                this.HelpSystem.TraceErrors(helpInfo.Errors);
                                // Add snapin qualified type name for this command..
                                // this will enable customizations of the help object.
                                helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture,
                                                                                    "ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name));

                                if (!string.IsNullOrEmpty(providerInfo.PSSnapInName))
                                {
                                    helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn));
                                    helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture,
                                                                                        "ProviderHelpInfo#{0}", providerInfo.PSSnapInName));
                                }
                                AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 50
0
 public Collection<string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider)
 {
     return SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);
 }
Esempio n. 51
0
        private void LoadHelpFile(ProviderInfo providerInfo)
        {
            if (providerInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("providerInfo");
            }
            string helpFile = providerInfo.HelpFile;

            if (!string.IsNullOrEmpty(helpFile) && !this._helpFiles.Contains(helpFile))
            {
                string              file        = helpFile;
                PSSnapInInfo        pSSnapIn    = providerInfo.PSSnapIn;
                Collection <string> searchPaths = new Collection <string>();
                if (pSSnapIn != null)
                {
                    file = Path.Combine(pSSnapIn.ApplicationBase, helpFile);
                }
                else if ((providerInfo.Module != null) && !string.IsNullOrEmpty(providerInfo.Module.Path))
                {
                    file = Path.Combine(providerInfo.Module.ModuleBase, helpFile);
                }
                else
                {
                    searchPaths.Add(base.GetDefaultShellSearchPath());
                    searchPaths.Add(GetProviderAssemblyPath(providerInfo));
                }
                string str3 = MUIFileSearcher.LocateFile(file, searchPaths);
                if (string.IsNullOrEmpty(str3))
                {
                    throw new FileNotFoundException(helpFile);
                }
                XmlDocument document = InternalDeserializer.LoadUnsafeXmlDocument(new FileInfo(str3), false, null);
                this._helpFiles[helpFile] = 0;
                System.Xml.XmlNode node = null;
                if (document.HasChildNodes)
                {
                    for (int i = 0; i < document.ChildNodes.Count; i++)
                    {
                        System.Xml.XmlNode node2 = document.ChildNodes[i];
                        if ((node2.NodeType == XmlNodeType.Element) && (string.Compare(node2.Name, "helpItems", StringComparison.OrdinalIgnoreCase) == 0))
                        {
                            node = node2;
                            break;
                        }
                    }
                }
                if (node != null)
                {
                    using (base.HelpSystem.Trace(str3))
                    {
                        if (node.HasChildNodes)
                        {
                            for (int j = 0; j < node.ChildNodes.Count; j++)
                            {
                                System.Xml.XmlNode xmlNode = node.ChildNodes[j];
                                if ((xmlNode.NodeType == XmlNodeType.Element) && (string.Compare(xmlNode.Name, "providerHelp", StringComparison.OrdinalIgnoreCase) == 0))
                                {
                                    HelpInfo helpInfo = ProviderHelpInfo.Load(xmlNode);
                                    if (helpInfo != null)
                                    {
                                        base.HelpSystem.TraceErrors(helpInfo.Errors);
                                        helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, "ProviderHelpInfo#{0}#{1}", new object[] { providerInfo.PSSnapInName, helpInfo.Name }));
                                        if (!string.IsNullOrEmpty(providerInfo.PSSnapInName))
                                        {
                                            helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn));
                                            helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, "ProviderHelpInfo#{0}", new object[] { providerInfo.PSSnapInName }));
                                        }
                                        base.AddCache(providerInfo.PSSnapInName + @"\" + helpInfo.Name, helpInfo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }