private static Type GetFieldType(FieldDescription field)
 {
     Type type = null;
     if (!String.IsNullOrEmpty(field.ParameterAssemblyFullName))
     {
         LanguagePrimitives.TryConvertTo(field.ParameterAssemblyFullName, out type);
     }
     if ((type == null) && !String.IsNullOrEmpty(field.ParameterTypeFullName))
     {
         LanguagePrimitives.TryConvertTo(field.ParameterTypeFullName, out type);
     }
     return type;
 }
Exemplo n.º 2
0
		private static Type GetFieldType(FieldDescription description, out bool isList)
		{
			Type elementType;
			Type type = null;
			if (!LanguagePrimitives.TryConvertTo<Type>(description.ParameterAssemblyFullName, out type))
			{
				if (description.ParameterTypeName.Equals(typeof(PSCredential).Name, StringComparison.OrdinalIgnoreCase) || description.ParameterTypeName.Equals(typeof(SecureString).Name, StringComparison.OrdinalIgnoreCase))
				{
					object[] parameterTypeFullName = new object[1];
					parameterTypeFullName[0] = description.ParameterTypeFullName;
					string str = string.Format(CultureInfo.CurrentCulture, Resources.PromptTypeConversionError_Format, parameterTypeFullName);
					throw new PromptingException(str);
				}
				else
				{
					isList = false;
					return typeof(string);
				}
			}
			else
			{
				isList = type.GetInterface(typeof(IList).FullName) != null;
				if (isList)
				{
					if (type.IsArray)
					{
						elementType = type.GetElementType();
					}
					else
					{
						elementType = typeof(object);
					}
					type = elementType;
				}
				return type;
			}
		}
Exemplo n.º 3
0
        internal static Type GetFieldType(FieldDescription field)
        {
            Type result;
            if (TypeResolver.TryResolveType(field.ParameterAssemblyFullName, out result) ||
                TypeResolver.TryResolveType(field.ParameterTypeFullName, out result))
            {
                return result;
            }

            return null;
        }
 private Collection<FieldDescription> CreatePromptDataStructures(Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
 {
     StringBuilder usedHotKeys = new StringBuilder();
     Collection<FieldDescription> collection = new Collection<FieldDescription>();
     foreach (MergedCompiledCommandParameter parameter in missingMandatoryParameters)
     {
         ParameterSetSpecificMetadata parameterSetData = parameter.Parameter.GetParameterSetData(base._currentParameterSetFlag);
         FieldDescription item = new FieldDescription(parameter.Parameter.Name);
         string helpMessage = null;
         try
         {
             helpMessage = parameterSetData.GetHelpMessage(this.Command);
         }
         catch (InvalidOperationException)
         {
         }
         catch (ArgumentException)
         {
         }
         if (!string.IsNullOrEmpty(helpMessage))
         {
             item.HelpMessage = helpMessage;
         }
         item.SetParameterType(parameter.Parameter.Type);
         item.Label = BuildLabel(parameter.Parameter.Name, usedHotKeys);
         foreach (ValidateArgumentsAttribute attribute in parameter.Parameter.ValidationAttributes)
         {
             item.Attributes.Add(attribute);
         }
         foreach (ArgumentTransformationAttribute attribute2 in parameter.Parameter.ArgumentTransformationAttributes)
         {
             item.Attributes.Add(attribute2);
         }
         item.IsMandatory = true;
         collection.Add(item);
     }
     return collection;
 }
      PSCredential IPSConsole.PromptForCredential(string caption, string message, string userName, string targetName)
      {
         var user = new FieldDescription("User");
         user.SetParameterType(typeof(string));
         user.DefaultValue = PSObject.AsPSObject(userName);
         user.IsMandatory = true;


         var pass = new FieldDescription("Password");
         pass.SetParameterType(typeof(SecureString));
         pass.IsMandatory = true;

         var cred = new Collection<FieldDescription>(new[] { user, pass });

         var login = ((IPSConsole)this).Prompt(caption, message, cred);

         return new PSCredential(
            (string)login["User"].BaseObject,
            (SecureString)login["Password"].BaseObject);
      }
      PSCredential IPSConsole.PromptForCredential(string caption, string message, string userName, string targetName, 
         PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
      {

         Collection<FieldDescription> fields;
         Dictionary<string, PSObject> login, password;

         // NOTE: I'm not sure this is the right action for the PromptForCredential targetName
         if (!String.IsNullOrEmpty(targetName))
         {
            caption = string.Format("Credential for {0}\n\n{1}", targetName, caption);
         }

         if ((options & PSCredentialUIOptions.ReadOnlyUserName) == PSCredentialUIOptions.Default )
         {
            var user = new FieldDescription("User");
            user.SetParameterType(typeof(string));
            user.Label = "Username";
            user.DefaultValue = PSObject.AsPSObject(userName);
            user.IsMandatory = true;

            do
            {
               fields = new Collection<FieldDescription>(new[] {user});
               login = ((IPSConsole) this).Prompt(caption, message, fields);
               userName = login["User"].BaseObject as string;
            } while ( userName != null && userName.Length == 0);
         }

         // I think this is all I can do with the allowedCredentialTypes
         // domain required
         if (allowedCredentialTypes > PSCredentialTypes.Generic)
         {
            // and no domain
            if (userName != null && userName.IndexOfAny(new[] { '\\', '@' }) < 0)
            {
               userName = string.Format("{0}\\{1}", targetName, userName);
            }
         }

         var pass = new FieldDescription("Password");
         pass.SetParameterType(typeof(SecureString));
         pass.Label = "Password for " + userName;
         pass.IsMandatory = true;

         fields = new Collection<FieldDescription>(new[] { pass });
         password = ((IPSConsole)this).Prompt(String.Empty, String.Empty, fields);

         // TODO: I'm not sure what to do with the PSCredentialUIOptions options, because PowerShell.exe ignores them
         return new PSCredential(userName, (SecureString)password["Password"].BaseObject);
      }
Exemplo n.º 7
0
		private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool fieldEchoOnPrompt, bool listInput, out bool endListInput, out bool cancelled)
		{
			string str;
			string str1 = null;
			endListInput = false;
			cancelled = false;
			bool flag = false;
			while (!flag)
			{
				//this.WriteToConsole(fieldPrompt, true);
				string oldPrompt = ConsoleControl.NativeMethods.Editor.Prompt;
				ConsoleControl.NativeMethods.Editor.Prompt = fieldPrompt;
				if (!fieldEchoOnPrompt)
				{
					char? nullable = null;
					ConsoleControl.NativeMethods.Editor.SecureInput = true;
					ConsoleControl.NativeMethods.Editor.SecureChar = nullable;
					object obj = this.ReadLineSafe(false, nullable);
					string str2 = obj as string;
					ConsoleControl.NativeMethods.Editor.SecureInput = false;
					str = str2;
				}
				else
				{
					str = this.ReadLine();
				}
				ConsoleControl.NativeMethods.Editor.Prompt = oldPrompt;

				if (str != null)
				{
					if (!str.StartsWith("!", false, CultureInfo.CurrentCulture))
					{
						if (str.Length == 0 && listInput)
						{
							endListInput = true;
						}
						str1 = str;
						break;
					}
					else
					{
						str1 = this.PromptCommandMode(str, desc, out flag);
					}
				}
				else
				{
					cancelled = true;
					break;
				}
			}
			return str1;
		}
Exemplo n.º 8
0
 protected override void BeginProcessing()
 {
     PSHostUserInterface uI = base.Host.UI;
     if (this.prompt != null)
     {
         string str;
         IEnumerator enumerator = LanguagePrimitives.GetEnumerator(this.prompt);
         if (enumerator != null)
         {
             StringBuilder builder = new StringBuilder();
             while (enumerator.MoveNext())
             {
                 string str2 = (string) LanguagePrimitives.ConvertTo(enumerator.Current, typeof(string), CultureInfo.InvariantCulture);
                 if (!string.IsNullOrEmpty(str2))
                 {
                     if (builder.Length > 0)
                     {
                         builder.Append(' ');
                     }
                     builder.Append(str2);
                 }
             }
             str = builder.ToString();
         }
         else
         {
             str = (string) LanguagePrimitives.ConvertTo(this.prompt, typeof(string), CultureInfo.InvariantCulture);
         }
         FieldDescription description = new FieldDescription(str);
         if (this.AsSecureString != 0)
         {
             description.SetParameterType(typeof(SecureString));
         }
         else
         {
             description.SetParameterType(typeof(string));
         }
         Collection<FieldDescription> descriptions = new Collection<FieldDescription> {
             description
         };
         Dictionary<string, PSObject> dictionary = base.Host.UI.Prompt("", "", descriptions);
         if (dictionary != null)
         {
             foreach (PSObject obj2 in dictionary.Values)
             {
                 base.WriteObject(obj2);
             }
         }
     }
     else
     {
         object obj3;
         if (this.AsSecureString != 0)
         {
             obj3 = base.Host.UI.ReadLineAsSecureString();
         }
         else
         {
             obj3 = base.Host.UI.ReadLine();
         }
         base.WriteObject(obj3);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// Write the prompt, then collect a line of input from the host, then
        /// output it to the output stream.
        ///
        /// </summary>
        protected override void BeginProcessing()
        {
            PSHostUserInterface ui = Host.UI;
            string promptString;

            if (_prompt != null)
            {
                IEnumerator e = LanguagePrimitives.GetEnumerator(_prompt);
                if (e != null)
                {
                    StringBuilder sb = new StringBuilder();

                    while (e.MoveNext())
                    {
                        // The current object might itself be a collection, like a string array, as in read/console "foo","bar","baz"  
                        // If it is, then the PSObject ToString() will take care of it.  We could go on unwrapping collections
                        // forever, but it's a pretty common use case to see a varags confused with an array.

                        string element = (string)LanguagePrimitives.ConvertTo(e.Current, typeof(string), CultureInfo.InvariantCulture);

                        if (!String.IsNullOrEmpty(element))
                        {
                            // Prepend a space if the stringbuilder isn't empty...
                            // We could consider using $OFS here but that's probably more
                            // effort than is really needed...
                            if (sb.Length > 0)
                                sb.Append(' ');
                            sb.Append(element);
                        }
                    }
                    promptString = sb.ToString();
                }
                else
                {
                    promptString = (string)LanguagePrimitives.ConvertTo(_prompt, typeof(string), CultureInfo.InvariantCulture);
                }

                FieldDescription fd = new FieldDescription(promptString);
                if (AsSecureString)
                {
                    fd.SetParameterType(typeof(System.Security.SecureString));
                }
                else
                {
                    fd.SetParameterType(typeof(String));
                }

                Collection<FieldDescription> fdc = new Collection<FieldDescription>();
                fdc.Add(fd);

                Dictionary<string, PSObject> result = Host.UI.Prompt("", "", fdc);
                // Result can be null depending on the host implementation. One typical
                // example of a null return is for a canceled dialog.
                if (result != null)
                {
                    foreach (PSObject o in result.Values)
                    {
                        WriteObject(o);
                    }
                }
            }
            else
            {
                object result;
                if (AsSecureString)
                {
                    result = Host.UI.ReadLineAsSecureString();
                }
                else
                {
                    result = Host.UI.ReadLine();
                }
                WriteObject(result);
            }
        }
Exemplo n.º 10
0
 internal static Type GetFieldType(FieldDescription field)
 {
     Exception exception;
     Type type = null;
     if ((type == null) && !string.IsNullOrEmpty(field.ParameterAssemblyFullName))
     {
         type = LanguagePrimitives.ConvertStringToType(field.ParameterAssemblyFullName, out exception);
     }
     if ((type == null) && !string.IsNullOrEmpty(field.ParameterTypeFullName))
     {
         type = LanguagePrimitives.ConvertStringToType(field.ParameterTypeFullName, out exception);
     }
     return type;
 }
        /// <summary>
        /// Handles Tilde Commands in Prompt
        /// If input does not start with PromptCommandPrefix (= "!"), returns input
        /// Tilde commands -
        /// !   end of list, only valid for input field types that implement IList, returns string.Empty
        /// !!*  input !* literally, returns !* where * is any string
        /// !h  prints out field's Quick Help, returns null
        /// All others tilde comments are invalid and return null
        /// 
        /// returns null iff there's nothing the caller can process
        /// </summary>
        /// <param name="input"></param>
        /// <param name="desc"></param>
        /// <param name="inputDone"></param>
        /// <returns></returns>

        private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone)
        {
            Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase),
                string.Format(CultureInfo.InvariantCulture, "input should start with {0}", PromptCommandPrefix));
            Dbg.Assert(desc != null, "desc should never be null when PromptCommandMode is called");
            string command = input.Substring(1);

            inputDone = true;
            if (command.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase))
            {
                return command;
            }
            if (command.Length == 1)
            {
                if (command[0] == '?')
                {
                    if (string.IsNullOrEmpty(desc.HelpMessage))
                    {
                        string noHelpErrMsg =
                            StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptNoHelpAvailableErrorTemplate, desc.Name);
                        s_tracer.TraceWarning(noHelpErrMsg);
                        WriteLineToConsole(WrapToCurrentWindowWidth(noHelpErrMsg));
                    }
                    else
                    {
                        WriteLineToConsole(WrapToCurrentWindowWidth(desc.HelpMessage));
                    }
                }
                else
                {
                    ReportUnrecognizedPromptCommand(input);
                }
                inputDone = false;
                return null;
            }
            if (command.Length == 2)
            {
                if (0 == string.Compare(command, "\"\"", StringComparison.OrdinalIgnoreCase))
                {
                    return string.Empty;
                }
            }
            if (0 == string.Compare(command, "$null", StringComparison.OrdinalIgnoreCase))
            {
                return null;
            }
            else
            {
                ReportUnrecognizedPromptCommand(input);
                inputDone = false;
                return null;
            }
        }
        /// <summary>
        /// Called by Prompt. Reads user input and processes tilde commands.
        /// </summary>
        /// <param name="fieldPrompt">prompt written to host for the field</param>
        /// <param name="desc">the field to be read</param>
        /// <param name="fieldEchoOnPrompt">true to echo user input</param>
        /// <param name="listInput">true if the field is a list</param>
        /// <param name="endListInput">valid only if listInput is true. set to true if the input signals end of list input </param>
        /// <param name="cancelled">true iff the input is canceled, e.g., by Ctrl-C or Ctrl-Break</param>
        /// <returns>processed input string to be converted with LanguagePrimitives.ConvertTo </returns>
        private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool fieldEchoOnPrompt,
                        bool listInput, out bool endListInput, out bool cancelled)
        {
            Dbg.Assert(fieldPrompt != null, "fieldPrompt should never be null when PromptReadInput is called");
            Dbg.Assert(desc != null, "desc should never be null when PromptReadInput is called");

            string processedInputString = null;
            endListInput = false;
            cancelled = false;
            bool inputDone = false;
            while (!inputDone)
            {
                WriteToConsole(fieldPrompt, true);
                string rawInputString = null;
                // Implement no echo here.
                if (fieldEchoOnPrompt)
                {
                    rawInputString = ReadLine();
                }
                else
                {
                    object userInput = ReadLineSafe(false, null);
                    string userInputString = userInput as string;
                    System.Management.Automation.Diagnostics.Assert(userInputString != null, "ReadLineSafe did not return a string");
                    rawInputString = userInputString;
                }
                if (rawInputString == null)
                {
                    // processedInputString is null as well. No need to assign null to it.
                    cancelled = true;
                    break;
                }
                else
                if (rawInputString.StartsWith(PromptCommandPrefix, StringComparison.CurrentCulture))
                {
                    processedInputString = PromptCommandMode(rawInputString, desc, out inputDone);
                }
                else
                {
                    if (rawInputString.Length == 0 && listInput)
                    {
                        endListInput = true;
                    }
                    processedInputString = rawInputString;
                    break;
                }
            }
            return processedInputString;
        }
        private string PromptForSingleItem(Type fieldType,
            string printFieldPrompt,
            string fieldPrompt,
            string caption,
            string message,
            FieldDescription desc,
            bool fieldEchoOnPrompt,
            bool listInput,
            out bool endListInput,
            out bool cancelInput,
            out object convertedObj
            )
        {
            cancelInput = false;
            endListInput = false;
            convertedObj = null;

            if (fieldType.Equals(typeof(SecureString)))
            {
                WriteToConsole(printFieldPrompt, true);
                SecureString secureString = ReadLineAsSecureString();
                convertedObj = secureString;
                cancelInput = (convertedObj == null);
                if ((secureString != null) && (secureString.Length == 0) && listInput)
                {
                    endListInput = true;
                }
            }
            else if (fieldType.Equals(typeof(PSCredential)))
            {
                WriteLineToConsole(WrapToCurrentWindowWidth(fieldPrompt));
                PSCredential credential = null;
                // the earlier implementation contained null 
                // for caption and message in the call below
                // Passing null is a potential security risk
                // as any modifications made with security in
                // mind is lost. This can lead to a malicious
                // server prompting the user for a request 
                // which can appear to come from locally.
                if (!PromptUsingConsole() && desc.ModifiedByRemotingProtocol)
                {
                    credential =
                        PromptForCredential(
                            caption,
                            message,
                            null,
                            string.Empty);
                }
                else
                {
                    credential =
                        PromptForCredential(
                            null,   // caption already written
                            null,   // message already written
                            null,
                            string.Empty);
                }
                convertedObj = credential;
                cancelInput = (convertedObj == null);
                if ((credential != null) && (credential.Password.Length == 0) && listInput)
                {
                    endListInput = true;
                }
            }
            else
            {
                string inputString = null;
                do
                {
                    inputString = PromptReadInput(
                        printFieldPrompt, desc, fieldEchoOnPrompt,
                        listInput, out endListInput, out cancelInput);
                }
                while (!cancelInput && !endListInput && PromptTryConvertTo(fieldType, desc.IsFromRemoteHost, inputString, out convertedObj) !=
                    PromptCommonInputErrors.None);
                return inputString;
            }

            return null;
        }
Exemplo n.º 14
0
		private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone)
		{
			string str = input.Substring(1);
			inputDone = true;
			if (!str.StartsWith("!", StringComparison.OrdinalIgnoreCase))
			{
				if (str.Length != 1)
				{
					if (str.Length != 2 || string.Compare(str, "\"\"", StringComparison.OrdinalIgnoreCase) != 0)
					{
						if (string.Compare(str, "$null", StringComparison.OrdinalIgnoreCase) != 0)
						{
							this.ReportUnrecognizedPromptCommand(input);
							inputDone = false;
							return null;
						}
						else
						{
							return null;
						}
					}
					else
					{
						return string.Empty;
					}
				}
				else
				{
					if (str[0] != '?')
					{
						this.ReportUnrecognizedPromptCommand(input);
					}
					else
					{
						if (!string.IsNullOrEmpty(desc.HelpMessage))
						{
							this.WriteLineToConsole(this.WrapToCurrentWindowWidth(desc.HelpMessage));
						}
						else
						{
							string str1 = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptNoHelpAvailableErrorTemplate, desc.Name);
							ConsoleHostUserInterface.tracer.TraceWarning(str1, new object[0]);
							this.WriteLineToConsole(this.WrapToCurrentWindowWidth(str1));
						}
					}
					inputDone = false;
					return null;
				}
			}
			else
			{
				return str;
			}
		}
Exemplo n.º 15
0
        public PSCredential PromptForCredentialInline(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes = PSCredentialTypes.Generic, PSCredentialUIOptions options = PSCredentialUIOptions.None)
        {
            Collection<FieldDescription> fields;

            // NOTE: I'm not sure this is the right action for the PromptForCredential targetName
            if (!String.IsNullOrEmpty(targetName))
            {
                caption = $"Credential for {targetName}\n\n{caption}";
            }

            if ((options & PSCredentialUIOptions.ReadOnlyUserName) == PSCredentialUIOptions.Default)
            {
                var user = new FieldDescription("User");
                user.SetParameterType(typeof(string));
                user.Label = "Username";
                user.DefaultValue = PSObject.AsPSObject(userName);
                user.IsMandatory = true;

                do
                {
                    fields = new Collection<FieldDescription>(new[] { user });
                    var username = new PromptForObjectEventArgs(caption, message, fields);
                    var login = OnPromptForObject(username);
                    userName = login["User"].BaseObject as string;
                } while (userName != null && userName.Length == 0);
            }

            // I think this is all I can do with the allowedCredentialTypes
            // domain required
            if (allowedCredentialTypes > PSCredentialTypes.Generic)
            {
                // and no domain
                if (userName != null && userName.IndexOfAny(new[] { '\\', '@' }) < 0)
                {
                    userName = $"{targetName}\\{userName}";
                }
            }

            var pass = new FieldDescription("Password");
            pass.SetParameterType(typeof(SecureString));
            pass.Label = "Password for " + userName;
            pass.IsMandatory = true;

            fields = new Collection<FieldDescription>(new[] { pass });
            var pwd = new PromptForObjectEventArgs(string.Empty, string.Empty, fields);
            var password = OnPromptForObject(pwd);

            // TODO: I'm not sure what to do with the PSCredentialUIOptions options, because PowerShell.exe ignores them
            return new PSCredential(userName, (SecureString)password["Password"].BaseObject);
        }
 internal static FieldDetails Create(FieldDescription fieldDescription)
 {
     return new FieldDetails(
         fieldDescription.Name,
         fieldDescription.Label,
         GetFieldTypeFromTypeName(fieldDescription.ParameterAssemblyFullName),
         fieldDescription.IsMandatory,
         fieldDescription.DefaultValue);
 }
Exemplo n.º 17
0
        private PSObject GetSingle(string caption, string message, string prompt, FieldDescription field, Type type)
        {
            string help = field.HelpMessage;
            PSObject psDefault = field.DefaultValue;

            if (null != type && type == typeof(PSCredential))
            {
                var credential = _host.UI.PromptForCredential(caption, message, psDefault?.ToString(), string.Empty, PSCredentialTypes.Default, PSCredentialUIOptions.Default);
                return credential != null ? PSObject.AsPSObject(credential) : null;
            }

            while (true)
            {
                // TODO: Only show the help message if they type '?' as their entry something, in which case show help and re-prompt.
                if (!String.IsNullOrEmpty(help))
                    Write(ConsoleBrushes.ConsoleColorFromBrush(ConsoleBrushes.VerboseForeground), ConsoleBrushes.ConsoleColorFromBrush(ConsoleBrushes.VerboseBackground), help + "\n");

                Write($"{prompt}: ");

                if (null != type && typeof(SecureString) == type)
                {
                    var userData = ReadLineAsSecureString() ?? new SecureString();
                    return PSObject.AsPSObject(userData);
                } // Note: This doesn't look the way it does in PowerShell, but it should work :)
                else
                {
                    if (psDefault != null && psDefault.ToString().Length > 0)
                    {
                        if (Dispatcher.CheckAccess())
                        {
                            CurrentCommand = psDefault.ToString();
                            CommandBox.SelectAll();
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action<string>)(def =>
                            {
                                CurrentCommand = def;
                                CommandBox.SelectAll();
                            }), psDefault.ToString());
                        }
                    }

                    var userData = ReadLine();

                    if (type != null && userData.Length > 0)
                    {
                        object output;
                        var ice = TryConvertTo(type, userData, out output);
                        // Special exceptions that happen when casting to numbers and such ...
                        if (ice == null)
                        {
                            return PSObject.AsPSObject(output);
                        }
                        if ((ice.InnerException is FormatException) || (ice.InnerException is OverflowException))
                        {
                            Write(ConsoleBrushes.ErrorForeground, ConsoleBrushes.ErrorBackground,
                                $@"Cannot recognize ""{userData}"" as a {type.FullName} due to a format error.\n");
                        }
                        else
                        {
                            return PSObject.AsPSObject(String.Empty);
                        }
                    }
                    else if (userData.Length == 0)
                    {
                        return PSObject.AsPSObject(String.Empty);
                    }
                    else return PSObject.AsPSObject(userData);
                }
            }
        }
        private Collection<FieldDescription> CreatePromptDataStructures(
            Collection<MergedCompiledCommandParameter> missingMandatoryParameters)
        {
            StringBuilder usedHotKeys = new StringBuilder();
            Collection<FieldDescription> fieldDescriptionList = new Collection<FieldDescription>();

            // See if any of the unbound parameters are mandatory

            foreach (MergedCompiledCommandParameter parameter in missingMandatoryParameters)
            {
                ParameterSetSpecificMetadata parameterSetMetadata =
                    parameter.Parameter.GetParameterSetData(_currentParameterSetFlag);

                FieldDescription fDesc = new FieldDescription(parameter.Parameter.Name);

                string helpInfo = null;

                try
                {
                    helpInfo = parameterSetMetadata.GetHelpMessage(Command);
                }
                catch (InvalidOperationException)
                {
                }
                catch (ArgumentException)
                {
                }

                if (!string.IsNullOrEmpty(helpInfo))
                {
                    fDesc.HelpMessage = helpInfo;
                }
                fDesc.SetParameterType(parameter.Parameter.Type);
                fDesc.Label = BuildLabel(parameter.Parameter.Name, usedHotKeys);

                foreach (ValidateArgumentsAttribute vaAttr in parameter.Parameter.ValidationAttributes)
                {
                    fDesc.Attributes.Add(vaAttr);
                }

                foreach (ArgumentTransformationAttribute arAttr in parameter.Parameter.ArgumentTransformationAttributes)
                {
                    fDesc.Attributes.Add(arAttr);
                }

                fDesc.IsMandatory = true;

                fieldDescriptionList.Add(fDesc);
            } // foreach unbound parameter

            return fieldDescriptionList;
        }
Exemplo n.º 19
0
 private string PromptNewItemType()
 {
     string str = null;
     if (base.Host != null)
     {
         FieldDescription description = new FieldDescription("Type");
         description.SetParameterType(typeof(string));
         Collection<FieldDescription> descriptions = new Collection<FieldDescription> {
             description
         };
         try
         {
             Dictionary<string, PSObject> dictionary = null;
             dictionary = base.Host.UI.Prompt(string.Empty, string.Empty, descriptions);
             if ((dictionary != null) && (dictionary.Count > 0))
             {
                 foreach (PSObject obj2 in dictionary.Values)
                 {
                     return (string) LanguagePrimitives.ConvertTo(obj2, typeof(string), Thread.CurrentThread.CurrentCulture);
                 }
             }
             return str;
         }
         catch (NotImplementedException)
         {
         }
     }
     return str;
 }
Exemplo n.º 20
0
        public override SecureString ReadLineAsSecureString()
        {
            if (Far.Api.UI.IsCommandMode)
            {
                for (; ; )
                {
                    var ui = new UI.ReadLine() { Password = true };
                    if (!ui.Show())
                    {
                        A.AskStopPipeline();
                        continue;
                    }

                    WriteLine("*");
                    return (SecureString)ValueToResult(ui.Text, true).BaseObject;
                }
            }

            const string name = " ";
            var field = new FieldDescription(name);
            field.SetParameterType(typeof(SecureString));
            var fields = new Collection<FieldDescription>() { field };

            var r = Prompt("", "", fields);
            if (r == null)
                return null;

            return (SecureString)r[name].BaseObject;
        }
Exemplo n.º 21
0
		private string PromptForSingleItem(Type fieldType, string printFieldPrompt, string fieldPrompt, string caption, string message, FieldDescription desc, bool fieldEchoOnPrompt, bool listInput, out bool endListInput, out bool cancelInput, out object convertedObj)
		{
			PSCredential pSCredential;
			cancelInput = false;
			endListInput = false;
			convertedObj = null;
			if (!fieldType.Equals(typeof(SecureString)))
			{
				if (!fieldType.Equals(typeof(PSCredential)))
				{
					string str = null;
					do
					{
						str = this.PromptReadInput(printFieldPrompt, desc, fieldEchoOnPrompt, listInput, out endListInput, out cancelInput);
					}
					while (!cancelInput && !endListInput && this.PromptTryConvertTo(fieldType, desc.IsFromRemoteHost, str, out convertedObj) != ConsoleHostUserInterface.PromptCommonInputErrors.None);
					return str;
				}
				else
				{
					this.WriteLineToConsole(this.WrapToCurrentWindowWidth(fieldPrompt));
					if (this.PromptUsingConsole() || !desc.ModifiedByRemotingProtocol)
					{
						pSCredential = this.PromptForCredential(null, null, null, string.Empty);
					}
					else
					{
						pSCredential = this.PromptForCredential(caption, message, null, string.Empty);
					}
					convertedObj = pSCredential;
					cancelInput = convertedObj == null;
					if (pSCredential != null && pSCredential.Password.Length == 0 && listInput)
					{
						endListInput = true;
					}
				}
			}
			else
			{
				this.WriteToConsole(printFieldPrompt, true);
				SecureString secureString = this.ReadLineAsSecureString();
				convertedObj = secureString;
				cancelInput = convertedObj == null;
				if (secureString != null && secureString.Length == 0 && listInput)
				{
					endListInput = true;
				}
			}
			return null;
		}