internal void ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host) { Exception reason = (Exception)null; bool flag; try { flag = this.ShouldRun(commandInfo, origin, host, out reason); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); flag = false; reason = (Exception)null; } if (flag) { return; } if (reason == null) { throw new PSSecurityException(ResourceManagerCache.GetResourceString("AuthorizationManagerBase", "AuthorizationManagerDefaultFailureReason")); } if (reason is PSSecurityException) { AuthorizationManager.tracer.TraceException(reason); throw reason; } PSSecurityException securityException = new PSSecurityException(reason.Message, reason); AuthorizationManager.tracer.TraceException((Exception)securityException); throw securityException; }
private ActionPreference InquireForActionPreference( string message, ExecutionContext context) { InternalHostUserInterface ui = (InternalHostUserInterface)context.EngineHostInterface.UI; Collection <ChoiceDescription> choices = new Collection <ChoiceDescription>(); string resourceString1 = ResourceManagerCache.GetResourceString("Parser", "ContinueLabel"); string resourceString2 = ResourceManagerCache.GetResourceString("Parser", "ContinueHelpMessage"); string resourceString3 = ResourceManagerCache.GetResourceString("Parser", "SilentlyContinueLabel"); string resourceString4 = ResourceManagerCache.GetResourceString("Parser", "SilentlyContinueHelpMessage"); string resourceString5 = ResourceManagerCache.GetResourceString("Parser", "BreakLabel"); string resourceString6 = ResourceManagerCache.GetResourceString("Parser", "BreakHelpMessage"); string resourceString7 = ResourceManagerCache.GetResourceString("Parser", "SuspendLabel"); string helpMessage = ResourceManagerCache.FormatResourceString("Parser", "SuspendHelpMessage"); choices.Add(new ChoiceDescription(resourceString1, resourceString2)); choices.Add(new ChoiceDescription(resourceString3, resourceString4)); choices.Add(new ChoiceDescription(resourceString5, resourceString6)); choices.Add(new ChoiceDescription(resourceString7, helpMessage)); string resourceString8 = ResourceManagerCache.GetResourceString("Parser", "ExceptionActionPromptCaption"); int num; while ((num = ui.PromptForChoice(resourceString8, message, choices, 0)) == 3) { context.EngineHostInterface.EnterNestedPrompt(); } if (num == 0) { return(ActionPreference.Continue); } return(num == 1 ? ActionPreference.SilentlyContinue : ActionPreference.Stop); }
public Job2 NewJob(JobInvocationInfo specification) { if (specification == null) { throw new ArgumentNullException("specification"); } if (specification.Definition == null) { throw new ArgumentException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "NewJobSpecificationError"), "specification"); } JobSourceAdapter jobSourceAdapter = this.GetJobSourceAdapter(specification.Definition); Job2 job = null; try { job = jobSourceAdapter.NewJob(specification); } catch (Exception exception) { this.Tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); throw; } return(job); }
internal static RuntimeException NewInterpreterExceptionWithInnerException( object targetObject, Type exceptionType, Token errToken, string resourceIdAndErrorId, Exception innerException, params object[] args) { if (string.IsNullOrEmpty(resourceIdAndErrorId)) { throw InterpreterError.tracer.NewArgumentException(nameof(resourceIdAndErrorId)); } RuntimeException runtimeException; try { string message = args == null || args.Length == 0 ? ResourceManagerCache.GetResourceString("Parser", resourceIdAndErrorId) : ResourceManagerCache.FormatResourceString("Parser", resourceIdAndErrorId, args); runtimeException = !string.IsNullOrEmpty(message) ? InterpreterError.NewInterpreterExceptionByMessage(exceptionType, errToken, message, resourceIdAndErrorId, innerException) : InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)null); } catch (InvalidOperationException ex) { runtimeException = InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)ex); } catch (MissingManifestResourceException ex) { runtimeException = InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)ex); } catch (FormatException ex) { runtimeException = InterpreterError.NewBackupInterpreterException(exceptionType, errToken, resourceIdAndErrorId, (Exception)ex); } runtimeException.SetTargetObject(targetObject); return(runtimeException); }
private void ProcessNewSubscriber( PSEventSubscriber subscriber, object source, string eventName, string sourceIdentifier, PSObject data, bool supportEvent, bool forwardEvent) { Delegate handler = (Delegate)null; if (this.eventAssembly == null) { this.debugMode = new StackFrame(0, true).GetFileName() != null; this.eventAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("PSEventHandler"), AssemblyBuilderAccess.Run); } if (this.eventModule == null) { this.eventModule = this.eventAssembly.DefineDynamicModule("PSGenericEventModule", this.debugMode); } if (source != null) { if (!(source is Type type)) { type = source.GetType(); } BindingFlags bindingAttr = BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; EventInfo eventInfo = type.GetEvent(eventName, bindingAttr); if (eventInfo == null) { throw new ArgumentException(ResourceManagerCache.FormatResourceString("EventingResources", "CouldNotFindEvent", (object)eventName), nameof(eventName)); } if (sourceIdentifier != null && sourceIdentifier.StartsWith("PowerShell.", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(ResourceManagerCache.FormatResourceString("EventingResources", "ReservedIdentifier", (object)sourceIdentifier), nameof(sourceIdentifier)); } if (type.GetProperty("EnableRaisingEvents") != null) { type.InvokeMember("EnableRaisingEvents", BindingFlags.SetProperty, (Binder)null, source, new object[1] { (object)true }, CultureInfo.CurrentCulture); } if (source is ManagementEventWatcher managementEventWatcher) { managementEventWatcher.Start(); } MethodInfo method = eventInfo.EventHandlerType.GetMethod("Invoke"); if (method.ReturnType != typeof(void)) { throw new ArgumentException(ResourceManagerCache.GetResourceString("EventingResources", "NonVoidDelegateNotSupported"), nameof(eventName)); } object eventHandler = this.GenerateEventHandler((PSEventManager)this, source, sourceIdentifier, data, method); handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, eventHandler, "EventDelegate"); eventInfo.AddEventHandler(source, handler); } lock (this.eventSubscribers) this.eventSubscribers[subscriber] = handler; }
public override PSEventSubscriber SubscribeEvent( object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent) { throw new NotSupportedException(ResourceManagerCache.GetResourceString("EventingResources", "RemoteOperationNotSupported")); }
private JobSourceAdapter AssertAndReturnJobSourceAdapter(string adapterTypeName) { JobSourceAdapter adapter; lock (this._syncObject) { if (!this._sourceAdapters.TryGetValue(adapterTypeName, out adapter)) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound")); } } return(adapter); }
internal override void DoBeginProcessing() { if (this.CommandRuntime is MshCommandRuntime commandRuntime && (bool)commandRuntime.UseTransaction && !this.Context.TransactionManager.HasTransaction) { string resourceString = ResourceManagerCache.GetResourceString("TransactionStrings", "NoTransactionStarted"); if (this.Context.TransactionManager.IsLastTransactionCommitted) { resourceString = ResourceManagerCache.GetResourceString("TransactionStrings", "NoTransactionStartedFromCommit"); } else if (this.Context.TransactionManager.IsLastTransactionRolledBack) { resourceString = ResourceManagerCache.GetResourceString("TransactionStrings", "NoTransactionStartedFromRollback"); } throw new InvalidOperationException(resourceString); } this.BeginProcessing(); }
internal ArrayList GetResults() { if (this.commandRuntime != null) { throw new InvalidOperationException(); } if (this is PSCmdlet) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("CommandBaseStrings", "CannotInvokePSCmdletsDirectly")); } ArrayList outputArrayList = new ArrayList(); this.CommandRuntime = (ICommandRuntime) new DefaultCommandRuntime(outputArrayList); this.BeginProcessing(); this.ProcessRecord(); this.EndProcessing(); return(outputArrayList); }
internal static void Trace( ExecutionContext context, int level, string messageId, params object[] args) { ActionPreference preference = ActionPreference.Continue; if (context.PSDebug <= level) { return; } string message = args == null || args.Length == 0 ? ResourceManagerCache.GetResourceString("Parser", messageId) : ResourceManagerCache.FormatResourceString("Parser", messageId, args); if (string.IsNullOrEmpty(message)) { message = "Could not load text for msh script tracing message id '" + messageId + "'"; } ((InternalHostUserInterface)context.EngineHostInterface.UI).WriteDebugLine(message, ref preference); }
private SessionStateCapacityVariable CreateCapacityVariable( string variableName, int defaultCapacity, int maxCapacity, int minCapacity, string descriptionResourceId) { SessionStateCapacityVariable sharedCapacityVariable = (SessionStateCapacityVariable)null; if (this.parent != null) { sharedCapacityVariable = this.parent.GetVariable(variableName) as SessionStateCapacityVariable; } SessionStateCapacityVariable capacityVariable = sharedCapacityVariable != null ? new SessionStateCapacityVariable(variableName, sharedCapacityVariable, ScopedItemOptions.None) : new SessionStateCapacityVariable(variableName, defaultCapacity, maxCapacity, minCapacity, ScopedItemOptions.None); if (string.IsNullOrEmpty(capacityVariable.Description)) { string resourceString = ResourceManagerCache.GetResourceString("SessionStateStrings", descriptionResourceId); capacityVariable.Description = resourceString; } return(capacityVariable); }
public override void UnsubscribeEvent(PSEventSubscriber subscriber) => throw new NotSupportedException(ResourceManagerCache.GetResourceString("EventingResources", "RemoteOperationNotSupported"));
public override IEnumerable <PSEventSubscriber> GetEventSubscribers( string sourceIdentifier) { throw new NotSupportedException(ResourceManagerCache.GetResourceString("EventingResources", "RemoteOperationNotSupported")); }
private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition) { string jobSourceAdapterTypeName; JobSourceAdapter adapter; if (!string.IsNullOrEmpty(definition.JobSourceAdapterTypeName)) { jobSourceAdapterTypeName = definition.JobSourceAdapterTypeName; } else { if (definition.JobSourceAdapterType == null) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound")); } jobSourceAdapterTypeName = definition.JobSourceAdapterType.Name; } bool flag = false; lock (this._syncObject) { flag = this._sourceAdapters.TryGetValue(jobSourceAdapterTypeName, out adapter); } if (flag) { return(adapter); } if (string.IsNullOrEmpty(definition.ModuleName)) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound")); } Exception innerException = null; try { InitialSessionState initialSessionState = InitialSessionState.CreateDefault2(); initialSessionState.Commands.Clear(); initialSessionState.Formats.Clear(); initialSessionState.Commands.Add(new SessionStateCmdletEntry("Import-Module", typeof(ImportModuleCommand), null)); using (PowerShell shell = PowerShell.Create(initialSessionState)) { shell.AddCommand("Import-Module"); shell.AddParameter("Name", definition.ModuleName); shell.Invoke(); if (shell.ErrorBuffer.Count > 0) { innerException = shell.ErrorBuffer[0].Exception; } } } catch (RuntimeException exception2) { innerException = exception2; } catch (InvalidOperationException exception3) { innerException = exception3; } catch (ScriptCallDepthException exception4) { innerException = exception4; } catch (SecurityException exception5) { innerException = exception5; } catch (ThreadAbortException exception6) { innerException = exception6; } if (innerException != null) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("RemotingErrorIdStrings", "JobSourceAdapterNotFound"), innerException); } return(this.AssertAndReturnJobSourceAdapter(jobSourceAdapterTypeName)); }
private static string GetSignatureStatusMessage( SignatureStatus status, uint error, string filePath) { using (Signature.tracer.TraceMethod()) { string str1 = (string)null; string resourceId = (string)null; string str2 = (string)null; switch (status) { case SignatureStatus.Valid: resourceId = "MshSignature_Valid"; break; case SignatureStatus.UnknownError: str1 = new Win32Exception(SecuritySupport.GetIntFromDWORD(error)).Message; break; case SignatureStatus.NotSigned: resourceId = "MshSignature_NotSigned"; str2 = filePath; break; case SignatureStatus.HashMismatch: resourceId = "MshSignature_HashMismatch"; str2 = filePath; break; case SignatureStatus.NotTrusted: resourceId = "MshSignature_NotTrusted"; str2 = filePath; break; case SignatureStatus.NotSupportedFileFormat: resourceId = "MshSignature_NotSupportedFileFormat"; str2 = System.IO.Path.GetExtension(filePath); if (string.IsNullOrEmpty(str2)) { resourceId = "MshSignature_NotSupportedFileFormat_NoExtension"; str2 = (string)null; break; } break; case SignatureStatus.Incompatible: resourceId = error != 2148073480U ? "MshSignature_Incompatible" : "MshSignature_Incompatible_HashAlgorithm"; str2 = filePath; break; } if (str1 == null) { if (str2 == null) { str1 = ResourceManagerCache.GetResourceString("MshSignature", resourceId); } else { str1 = ResourceManagerCache.FormatResourceString("MshSignature", resourceId, (object)str2); } } return(str1); } }
public PipelineStoppedException() : base(ResourceManagerCache.GetResourceString("GetErrorText", nameof(PipelineStoppedException))) { this.SetErrorId("PipelineStopped"); this.SetErrorCategory(ErrorCategory.OperationStopped); }
internal static PSCredential CredUIPromptForCredential( string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options, IntPtr parentHWND) { using (HostUtilities.tracer.TraceMethod()) { if (string.IsNullOrEmpty(caption)) { caption = ResourceManagerCache.GetResourceString("CredUI", "PromptForCredential_DefaultCaption"); } if (string.IsNullOrEmpty(message)) { message = ResourceManagerCache.GetResourceString("CredUI", "PromptForCredential_DefaultMessage"); } HostUtilities.CREDUI_INFO pUiInfo = new HostUtilities.CREDUI_INFO(); pUiInfo.pszCaptionText = caption; pUiInfo.pszMessageText = message; StringBuilder pszUserName = new StringBuilder(userName, 513); StringBuilder pszPassword = new StringBuilder(256); int int32 = Convert.ToInt32(false); pUiInfo.cbSize = Marshal.SizeOf((object)pUiInfo); pUiInfo.hwndParent = parentHWND; HostUtilities.CREDUI_FLAGS dwFlags = HostUtilities.CREDUI_FLAGS.DO_NOT_PERSIST; if ((allowedCredentialTypes & PSCredentialTypes.Domain) != PSCredentialTypes.Domain) { dwFlags |= HostUtilities.CREDUI_FLAGS.GENERIC_CREDENTIALS; if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt) { dwFlags |= HostUtilities.CREDUI_FLAGS.ALWAYS_SHOW_UI; } } HostUtilities.CredUIReturnCodes credUiReturnCodes = HostUtilities.CredUIReturnCodes.ERROR_INVALID_PARAMETER; if (pszUserName.Length <= 513 && pszPassword.Length <= 256) { credUiReturnCodes = HostUtilities.CredUIPromptForCredentials(ref pUiInfo, targetName, IntPtr.Zero, 0, pszUserName, 513, pszPassword, 256, ref int32, dwFlags); } PSCredential psCredential; switch (credUiReturnCodes) { case HostUtilities.CredUIReturnCodes.NO_ERROR: string userName1 = (string)null; if (pszUserName != null) { userName1 = pszUserName.ToString(); } SecureString password = new SecureString(); for (int index = 0; index < pszPassword.Length; ++index) { password.AppendChar(pszPassword[index]); pszPassword[index] = char.MinValue; } psCredential = string.IsNullOrEmpty(userName1) ? (PSCredential)null : new PSCredential(userName1, password); break; case HostUtilities.CredUIReturnCodes.ERROR_CANCELLED: psCredential = (PSCredential)null; break; default: HostUtilities.tracer.TraceError("CredUIPromptForCredentials returned an error: " + credUiReturnCodes.ToString()); goto case HostUtilities.CredUIReturnCodes.ERROR_CANCELLED; } return(psCredential); } }
public static string GetHelpComments(PSObject help) { if (help == null) { throw new ArgumentNullException(nameof(help)); } bool flag = false; foreach (string typeName in help.TypeNames) { if (typeName.Contains("HelpInfo")) { flag = true; break; } } if (!flag) { throw new InvalidOperationException(ResourceManagerCache.GetResourceString("ProxyCommandStrings", "HelpInfoObjectRequired")); } StringBuilder sb = new StringBuilder(); ProxyCommand.AppendContent(sb, ".SYNOPSIS", (object)ProxyCommand.GetProperty <string>(help, "Synopsis")); ProxyCommand.AppendContent(sb, ".DESCRIPTION", ProxyCommand.GetProperty <PSObject[]>(help, "Description")); PSObject[] property1 = ProxyCommand.GetProperty <PSObject[]>(ProxyCommand.GetProperty <PSObject>(help, "Parameters"), "Parameter"); if (property1 != null) { foreach (PSObject psObject1 in property1) { PSObject property2 = ProxyCommand.GetProperty <PSObject>(psObject1, "Name"); PSObject[] property3 = ProxyCommand.GetProperty <PSObject[]>(psObject1, "Description"); sb.AppendFormat("\n.PARAMETER {0}\n\n", (object)property2); foreach (PSObject psObject2 in property3) { string str = ProxyCommand.GetProperty <string>(psObject2, "Text") ?? psObject2.ToString(); if (!string.IsNullOrEmpty(str)) { sb.Append(str); sb.Append("\n"); } } } } PSObject[] property4 = ProxyCommand.GetProperty <PSObject[]>(ProxyCommand.GetProperty <PSObject>(help, "examples"), "example"); if (property4 != null) { foreach (PSObject psObject1 in property4) { StringBuilder stringBuilder = new StringBuilder(); PSObject[] property2 = ProxyCommand.GetProperty <PSObject[]>(psObject1, "introduction"); if (property2 != null) { foreach (PSObject psObject2 in property2) { if (psObject2 != null) { stringBuilder.Append(ProxyCommand.GetObjText((object)psObject2)); } } } PSObject property3 = ProxyCommand.GetProperty <PSObject>(psObject1, "code"); if (property3 != null) { stringBuilder.Append(property3.ToString()); } PSObject[] property5 = ProxyCommand.GetProperty <PSObject[]>(psObject1, "remarks"); if (property5 != null) { stringBuilder.Append("\n"); foreach (PSObject psObject2 in property5) { string property6 = ProxyCommand.GetProperty <string>(psObject2, "text"); stringBuilder.Append(property6.ToString()); } } if (stringBuilder.Length > 0) { sb.Append("\n\n.EXAMPLE\n\n"); sb.Append(stringBuilder.ToString()); } } } PSObject property7 = ProxyCommand.GetProperty <PSObject>(help, "alertSet"); ProxyCommand.AppendContent(sb, ".NOTES", ProxyCommand.GetProperty <PSObject[]>(property7, "alert")); PSObject property8 = ProxyCommand.GetProperty <PSObject>(ProxyCommand.GetProperty <PSObject>(help, "inputTypes"), "inputType"); ProxyCommand.AppendType(sb, ".INPUTS", property8); PSObject property9 = ProxyCommand.GetProperty <PSObject>(ProxyCommand.GetProperty <PSObject>(help, "returnValues"), "returnValue"); ProxyCommand.AppendType(sb, ".OUTPUTS", property9); PSObject[] property10 = ProxyCommand.GetProperty <PSObject[]>(ProxyCommand.GetProperty <PSObject>(help, "relatedLinks"), "navigationLink"); if (property10 != null) { foreach (PSObject psObject in property10) { ProxyCommand.AppendContent(sb, ".LINK", (object)ProxyCommand.GetProperty <PSObject>(psObject, "uri")); ProxyCommand.AppendContent(sb, ".LINK", (object)ProxyCommand.GetProperty <PSObject>(psObject, "linkText")); } } ProxyCommand.AppendContent(sb, ".COMPONENT", (object)ProxyCommand.GetProperty <PSObject>(help, "Component")); ProxyCommand.AppendContent(sb, ".ROLE", (object)ProxyCommand.GetProperty <PSObject>(help, "Role")); ProxyCommand.AppendContent(sb, ".FUNCTIONALITY", (object)ProxyCommand.GetProperty <PSObject>(help, "Functionality")); return(sb.ToString()); }
public ActionPreferenceStopException() : this(ResourceManagerCache.GetResourceString("GetErrorText", "ActionPreferenceStop")) { }
internal static ArrayList GetSuggestion( HistoryInfo lastHistory, object lastError, ArrayList errorList) { ArrayList arrayList = new ArrayList(); PSModuleInfo invocationModule = new PSModuleInfo(true); invocationModule.SessionState.PSVariable.Set(nameof(lastHistory), (object)lastHistory); invocationModule.SessionState.PSVariable.Set(nameof(lastError), lastError); foreach (Hashtable suggestion in HostUtilities.suggestions) { int count = errorList.Count; if (LanguagePrimitives.IsTrue(suggestion[(object)"Enabled"])) { SuggestionMatchType suggestionMatchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(suggestion[(object)"MatchType"], typeof(SuggestionMatchType), (IFormatProvider)CultureInfo.InvariantCulture); if (suggestionMatchType == SuggestionMatchType.Dynamic) { if (!(suggestion[(object)"Rule"] is ScriptBlock sb)) { suggestion[(object)"Enabled"] = (object)false; throw new ArgumentException(ResourceManagerCache.GetResourceString("SuggestionStrings", "RuleMustBeScriptBlock"), "Rule"); } object obj; try { obj = invocationModule.Invoke(sb, (object[])null); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); suggestion[(object)"Enabled"] = (object)false; continue; } if (LanguagePrimitives.IsTrue(obj)) { string suggestionText = HostUtilities.GetSuggestionText(suggestion[(object)"Suggestion"], invocationModule); if (!string.IsNullOrEmpty(suggestionText)) { string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", (object)(int)suggestion[(object)"Id"], (object)(string)suggestion[(object)"Category"], (object)suggestionText); arrayList.Add((object)str); } } } else { string input = string.Empty; if (suggestionMatchType == SuggestionMatchType.Command) { input = lastHistory.CommandLine; } else if (suggestionMatchType == SuggestionMatchType.Error) { if (lastError != null) { input = !(lastError is Exception exception) ? lastError.ToString() : exception.Message; } } else { suggestion[(object)"Enabled"] = (object)false; throw new ArgumentException(ResourceManagerCache.GetResourceString("SuggestionStrings", "InvalidMatchType"), "MatchType"); } if (Regex.IsMatch(input, (string)suggestion[(object)"Rule"], RegexOptions.IgnoreCase)) { string suggestionText = HostUtilities.GetSuggestionText(suggestion[(object)"Suggestion"], invocationModule); if (!string.IsNullOrEmpty(suggestionText)) { string str = string.Format((IFormatProvider)Thread.CurrentThread.CurrentCulture, "Suggestion [{0},{1}]: {2}", (object)(int)suggestion[(object)"Id"], (object)(string)suggestion[(object)"Category"], (object)suggestionText); arrayList.Add((object)str); } } } if (errorList.Count != count) { suggestion[(object)"Enabled"] = (object)false; } } } return(arrayList); }
internal XmlDocument BuildXmlFromComments() { this.doc = new XmlDocument(); XmlElement element1 = this.doc.CreateElement("command:command", HelpCommentsParser.commandURI); element1.SetAttribute("xmlns:maml", HelpCommentsParser.mamlURI); element1.SetAttribute("xmlns:command", HelpCommentsParser.commandURI); element1.SetAttribute("xmlns:dev", HelpCommentsParser.devURI); this.doc.AppendChild((XmlNode)element1); XmlElement element2 = this.doc.CreateElement("command:details", HelpCommentsParser.commandURI); element1.AppendChild((XmlNode)element2); XmlElement element3 = this.doc.CreateElement("command:name", HelpCommentsParser.commandURI); XmlText textNode1 = this.doc.CreateTextNode(this.commandName); element2.AppendChild((XmlNode)element3).AppendChild((XmlNode)textNode1); if (!string.IsNullOrEmpty(this.sections.synopsis)) { XmlElement element4 = this.doc.CreateElement("maml:description", HelpCommentsParser.mamlURI); XmlElement element5 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(this.sections.synopsis); element2.AppendChild((XmlNode)element4).AppendChild((XmlNode)element5).AppendChild((XmlNode)textNode2); } this.DetermineParameterDescriptions(); XmlElement element6 = this.doc.CreateElement("command:syntax", HelpCommentsParser.commandURI); MergedCommandParameterMetadata parameterMetadata = this.commandMetadata.StaticCommandParameterMetadata; if (parameterMetadata.ParameterSetCount > 0) { for (int i = 0; i < parameterMetadata.ParameterSetCount; ++i) { this.BuildSyntaxForParameterSet(element1, element6, parameterMetadata, i); } } else { this.BuildSyntaxForParameterSet(element1, element6, parameterMetadata, int.MaxValue); } XmlElement element7 = this.doc.CreateElement("command:parameters", HelpCommentsParser.commandURI); foreach (KeyValuePair <string, MergedCompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters) { MergedCompiledCommandParameter commandParameter = bindableParameter.Value; if (commandParameter.BinderAssociation != ParameterBinderAssociation.CommonParameters) { string key = bindableParameter.Key; string parameterDescription = this.GetParameterDescription(key); ParameterSetSpecificMetadata specificMetadata = (ParameterSetSpecificMetadata)null; bool isMandatory = false; bool valueFromPipeline = false; bool valueFromPipelineByPropertyName = false; string position = "named"; int num = 0; CompiledCommandParameter parameter = commandParameter.Parameter; parameter.ParameterSetData.TryGetValue("__AllParameterSets", out specificMetadata); while (specificMetadata == null && num < 32) { specificMetadata = parameter.GetParameterSetData((uint)(1 << num++)); } if (specificMetadata != null) { isMandatory = specificMetadata.IsMandatory; valueFromPipeline = specificMetadata.ValueFromPipeline; valueFromPipelineByPropertyName = specificMetadata.ValueFromPipelineByPropertyName; position = specificMetadata.IsPositional ? (1 + specificMetadata.Position).ToString((IFormatProvider)CultureInfo.InvariantCulture) : "named"; } XmlElement xmlElement = this.BuildXmlForParameter(key, isMandatory, valueFromPipeline, valueFromPipelineByPropertyName, position, parameter.Type, parameterDescription, false); element7.AppendChild((XmlNode)xmlElement); } } element1.AppendChild((XmlNode)element7); if (!string.IsNullOrEmpty(this.sections.description)) { XmlElement element4 = this.doc.CreateElement("maml:description", HelpCommentsParser.mamlURI); XmlElement element5 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(this.sections.description); element1.AppendChild((XmlNode)element4).AppendChild((XmlNode)element5).AppendChild((XmlNode)textNode2); } if (!string.IsNullOrEmpty(this.sections.notes)) { XmlElement element4 = this.doc.CreateElement("maml:alertSet", HelpCommentsParser.mamlURI); XmlElement element5 = this.doc.CreateElement("maml:alert", HelpCommentsParser.mamlURI); XmlElement element8 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(this.sections.notes); element1.AppendChild((XmlNode)element4).AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)textNode2); } if (this.sections.examples.Count > 0) { XmlElement element4 = this.doc.CreateElement("command:examples", HelpCommentsParser.commandURI); int num = 1; foreach (string example in this.sections.examples) { XmlElement element5 = this.doc.CreateElement("command:example", HelpCommentsParser.commandURI); XmlElement element8 = this.doc.CreateElement("maml:title", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "\t\t\t\t-------------------------- {0} {1} --------------------------", (object)ResourceManagerCache.GetResourceString("HelpDisplayStrings", "ExampleUpperCase"), (object)num++)); element5.AppendChild((XmlNode)element8).AppendChild((XmlNode)textNode2); string prompt_str; string code_str; string remarks_str; this.GetExampleSections(example, out prompt_str, out code_str, out remarks_str); XmlElement element9 = this.doc.CreateElement("maml:introduction", HelpCommentsParser.mamlURI); XmlElement element10 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode3 = this.doc.CreateTextNode(prompt_str); element5.AppendChild((XmlNode)element9).AppendChild((XmlNode)element10).AppendChild((XmlNode)textNode3); XmlElement element11 = this.doc.CreateElement("dev:code", HelpCommentsParser.devURI); XmlText textNode4 = this.doc.CreateTextNode(code_str); element5.AppendChild((XmlNode)element11).AppendChild((XmlNode)textNode4); XmlElement element12 = this.doc.CreateElement("dev:remarks", HelpCommentsParser.devURI); XmlElement element13 = this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI); XmlText textNode5 = this.doc.CreateTextNode(remarks_str); element5.AppendChild((XmlNode)element12).AppendChild((XmlNode)element13).AppendChild((XmlNode)textNode5); for (int index = 0; index < 4; ++index) { element12.AppendChild((XmlNode)this.doc.CreateElement("maml:para", HelpCommentsParser.mamlURI)); } element4.AppendChild((XmlNode)element5); } element1.AppendChild((XmlNode)element4); } if (this.sections.inputs.Count > 0) { XmlElement element4 = this.doc.CreateElement("command:inputTypes", HelpCommentsParser.commandURI); foreach (string input in this.sections.inputs) { XmlElement element5 = this.doc.CreateElement("command:inputType", HelpCommentsParser.commandURI); XmlElement element8 = this.doc.CreateElement("dev:type", HelpCommentsParser.devURI); XmlElement element9 = this.doc.CreateElement("maml:name", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(input); element4.AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)element9).AppendChild((XmlNode)textNode2); } element1.AppendChild((XmlNode)element4); } IEnumerable enumerable = (IEnumerable)null; if (this.sections.outputs.Count > 0) { enumerable = (IEnumerable)this.sections.outputs; } else if (this.scriptBlock.OutputType.Count > 0) { enumerable = (IEnumerable)this.scriptBlock.OutputType; } if (enumerable != null) { XmlElement element4 = this.doc.CreateElement("command:returnValues", HelpCommentsParser.commandURI); foreach (object obj in enumerable) { XmlElement element5 = this.doc.CreateElement("command:returnValue", HelpCommentsParser.commandURI); XmlElement element8 = this.doc.CreateElement("dev:type", HelpCommentsParser.devURI); XmlElement element9 = this.doc.CreateElement("maml:name", HelpCommentsParser.mamlURI); if (!(obj is string text)) { text = ((PSTypeName)obj).Name; } XmlText textNode2 = this.doc.CreateTextNode(text); element4.AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)element9).AppendChild((XmlNode)textNode2); } element1.AppendChild((XmlNode)element4); } if (this.sections.links.Count > 0) { XmlElement element4 = this.doc.CreateElement("maml:relatedLinks", HelpCommentsParser.mamlURI); foreach (string link in this.sections.links) { XmlElement element5 = this.doc.CreateElement("maml:navigationLink", HelpCommentsParser.mamlURI); XmlElement element8 = this.doc.CreateElement(Uri.IsWellFormedUriString(Uri.EscapeUriString(link), UriKind.Absolute) ? "maml:uri" : "maml:linkText", HelpCommentsParser.mamlURI); XmlText textNode2 = this.doc.CreateTextNode(link); element4.AppendChild((XmlNode)element5).AppendChild((XmlNode)element8).AppendChild((XmlNode)textNode2); } element1.AppendChild((XmlNode)element4); } return(this.doc); }
private void ReadXml() { try { Deserializer deserializer = new Deserializer((XmlReader) new XmlTextReader((TextReader)this.streamReader)); while (!deserializer.Done()) { string streamName; object obj = deserializer.Deserialize(out streamName); MinishellStream stream = MinishellStream.Unknown; if (streamName != null) { stream = StringToMinishellStreamConverter.ToMinishellStream(streamName); } if (stream == MinishellStream.Unknown) { stream = this.isOutput ? MinishellStream.Output : MinishellStream.Error; } if (stream == MinishellStream.Output || obj != null) { switch (stream) { case MinishellStream.Error: if (obj is PSObject) { obj = (object)ErrorRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj)); break; } string message; try { message = (string)LanguagePrimitives.ConvertTo(obj, typeof(string), (IFormatProvider)CultureInfo.InvariantCulture); } catch (PSInvalidCastException ex) { ProcessStreamReader.tracer.TraceException((Exception)ex); continue; } obj = (object)new ErrorRecord((Exception) new RemoteException(message), "NativeCommandError", ErrorCategory.NotSpecified, (object)message); break; case MinishellStream.Verbose: case MinishellStream.Warning: case MinishellStream.Debug: try { obj = LanguagePrimitives.ConvertTo(obj, typeof(string), (IFormatProvider)CultureInfo.InvariantCulture); break; } catch (PSInvalidCastException ex) { ProcessStreamReader.tracer.TraceException((Exception)ex); continue; } } this.AddObjectToWriter(obj, stream); } } } catch (XmlException ex) { ProcessStreamReader.tracer.TraceException((Exception)ex); this.AddObjectToWriter((object)new ErrorRecord((Exception) new XmlException(string.Format((IFormatProvider)null, ResourceManagerCache.GetResourceString("NativeCP", "CliXmlError"), (object)(MinishellStream)(this.isOutput ? 0 : 1), (object)this.processPath, (object)ex.Message), (Exception)ex), "ProcessStreamReader_CliXmlError", ErrorCategory.SyntaxError, (object)this.processPath), MinishellStream.Error); } }
internal static string GetResourceString(string baseName, string resourceId) { using (ResourceManagerCache.tracer.TraceMethod()) return(ResourceManagerCache.GetResourceString(Assembly.GetCallingAssembly(), baseName, resourceId)); }
private void ValidatePSTypeName(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, bool retryOtherBindingAfterFailure, object parameterValue) { if (parameterValue != null) { IEnumerable <string> internalTypeNames = PSObject.AsPSObject(parameterValue).InternalTypeNames; string pSTypeName = parameterMetadata.PSTypeName; if (!internalTypeNames.Contains <string>(pSTypeName, StringComparer.OrdinalIgnoreCase)) { ParameterBindingException exception2; object[] arguments = new object[] { ((this.invocationInfo != null) && (this.invocationInfo.MyCommand != null)) ? this.invocationInfo.MyCommand.Name : string.Empty, parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), 0, 0, pSTypeName }; PSInvalidCastException innerException = new PSInvalidCastException(ErrorCategory.InvalidArgument.ToString(), null, ResourceManagerCache.GetResourceString("ParameterBinderStrings", "MismatchedPSTypeName"), arguments); if (!retryOtherBindingAfterFailure) { exception2 = new ParameterBindingArgumentTransformationException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), "ParameterBinderStrings", "MismatchedPSTypeName", new object[] { pSTypeName }); } else { exception2 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), "ParameterBinderStrings", "MismatchedPSTypeName", new object[] { pSTypeName }); } throw exception2; } } }
internal PSUICultureVariable() : base("PSUICulture", (object)true, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, ResourceManagerCache.GetResourceString("RunspaceInit", "DollarPSUICultureDescription")) { }