Exemplo n.º 1
0
        public T Start()
        {
            using (var scope = new ConsoleScope())
            {
                T result;

                while (true)
                {
                    scope.Render(Template, new TemplateModel {
                        Message = _message, DefaultValue = _defaultValue
                    });

                    var input = scope.ReadLine();

                    if (!scope.Validate(input, _validators))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(input))
                    {
                        if (_targetType.IsValueType && _underlyingType == null && _defaultValue == null)
                        {
                            scope.SetError(new ValidationError("Value is required"));

                            continue;
                        }

                        result = (T)_defaultValue;

                        break;
                    }

                    try
                    {
                        result = (T)Convert.ChangeType(input, _underlyingType ?? _targetType);
                        break;
                    }
                    catch (Exception ex)
                    {
                        scope.SetException(ex);
                    }
                }

                scope.Render(FinishTemplate, new FinishTemplateModel {
                    Message = _message, Result = result
                });

                return(result);
            }
        }
Exemplo n.º 2
0
        public string Start()
        {
            using (var scope = new ConsoleScope())
            {
                var result = "";

                while (true)
                {
                    scope.Render(Template, new TemplateModel {
                        Message = _message, InputLength = result.Length
                    });

                    var keyInfo = scope.ReadKey();

                    if (keyInfo.Key == ConsoleKey.Enter)
                    {
                        if (scope.Validate(result, _validators))
                        {
                            break;
                        }

                        result = "";
                    }
                    else if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        if (result.Length == 0)
                        {
                            scope.Beep();
                        }
                        else
                        {
                            result = result.Remove(result.Length - 1, 1);
                        }
                    }
                    else if (!char.IsControl(keyInfo.KeyChar))
                    {
                        result += keyInfo.KeyChar;
                    }
                }

                return(result);
            }
        }