private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
 {
     using (_trace.TraceEventHandlers())
     {
         if (fsmEventArg == null)
         {
             throw PSTraceSource.NewArgumentNullException("fsmEventArg");
         }
         if (fsmEventArg.StateEvent != RemoteSessionEvent.ConnectFailed)
         {
             throw PSTraceSource.NewArgumentException("fsmEventArg");
         }
         throw PSTraceSource.NewInvalidOperationException();
     }
 }
Exemplo n.º 2
0
        private string ResolveProviderAndPath(string path)
        {
            CmdletProviderContext currentCommandContext = new CmdletProviderContext(this);
            PathInfo info = this.ResolvePath(path, true, currentCommandContext);

            if (info == null)
            {
                return(null);
            }
            if (info.Provider.ImplementingType != typeof(FileSystemProvider))
            {
                throw PSTraceSource.NewInvalidOperationException("ConsoleInfoErrorStrings", "ProviderNotSupported", new object[] { info.Provider.Name });
            }
            return(info.Path);
        }
        /// <summary>
        /// Read a value from the configuration file.
        /// </summary>
        /// <typeparam name="T">The type of the value</typeparam>
        /// <param name="scope">The ConfigScope of the configuration file to update.</param>
        /// <param name="key">The string key of the value.</param>
        /// <param name="defaultValue">The default value to return if the key is not present.</param>
        private T ReadValueFromFile <T>(ConfigScope scope, string key, T defaultValue = default)
        {
            string  fileName   = GetConfigFilePath(scope);
            JObject configData = configRoots[(int)scope];

            if (configData == null)
            {
                if (File.Exists(fileName))
                {
                    try
                    {
                        // Open file for reading, but allow multiple readers
                        fileLock.EnterReadLock();

                        using var stream     = OpenFileStreamWithRetry(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        using var jsonReader = new JsonTextReader(new StreamReader(stream));

                        configData = serializer.Deserialize <JObject>(jsonReader) ?? emptyConfig;
                    }
                    catch (Exception exc)
                    {
                        throw PSTraceSource.NewInvalidOperationException(exc, PSConfigurationStrings.CanNotConfigurationFile, args: fileName);
                    }
                    finally
                    {
                        fileLock.ExitReadLock();
                    }
                }
                else
                {
                    configData = emptyConfig;
                }

                // Set the configuration cache.
                JObject originalValue = Interlocked.CompareExchange(ref configRoots[(int)scope], configData, null);
                if (originalValue != null)
                {
                    configData = originalValue;
                }
            }

            if (configData != emptyConfig && configData.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out JToken jToken))
            {
                return(jToken.ToObject <T>(serializer) ?? defaultValue);
            }

            return(defaultValue);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Update the given collection with the items in Add and Remove.
        /// </summary>
        /// <param name="collectionToUpdate">The collection to update.</param>
        public void ApplyTo(object collectionToUpdate)
        {
            if (collectionToUpdate == null)
            {
                throw new ArgumentNullException(nameof(collectionToUpdate));
            }

            collectionToUpdate = PSObject.Base(collectionToUpdate);

            if (!(collectionToUpdate is IList list))
            {
                throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed);
            }

            ApplyTo(list);
        }
        private string GetScript(string filePath)
        {
            InvalidOperationException ioe = null;

            try
            {
                // 197751: WR BUG BASH: Powershell: localized text display as garbage
                // leaving the encoding to be decided by the StreamReader. StreamReader
                // will read the preamble and decide proper encoding.
                using (FileStream scriptStream = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (StreamReader scriptReader = new(scriptStream))
                    {
                        return(scriptReader.ReadToEnd());
                    }
            }
            catch (ArgumentException e)
            {
                ioe = PSTraceSource.NewInvalidOperationException(
                    ImportLocalizedDataStrings.ErrorOpeningFile,
                    filePath,
                    e.Message);
            }
            catch (IOException e)
            {
                ioe = PSTraceSource.NewInvalidOperationException(
                    ImportLocalizedDataStrings.ErrorOpeningFile,
                    filePath,
                    e.Message);
            }
            catch (NotSupportedException e)
            {
                ioe = PSTraceSource.NewInvalidOperationException(
                    ImportLocalizedDataStrings.ErrorOpeningFile,
                    filePath,
                    e.Message);
            }
            catch (UnauthorizedAccessException e)
            {
                ioe = PSTraceSource.NewInvalidOperationException(
                    ImportLocalizedDataStrings.ErrorOpeningFile,
                    filePath,
                    e.Message);
            }

            WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.OpenError, filePath));
            return(null);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Analyze a value for generic/text statistics.
        /// Side effects: Updates statistics. May set nonNumericError.
        /// <param name="propertyName">The property this value corresponds to.</param>
        /// <param name="objValue">The value to analyze.</param>
        /// </summary>
        private void AnalyzeValue(string propertyName, object objValue)
        {
            if (propertyName == null)
            {
                propertyName = thisObject;
            }

            Statistics stat = _statistics.EnsureEntry(propertyName);

            // Update common properties.
            stat.count++;

            if (_measureCharacters || _measureWords || _measureLines)
            {
                string strValue = (objValue == null) ? string.Empty : objValue.ToString();
                AnalyzeString(strValue, stat);
            }

            if (_measureAverage || _measureSum || _measureStandardDeviation)
            {
                double numValue = 0.0;
                if (!LanguagePrimitives.TryConvertTo(objValue, out numValue))
                {
                    _nonNumericError = true;
                    ErrorRecord errorRecord = new ErrorRecord(
                        PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue),
                        "NonNumericInputObject",
                        ErrorCategory.InvalidType,
                        objValue);
                    WriteError(errorRecord);
                    return;
                }

                AnalyzeNumber(numValue, stat);
            }

            // Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo
            if (_measureMin)
            {
                stat.min = Compare(objValue, stat.min, true);
            }

            if (_measureMax)
            {
                stat.max = Compare(objValue, stat.max, false);
            }
        }
Exemplo n.º 7
0
        internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock)
        {
            PipelineBase currentlyRunningPipeline = (PipelineBase)this.RunspaceBase.GetCurrentlyRunningPipeline();

            if (!this.IsNested)
            {
                if (currentlyRunningPipeline != null)
                {
                    if ((currentlyRunningPipeline != this.RunspaceBase.PulsePipeline) && (!currentlyRunningPipeline.IsNested || (this.RunspaceBase.PulsePipeline == null)))
                    {
                        throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "ConcurrentInvokeNotAllowed", new object[0]);
                    }
                    if (isInLock)
                    {
                        Monitor.Exit(syncObject);
                    }
                    try
                    {
                        this.RunspaceBase.WaitForFinishofPipelines();
                    }
                    finally
                    {
                        if (isInLock)
                        {
                            Monitor.Enter(syncObject);
                        }
                    }
                    this.DoConcurrentCheck(syncCall, syncObject, isInLock);
                }
            }
            else if (this._performNestedCheck)
            {
                if (!syncCall)
                {
                    throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NestedPipelineInvokeAsync", new object[0]);
                }
                if (currentlyRunningPipeline == null)
                {
                    throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NestedPipelineNoParentPipeline", new object[0]);
                }
                Thread currentThread = Thread.CurrentThread;
                if (!currentlyRunningPipeline.NestedPipelineExecutionThread.Equals(currentThread))
                {
                    throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NestedPipelineNoParentPipeline", new object[0]);
                }
            }
        }
Exemplo n.º 8
0
        internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable)
        {
            if (!originalParameterWasHashTable)
            {
                throw PSTraceSource.NewInvalidOperationException();
            }
            string str = val as string;

            if (string.IsNullOrEmpty(str))
            {
                string msg = StringUtil.Format(FormatAndOut_MshParameter.EmptyFormatStringValueError, base.KeyName);
                ParameterProcessor.ThrowParameterBindingException(invocationContext, "FormatStringEmpty", msg);
            }
            return(new FieldFormattingDirective {
                formatString = str
            });
        }
Exemplo n.º 9
0
        public void ReleaseRunspace(Runspace runspace)
        {
            if (runspace == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspace");
            }
            this.AssertPoolIsOpen();
            bool flag  = false;
            bool flag2 = false;

            lock (this.runspaceList)
            {
                if (!this.runspaceList.Contains(runspace))
                {
                    throw PSTraceSource.NewInvalidOperationException(resBaseName, "RunspaceNotBelongsToPool", new object[0]);
                }
            }
            if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
            {
                lock (this.pool)
                {
                    if (this.pool.Count < this.maxPoolSz)
                    {
                        flag = true;
                        this.pool.Push(runspace);
                    }
                    else
                    {
                        flag  = true;
                        flag2 = true;
                    }
                    goto Label_00B3;
                }
            }
            flag2 = true;
            flag  = true;
Label_00B3:
            if (flag2)
            {
                this.DestroyRunspace(runspace);
            }
            if (flag)
            {
                this.EnqueueCheckAndStartRequestServicingThread(null, false);
            }
        }
Exemplo n.º 10
0
        internal static ConfigurationDataFromXML LoadEndPointConfiguration(string shellId, string initializationParameters)
        {
            ConfigurationDataFromXML mxml = null;

            if (!ssnStateProviders.ContainsKey(initializationParameters))
            {
                LoadRSConfigProvider(shellId, initializationParameters);
            }
            lock (syncObject)
            {
                if (!ssnStateProviders.TryGetValue(initializationParameters, out mxml))
                {
                    throw PSTraceSource.NewInvalidOperationException("remotingerroridstrings", "NonExistentInitialSessionStateProvider", new object[] { shellId });
                }
            }
            return(mxml);
        }
Exemplo n.º 11
0
 internal void LinkPipelineErrorOutput(Pipe pipeToUse)
 {
     for (int i = 0; i < this._commands.Count; i++)
     {
         CommandProcessorBase base2 = this._commands[i];
         if ((base2 == null) || (base2.CommandRuntime == null))
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         Pipe errorOutputPipe = base2.CommandRuntime.ErrorOutputPipe;
         if (base2.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null)
         {
             base2.CommandRuntime.ErrorOutputPipe = pipeToUse;
         }
     }
     this._linkedErrorOutput = true;
 }
Exemplo n.º 12
0
        /// <summary>
        /// Opens the Uri. System's default application will be used
        /// to show the uri.
        /// </summary>
        /// <param name="uriToLaunch"></param>
        private void LaunchOnlineHelp(Uri uriToLaunch)
        {
            Diagnostics.Assert(null != uriToLaunch, "uriToLaunch should not be null");

            if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
                !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw PSTraceSource.NewInvalidOperationException(HelpErrors.ProtocolNotSupported,
                                                                 uriToLaunch.ToString(),
                                                                 "http",
                                                                 "https");
            }

            Exception exception = null;

            try
            {
                this.WriteVerbose(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                System.Diagnostics.Process browserProcess = new System.Diagnostics.Process();

#if UNIX
                browserProcess.StartInfo.FileName  = Platform.IsLinux ? "xdg-open" : /* OS X */ "open";
                browserProcess.StartInfo.Arguments = uriToLaunch.OriginalString;
                browserProcess.Start();
#elif CORECLR
                throw new PlatformNotSupportedException();
#else
                browserProcess.StartInfo.FileName = uriToLaunch.OriginalString;
                browserProcess.Start();
#endif
            }
            catch (InvalidOperationException ioe)
            {
                exception = ioe;
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                exception = we;
            }

            if (null != exception)
            {
                throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
            }
        }
Exemplo n.º 13
0
 private void CoreInvoke(IEnumerable input, bool syncCall)
 {
     lock (this.SyncRoot)
     {
         if (this._disposed)
         {
             throw PSTraceSource.NewObjectDisposedException("pipeline");
         }
         if ((base.Commands == null) || (base.Commands.Count == 0))
         {
             throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NoCommandInPipeline", new object[0]);
         }
         if (this.PipelineState != System.Management.Automation.Runspaces.PipelineState.NotStarted)
         {
             InvalidPipelineStateException exception = new InvalidPipelineStateException(StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed, new object[0]), this.PipelineState, System.Management.Automation.Runspaces.PipelineState.NotStarted);
             throw exception;
         }
         if ((syncCall && !(this._inputStream is PSDataCollectionStream <PSObject>)) && !(this._inputStream is PSDataCollectionStream <object>))
         {
             if (input != null)
             {
                 foreach (object obj2 in input)
                 {
                     this._inputStream.Write(obj2);
                 }
             }
             this._inputStream.Close();
         }
         this._syncInvokeCall        = syncCall;
         this._pipelineFinishedEvent = new ManualResetEvent(false);
         this.RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);
         this.SetPipelineState(System.Management.Automation.Runspaces.PipelineState.Running);
     }
     try
     {
         this.StartPipelineExecution();
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
         this.RunspaceBase.RemoveFromRunningPipelineList(this);
         this.SetPipelineState(System.Management.Automation.Runspaces.PipelineState.Failed, exception2);
         throw;
     }
 }
Exemplo n.º 14
0
 private void RetrieveProcessesByInput()
 {
     if (this.InputObject != null)
     {
         Process[] inputObject = this.InputObject;
         for (int i = 0; i < (int)inputObject.Length; i++)
         {
             Process process = inputObject[i];
             ProcessBaseCommand.SafeRefresh(process);
             this.AddIdempotent(process);
         }
         return;
     }
     else
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
 }
 BeginProcessing()
 {
     try
     {
         string outFilename = Host.UI.StopTranscribing();
         if (outFilename != null)
         {
             PSObject outputObject = new PSObject(
                 StringUtil.Format(TranscriptStrings.TranscriptionStopped, outFilename));
             outputObject.Properties.Add(new PSNoteProperty("Path", outFilename));
             WriteObject(outputObject);
         }
     }
     catch (Exception e)
     {
         throw PSTraceSource.NewInvalidOperationException(
                   e, TranscriptStrings.ErrorStoppingTranscript, e.Message);
     }
 }
 private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
 {
     using (_trace.TraceEventHandlers())
     {
         if (fsmEventArg == null)
         {
             throw PSTraceSource.NewArgumentNullException("fsmEventArg");
         }
         if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationCompleted)
         {
             throw PSTraceSource.NewArgumentException("fsmEventArg");
         }
         if (this._state != RemoteSessionState.NegotiationSent)
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         this.SetState(RemoteSessionState.Established, null);
     }
 }
Exemplo n.º 17
0
        private CommandInfo GetImportModuleCommandInfo(string moduleName, ref List <ErrorRecord> errors)
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            if (LoadAssemblyHelper(executingAssembly.FullName, ref errors) != null)
            {
                Exception exception;
                Type      implementingType = LanguagePrimitives.ConvertStringToType("Microsoft.PowerShell.Commands.ImportModuleCommand", out exception);
                if (exception != null)
                {
                    errors.Add(new ErrorRecord(exception, "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", ErrorCategory.InvalidType, null));
                }
                if (implementingType != null)
                {
                    return(new CmdletInfo("Import-Module", implementingType, null, null, this._engine.Context));
                }
                errors.Add(new ErrorRecord(PSTraceSource.NewInvalidOperationException("RunspaceStrings", "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", new object[] { moduleName }), "CmdletNotFoundWhileLoadingModulesOnRunspaceOpen", ErrorCategory.InvalidOperation, null));
            }
            return(null);
        }
        private List <ServiceController> MatchingServicesByInput()
        {
            List <ServiceController> serviceControllers = new List <ServiceController>();

            if (this.InputObject != null)
            {
                ServiceController[] inputObject = this.InputObject;
                for (int i = 0; i < (int)inputObject.Length; i++)
                {
                    ServiceController serviceController = inputObject[i];
                    serviceController.Refresh();
                    this.IncludeExcludeAdd(serviceControllers, serviceController, false);
                }
                return(serviceControllers);
            }
            else
            {
                throw PSTraceSource.NewInvalidOperationException();
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Resolves the specified path and verifies the path belongs to
        /// FileSystemProvider.
        /// </summary>
        /// <param name="path">Path to resolve</param>
        /// <returns>A fully qualified string representing filename.</returns>
        private string ResolveProviderAndPath(string path)
        {
            // Construct cmdletprovidercontext
            CmdletProviderContext cmdContext = new CmdletProviderContext(this);
            // First resolve path
            PathInfo resolvedPath = ResolvePath(path, true, cmdContext);

            // Check whether this is FileSystemProvider..
            if (resolvedPath != null)
            {
                if (resolvedPath.Provider.ImplementingType == typeof(FileSystemProvider))
                {
                    return(resolvedPath.Path);
                }

                throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ProviderNotSupported, resolvedPath.Provider.Name);
            }

            return(null);
        }
Exemplo n.º 20
0
 internal void Update(AuthorizationManager authorizationManager, PSHost host)
 {
     if (!this.DisableFormatTableUpdates)
     {
         if (this.isShared)
         {
             throw PSTraceSource.NewInvalidOperationException("FormatAndOutXmlLoadingStrings", "SharedFormatTableCannotBeUpdated", new object[0]);
         }
         Collection <PSSnapInTypeAndFormatErrors> mshsnapins = new Collection <PSSnapInTypeAndFormatErrors>();
         lock (this.formatFileList)
         {
             foreach (string str in this.formatFileList)
             {
                 PSSnapInTypeAndFormatErrors item = new PSSnapInTypeAndFormatErrors(string.Empty, str);
                 mshsnapins.Add(item);
             }
         }
         this.UpdateDataBase(mshsnapins, authorizationManager, host, false);
     }
 }
Exemplo n.º 21
0
        private Array RetrieveResults(Hashtable errorResults)
        {
            if (!this._linkedErrorOutput)
            {
                for (int i = 0; i < this._commands.Count; i++)
                {
                    CommandProcessorBase base2 = this._commands[i];
                    if ((base2 == null) || (base2.CommandRuntime == null))
                    {
                        throw PSTraceSource.NewInvalidOperationException();
                    }
                    Pipe errorOutputPipe = base2.CommandRuntime.ErrorOutputPipe;
                    if ((errorOutputPipe.DownstreamCmdlet == null) && !errorOutputPipe.Empty)
                    {
                        if (errorResults != null)
                        {
                            errorResults.Add(i + 1, errorOutputPipe.ToArray());
                        }
                        errorOutputPipe.Clear();
                    }
                }
            }
            if (this._linkedSuccessOutput)
            {
                return(MshCommandRuntime.StaticEmptyArray);
            }
            CommandProcessorBase base3 = this._commands[this._commands.Count - 1];

            if ((base3 == null) || (base3.CommandRuntime == null))
            {
                throw PSTraceSource.NewInvalidOperationException();
            }
            Array resultsAsArray = base3.CommandRuntime.GetResultsAsArray();

            base3.CommandRuntime.OutputPipe.Clear();
            if (resultsAsArray == null)
            {
                return(MshCommandRuntime.StaticEmptyArray);
            }
            return(resultsAsArray);
        }
Exemplo n.º 22
0
        private CommandProcessorBase _CreateCommand(string commandName,
                                                    CommandOrigin commandOrigin, bool?useLocalScope)
        {
            if (_context == null)
            {
                throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.ExecutionContextNotSet);
            }

            // Look for a cmdlet...
            CommandDiscovery discovery = _context.CommandDiscovery;

            if (discovery == null)
            {
                throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.CommandDiscoveryMissing);
            }

            // Look for the command using command discovery mechanisms.  This will resolve
            // aliases, functions, filters, cmdlets, scripts, and applications.

            return(discovery.LookupCommandProcessor(commandName, commandOrigin, useLocalScope));
        }
        internal static System.Management.Automation.Language.StringConstantType MapTokenKindToStringContantKind(Token token)
        {
            switch (token.Kind)
            {
            case TokenKind.Generic:
                return(System.Management.Automation.Language.StringConstantType.BareWord);

            case TokenKind.StringLiteral:
                return(System.Management.Automation.Language.StringConstantType.SingleQuoted);

            case TokenKind.StringExpandable:
                return(System.Management.Automation.Language.StringConstantType.DoubleQuoted);

            case TokenKind.HereStringLiteral:
                return(System.Management.Automation.Language.StringConstantType.SingleQuotedHereString);

            case TokenKind.HereStringExpandable:
                return(System.Management.Automation.Language.StringConstantType.DoubleQuotedHereString);
            }
            throw PSTraceSource.NewInvalidOperationException();
        }
Exemplo n.º 24
0
        private void RetrieveMatchingProcessesById()
        {
            Process processById;

            if (this.processIds != null)
            {
                int[] numArray = this.processIds;
                for (int i = 0; i < (int)numArray.Length; i++)
                {
                    int num = numArray[i];
                    try
                    {
                        if ((int)this.SuppliedComputerName.Length <= 0)
                        {
                            processById = Process.GetProcessById(num);
                            this.AddIdempotent(processById);
                        }
                        else
                        {
                            string[] suppliedComputerName = this.SuppliedComputerName;
                            for (int j = 0; j < (int)suppliedComputerName.Length; j++)
                            {
                                string str = suppliedComputerName[j];
                                processById = Process.GetProcessById(num, str);
                                this.AddIdempotent(processById);
                            }
                        }
                    }
                    catch (ArgumentException argumentException)
                    {
                        this.WriteNonTerminatingError("", num, num, null, ProcessResources.NoProcessFoundForGivenId, "NoProcessFoundForGivenId", ErrorCategory.ObjectNotFound);
                    }
                }
                return;
            }
            else
            {
                throw PSTraceSource.NewInvalidOperationException();
            }
        }
Exemplo n.º 25
0
        internal IEnumerable <PSObject> ParseSchemaJson(string filePath, bool useNewRunspace = false)
        {
            try
            {
                string json = File.ReadAllText(filePath);
                string fileNameDefiningClass = Path.GetFileNameWithoutExtension(filePath);
                int    dotIndex = fileNameDefiningClass.IndexOf(".schema", StringComparison.InvariantCultureIgnoreCase);
                if (dotIndex != -1)
                {
                    fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex);
                }

                IEnumerable <PSObject> result = _jsonDeserializer.DeserializeClasses(json, useNewRunspace);
                foreach (dynamic classObject in result)
                {
                    string superClassName = classObject.SuperClassName;
                    string className      = classObject.ClassName;
                    if (string.Equals(superClassName, "OMI_BaseResource", StringComparison.OrdinalIgnoreCase))
                    {
                        // Get the name of the file without schema.mof/json extension
                        if (!className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase))
                        {
                            PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                                ParserStrings.ClassNameNotSameAsDefiningFile, className, fileNameDefiningClass);
                            throw e;
                        }
                    }
                }

                return(result);
            }
            catch (Exception exception)
            {
                PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
                    exception, ParserStrings.CimDeserializationError, filePath);

                e.SetErrorId("CimDeserializationError");
                throw e;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// This is the handler for ConnectFailed event. In this implementation, this should never
        /// happen. This is because the IO channel is stdin/stdout/stderr redirection.
        /// Therefore, the connection is a dummy operation.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="fsmEventArg">
        /// This parameter contains the FSM event.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// If the parameter <paramref name="fsmEventArg"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If the parameter <paramref name="fsmEventArg"/> does not contain ConnectFailed event.
        /// </exception>
        private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
        {
            using (s_trace.TraceEventHandlers())
            {
                if (fsmEventArg == null)
                {
                    throw PSTraceSource.NewArgumentNullException("fsmEventArg");
                }

                Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ConnectFailed, "StateEvent must be ConnectFailed");

                if (fsmEventArg.StateEvent != RemoteSessionEvent.ConnectFailed)
                {
                    throw PSTraceSource.NewArgumentException("fsmEventArg");
                }

                Dbg.Assert(_state == RemoteSessionState.Connecting, "session State must be Connecting");

                // This method should not be called in this implementation.
                throw PSTraceSource.NewInvalidOperationException();
            }
        }
Exemplo n.º 27
0
 private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
 {
     for (int i = 0; i < this._commands.Count; i++)
     {
         CommandProcessorBase objB = this._commands[i];
         if (objB == null)
         {
             throw PSTraceSource.NewInvalidOperationException();
         }
         if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, objB))
         {
             commandRequestingUpstreamCommandsToStop = null;
         }
         else if (commandRequestingUpstreamCommandsToStop == null)
         {
             try
             {
                 objB.DoComplete();
             }
             catch (PipelineStoppedException)
             {
                 StopUpstreamCommandsException firstTerminatingError = this.firstTerminatingError as StopUpstreamCommandsException;
                 if (firstTerminatingError == null)
                 {
                     throw;
                 }
                 this.firstTerminatingError = null;
                 commandRequestingUpstreamCommandsToStop = firstTerminatingError.RequestingCommandProcessor;
             }
             EtwActivity.SetActivityId(objB.PipelineActivityId);
             MshLog.LogCommandLifecycleEvent(objB.Command.Context, CommandState.Stopped, objB.Command.MyInvocation);
         }
     }
     if (this.firstTerminatingError != null)
     {
         this.LogExecutionException(this.firstTerminatingError);
         throw this.firstTerminatingError;
     }
 }
Exemplo n.º 28
0
        /// <summary>
        /// Update the format data database. If there is any error in loading the format xml files,
        /// the old database is unchanged.
        /// The reference returned should NOT be modified by any means by the caller
        /// </summary>
        /// <param name="mshsnapins">files to be loaded and errors to be updated</param>
        /// <param name="authorizationManager">
        /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed)
        /// </param>
        /// <param name="host">
        /// Host passed to <paramref name="authorizationManager"/>.  Can be null if no interactive questions should be asked.
        /// </param>
        /// <param name="preValidated">
        /// True if the format data has been pre-validated (build time, manual testing, etc) so that validation can be
        /// skipped at runtime.
        /// </param>
        /// <returns> database instance</returns>
        internal void UpdateDataBase(
            Collection <PSSnapInTypeAndFormatErrors> mshsnapins,
            AuthorizationManager authorizationManager,
            PSHost host,
            bool preValidated
            )
        {
            if (DisableFormatTableUpdates)
            {
                return;
            }

            if (isShared)
            {
                throw PSTraceSource.NewInvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated);
            }

            PSPropertyExpressionFactory expressionFactory = new PSPropertyExpressionFactory();
            List <XmlLoaderLoggerEntry> logEntries        = null;

            LoadFromFile(mshsnapins, expressionFactory, false, authorizationManager, host, preValidated, out logEntries);
        }
Exemplo n.º 29
0
        internal override object Verify(object val,
                                        TerminatingErrorContext invocationContext,
                                        bool originalParameterWasHashTable)
        {
            if (!originalParameterWasHashTable)
            {
                // this should never happen
                throw PSTraceSource.NewInvalidOperationException();
            }

            // it is a string, need to check for partial match in a case insensitive way
            // and normalize
            string s = val as string;

            if (!string.IsNullOrEmpty(s))
            {
                for (int k = 0; k < s_legalValues.Length; k++)
                {
                    if (CommandParameterDefinition.FindPartialMatch(s, s_legalValues[k]))
                    {
                        if (k == 0)
                        {
                            return(TextAlignment.Left);
                        }

                        if (k == 1)
                        {
                            return(TextAlignment.Center);
                        }

                        return(TextAlignment.Right);
                    }
                }
            }

            // nothing found, we have an illegal value
            ProcessIllegalValue(s, invocationContext);
            return(null);
        }
Exemplo n.º 30
0
        protected override void BeginProcessing()
        {
            InternalHost host = base.Host as InternalHost;

            if (host != null)
            {
                ConsoleHost externalHost = host.ExternalHost as ConsoleHost;
                if (externalHost != null)
                {
                    if (!externalHost.IsTranscribing)
                    {
                        base.WriteObject(TranscriptStrings.TranscriptionNotInProgress);
                    }
                    try
                    {
                        string str = externalHost.StopTranscribing();
                        base.WriteObject(StringUtil.Format(TranscriptStrings.TranscriptionStopped, str));
                    }
                    catch (Exception exception1)
                    {
                        Exception exception = exception1;
                        ConsoleHost.CheckForSevereException(exception);
                        object[] message = new object[1];
                        message[0] = exception.Message;
                        throw PSTraceSource.NewInvalidOperationException(exception, "TranscriptStrings", "ErrorStoppingTranscript", message);
                    }
                    return;
                }
                else
                {
                    throw PSTraceSource.NewNotSupportedException("TranscriptStrings", "HostDoesNotSupportTranscript", new object[0]);
                }
            }
            else
            {
                throw PSTraceSource.NewNotSupportedException("TranscriptStrings", "HostDoesNotSupportTranscript", new object[0]);
            }
        }