private string BuildStackTrace(string trace) { var items = trace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var newStackTrace = new Text.StringBuilder(); var found = false; foreach (var item in items) { // Only include lines that has files in the source code if (item.Contains(":")) { if (item.Contains("System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()")) { // Stacktrace from here on will be added by the CLR break; } if (found) { newStackTrace.Append(Environment.NewLine); } found = true; newStackTrace.Append(item); } else if (found) { break; } } var result = newStackTrace.ToString(); return(result); }
static void Main(string[] args) { bool[,] gameBoard; //variable que representa el tablero int boardWidth; //variabe que representa el ancho del tablero int boardHeight; //variabe que representa altura del tablero while (true) { Console.Clear(); Text.StringBuilder s = new Text.StringBuilder(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (b[x, y]) { s.Append("|X|"); } else { s.Append("___"); } } s.Append("\n"); } Console.WriteLine(s.ToString()); //================================================= //Invocar método para calcular siguiente generación //================================================= Threading.Sleep(300); } }
/// <summary> /// 把集合中的所有元素放入一个字符串。 /// </summary> /// <typeparam name="T">数据类型。</typeparam> /// <param name="items">原集合。</param> /// <param name="callback">回调方法。</param> /// <param name="separator">分隔符。</param> /// <param name="start">起始文本。如果集合为空,不包含此数据。</param> /// <param name="end">结尾文本。如果集合为空,不包含此数据。</param> /// <returns>拼接后的字符串。</returns> public static string Join <T>(this IEnumerable <T> items, Func <T, string> callback, string separator = ",", string start = null, string end = null) { Text.StringBuilder builder = new Text.StringBuilder(); foreach (var item in items) { if (builder.Length > 0) { builder.Append(separator); } builder.Append(callback(item)); } if (builder.Length == 0) { return(string.Empty); } if (start != null) { builder.Insert(0, start); } if (end != null) { builder.Append(end); } return(builder.ToString()); }
public static string Concatenate <T>(this ICollection <T> collection, Func <T, string> stringFunction, string separator = "") { var sb = new Text.StringBuilder(); if (collection.IsNotEmpty()) { foreach (var item in collection) { sb.Append(stringFunction(item)); if (separator != "") { sb.Append(separator); } } } string result = sb.ToString(); if (separator != "") { int lastSpearatorIndex = result.LastIndexOf(separator); return(result.Substring(0, lastSpearatorIndex)); } return(result); }
/// <summary> /// 把集合中的所有元素放入一个字符串。 /// </summary> /// <typeparam name="T">数据类型。</typeparam> /// <param name="items">原集合。</param> /// <param name="callback">回调方法。</param> /// <param name="separator">分隔符。</param> /// <param name="start">起始文本。如果集合为空,不包含此数据。</param> /// <param name="end">结尾文本。如果集合为空,不包含此数据。</param> /// <param name="ignoreEmptyItem">指示是否忽略集合中为 null 或 <see cref="string.Empty"/> 值的项。</param> /// <returns>拼接后的字符串。</returns> public static string Join <T>(this IEnumerable <T> items, Func <T, string> callback, string separator = ",", string start = null, string end = null, bool ignoreEmptyItem = true) { var builder = new Text.StringBuilder(); var isStringType = typeof(T) == DefineTypes.String; foreach (var item in items) { if (ignoreEmptyItem && (item == null || (isStringType && item.ToString().Length == 0))) { continue; } if (builder.Length > 0) { builder.Append(separator); } builder.Append(callback(item)); } if (builder.Length == 0) { return(string.Empty); } if (start != null) { builder.Insert(0, start); } if (end != null) { builder.Append(end); } return(builder.ToString()); }
// name could be null // logicalMethodName is MethodInfo.Name with Begin removed for async pattern internal static string GetMessageAction(XmlQualifiedName contractName, string opname, string action, bool isResponse) { if (action != null) { return(action); } Text.StringBuilder actionBuilder = new Text.StringBuilder(64); if (String.IsNullOrEmpty(contractName.Namespace)) { actionBuilder.Append("urn:"); } else { actionBuilder.Append(contractName.Namespace); if (!contractName.Namespace.EndsWith("/", StringComparison.Ordinal)) { actionBuilder.Append('/'); } } actionBuilder.Append(contractName.Name); actionBuilder.Append('/'); action = isResponse ? opname + "Response" : opname; return(CombineUriStrings(actionBuilder.ToString(), action)); }
public void CopyAllData(string tableFrom, string tableTo) { DataTable dt1 = Select(string.Format("select * from `{0}` where 1 = 2;", tableFrom)); DataTable dt2 = Select(string.Format("select * from `{0}` where 1 = 2;", tableTo)); Dictionary <string, bool> dic = new Dictionary <string, bool>(); foreach (DataColumn dc in dt1.Columns) { if (dt2.Columns.Contains(dc.ColumnName)) { if (!dic.ContainsKey(dc.ColumnName)) { dic[dc.ColumnName] = true; } } } foreach (DataColumn dc in dt2.Columns) { if (dt1.Columns.Contains(dc.ColumnName)) { if (!dic.ContainsKey(dc.ColumnName)) { dic[dc.ColumnName] = true; } } } StringBuilder sb = new Text.StringBuilder(); foreach (KeyValuePair <string, bool> kv in dic) { if (sb.Length > 0) { sb.Append(","); } sb.Append("`"); sb.Append(kv.Key); sb.Append("`"); } StringBuilder sb2 = new Text.StringBuilder(); sb2.Append("insert into `"); sb2.Append(tableTo); sb2.Append("`("); sb2.Append(sb.ToString()); sb2.Append(") select "); sb2.Append(sb.ToString()); sb2.Append(" from `"); sb2.Append(tableFrom); sb2.Append("`;"); cmd.CommandText = sb2.ToString(); cmd.ExecuteNonQuery(); }
private static string CreateFilter(IEnumerable <FileType> fileTypes) { var builder = new Text.StringBuilder(); foreach (var fileType in fileTypes) { if (builder.Length > 0) { builder.Append("|"); } builder.Append(fileType.Description + "|*" + fileType.FileExtension); } return(builder.ToString()); }
/// <summary> /// Returns the ESpec for the EncodingFile itself /// </summary> /// <param name="substreams"></param> /// <returns></returns> private string GetFileESpec(IEnumerable <BlockTableSubStream> substreams) { Text.StringBuilder sb = new Text.StringBuilder(_EncodingMap.Length * 0xA); // explicit sizes for the previous blocks foreach (var stream in substreams.Take(substreams.Count() - 1)) { sb.Append($"{stream.Length}={(char)stream.EncodingMap.Type},"); } // greedy final block sb.Append($"*={(char)substreams.Last().EncodingMap.Type}"); return("b:{" + sb.ToString().ToLowerInvariant() + "}"); }
private static void AppendFormatCommandParameterInfo(CommandParameterInfo parameter, Text.StringBuilder result) { if (result.Length > 0) { // Add a space between parameters result.Append(" "); } if (parameter.ParameterType == typeof(SwitchParameter)) { result.AppendFormat(CultureInfo.InvariantCulture, parameter.IsMandatory ? "-{0}" : "[-{0}]", parameter.Name); } else { string parameterTypeString = GetParameterTypeString(parameter.ParameterType, parameter.Attributes); if (parameter.IsMandatory) { result.AppendFormat(CultureInfo.InvariantCulture, parameter.Position != int.MinValue ? "[-{0}] <{1}>" : "-{0} <{1}>", parameter.Name, parameterTypeString); } else { result.AppendFormat(CultureInfo.InvariantCulture, parameter.Position != int.MinValue ? "[[-{0}] <{1}>]" : "[-{0} <{1}>]", parameter.Name, parameterTypeString); } } }
private static void GetCustomBindingDetails(Channels.CustomBinding binding, ref string name, ref string mode, ref string credentialType) { name = GetBindingName <Channels.CustomBinding>(binding); Text.StringBuilder sb = new Text.StringBuilder(); foreach (Channels.BindingElement element in binding.Elements) { if (sb.Length > 0) { sb.Append(","); } // Only dump the name with the known binding elements sb.Append(IsKnownType(element) ? (element.GetType().Name) : "UserBindingElement"); } mode = sb.ToString(); }
public override string ToString() { Text.StringBuilder builder = new Text.StringBuilder(); if (segments.Count == 0) { builder.Append(rootContainer.Name); } else { foreach (ContainmentQuerySegment segment in segments) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(segment.attribute.ParentContainer.Name); if (segment.omitParent) { builder.Append("(o)"); } builder.Append("->"); builder.Append(segment.attribute.ChildContainer.Name); if (segment.abbreviateChild) { builder.Append("(a)"); } } } return(builder.ToString()); }
public string ToString(string format) { System.Text.StringBuilder fmt = new Text.StringBuilder(); fmt.Append("["); if (Vector != null) { for (int j = 0; j < Vector.Length; j++) { if (j > 0) { fmt.Append(" "); } fmt.Append(Vector[j].ToString(format)); } } fmt.Append("]"); return(fmt.ToString()); }
/// <summary> /// Gets the synopsis for the cmdlet as a string /// </summary> public override string ToString() { Text.StringBuilder result = new Text.StringBuilder(); GenerateParametersInDisplayOrder( parameter => AppendFormatCommandParameterInfo(parameter, result), delegate(string str) { if (result.Length > 0) { result.Append(" "); } result.Append("["); result.Append(str); result.Append("]"); }); return(result.ToString()); }
/// <summary> /// /// </summary> /// <param name="isCapabilityWorkflow"> /// This boolean is used to suppress common workflow parameters (or) display /// them separately towards the end /// </param> /// <returns></returns> internal string ToString(bool isCapabilityWorkflow) { Text.StringBuilder result = new Text.StringBuilder(); GenerateParametersInDisplayOrder(isCapabilityWorkflow, parameter => AppendFormatCommandParameterInfo(parameter, ref result), delegate(string str) { if (result.Length > 0) { result.Append(" "); } result.Append("["); result.Append(str); result.Append("]"); }); return(result.ToString()); }
public static Type MakeArrayType(this Type self, int rank) { var builder = new Text.StringBuilder(); for (int i = 1; i < rank; i++) { builder.Append(","); } return(Type.GetType(self.FullName + "[" + builder + "]")); }
public static void ExtractFiltered(string cabPath, string extractPath, string[] filters, bool inclusive) { var sb = new Text.StringBuilder(); if (filters != null && filters.Length > 0) { sb.Append(filters[0]); } for (int i = 1; i < filters.Length; i++) { sb.Append(','); sb.Append(filters[i]); } using (var pin = new PinCollection()) { NativeCommon.CabExtractFiltered( pin.AddBlittable(cabPath), pin.AddBlittable(extractPath), pin.AddBlittable(sb.ToString()), NativeTypes.ToBOOLEAN(inclusive)); } }
/// <summary> /// Displays a message box containing the specified <see cref="Exception"/> /// including a full traceback of inner exceptions, with the specified caption. /// The <paramref name="prefix"/> text is display before the exception trace. /// The text can be copied. /// </summary> /// <param name="ex">A <see cref="Exception"/> to display.</param> /// <param name="prefix">Text to display before the exception.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> public static void IssueException(Exception ex, string prefix, string caption) { System.Text.StringBuilder sb = new Text.StringBuilder(); sb.Append(prefix); sb.Append("\n== START =="); for (Exception inex = ex; inex != null; inex = inex.InnerException) { sb.Append("\nSource: " + inex.Source); sb.Append("\nAssembly: " + inex.TargetSite.DeclaringType.Assembly.FullName); sb.Append("\n" + inex.Message); sb.Append("\n" + inex.StackTrace); sb.Append("\n-----"); } sb.Append("\n== END =="); CopyableMessageBox.Show(sb.ToString(), caption, CopyableMessageBoxButtons.OK, CopyableMessageBoxIcon.Stop); }
/// <summary> /// Renders HTML for a drop down list with a preselected value /// </summary> /// <param name="helper"></param> /// <param name="list"></param> /// <param name="name"></param> /// <param name="text"></param> /// <returns></returns> public static MvcHtmlString DropDownListPreselectByText(this HtmlHelper helper, IEnumerable <SelectListItem> list, string name, string text) { System.Text.StringBuilder sb = new Text.StringBuilder(); sb.AppendFormat("<select id=\"{0}\" name=\"{0}\">", name, name); foreach (SelectListItem item in list) { if (text != null && item.Text.Equals(text)) { sb.AppendFormat(" <option value=\"{0}\" selected=\"selected\">{1}</option>", item.Value, item.Text); } else { sb.AppendFormat(" <option value=\"{0}\">{1}</option>", item.Value, item.Text); } } sb.Append("</select>"); return(new MvcHtmlString(sb.ToString())); }
public static MvcHtmlString ToolButton(this HtmlHelper helper, string id, string icon, string text, List <permModel> perm, string keycode, bool hr) { if (perm.Where(a => a.KeyCode == keycode).Count() > 0) { var sb = new Text.StringBuilder(); sb.AppendFormat("<a id=\"{0}\" style=\"float: left;\" class=\"l-btn l-btn-plain\">", id); sb.AppendFormat("<span class=\"l-btn-left\"><span class=\"l-btn-text {0}\" style=\"padding-left: 20px;\">", icon); sb.AppendFormat("{0}</span></span></a>", text); if (hr) { sb.Append("<div class=\"datagrid-btn-separator\"></div>"); } return(new MvcHtmlString(sb.ToString())); } else { return(new MvcHtmlString("")); } }
public void CreateTable(DataTable table) { StringBuilder sb = new Text.StringBuilder(); sb.Append("create table if not exists `"); sb.Append(table.TableName); sb.AppendLine("`("); bool firstRecord = true; foreach (DataColumn col in table.Columns) { if (col.ColumnName.Trim().Length == 0) { throw new Exception("Column name cannot be blank."); } if (firstRecord) { firstRecord = false; } else { sb.AppendLine(","); } sb.Append(col.ColumnName); sb.Append(" "); if (col.AutoIncrement) { sb.Append("integer primary key autoincrement"); continue; } sb.Append("text"); /* if (col.Table.PrimaryKey.) * sb.Append(" primary key");*/ } sb.AppendLine(");"); cmd.CommandText = sb.ToString(); cmd.ExecuteNonQuery(); }
private string BuildStackTrace(string trace) { var items = trace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var newStackTrace = new Text.StringBuilder(); var found = false; foreach (var item in items) { // Only include lines that has files in the source code if (item.Contains(":")) { if (item.Contains("System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()")) { // Stacktrace from here on will be added by the CLR break; } if (found) { newStackTrace.Append(Environment.NewLine); } found = true; newStackTrace.Append(item); } else if (found) { break; } } var result = newStackTrace.ToString(); return result; }
public void CreateTable(SQLiteTable table) { StringBuilder sb = new Text.StringBuilder(); sb.Append("create table if not exists `"); sb.Append(table.TableName); sb.AppendLine("`("); bool firstRecord = true; foreach (SQLiteColumn col in table.Columns) { if (col.ColumnName.Trim().Length == 0) { throw new Exception("Column name cannot be blank."); } if (firstRecord) { firstRecord = false; } else { sb.AppendLine(","); } sb.Append(col.ColumnName); sb.Append(" "); if (col.AutoIncrement) { sb.Append("integer primary key autoincrement"); continue; } switch (col.ColDataType) { case ColType.Text: sb.Append("text"); break; case ColType.Integer: sb.Append("integer"); break; case ColType.Decimal: sb.Append("decimal"); break; case ColType.DateTime: sb.Append("datetime"); break; case ColType.BLOB: sb.Append("blob"); break; } if (col.PrimaryKey) { sb.Append(" primary key"); } else if (col.NotNull) { sb.Append(" not null"); } else if (col.DefaultValue.Length > 0) { sb.Append(" default "); if (col.DefaultValue.Contains(" ") || col.ColDataType == ColType.Text || col.ColDataType == ColType.DateTime) { sb.Append("'"); sb.Append(col.DefaultValue); sb.Append("'"); } else { sb.Append(col.DefaultValue); } } } sb.AppendLine(");"); cmd.CommandText = sb.ToString(); cmd.ExecuteNonQuery(); }
/// <summary> /// This method is added to be backward compatible with V1 hosts w.r.t /// new PromptForChoice method added in PowerShell V2. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoices"></param> /// <returns></returns> /// <exception cref="ArgumentException"> /// 1. Choices is null. /// 2. Choices.Count = 0 /// 3. DefaultChoice is either less than 0 or greater than Choices.Count /// </exception> private Collection <int> EmulatePromptForMultipleChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { Dbg.Assert(_externalUI != null, "externalUI cannot be null."); if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(choices), InternalHostUserInterfaceStrings.EmptyChoicesError, "choices"); } Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, InternalHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } defaultChoiceKeys.TryAdd(defaultChoice, true); } } // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); choicesMessage.Append(newLine); } if (!string.IsNullOrEmpty(message)) { choicesMessage.Append(message); choicesMessage.Append(newLine); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = string.Format( Globalization.CultureInfo.InvariantCulture, choiceTemplate, hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i]); choicesMessage.Append(choice); choicesMessage.Append(newLine); } // default choices string defaultPrompt = string.Empty; if (defaultChoiceKeys.Count > 0) { string prepend = string.Empty; Text.StringBuilder defaultChoicesBuilder = new Text.StringBuilder(); foreach (int defaultChoice in defaultChoiceKeys.Keys) { string defaultStr = hotkeysAndPlainLabels[0, defaultChoice]; if (string.IsNullOrEmpty(defaultStr)) { defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture, "{0}{1}", prepend, defaultStr)); prepend = ","; } string defaultChoicesStr = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, defaultChoicesStr); } else { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, defaultChoicesStr); } } string messageToBeDisplayed = choicesMessage.ToString() + defaultPrompt + newLine; // read choices from the user Collection <int> result = new Collection <int>(); int choicesSelected = 0; while (true) { string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected); messageToBeDisplayed += choiceMsg; _externalUI.WriteLine(messageToBeDisplayed); string response = _externalUI.ReadLine(); // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // reset messageToBeDisplayed messageToBeDisplayed = string.Empty; } return(result); }
private string FixUpStatementExtent(int startColNum, string stateExtentText) { Text.StringBuilder sb = new Text.StringBuilder(); sb.Append(' ', startColNum); sb.Append(stateExtentText); return sb.ToString(); }
/// <summary> /// /// </summary> /// <param name="isCapabilityWorkflow"> /// This boolean is used to suppress common workflow parameters (or) display /// them separately towards the end /// </param> /// <returns></returns> internal string ToString(bool isCapabilityWorkflow) { Text.StringBuilder result = new Text.StringBuilder(); GenerateParametersInDisplayOrder(isCapabilityWorkflow, parameter => AppendFormatCommandParameterInfo(parameter, ref result), delegate (string str) { if (result.Length > 0) { result.Append(" "); } result.Append("["); result.Append(str); result.Append("]"); }); return result.ToString(); }
/// <summary> /// This method is added to be backward compatible with V1 hosts w.r.t /// new PromptForChoice method added in PowerShell V2. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoices"></param> /// <returns></returns> /// <exception cref="ArgumentException"> /// 1. Choices is null. /// 2. Choices.Count = 0 /// 3. DefaultChoice is either less than 0 or greater than Choices.Count /// </exception> private Collection<int> EmulatePromptForMultipleChoice(string caption, string message, Collection<ChoiceDescription> choices, IEnumerable<int> defaultChoices) { Dbg.Assert(null != _externalUI, "externalUI cannot be null."); if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", InternalHostUserInterfaceStrings.EmptyChoicesError, "choices"); } Dictionary<int, bool> defaultChoiceKeys = new Dictionary<int, bool>(); if (null != defaultChoices) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, InternalHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } if (!defaultChoiceKeys.ContainsKey(defaultChoice)) { defaultChoiceKeys.Add(defaultChoice, true); } } } // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); choicesMessage.Append(newLine); } if (!string.IsNullOrEmpty(message)) { choicesMessage.Append(message); choicesMessage.Append(newLine); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = String.Format( Globalization.CultureInfo.InvariantCulture, choiceTemplate, hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i]); choicesMessage.Append(choice); choicesMessage.Append(newLine); } // default choices string defaultPrompt = ""; if (defaultChoiceKeys.Count > 0) { string prepend = ""; Text.StringBuilder defaultChoicesBuilder = new Text.StringBuilder(); foreach (int defaultChoice in defaultChoiceKeys.Keys) { string defaultStr = hotkeysAndPlainLabels[0, defaultChoice]; if (string.IsNullOrEmpty(defaultStr)) { defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture, "{0}{1}", prepend, defaultStr)); prepend = ","; } string defaultChoicesStr = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, defaultChoicesStr); } else { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, defaultChoicesStr); } } string messageToBeDisplayed = choicesMessage.ToString() + defaultPrompt + newLine; // read choices from the user Collection<int> result = new Collection<int>(); int choicesSelected = 0; do { string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected); messageToBeDisplayed += choiceMsg; _externalUI.WriteLine(messageToBeDisplayed); string response = _externalUI.ReadLine(); // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // reset messageToBeDisplayed messageToBeDisplayed = ""; } while (true); return result; }
/// <summary> /// Computes a name from a text label by removing all spaces and non-alphanumeric characters. /// </summary> private string NameFromText(string text, Type itemType, INameCreationService nameCreationService, bool adjustCapitalization) { string baseName; // for separators, name them ToolStripSeparator... if (text == "-") { baseName = "toolStripSeparator"; } else { string nameSuffix = itemType.Name; // remove all the non letter and number characters. Append length of "MenuItem" Text.StringBuilder name = new Text.StringBuilder(text.Length + nameSuffix.Length); bool firstCharSeen = false; for (int i = 0; i < text.Length; i++) { char c = text[i]; if (char.IsLetterOrDigit(c)) { if (!firstCharSeen) { c = char.ToLower(c, CultureInfo.CurrentCulture); firstCharSeen = true; } name.Append(c); } } name.Append(nameSuffix); baseName = name.ToString(); if (adjustCapitalization) { string nameOfRandomItem = ToolStripDesigner.NameFromText(null, typeof(ToolStripMenuItem), _designer.Component.Site); if (!string.IsNullOrEmpty(nameOfRandomItem) && char.IsUpper(nameOfRandomItem[0])) { baseName = char.ToUpper(baseName[0], CultureInfo.InvariantCulture) + baseName.Substring(1); } } } // see if this name matches another one in the container.. object existingComponent = _host.Container.Components[baseName]; if (existingComponent is null) { if (!nameCreationService.IsValidName(baseName)) { // we don't have a name collision but this still isn't a valid name...something is wrong and we can't make a valid identifier out of this so bail. return(nameCreationService.CreateName(_host.Container, itemType)); } else { return(baseName); } } else { // start appending numbers. string newName = baseName; for (int indexer = 1; !nameCreationService.IsValidName(newName); indexer++) { newName = baseName + indexer.ToString(CultureInfo.InvariantCulture); } return(newName); } }
/// <summary> /// Constructs a string of the choices and their hotkeys. /// </summary> /// <param name="choices"></param> /// <param name="hotkeysAndPlainLabels"></param> /// <exception cref="ArgumentException"> /// 1. Cannot process the hot key because a question mark ("?") cannot be used as a hot key. /// </exception> internal static void BuildHotkeysAndPlainLabels(Collection<ChoiceDescription> choices, out string[,] hotkeysAndPlainLabels) { // we will allocate the result array hotkeysAndPlainLabels = new string[2, choices.Count]; for (int i = 0; i < choices.Count; ++i) { #region SplitLabel hotkeysAndPlainLabels[0, i] = string.Empty; int andPos = choices[i].Label.IndexOf('&'); if (andPos >= 0) { Text.StringBuilder splitLabel = new Text.StringBuilder(choices[i].Label.Substring(0, andPos), choices[i].Label.Length); if (andPos + 1 < choices[i].Label.Length) { splitLabel.Append(choices[i].Label.Substring(andPos + 1)); hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.Substring(andPos + 1, 1).Trim()); } hotkeysAndPlainLabels[1, i] = splitLabel.ToString().Trim(); } else { hotkeysAndPlainLabels[1, i] = choices[i].Label; } #endregion SplitLabel // ? is not localizable if (string.Compare(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal) == 0) { Exception e = PSTraceSource.NewArgumentException( String.Format(Globalization.CultureInfo.InvariantCulture, "choices[{0}].Label", i), InternalHostUserInterfaceStrings.InvalidChoiceHotKeyError); throw e; } } }