Esempio n. 1
0
        internal PSNotSupportedException NewNotSupportedException()
        {
            PSNotSupportedException supportedException = new PSNotSupportedException(ResourceManagerCache.FormatResourceString(Assembly.GetAssembly(typeof(PSObject)), "AutomationExceptions", "NotSupported", (object)new StackTrace().GetFrame(0).ToString()));

            this.TraceException((Exception)supportedException);
            return(supportedException);
        }
Esempio n. 2
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This is not allowed to call other
        /// Throw*Exception variants, since they call this.
        /// </summary>
        /// <returns>Exception instance ready to throw.</returns>
        internal static PSNotSupportedException NewNotSupportedException()
        {
            string message = StringUtil.Format(AutomationExceptions.NotSupported,
                                               new System.Diagnostics.StackTrace().GetFrame(0).ToString());
            var e = new PSNotSupportedException(message);

            return(e);
        }
Esempio n. 3
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This is not allowed to call other
        /// Throw*Exception variants, since they call this.
        /// </summary>
        /// <returns>Exception instance ready to throw</returns>
        internal static PSNotSupportedException NewNotSupportedException()
        {
#if CORECLR //TODO:CORECLR StackTrace is not in CoreCLR
            string message = string.Empty;
#else
            string message = StringUtil.Format(AutomationExceptions.NotSupported,
                                               new System.Diagnostics.StackTrace().GetFrame(0).ToString());
#endif
            var e = new PSNotSupportedException(message);

            return(e);
        }
Esempio n. 4
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This is not allowed to call other
        /// Throw*Exception variants, since they call this.
        /// </summary>
        /// <param name="resourceString">
        /// The template string for this error
        /// </param>
        /// <param name="args">
        /// Objects corresponding to {0}, {1}, etc. in the resource string
        /// </param>
        /// <returns>Exception instance ready to throw.</returns>
        internal static PSNotSupportedException NewNotSupportedException(
            string resourceString,
            params object[] args)
        {
            if (string.IsNullOrEmpty(resourceString))
            {
                throw NewArgumentNullException(nameof(resourceString));
            }

            string message = StringUtil.Format(resourceString, args);
            var    e       = new PSNotSupportedException(message);

            return(e);
        }
Esempio n. 5
0
        internal PSNotSupportedException NewNotSupportedException(
            string baseName,
            string resourceId,
            params object[] args)
        {
            if (string.IsNullOrEmpty(baseName))
            {
                throw this.NewArgumentNullException(nameof(baseName));
            }
            if (string.IsNullOrEmpty(resourceId))
            {
                throw this.NewArgumentNullException(nameof(resourceId));
            }
            PSNotSupportedException supportedException = new PSNotSupportedException(ResourceManagerCache.FormatResourceString(Assembly.GetCallingAssembly(), baseName, resourceId, args));

            this.TraceException((Exception)supportedException);
            return(supportedException);
        }
Esempio n. 6
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This is not allowed to call other
        /// Throw*Exception variants, since they call this.
        /// </summary>
        /// 
        /// <param name="resourceString">
        /// The template string for this error
        /// </param>
        /// 
        /// <param name="args">
        /// Objects corresponding to {0}, {1}, etc. in the resource string
        /// </param>
        /// 
        /// <returns>Exception instance ready to throw</returns>
        internal static PSNotSupportedException NewNotSupportedException(
            string resourceString,
            params object[] args)
        {
            if (String.IsNullOrEmpty(resourceString))
            {
                throw NewArgumentNullException("resourceString");
            }

            string message = StringUtil.Format(resourceString, args);
            var e = new PSNotSupportedException(message);

            return e;
        }
Esempio n. 7
0
        /// <summary>
        /// Traces the Message and StackTrace properties of the exception
        /// and returns the new exception. This is not allowed to call other
        /// Throw*Exception variants, since they call this.
        /// </summary>
        /// <returns>Exception instance ready to throw</returns>
        internal static PSNotSupportedException NewNotSupportedException()
        {
#if CORECLR //TODO:CORECLR StackTrace is not in CoreCLR
            string message = string.Empty;
#else
            string message = StringUtil.Format(AutomationExceptions.NotSupported,
                new System.Diagnostics.StackTrace().GetFrame(0).ToString());
#endif
            var e = new PSNotSupportedException(message);

            return e;
        }
Esempio n. 8
0
        /// <summary>
        /// Perform runspace disconnect processing on all input.
        /// </summary>
        protected override void ProcessRecord()
        {
            Dictionary<Guid, PSSession> psSessions;
            List<IThrottleOperation> disconnectOperations = new List<IThrottleOperation>();

            try
            {
                // Get all remote runspaces to disconnect.
                if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet)
                {
                    if (Session == null || Session.Length == 0)
                    {
                        return;
                    }

                    psSessions = new Dictionary<Guid, PSSession>();
                    foreach (PSSession psSession in Session)
                    {
                        psSessions.Add(psSession.InstanceId, psSession);
                    }
                }
                else
                {
                    psSessions = GetMatchingRunspaces(false, true);
                }

                // Look for local sessions that have the EnableNetworkAccess property set and 
                // return a string containing all of the session names.  Emit a warning for 
                // these sessions.
                string cnNames = GetLocalhostWithNetworkAccessEnabled(psSessions);
                if (!string.IsNullOrEmpty(cnNames))
                {
                    WriteWarning(
                        StringUtil.Format(RemotingErrorIdStrings.EnableNetworkAccessWarning, cnNames));
                }

                // Create a disconnect operation for each runspace to disconnect.
                foreach (PSSession psSession in psSessions.Values)
                {
                    if (ShouldProcess(psSession.Name, VerbsCommunications.Disconnect))
                    {
                        // PS session disconnection is not supported for VM/Container sessions.
                        if (psSession.ComputerType != TargetMachineType.RemoteMachine)
                        {
                            // Write error record.
                            string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnectedForVMContainerSession,
                                psSession.Name, psSession.ComputerName, psSession.ComputerType);
                            Exception reason = new PSNotSupportedException(msg);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "CannotDisconnectVMContainerSession", ErrorCategory.InvalidOperation, psSession);
                            WriteError(errorRecord);
                            continue;
                        }

                        // Can only disconnect an Opened runspace.
                        if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                        {
                            // Update the connectionInfo object with passed in session options.
                            if (_sessionOption != null)
                            {
                                psSession.Runspace.ConnectionInfo.SetSessionOptions(_sessionOption);
                            }

                            // Validate the ConnectionInfo IdleTimeout value against the MaxIdleTimeout
                            // value returned by the server and the hard coded minimum allowed value.
                            if (!ValidateIdleTimeout(psSession))
                            {
                                continue;
                            }

                            DisconnectRunspaceOperation disconnectOperation = new DisconnectRunspaceOperation(psSession, _stream);
                            disconnectOperations.Add(disconnectOperation);
                        }
                        else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected)
                        {
                            // Write error record.
                            string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnected, psSession.Name);
                            Exception reason = new RuntimeException(msg);
                            ErrorRecord errorRecord = new ErrorRecord(reason, "CannotDisconnectSessionWhenNotOpened", ErrorCategory.InvalidOperation, psSession);
                            WriteError(errorRecord);
                        }
                        else
                        {
                            // Session is already disconnected.  Write to output.
                            WriteObject(psSession);
                        }
                    }
                }
            }
            catch (PSRemotingDataStructureException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }
            catch (PSRemotingTransportException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }
            catch (RemoteException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }
            catch (InvalidRunspaceStateException)
            {
                // Allow cmdlet to end and then re-throw exception.
                _operationsComplete.Set();
                throw;
            }

            if (disconnectOperations.Count > 0)
            {
                // Make sure operations are not set as complete while processing input.
                _operationsComplete.Reset();

                // Submit list of disconnect operations.
                _throttleManager.SubmitOperations(disconnectOperations);

                // Write any output now.
                Collection<object> streamObjects = _stream.ObjectReader.NonBlockingRead();
                foreach (object streamObject in streamObjects)
                {
                    WriteStreamObject((Action<Cmdlet>)streamObject);
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Gets the PSSession object to connect based on Id, Name, etc.
        /// Connects the running command associated with the PSSession runspace object.
        /// Command output is either returned (OutTarget.Host) or collected
        /// in a job object that is returned (OutTarget.Job).
        /// </summary>
        private void GetAndConnectSessionCommand()
        {
            PSSession session = null;

            if (ParameterSetName == ReceivePSSessionCommand.SessionParameterSet)
            {
                session = Session;
            }
            else if (ParameterSetName == ReceivePSSessionCommand.IdParameterSet)
            {
                session = GetSessionById(Id);
                if (session == null)
                {
                    WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId,
                                              RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId,
                                              Id);

                    return;
                }
            }
            else if (ParameterSetName == ReceivePSSessionCommand.NameParameterSet)
            {
                session = GetSessionByName(Name);
                if (session == null)
                {
                    WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName,
                                              RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName,
                                              Name);

                    return;
                }
            }
            else if (ParameterSetName == ReceivePSSessionCommand.InstanceIdParameterSet)
            {
                session = GetSessionByInstanceId(InstanceId);
                if (session == null)
                {
                    WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId,
                                              RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId,
                                              InstanceId);

                    return;
                }
            }
            else
            {
                Dbg.Assert(false, "Invalid Parameter Set");
            }

            // PS session disconnection is not supported for VM/Container sessions.
            if (session.ComputerType != TargetMachineType.RemoteMachine)
            {
                string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeReceivedForVMContainerSession,
                    session.Name, session.ComputerName, session.ComputerType);
                Exception reason = new PSNotSupportedException(msg);
                ErrorRecord errorRecord = new ErrorRecord(reason, "CannotReceiveVMContainerSession", ErrorCategory.InvalidOperation, session);
                WriteError(errorRecord);
                return;
            }

            if (ShouldProcess(session.Name, VerbsCommunications.Receive))
            {
                Exception ex;
                if (ConnectSession(session, out ex) == null)
                {
                    // Unable to connect runspace.  If this was a *reconnect* runspace then try
                    // obtaining a connectable runspace directly from the server and do a 
                    // *reconstruct* connect.
                    PSSession oldSession = session;
                    session = TryGetSessionFromServer(oldSession);
                    if (session == null)
                    {
                        // No luck.  Return error.
                        String message = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, oldSession.Name);
                        WriteError(new ErrorRecord(new ArgumentException(message, ex), "ReceivePSSessionCannotConnectSession",
                                   ErrorCategory.InvalidOperation, oldSession));

                        return;
                    }
                }

                // Look to see if there exists a job associated with this runspace.
                // If so then we use this job object, unless the user explicitly specifies
                // output to host.
                PSRemotingJob job = FindJobForSession(session);
                if (job != null)
                {
                    // Default is to route data to job.
                    if (OutTarget == OutTarget.Host)
                    {
                        // This performs a *reconstruct* connection scenario where a new
                        // pipeline object is created and connected.
                        ConnectSessionToHost(session, job);
                    }
                    else
                    {
                        // This preforms a *reconnect* scenario where the existing job
                        // and runspace objects are reconnected.
                        ConnectSessionToJob(session, job);
                    }
                }
                else
                {
                    // Default is to route data to host.
                    if (OutTarget == OutTarget.Job)
                    {
                        // This performs a *reconstruct* connection scenario where new
                        // pipeline/job objects are created and connected.
                        ConnectSessionToJob(session);
                    }
                    else
                    {
                        // This performs a *reconstruct* connection scenario where a new
                        // pipeline object is created and connected.
                        ConnectSessionToHost(session);
                    }
                }

                // Make sure that if this session is successfully connected that it is included 
                // in the PSSession repository.  If it already exists then replace it because we 
                // want the latest/connected session in the repository.
                if (session.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected)
                {
                    this.RunspaceRepository.AddOrReplace(session);
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Connect all disconnected sessions.
        /// </summary>
        private void ConnectSessions(Collection<PSSession> psSessions)
        {
            List<IThrottleOperation> connectOperations = new List<IThrottleOperation>();

            // Create a disconnect operation for each runspace to disconnect.
            foreach (PSSession psSession in psSessions)
            {
                if (ShouldProcess(psSession.Name, VerbsCommunications.Connect))
                {
                    if (psSession.ComputerType != TargetMachineType.RemoteMachine)
                    {
                        // PS session disconnection is not supported for VM/Container sessions.
                        string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnectedForVMContainerSession,
                            psSession.Name, psSession.ComputerName, psSession.ComputerType);
                        Exception reason = new PSNotSupportedException(msg);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "CannotConnectVMContainerSession", ErrorCategory.InvalidOperation, psSession);
                        WriteError(errorRecord);
                    }
                    else if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Disconnected &&
                        psSession.Runspace.RunspaceAvailability == RunspaceAvailability.None)
                    {
                        // Can only connect sessions that are in Disconnected state.                    
                        // Update session connection information based on cmdlet parameters.
                        UpdateConnectionInfo(psSession.Runspace.ConnectionInfo as WSManConnectionInfo);

                        ConnectRunspaceOperation connectOperation = new ConnectRunspaceOperation(
                            psSession,
                            _stream,
                            this.Host,
                            null,
                            _failedSessions);
                        connectOperations.Add(connectOperation);
                    }
                    else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)
                    {
                        // Write error record if runspace is not already in the Opened state.
                        string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, psSession.Name);
                        Exception reason = new RuntimeException(msg);
                        ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionConnectFailed", ErrorCategory.InvalidOperation, psSession);
                        WriteError(errorRecord);
                    }
                    else
                    {
                        // Session is already connected.  Write to output.
                        WriteObject(psSession);
                    }
                }

                _allSessions.Add(psSession);
            }

            if (connectOperations.Count > 0)
            {
                // Make sure operations are not set as complete while processing input.
                _operationsComplete.Reset();

                // Submit list of connect operations.
                _throttleManager.SubmitOperations(connectOperations);

                // Write any output now.
                Collection<object> streamObjects = _stream.ObjectReader.NonBlockingRead();
                foreach (object streamObject in streamObjects)
                {
                    WriteStreamObject((Action<Cmdlet>)streamObject);
                }
            }
        }
Esempio n. 11
0
        protected Database OpenDatabase(string path)
        {
            var type = FileInfo.GetFileTypeInternal(path);
            if (FileType.Package == type)
            {
                var db = new InstallPackage(path, DatabaseOpenMode.ReadOnly);
                this.ApplyTransforms(db);

                return db;
            }
            else if (FileType.Patch == type)
            {
                return new PatchPackage(path);
            }
            else
            {
                var message = string.Format(Resources.Error_InvalidStorage, path);
                var ex = new PSNotSupportedException(message);
                if (null != ex.ErrorRecord)
                {
                    base.WriteError(ex.ErrorRecord);
                }

                return null;
            }
        }