public string GetCommandText(string connectionString, CommandSchema commandSchema) { StringBuilder builder = new StringBuilder(); string str = string.Format("SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = '{0}' AND ROUTINE_NAME = '{1}'", commandSchema.Database.Name, commandSchema.Name); using (DbConnection connection = CreateConnection(connectionString)) { connection.Open(); DbCommand command = connection.CreateCommand(); command.CommandText = str; command.Connection = connection; using (IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { builder.Append(reader.GetString(0)); } if (!reader.IsClosed) { reader.Close(); } } if (connection.State != ConnectionState.Closed) { connection.Close(); } } return builder.ToString(); }
/// <summary> /// Resolves <see cref="CommandSchema"/>. /// </summary> public static CommandSchema Resolve(Type type) { if (!CommandSchema.IsCommandType(type)) { throw InternalTypinExceptions.InvalidCommandType(type); } CommandAttribute attribute = type.GetCustomAttribute <CommandAttribute>() !; string?name = attribute.Name; CommandOptionSchema[] builtInOptions = string.IsNullOrWhiteSpace(name) ? new[] { CommandOptionSchema.HelpOption, CommandOptionSchema.VersionOption } : new[] { CommandOptionSchema.HelpOption }; CommandParameterSchema?[] parameters = type.GetProperties() .Select(CommandParameterSchemaResolver.TryResolve) .Where(p => p != null) .ToArray(); CommandOptionSchema?[] options = type.GetProperties() .Select(CommandOptionSchemaResolver.TryResolve) .Where(o => o != null) .Concat(builtInOptions) .ToArray(); CommandSchema command = new CommandSchema( type, name, attribute.Description, attribute.Manual, attribute.InteractiveModeOnly, parameters !, options ! ); ValidateParameters(command); ValidateOptions(command); return(command); }
public static CommandSchema GenerateSchema(Type command) { var commandSchema = new CommandSchema(); var propertyTypeTable = new Dictionary <Type, Action <PropertyInfo> > { { typeof(string), prop => addPropertyToSchema(commandSchema, prop, new JsonSchema { Type = JsonSchemaType.String }) }, { typeof(int), prop => addPropertyToSchema(commandSchema, prop, new JsonSchema { Type = JsonSchemaType.Integer }) }, { typeof(float), prop => addPropertyToSchema(commandSchema, prop, new JsonSchema { Type = JsonSchemaType.Float }) }, { typeof(bool), prop => addPropertyToSchema(commandSchema, prop, new JsonSchema { Type = JsonSchemaType.Boolean }) } }; foreach (var property in command.GetProperties()) { var propertyType = property.PropertyType; if (propertyTypeTable.ContainsKey(propertyType)) { propertyTypeTable[propertyType](property); } else { // TODO: Is object the best type? Should this be an exception instead? addPropertyToSchema(commandSchema, property, new JsonSchema { Type = JsonSchemaType.Object }); } } addQueryValidation(commandSchema, command); return(commandSchema); }
public async Task HandleAsync(ICliContext context, CommandPipelineHandlerDelegate next, CancellationToken cancellationToken) { //Get input and command schema from context CommandInput input = context.Input; CommandSchema commandSchema = context.CommandSchema; Type currentModeType = _applicationLifetime.CurrentModeType !; // Handle commands not supported in current mode if (!commandSchema.CanBeExecutedInMode(currentModeType)) { throw ModeEndUserExceptions.CommandExecutedInInvalidMode(commandSchema, currentModeType); } // Get command instance from context and bind arguments ICommand instance = context.Command; commandSchema.BindParameters(instance, input.Parameters); commandSchema.BindOptions(instance, input.Options, _optionFallbackProvider); await next(); }
private int?Execute(CliContext context) { RootSchema root = context.RootSchema; CommandInput input = context.Input; // Try to get the command matching the input or fallback to default bool hasDefaultDirective = input.HasDirective(BuiltInDirectives.Default); CommandSchema command = root.TryFindCommand(input.CommandName, hasDefaultDirective) ?? StubDefaultCommand.Schema; // Forbid to execute real default command in interactive mode without [!] directive. if (!(command.IsHelpOptionAvailable && input.IsHelpOptionSpecified) && context.IsInteractiveMode && command.IsDefault && !hasDefaultDirective) { command = StubDefaultCommand.Schema; } // Update CommandSchema context.CommandSchema = command; return(null); }
private async Task <int> Execute(CliContext context) { //Get input and command schema from context CommandInput input = context.Input; CommandSchema commandSchema = context.CommandSchema; // Execute directives if (!await ProcessDefinedDirectives(context)) { return(ExitCodes.Success); } // Get command instance from context and bind arguments ICommand instance = context.Command; commandSchema.Bind(instance, input, _optionFallbackProvider); // Execute command await instance.ExecuteAsync(context.Console); return(context.ExitCode ??= ExitCodes.Success); }
/// <inheritdoc /> public void InitializeCommand(ICommand command, CommandSchema commandSchema, CommandInput commandInput) { command.GuardNotNull(nameof(command)); commandSchema.GuardNotNull(nameof(commandSchema)); commandInput.GuardNotNull(nameof(commandInput)); // Keep track of unset required options to report an error at a later stage var unsetRequiredOptions = commandSchema.Options.Where(o => o.IsRequired).ToList(); // Set command options foreach (var optionInput in commandInput.Options) { // Find matching option schema for this option input var optionSchema = commandSchema.Options.FindByAlias(optionInput.Alias); if (optionSchema == null) { continue; } // Convert option to the type of the underlying property var convertedValue = _commandOptionInputConverter.ConvertOptionInput(optionInput, optionSchema.Property.PropertyType); // Set value of the underlying property optionSchema.Property.SetValue(command, convertedValue); // Mark this required option as set if (optionSchema.IsRequired) { unsetRequiredOptions.Remove(optionSchema); } } // Throw if any of the required options were not set if (unsetRequiredOptions.Any()) { var unsetRequiredOptionNames = unsetRequiredOptions.Select(o => o.GetAliases().FirstOrDefault()).JoinToString(", "); throw new CliFxException($"One or more required options were not set: {unsetRequiredOptionNames}."); } }
private void WriteCommandParameters(CommandSchema command) { if (!command.Parameters.Any()) { return; } if (!IsEmpty) { WriteVerticalMargin(); } WriteHeader("Parameters"); foreach (CommandParameterSchema parameter in command.Parameters.OrderBy(p => p.Order)) { Write(RequiredColor, "* "); Write(RequiredParameterNameColor, $"{parameter.Name}"); WriteColumnMargin(); // Description if (!string.IsNullOrWhiteSpace(parameter.Description)) { Write(parameter.Description); Write(' '); } // Valid values var validValues = parameter.Bindable.GetValidValues(); if (validValues.Count > 0) { WriteValidValues(parameter.Bindable.IsScalar, validValues); } WriteLine(); } }
public ParameterSchema[] GetCommandParameters(string connectionString, CommandSchema commandSchema) { string arg = commandSchema.ExtendedProperties["CS_Name"].Value as string; List <ParameterSchema> list = new List <ParameterSchema>(); using (NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connectionString)) { npgsqlConnection.Open(); string text = string.Format("select * from information_schema.parameters where specific_schema='public' and specific_name = '{0}' order by ordinal_position", arg); using (NpgsqlCommand npgsqlCommand = new NpgsqlCommand(text, npgsqlConnection)) { using (NpgsqlDataReader npgsqlDataReader = npgsqlCommand.ExecuteReader(CommandBehavior.CloseConnection)) { while (npgsqlDataReader.Read()) { string name = npgsqlDataReader.IsDBNull(7) ? string.Empty : npgsqlDataReader.GetString(7); int size = npgsqlDataReader.IsDBNull(9) ? 0 : npgsqlDataReader.GetInt32(9); int scale = npgsqlDataReader.IsDBNull(19) ? 0 : npgsqlDataReader.GetInt32(19); byte precision = npgsqlDataReader.IsDBNull(17) ? (byte)0 : npgsqlDataReader.GetByte(17); string @string = npgsqlDataReader.GetString(8); list.Add(new ParameterSchema(commandSchema, name, PostgreSQLSchemaProvider.GetParameterDirection(npgsqlDataReader.GetString(4)), PostgreSQLSchemaProvider.GetDbType(npgsqlDataReader.GetString(8)), @string, size, precision, scale, false, new ExtendedProperty[] { new ExtendedProperty("NpgsqlDbType", PostgreSQLSchemaProvider.GetNativeDbType(@string), DbType.String) })); } if (!npgsqlDataReader.IsClosed) { npgsqlDataReader.Close(); } } } if (npgsqlConnection.State != ConnectionState.Closed) { npgsqlConnection.Close(); } } return(list.ToArray()); }
private void WriteCommandManual(CommandSchema command) { if (string.IsNullOrWhiteSpace(command.Manual)) { return; } if (!IsEmpty) { WriteVerticalMargin(); } WriteHeader("Manual"); WriteHorizontalMargin(); string text = TextUtils.ConvertTabsToSpaces(command.Manual); text = TextUtils.AdjustNewLines(text); Write(text); WriteLine(); }
public static List <Para> GetSpParas(CommandSchema command) { List <Para> ret = new List <Para>(); foreach (SchemaExplorer.ParameterSchema i in command.Parameters) { if (i.Direction == System.Data.ParameterDirection.ReturnValue) { continue; } Para item = new Para(); item.MethodName = ConvertFirstLowerStr(i.Name.Substring(1)); item.MethodType = GetCType(i, command.ExtendedProperties); item.SpName = i.Name; item.SpType = GetSqlDbType(i.NativeType); item.SpSize = GetParamSize(i).ToString(); item.Remark = item.MethodName; item.Direction = i.Direction; ret.Add(item); } return(ret); }
/// <inheritdoc/> public void Write(CommandSchema command, IReadOnlyDictionary <ArgumentSchema, object?> defaultValues) { RootSchema root = _context.RootSchema; IEnumerable <CommandSchema> childCommands = root.GetChildCommands(command.Name) .OrderBy(x => x.Name); _console.ResetColor(); _console.ForegroundColor = ConsoleColor.Gray; if (command.IsDefault) { WriteApplicationInfo(); } WriteCommandDescription(command); WriteCommandUsage(root.Directives, command, childCommands); WriteCommandParameters(command); WriteCommandOptions(command, defaultValues); WriteCommandChildren(command, childCommands); WriteDirectivesManual(root.Directives); WriteCommandManual(command); }
private void ResolveCommands(IReadOnlyList <Type> commandTypes) { CommandSchema?defaultCommand = null; var commands = new Dictionary <string, CommandSchema>(); var invalidCommands = new List <CommandSchema>(); foreach (Type commandType in commandTypes) { CommandSchema command = CommandSchemaResolver.Resolve(commandType); if (command.IsDefault) { defaultCommand = defaultCommand is null ? command : throw InternalTypinExceptions.TooManyDefaultCommands(); } else if (!commands.TryAdd(command.Name !, command)) { invalidCommands.Add(command); } } if (commands.Count == 0 && defaultCommand is null) { throw InternalTypinExceptions.NoCommandsDefined(); } if (invalidCommands.Count > 0) { IGrouping <string, CommandSchema> duplicateNameGroup = invalidCommands.Union(commands.Values) .GroupBy(c => c.Name !, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(); throw InternalTypinExceptions.CommandsWithSameName(duplicateNameGroup.Key, duplicateNameGroup.ToArray()); } DefaultCommand = defaultCommand; Commands = commands; }
private int?Execute(CliContext context) { //Get configuration and input from context ApplicationConfiguration _configuration = context.Configuration; CommandInput input = context.Input; // Get command schema from context CommandSchema commandSchema = context.CommandSchema; // Handle commands not supported in normal mode if (!_configuration.IsInteractiveModeAllowed && commandSchema.InteractiveModeOnly) { throw EndUserTypinExceptions.InteractiveOnlyCommandButThisIsNormalApplication(commandSchema); } // Handle commands supported only in interactive mode when interactive mode was not started if (_configuration.IsInteractiveModeAllowed && commandSchema.InteractiveModeOnly && !(context.IsInteractiveMode || input.IsInteractiveDirectiveSpecified)) { throw EndUserTypinExceptions.InteractiveOnlyCommandButInteractiveModeNotStarted(commandSchema); } return(null); }
/// <summary> /// Return the parameters of a given command (stored procedure...) /// </summary> /// <param name="connectionString"></param> /// <param name="command"></param> /// <returns></returns> public List <ParameterSchema> GetCommandParameters(string connectionString, CommandSchema command) { DataTable table = new SchemaHelper().GetProcedureParameters(connectionString, command.Database.Name, command.Owner, command.Name, null); List <ParameterSchema> schemaArray = new List <ParameterSchema>(table.Rows.Count); for (int i = 0; i < table.Rows.Count; i++) { string name = (string)table.Rows[i]["PARAMETER_NAME"]; ParameterDirection direction = GetParamDirection((string)table.Rows[i]["PARAMETER_MODE"]); string nativeType = (string)table.Rows[i]["DATA_TYPE"]; DbType dataType = _DataTypes.First(p => p.StringType == ((string)table.Rows[i]["DATA_TYPE"])).eDbType; int size = table.Rows[i].IsNull("CHARACTER_MAXIMUM_LENGTH") ? 0 : ((int)table.Rows[i]["CHARACTER_MAXIMUM_LENGTH"]); byte precision = table.Rows[i].IsNull("NUMERIC_PRECISION") ? ((byte)0) : ((byte)table.Rows[i]["NUMERIC_PRECISION"]); int scale = table.Rows[i].IsNull("NUMERIC_SCALE") ? 0 : ((int)table.Rows[i]["NUMERIC_SCALE"]); bool allowDBNull = false; //default value ? //list.Add(new ExtendedProperty(c.a("\x0019\t\x0005\x001e?<;/6."), str4, DbType.String)); schemaArray.Add(new ParameterSchema(command, name, direction, dataType, nativeType, size, Convert.ToByte(precision), scale, allowDBNull)); } return(schemaArray); }
private void WriteModeRestrictionsManual(CommandSchema command) { IReadOnlyList <Type> modesInApplication = _context.Configuration.ModeTypes; if (modesInApplication.Count == 1) { return; } if (!IsEmpty) { WriteVerticalMargin(); } WriteHeader("Supported modes"); IEnumerable <Type> commandModes = (command.SupportedModes?.Count ?? 0) > 0 ? command.SupportedModes ! : modesInApplication; if ((command.ExcludedModes?.Count ?? 0) > 0) { commandModes = commandModes.Except(command.ExcludedModes !); } foreach (Type mode in commandModes) { WriteHorizontalMargin(); Write(ModeRestrictedColor, mode.FullName ?? mode.Name); WriteLine(); } WriteLine(); Write(CommentColor, "TIP: Commands and directives marked with "); Write(ModeRestrictedColor, "@"); Write(CommentColor, " cannot be executed in every mode in the app."); WriteLine(); }
public ParameterSchema[] GetCommandParameters(string connectionString, CommandSchema command) { var parameters = new List <ParameterSchema>(); var extendedProperties = new List <ExtendedProperty>(); string sql = string.Format("SELECT PARAM_ORDER, PARAM_NAME, PARAM_TYPE, IS_PARAM_OUT, DEFAULT_VALUE FROM sp_stored_procedures() WHERE PROC_NAME = '{0}'", command.Name); using (VistaDBConnection connection = GetConnection(connectionString)) using (var adapter = new VistaDBDataAdapter(sql, connection)) using (var table = new DataTable()) { adapter.Fill(table); foreach (DataRow row in table.Rows) { string name = row["PARAM_NAME"].ToString(); var vistaType = (VistaDBType)(row["PARAM_TYPE"] ?? VistaDBType.Unknown); var isOut = (bool)(row["IS_PARAM_OUT"] ?? false); string defaultValue = row["DEFAULT_VALUE"].ToString(); extendedProperties.Clear(); extendedProperties.Add(ExtendedProperty.Readonly(ExtendedPropertyNames.Description, string.Empty)); extendedProperties.Add(ExtendedProperty.Readonly(ExtendedPropertyNames.DefaultValue, defaultValue)); var parameter = new ParameterSchema(command, name, isOut ? ParameterDirection.InputOutput : ParameterDirection.Input, GetDbType(vistaType.ToString()), vistaType.ToString(), 0, 0, 0, true, extendedProperties.ToArray()); parameters.Add(parameter); } } return(parameters.ToArray()); }
private void BindOptions(CommandInput commandInput, CommandSchema commandSchema, ICommand commandInstance) { // Ensure there are no unrecognized options and that all required options are set var remainingOptionInputs = commandInput.Options.ToList(); var remainingRequiredOptionSchemas = commandSchema.Options.Where(o => o.IsRequired).ToList(); foreach (var optionSchema in commandSchema.Options) { var optionInputs = commandInput .Options .Where(o => optionSchema.MatchesIdentifier(o.Identifier)) .ToArray(); var environmentVariableInput = commandInput .EnvironmentVariables .FirstOrDefault(e => optionSchema.MatchesEnvironmentVariable(e.Name)); // Direct input if (optionInputs.Any()) { var rawValues = optionInputs.SelectMany(o => o.Values).ToArray(); BindMember(optionSchema, commandInstance, rawValues); // Required options require at least one value to be set if (rawValues.Any()) { remainingRequiredOptionSchemas.Remove(optionSchema); } } // Environment variable else if (environmentVariableInput is not null) { var rawValues = optionSchema.Property.IsScalar() ? new[] { environmentVariableInput.Value } : environmentVariableInput.SplitValues(); BindMember(optionSchema, commandInstance, rawValues); // Required options require at least one value to be set if (rawValues.Any()) { remainingRequiredOptionSchemas.Remove(optionSchema); } } // No input - skip else { continue; } remainingOptionInputs.RemoveRange(optionInputs); } if (remainingOptionInputs.Any()) { throw CliFxException.UserError( "Unrecognized option(s):" + Environment.NewLine + remainingOptionInputs .Select(o => o.GetFormattedIdentifier()) .JoinToString(", ") ); } if (remainingRequiredOptionSchemas.Any()) { throw CliFxException.UserError( "Missing required option(s):" + Environment.NewLine + remainingRequiredOptionSchemas .Select(o => o.GetFormattedIdentifier()) .JoinToString(", ") ); } }
private void BindParameters(CommandInput commandInput, CommandSchema commandSchema, ICommand commandInstance) { // Ensure there are no unexpected parameters and that all parameters are provided var remainingParameterInputs = commandInput.Parameters.ToList(); var remainingRequiredParameterSchemas = commandSchema.Parameters.Where(p => p.IsRequired).ToList(); var position = 0; foreach (var parameterSchema in commandSchema.Parameters.OrderBy(p => p.Order)) { // Break when there are no remaining inputs if (position >= commandInput.Parameters.Count) { break; } // Scalar - take one input at the current position if (parameterSchema.Property.IsScalar()) { var parameterInput = commandInput.Parameters[position]; var rawValues = new[] { parameterInput.Value }; BindMember(parameterSchema, commandInstance, rawValues); position++; remainingParameterInputs.Remove(parameterInput); } // Non-scalar - take all remaining inputs starting from the current position else { var parameterInputs = commandInput.Parameters.Skip(position).ToArray(); var rawValues = parameterInputs.Select(p => p.Value).ToArray(); BindMember(parameterSchema, commandInstance, rawValues); position += parameterInputs.Length; remainingParameterInputs.RemoveRange(parameterInputs); } remainingRequiredParameterSchemas.Remove(parameterSchema); } if (remainingParameterInputs.Any()) { throw CliFxException.UserError( "Unexpected parameter(s):" + Environment.NewLine + remainingParameterInputs .Select(p => p.GetFormattedIdentifier()) .JoinToString(" ") ); } if (remainingRequiredParameterSchemas.Any()) { throw CliFxException.UserError( "Missing required parameter(s):" + Environment.NewLine + remainingRequiredParameterSchemas .Select(o => o.GetFormattedIdentifier()) .JoinToString(" ") ); } }
/// <summary> /// Indicates if the output rowset of the command is compliant with the view rowset. /// </summary> /// <param name="command">The stored procedure</param> /// <param name="view">The view</param> public bool IsMatching(CommandSchema command, ViewSchema view) { if (command.CommandResults.Count != 1) { return false; } if (command.CommandResults[0].Columns.Count != view.Columns.Count) { return false; } for(int i=0; i<view.Columns.Count; i++) { if (command.CommandResults[0].Columns[i].Name != view.Columns[i].Name) { return false; } if (command.CommandResults[0].Columns[i].NativeType != view.Columns[i].NativeType) { return false; } } return true; }
public ParameterSchema[] GetCommandParameters(string connectionString, CommandSchema command) { throw new NotSupportedException("GetCommandParameters() is not supported in this release."); }
public ParameterSchema[] GetCommandParameters(string connectionString, CommandSchema command) { // NetTiers shouldn't be using this, so unimplemented right now return new ParameterSchema[0]; }
private void CreateFunction(CommandSchema commandSchema) { Function function; string key = commandSchema.FullName; bool isNew = !Database.Functions.Contains(key); if (isNew) { function = new Function(key); Database.Functions.Add(function); } else { function = Database.Functions[key]; } //Function/@Method is safe to update if (string.IsNullOrEmpty(function.Method)) { string methodName = ToLegalName(commandSchema.Name); if (ClassNames.Contains(methodName)) methodName += "Procedure"; function.Method = MakeUnique(FunctionNames, methodName); } function.IsComposable = IsFunction(commandSchema); ParameterSchema returnParameter = null; function.Parameters.Clear(); foreach (ParameterSchema p in commandSchema.Parameters) { if (p.Direction == System.Data.ParameterDirection.ReturnValue) returnParameter = p; else CreateParameter(function, p); } try { for (int i = 0; i < commandSchema.CommandResults.Count; i++) { var r = commandSchema.CommandResults[i]; string defaultName = function.Method + "Result"; if (commandSchema.CommandResults.Count > 1) defaultName += (i + 1).ToString(); CreateResult(function, r, defaultName, i); } } catch (Exception ex) { Debug.WriteLine("Error reading result schema: " + ex.Message); } function.HasMultipleResults = function.Types.Count > 1; function.IsProcessed = true; if (function.Types.Count != 0) return; if (function.Return == null) function.Return = new Return("System.Int32"); if (commandSchema.ReturnValueParameter != null) { function.Return.Type = GetSystemType(commandSchema.ReturnValueParameter); function.Return.DbType = GetDbType(commandSchema.ReturnValueParameter); } else if (returnParameter != null) { function.Return.Type = GetSystemType(returnParameter); function.Return.DbType = GetDbType(returnParameter); } else { function.Return.Type = "System.Int32"; function.Return.DbType = "int"; } }
/// <summary> /// Get the owner of a command /// </summary> /// <param name="command">The command to check</param> /// <returns>The safe name of the owner of the command</returns> public string GetOwner(CommandSchema command) { return (command.Owner.Length > 0) ? GetSafeName(command.Owner) + "." : ""; }
private void WriteCommandUsage(IReadOnlyDictionary <string, DirectiveSchema> directives, CommandSchema command, IEnumerable <CommandSchema> childCommands) { if (!IsEmpty) { WriteVerticalMargin(); } WriteHeader("Usage"); // Exe name if (command.HasModeRestrictions()) { Write(ModeRestrictedColor, "@"); WriteHorizontalMargin(1); } else { WriteHorizontalMargin(); } Write(CommentColor, _context.Metadata.ExecutableName); // Child command placeholder if (directives.Any()) { Write(' '); Write(DirectiveNameColor, "[directives]"); } // Command name if (!string.IsNullOrWhiteSpace(command.Name)) { Write(' '); Write(CommandNameColor, command.Name); } // Child command placeholder if (childCommands.Any()) { Write(' '); Write(CommandNameColor, "[command]"); } // Parameters foreach (CommandParameterSchema parameter in command.Parameters) { Write(' '); Write(parameter.Bindable.IsScalar ? $"<{parameter.Name}>" : $"<{parameter.Name}...>"); } // Required options foreach (CommandOptionSchema option in command.Options.Where(o => o.IsRequired)) { Write(' '); Write(ParametersColor, !string.IsNullOrWhiteSpace(option.Name) ? $"--{option.Name}" : $"-{option.ShortName}"); Write(' '); Write(option.Bindable.IsScalar ? "<value>" : "<values...>"); } // Options placeholder Write(' '); Write(OptionsPlaceholderColor, "[options]"); WriteLine(); }
private static void ValidateOptions(CommandSchema command) { IEnumerable <CommandOptionSchema> noNameGroup = command.Options .Where(o => o.ShortName == null && string.IsNullOrWhiteSpace(o.Name)); if (noNameGroup.Any()) { throw InternalTypinExceptions.OptionsWithNoName( command, noNameGroup.ToArray() ); } IEnumerable <CommandOptionSchema> digitStartingGroup = command.Options .Where(o => char.IsDigit(o.ShortName ?? 'a') || char.IsDigit(o.Name?.FirstOrDefault() ?? 'a')); if (digitStartingGroup.Any()) { throw InternalTypinExceptions.OptionsWithDigitStartingName( command, digitStartingGroup.ToArray() ); } CommandOptionSchema[] invalidLengthNameGroup = command.Options .Where(o => !string.IsNullOrWhiteSpace(o.Name)) .Where(o => o.Name !.Length <= 1) .ToArray(); if (invalidLengthNameGroup.Any()) { throw InternalTypinExceptions.OptionsWithInvalidLengthName( command, invalidLengthNameGroup ); } IGrouping <string, CommandOptionSchema>?duplicateNameGroup = command.Options .Where(o => !string.IsNullOrWhiteSpace(o.Name)) .GroupBy(o => o.Name !, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(g => g.Count() > 1); if (duplicateNameGroup != null) { throw InternalTypinExceptions.OptionsWithSameName( command, duplicateNameGroup.Key, duplicateNameGroup.ToArray() ); } IGrouping <char, CommandOptionSchema>?duplicateShortNameGroup = command.Options .Where(o => o.ShortName != null) .GroupBy(o => o.ShortName !.Value) .FirstOrDefault(g => g.Count() > 1); if (duplicateShortNameGroup != null) { throw InternalTypinExceptions.OptionsWithSameShortName( command, duplicateShortNameGroup.Key, duplicateShortNameGroup.ToArray() ); } IGrouping <string, CommandOptionSchema>?duplicateEnvironmentVariableNameGroup = command.Options .Where(o => !string.IsNullOrWhiteSpace(o.FallbackVariableName)) .GroupBy(o => o.FallbackVariableName !, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(g => g.Count() > 1); if (duplicateEnvironmentVariableNameGroup != null) { throw InternalTypinExceptions.OptionsWithSameEnvironmentVariableName( command, duplicateEnvironmentVariableNameGroup.Key, duplicateEnvironmentVariableNameGroup.ToArray() ); } }
public CommandResultSchema[] GetCommandResultSchemas(string connectionString, CommandSchema command) { throw new NotSupportedException("GetCommandResultSchemas() is not supported in this release."); }
public void Bind(CommandInput commandInput, CommandSchema commandSchema, ICommand commandInstance) { BindParameters(commandInput, commandSchema, commandInstance); BindOptions(commandInput, commandSchema, commandInstance); }
public string GetCommandText(string connectionString, CommandSchema command) { // NetTiers shouldn't be using this, so unimplemented right now return ""; }
private void LoadProperties(CommandSchema command, int resultSetIndex, StringCollection uniqueColumns, StringCollection filterColumns) { foreach (CommandResultColumnSchema col in command.CommandResults[resultSetIndex].Columns) { bool isUniqueMember = false; bool isFilterMember = false; if (resultSetIndex == 0 && !IsChild && CslaObjectType != ObjectType.NameValueList) { bool isParameterMember = command.InputParameters.Contains("@" + col.Name); isUniqueMember = isParameterMember && !IsCollection; isFilterMember = isParameterMember && IsCollection; } else { isUniqueMember = uniqueColumns.ToString().ToLower().IndexOf(col.Name.ToLower()) >= 0; isFilterMember = filterColumns.ToString().ToLower().IndexOf(col.Name.ToLower()) >= 0; } PropertyInfo prop = new PropertyInfo(col, this, isUniqueMember, isFilterMember); _properties.Add(prop); if (prop.IsPrimaryKey) _uniqueProperties.Add(prop); if (prop.IsFilterKey) _filterProperties.Add(prop); } }
public ParameterSchema[] GetCommandParameters(string connectionString, CommandSchema command) { throw new NotSupportedException("GetCommandParameters() is not supported in this release."); }
/// <inheritdoc /> public ICommand CreateCommand(CommandSchema commandSchema) => (ICommand)Activator.CreateInstance(commandSchema.Type);
public string GetCommandText(string connectionString, CommandSchema command) { throw new Exception("The method or operation is not implemented."); }
private void CreateFunction(CommandSchema commandSchema) { Function function; string key = commandSchema.FullName; bool isNew = !Database.Functions.Contains(key); if (isNew) { function = new Function(key); Database.Functions.Add(function); } else { function = Database.Functions[key]; } //Function/@Method is safe to update if (string.IsNullOrEmpty(function.Method)) { string methodName = ToLegalName(commandSchema.Name); if (ClassNames.Contains(methodName)) { methodName += "Procedure"; } function.Method = MakeUnique(FunctionNames, methodName); } function.IsComposable = IsFunction(commandSchema); ParameterSchema returnParameter = null; function.Parameters.Clear(); foreach (ParameterSchema p in commandSchema.Parameters) { if (p.Direction == System.Data.ParameterDirection.ReturnValue) { returnParameter = p; } else { CreateParameter(function, p); } } try { for (int i = 0; i < commandSchema.CommandResults.Count; i++) { var r = commandSchema.CommandResults[i]; string defaultName = function.Method + "Result"; if (commandSchema.CommandResults.Count > 1) { defaultName += (i + 1).ToString(); } CreateResult(function, r, defaultName, i); } } catch (Exception ex) { Debug.WriteLine("Error reading result schema: " + ex.Message); } function.HasMultipleResults = function.Types.Count > 1; function.IsProcessed = true; if (function.Types.Count != 0) { return; } if (function.Return == null) { function.Return = new Return("System.Int32"); } if (commandSchema.ReturnValueParameter != null) { function.Return.Type = GetSystemType(commandSchema.ReturnValueParameter); function.Return.DbType = GetDbType(commandSchema.ReturnValueParameter); } else if (returnParameter != null) { function.Return.Type = GetSystemType(returnParameter); function.Return.DbType = GetDbType(returnParameter); } else { function.Return.Type = "System.Int32"; function.Return.DbType = "int"; } }
public CommandResultSchema[] GetCommandResultSchemas(string connectionString, CommandSchema command) { throw new Exception("The method or operation is not implemented."); }
public CommandResultSchema[] GetCommandResultSchemas(string connectionString, CommandSchema command) { // NetTiers shouldn't be using this, so unimplemented right now return new CommandResultSchema[0]; }
/// <summary> /// Does the command have a resultset? /// </summary> /// <param name="cmd">Command in question</param> /// <returns>Resultset?</returns> public bool HasResultset(CommandSchema cmd) { return cmd.CommandResults.Count > 0; }
/// <inheritdoc /> public ICommand CreateCommand(CommandSchema commandSchema) { commandSchema.GuardNotNull(nameof(commandSchema)); return(_factoryMethod(commandSchema)); }
private void WriteCommandOptions(CommandSchema command, IReadOnlyDictionary <ArgumentSchema, object?> argumentDefaultValues) { if (!IsEmpty) { WriteVerticalMargin(); } WriteHeader("Options"); foreach (CommandOptionSchema option in command.Options.OrderByDescending(o => o.IsRequired)) { if (option.IsRequired) { Write(RequiredColor, "* "); } else { WriteHorizontalMargin(); } // Short name if (option.ShortName is not null) { Write(OptionNameColor, $"-{option.ShortName}"); } // Separator if (!string.IsNullOrWhiteSpace(option.Name) && option.ShortName is not null) { Write('|'); } // Name if (!string.IsNullOrWhiteSpace(option.Name)) { Write(OptionNameColor, $"--{option.Name}"); } WriteColumnMargin(); // Description if (!string.IsNullOrWhiteSpace(option.Description)) { Write(option.Description); Write(' '); } // Valid values var validValues = option.Bindable.GetValidValues(); if (validValues.Count > 0) { WriteValidValues(option.Bindable.IsScalar, validValues); } // Environment variable if (!string.IsNullOrWhiteSpace(option.FallbackVariableName)) { Write($"Fallback variable: \"{option.FallbackVariableName}\"."); Write(' '); } // Default value if (!option.IsRequired) { object?defaultValue = argumentDefaultValues.GetValueOrDefault(option); string?defaultValueFormatted = FormatDefaultValue(defaultValue); if (defaultValueFormatted is not null) { Write("(Default: "); Write(defaultValueFormatted); Write(')'); } } WriteLine(); } }
public CommandResultSchema[] GetCommandResultSchemas(string connectionString, CommandSchema command) { throw new NotSupportedException("GetCommandResultSchemas() is not supported in this release."); }
private void WriteCommandChildren(CommandSchema command, IEnumerable <CommandSchema> childCommands) { if (!childCommands.Any()) { return; } if (!IsEmpty) { WriteVerticalMargin(); } WriteHeader("Commands"); foreach (CommandSchema childCommand in childCommands) { string relativeCommandName = !string.IsNullOrWhiteSpace(command.Name) ? childCommand.Name !.Substring(command.Name.Length).Trim() : childCommand.Name !; // Name if (childCommand.HasModeRestrictions()) { Write(ModeRestrictedColor, "@"); WriteHorizontalMargin(1); } else { WriteHorizontalMargin(); } Write(CommandNameColor, relativeCommandName); // Description if (!string.IsNullOrWhiteSpace(childCommand.Description)) { WriteColumnMargin(); Write(childCommand.Description); } WriteLine(); } // Child command help tip WriteVerticalMargin(); Write(CommentColor, "TIP: You can run `"); bool isDirectMode = _applicationLifetime.CurrentMode is DirectMode; if (isDirectMode) { Write(_context.Metadata.ExecutableName); } if (!string.IsNullOrWhiteSpace(command.Name)) { if (isDirectMode) { Write(' '); } Write(ConsoleColor.Cyan, command.Name); } if (isDirectMode) { Write(' '); } Write(ConsoleColor.Cyan, "[command]"); Write(' '); Write(ConsoleColor.White, "--help"); Write(CommentColor, "` to show help on a specific command."); WriteLine(); }
public ParameterSchema[] GetCommandParameters(string connectionString, CommandSchema command) { throw new Exception("The method or operation is not implemented."); }
/// <inheritdoc /> public ICommand CreateCommand(CommandSchema commandSchema) => _factoryMethod(commandSchema);
private ICommand GetCommandInstance(CommandSchema command) => command != StubDefaultCommand.Schema ? (ICommand)_typeActivator.CreateInstance(command.Type) : new StubDefaultCommand();
/// <summary> /// Indicates if the output rowset of the command is compliant with the table rowset. /// </summary> /// <param name="command">The stored procedure</param> /// <param name="table">The table</param> public bool IsMatching(CommandSchema command, TableSchema table) { if (command.CommandResults.Count != 1) { return false; } if (command.CommandResults[0].Columns.Count != table.Columns.Count) { return false; } for(int i=0; i<table.Columns.Count; i++) // CommandResultSchema cmdResult in command.CommandResults) { if (command.CommandResults[0].Columns[i].Name != table.Columns[i].Name) { return false; } if (command.CommandResults[0].Columns[i].NativeType != table.Columns[i].NativeType) { return false; } } return true; }