protected virtual void GenerateEntityTypes( IReadOnlyList<IEntityType> entityTypes, IndentedStringBuilder stringBuilder) { Check.NotNull(entityTypes, nameof(entityTypes)); Check.NotNull(stringBuilder, nameof(stringBuilder)); foreach (var entityType in entityTypes) { stringBuilder.AppendLine(); GenerateEntityType(entityType, stringBuilder, GenerateEntityTypeOptions.Declared); } foreach (var entityType in entityTypes.Where(e => e.BaseType != null)) { stringBuilder.AppendLine(); GenerateEntityType(entityType, stringBuilder, GenerateEntityTypeOptions.BaseType); } foreach (var entityType in entityTypes.Where(e => e.GetForeignKeys().Any())) { stringBuilder.AppendLine(); GenerateEntityType(entityType, stringBuilder, GenerateEntityTypeOptions.Relationships); } }
public virtual string WriteCode( [NotNull] EntityConfiguration entityConfiguration) { Check.NotNull(entityConfiguration, nameof(entityConfiguration)); _entity = entityConfiguration; _sb = new IndentedStringBuilder(); _sb.AppendLine("using System;"); _sb.AppendLine("using System.Collections.Generic;"); if (!_entity.ModelConfiguration.CustomConfiguration.UseFluentApiOnly) { _sb.AppendLine("using System.ComponentModel.DataAnnotations;"); _sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;"); } _sb.AppendLine(); _sb.AppendLine("namespace " + _entity.ModelConfiguration.Namespace()); _sb.AppendLine("{"); using (_sb.Indent()) { AddClass(); } _sb.AppendLine("}"); return _sb.ToString(); }
/// <summary> /// 重新排序。 /// </summary> /// <param name="command">当前命令。</param> /// <param name="builder">SQL语句构建实例。</param> protected virtual void Generate(RestartSequenceCommand command, IndentedStringBuilder builder) { Check.NotNull(command, nameof(command)); Check.NotNull(builder, nameof(builder)); builder .Append("ALTER SEQUENCE ") .Append(Sql.DelimitIdentifier(Prefix(command.Name), command.Schema)) .Append(" RESTART WITH ") .Append(Sql.GenerateLiteral(command.StartValue)); }
public void Append_line_at_start_with_indent() { var indentedStringBuilder = new IndentedStringBuilder(); using (indentedStringBuilder.Indent()) { indentedStringBuilder.AppendLine("Foo"); } Assert.Equal(" Foo" + _nl, indentedStringBuilder.ToString()); }
public void Append_line_in_middle_when_no_new_line() { var indentedStringBuilder = new IndentedStringBuilder(); indentedStringBuilder.AppendLine("Foo"); using (indentedStringBuilder.Indent()) { indentedStringBuilder.AppendLine("Foo"); } Assert.Equal($"Foo{_nl} Foo{_nl}", indentedStringBuilder.ToString()); }
public override string Generate( string migrationNamespace, string migrationName, IReadOnlyList<MigrationOperation> upOperations, IReadOnlyList<MigrationOperation> downOperations) { Check.NotEmpty(migrationNamespace, nameof(migrationNamespace)); Check.NotEmpty(migrationName, nameof(migrationName)); Check.NotNull(upOperations, nameof(upOperations)); Check.NotNull(downOperations, nameof(downOperations)); var builder = new IndentedStringBuilder(); builder .AppendLine("using System.Collections.Generic;") .AppendLine("using Microsoft.Data.Entity.Migrations;") .AppendLine("using Microsoft.Data.Entity.Migrations.Builders;") .AppendLine("using Microsoft.Data.Entity.Migrations.Operations;") .AppendLine() .Append("namespace ").AppendLine(_code.Identifier(migrationNamespace)) .AppendLine("{"); using (builder.Indent()) { builder .Append("public partial class ").Append(_code.Identifier(migrationName)).AppendLine(" : Migration") .AppendLine("{"); using (builder.Indent()) { builder .AppendLine("public override void Up(MigrationBuilder migration)") .AppendLine("{"); using (builder.Indent()) { _operationGenerator.Generate("migration", upOperations, builder); } builder .AppendLine("}") .AppendLine() .AppendLine("public override void Down(MigrationBuilder migration)") .AppendLine("{"); using (builder.Indent()) { _operationGenerator.Generate("migration", downOperations, builder); } builder.AppendLine("}"); } builder.AppendLine("}"); } builder.AppendLine("}"); return builder.ToString(); }
/// <summary> /// 修改索引名称。 /// </summary> /// <param name="command">当前命令。</param> /// <param name="builder">SQL语句构建实例。</param> protected override void Generate( RenameIndexCommand command, IndentedStringBuilder builder) { Check.NotNull(command, nameof(command)); Check.NotNull(builder, nameof(builder)); var qualifiedName = new StringBuilder(); if (command.Schema != null) { qualifiedName .Append(command.Schema) .Append("."); } qualifiedName .Append(Prefix(command.Table)) .Append(".") .Append(Prefix(command.Name)); Rename(qualifiedName.ToString(), Prefix(command.NewName), "INDEX", builder); }
public virtual string WriteCode( [NotNull] ModelConfiguration modelConfiguration) { Check.NotNull(modelConfiguration, nameof(modelConfiguration)); _model = modelConfiguration; _sb = new IndentedStringBuilder(); _sb.AppendLine("using Microsoft.Data.Entity;"); _sb.AppendLine("using Microsoft.Data.Entity.Metadata;"); _sb.AppendLine(); _sb.AppendLine("namespace " + _model.Namespace()); _sb.AppendLine("{"); using (_sb.Indent()) { AddClass(); } _sb.Append("}"); return _sb.ToString(); }
/// <summary> /// 修改列。 /// </summary> /// <param name="command">当前命令。</param> /// <param name="builder">SQL语句构建实例。</param> protected override void Generate( AlterColumnCommand command, IndentedStringBuilder builder) { Check.NotNull(command, nameof(command)); Check.NotNull(builder, nameof(builder)); DropDefaultConstraint(command.Schema, command.Table, command.Name, builder); builder .Append("ALTER TABLE ") .Append(Sql.DelimitIdentifier(Prefix(command.Table), command.Schema)) .Append(" ALTER COLUMN "); ColumnDefinition( command.Schema, command.Table, command.Name, command.ClrType, command.ColumnType, command.IsNullable, /*identity:*/ false, /*defaultValue:*/ null, /*defaultValueSql:*/ null, command.ComputedColumnSql, command, builder); if (command.DefaultValue != null || command.DefaultValueSql != null) { builder .AppendLine(";") .Append("ALTER TABLE ") .Append(Sql.DelimitIdentifier(Prefix(command.Table), command.Schema)) .Append(" ADD"); DefaultValue(command.DefaultValue, command.DefaultValueSql, builder); builder .Append(" FOR ") .Append(Sql.DelimitIdentifier(command.Name)); } }
public virtual string Create(bool ifNotExists) { var builder = new IndentedStringBuilder(); builder.Append("CREATE TABLE "); if (ifNotExists) { builder.Append("IF NOT EXISTS "); } builder.Append(_sql.DelimitIdentifier(MigrationTableName)) .AppendLine(" ("); using (builder.Indent()) { builder .AppendLine("MigrationId TEXT PRIMARY KEY,") .AppendLine("ContextKey TEXT NOT NULL,") .AppendLine("ProductVersion TEXT NOT NULL"); } builder.Append(");"); return builder.ToString(); }
/// <summary> /// 外键约束操作。 /// </summary> /// <param name="referentialAction">操作枚举。</param> /// <param name="builder">SQL构建实例。</param> protected override void ForeignKeyAction(ReferentialAction referentialAction, IndentedStringBuilder builder) { Check.NotNull(builder, nameof(builder)); if (referentialAction == ReferentialAction.Restrict) { builder.Append("NO ACTION"); } else { base.ForeignKeyAction(referentialAction, builder); } }
private async Task <SearchResult> SearchImpl(SearchOptions searchOptions, bool historySearch, CancellationToken cancellationToken) { Expression searchExpression = searchOptions.Expression; // AND in the continuation token if (!string.IsNullOrWhiteSpace(searchOptions.ContinuationToken) && !searchOptions.CountOnly) { var continuationToken = ContinuationToken.FromString(searchOptions.ContinuationToken); if (continuationToken != null) { // in case it's a _lastUpdated sort optimization if (string.IsNullOrEmpty(continuationToken.SortValue)) { (SearchParameterInfo searchParamInfo, SortOrder sortOrder) = searchOptions.Sort.Count == 0 ? default : searchOptions.Sort[0]; Expression lastUpdatedExpression = sortOrder == SortOrder.Ascending ? Expression.GreaterThan(SqlFieldName.ResourceSurrogateId, null, continuationToken.ResourceSurrogateId) : Expression.LessThan(SqlFieldName.ResourceSurrogateId, null, continuationToken.ResourceSurrogateId); var tokenExpression = Expression.SearchParameter(SqlSearchParameters.ResourceSurrogateIdParameter, lastUpdatedExpression); searchExpression = searchExpression == null ? tokenExpression : (Expression)Expression.And(tokenExpression, searchExpression); } } else { throw new BadRequestException(Resources.InvalidContinuationToken); } } if (searchOptions.CountOnly) { // if we're only returning a count, discard any _include parameters since included resources are not counted. searchExpression = searchExpression?.AcceptVisitor(RemoveIncludesRewriter.Instance); } SqlRootExpression expression = (SqlRootExpression)searchExpression ?.AcceptVisitor(LastUpdatedToResourceSurrogateIdRewriter.Instance) .AcceptVisitor(DateTimeEqualityRewriter.Instance) .AcceptVisitor(FlatteningRewriter.Instance) .AcceptVisitor(UntypedReferenceRewriter.Instance) .AcceptVisitor(_sqlRootExpressionRewriter) .AcceptVisitor(_sortRewriter, searchOptions) .AcceptVisitor(DenormalizedPredicateRewriter.Instance) .AcceptVisitor(NormalizedPredicateReorderer.Instance) .AcceptVisitor(_chainFlatteningRewriter) .AcceptVisitor(DateTimeBoundedRangeRewriter.Instance) .AcceptVisitor(StringOverflowRewriter.Instance) .AcceptVisitor(NumericRangeRewriter.Instance) .AcceptVisitor(MissingSearchParamVisitor.Instance) .AcceptVisitor(NotExpressionRewriter.Instance) .AcceptVisitor(IncludeDenormalizedRewriter.Instance) .AcceptVisitor(TopRewriter.Instance, searchOptions) .AcceptVisitor(IncludeRewriter.Instance) ?? SqlRootExpression.WithDenormalizedExpressions(); using (SqlConnectionWrapper sqlConnectionWrapper = await _sqlConnectionWrapperFactory.ObtainSqlConnectionWrapperAsync(cancellationToken, true)) using (SqlCommandWrapper sqlCommandWrapper = sqlConnectionWrapper.CreateSqlCommand()) { var stringBuilder = new IndentedStringBuilder(new StringBuilder()); EnableTimeAndIoMessageLogging(stringBuilder, sqlConnectionWrapper); var queryGenerator = new SqlQueryGenerator(stringBuilder, new SqlQueryParameterManager(sqlCommandWrapper.Parameters), _model, historySearch, _schemaInformation); expression.AcceptVisitor(queryGenerator, searchOptions); sqlCommandWrapper.CommandText = stringBuilder.ToString(); LogSqlCommand(sqlCommandWrapper); using (var reader = await sqlCommandWrapper.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken)) { if (searchOptions.CountOnly) { await reader.ReadAsync(cancellationToken); var searchResult = new SearchResult(reader.GetInt32(0), searchOptions.UnsupportedSearchParams); // call NextResultAsync to get the info messages await reader.NextResultAsync(cancellationToken); return(searchResult); } var resources = new List <SearchResultEntry>(searchOptions.MaxItemCount); long?newContinuationId = null; bool moreResults = false; int matchCount = 0; // Currently we support only date time sort type. DateTime?sortValue = null; var isResultPartial = false; while (await reader.ReadAsync(cancellationToken)) { (short resourceTypeId, string resourceId, int version, bool isDeleted, long resourceSurrogateId, string requestMethod, bool isMatch, bool isPartialEntry, bool isRawResourceMetaSet, Stream rawResourceStream) = reader.ReadRow( VLatest.Resource.ResourceTypeId, VLatest.Resource.ResourceId, VLatest.Resource.Version, VLatest.Resource.IsDeleted, VLatest.Resource.ResourceSurrogateId, VLatest.Resource.RequestMethod, _isMatch, _isPartial, VLatest.Resource.IsRawResourceMetaSet, VLatest.Resource.RawResource); // If we get to this point, we know there are more results so we need a continuation token // Additionally, this resource shouldn't be included in the results if (matchCount >= searchOptions.MaxItemCount && isMatch) { moreResults = true; // At this point we are at the last row. // if we have more columns, it means sort expressions were added. if (reader.FieldCount > 10) { sortValue = reader.GetValue(SortValueColumnName) as DateTime?; } continue; } // See if this resource is a continuation token candidate and increase the count if (isMatch) { newContinuationId = resourceSurrogateId; matchCount++; } string rawResource; using (rawResourceStream) { rawResource = await CompressedRawResourceConverter.ReadCompressedRawResource(rawResourceStream); } // as long as at least one entry was marked as partial, this resultset // should be marked as partial isResultPartial = isResultPartial || isPartialEntry; resources.Add(new SearchResultEntry( new ResourceWrapper( resourceId, version.ToString(CultureInfo.InvariantCulture), _model.GetResourceTypeName(resourceTypeId), new RawResource(rawResource, FhirResourceFormat.Json, isMetaSet: isRawResourceMetaSet), new ResourceRequest(requestMethod), new DateTimeOffset(ResourceSurrogateIdHelper.ResourceSurrogateIdToLastUpdated(resourceSurrogateId), TimeSpan.Zero), isDeleted, null, null, null), isMatch ? SearchEntryMode.Match : SearchEntryMode.Include)); } // call NextResultAsync to get the info messages await reader.NextResultAsync(cancellationToken); // Continuation token prep ContinuationToken continuationToken = null; if (moreResults) { if (sortValue.HasValue) { continuationToken = new ContinuationToken(new object[] { sortValue.Value.ToString("o"), newContinuationId ?? 0, }); } else { continuationToken = new ContinuationToken(new object[] { newContinuationId ?? 0, }); } } if (isResultPartial) { _requestContextAccessor.FhirRequestContext.BundleIssues.Add( new OperationOutcomeIssue( OperationOutcomeConstants.IssueSeverity.Warning, OperationOutcomeConstants.IssueType.Incomplete, Core.Resources.TruncatedIncludeMessage)); } return(new SearchResult(resources, continuationToken?.ToJson(), searchOptions.Sort, searchOptions.UnsupportedSearchParams)); } } }
protected virtual void GenerateForeignKeyAnnotations([NotNull] IForeignKey foreignKey, [NotNull] IndentedStringBuilder stringBuilder) { Check.NotNull(foreignKey, nameof(foreignKey)); Check.NotNull(stringBuilder, nameof(stringBuilder)); var annotations = foreignKey.GetAnnotations().ToList(); GenerateFluentApiForAnnotation(ref annotations, RelationalFullAnnotationNames.Instance.Name, foreignKey.IsUnique ? nameof(RelationalReferenceReferenceBuilderExtensions.HasConstraintName) : nameof(RelationalReferenceCollectionBuilderExtensions.HasConstraintName), stringBuilder); GenerateAnnotations(annotations, stringBuilder); }
/// <summary> /// Constructs blueprint of the given <paramref name="sequence"/>. /// </summary> /// <param name="sequence">SequenceType for which mapper being generated.</param> /// <returns>Mapper for the <paramref name="sequence"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// The below example shows possible mapper string for SequenceType. /// type: { /// name: 'Sequence', /// element: { /// *** -- mapper of the IType from the sequence element /// } /// } /// </example> private static string ContructMapperForSequenceType(this SequenceType sequence) { if (sequence == null) { throw new ArgumentNullException(nameof(sequence)); } IndentedStringBuilder builder = new IndentedStringBuilder(" "); builder.AppendLine("type: {").Indent() .AppendLine("name: 'Sequence',") .AppendLine("element: {").Indent() .AppendLine("{0}", sequence.ElementType.ConstructMapper(sequence.ElementType.Name + "ElementType", null, false)).Outdent() .AppendLine("}").Outdent() .AppendLine("}"); return builder.ToString(); }
public abstract void GenerateEntityNavigations([NotNull] IndentedStringBuilder sb);
public override string GenerateSnapshot( string modelSnapshotNamespace, Type contextType, string modelSnapshotName, IModel model) { Check.NotEmpty(modelSnapshotNamespace, nameof(modelSnapshotNamespace)); Check.NotNull(contextType, nameof(contextType)); Check.NotEmpty(modelSnapshotName, nameof(modelSnapshotName)); Check.NotNull(model, nameof(model)); var builder = new IndentedStringBuilder(); var namespaces = new List<string> { "System", "Microsoft.Data.Entity", "Microsoft.Data.Entity.Infrastructure", "Microsoft.Data.Entity.Metadata", "Microsoft.Data.Entity.Migrations", contextType.Namespace }; namespaces.AddRange(GetNamespaces(model)); foreach (var n in namespaces.Distinct()) { builder .Append("using ") .Append(n) .AppendLine(";"); } builder .AppendLine() .Append("namespace ").AppendLine(_code.Namespace(modelSnapshotNamespace)) .AppendLine("{"); using (builder.Indent()) { builder .Append("[DbContext(typeof(").Append(_code.Reference(contextType)).AppendLine("))]") .Append("partial class ").Append(_code.Identifier(modelSnapshotName)).AppendLine(" : ModelSnapshot") .AppendLine("{"); using (builder.Indent()) { builder .AppendLine("protected override void BuildModel(ModelBuilder modelBuilder)") .AppendLine("{"); using (builder.Indent()) { _modelGenerator.Generate("modelBuilder", model, builder); } builder.AppendLine("}"); } builder.AppendLine("}"); } builder.AppendLine("}"); return builder.ToString(); }
public override void GenerateSql([NotNull] MigrationOperationSqlGenerator generator, [NotNull] IndentedStringBuilder stringBuilder, bool generateIdempotentSql) { Check.NotNull(generator, "generator"); Check.NotNull(stringBuilder, "stringBuilder"); generator.Generate(this, stringBuilder, generateIdempotentSql); }
public void Execute(SourceGeneratorContext context) { // Search for the GeneratedPropertyAttribute symbol var _generatedPropertyAttributeSymbol = context.Compilation.GetTypeByMetadataName("Fonderie.GeneratedPropertyAttribute"); if (_generatedPropertyAttributeSymbol != null) { // Search in all types defined in the current compilation (not in the dependents) var query = from typeSymbol in context.Compilation.SourceModule.GlobalNamespace.GetNamespaceTypes() from property in typeSymbol.GetFields() // Find the attribute on the field let info = property.FindAttributeFlattened(_generatedPropertyAttributeSymbol) where info != null // Group properties by type group property by typeSymbol into g select g; foreach (var type in query) { // Let's generate the needed class var builder = new IndentedStringBuilder(); builder.AppendLineInvariant("using System;"); builder.AppendLineInvariant("using System.ComponentModel;"); using (builder.BlockInvariant($"namespace {type.Key.ContainingNamespace}")) { using (builder.BlockInvariant($"partial class {type.Key.Name} : INotifyPropertyChanged")) { builder.AppendLineInvariant($"public event PropertyChangedEventHandler PropertyChanged;"); foreach (var fieldInfo in type) { var propertyName = fieldInfo.Name.TrimStart('_'); // Uppercase name for camel case propertyName = propertyName[0].ToString().ToUpperInvariant() + propertyName.Substring(1); using (builder.BlockInvariant($"public {fieldInfo.Type} {propertyName}")) { builder.AppendLineInvariant($"get => {fieldInfo.Name};"); using (builder.BlockInvariant($"set")) { builder.AppendLineInvariant($"var previous = {fieldInfo.Name};"); builder.AppendLineInvariant($"{fieldInfo.Name} = value;"); builder.AppendLineInvariant($"PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof({propertyName})));"); builder.AppendLineInvariant($"On{propertyName}Changed(previous, value);"); } } builder.AppendLineInvariant($"partial void On{propertyName}Changed({fieldInfo.Type} previous, {fieldInfo.Type} value);"); } } } var sanitizedName = type.Key.ToDisplayString().Replace(".", "_").Replace("+", "_"); context.AddSource(sanitizedName, SourceText.From(builder.ToString(), Encoding.UTF8)); } } }
/// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public abstract bool TryPrintConstant( [NotNull] ConstantExpression constantExpression, [NotNull] IndentedStringBuilder stringBuilder, bool removeFormatting);
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual string GenerateScript( string fromMigration = null, string toMigration = null, MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) { options |= MigrationsSqlGenerationOptions.Script; var idempotent = options.HasFlag(MigrationsSqlGenerationOptions.Idempotent); var noTransactions = options.HasFlag(MigrationsSqlGenerationOptions.NoTransactions); IEnumerable <string> appliedMigrations; if (string.IsNullOrEmpty(fromMigration) || fromMigration == Migration.InitialDatabase) { appliedMigrations = Enumerable.Empty <string>(); } else { var fromMigrationId = _migrationsAssembly.GetMigrationId(fromMigration); appliedMigrations = _migrationsAssembly.Migrations .Where(t => string.Compare(t.Key, fromMigrationId, StringComparison.OrdinalIgnoreCase) <= 0) .Select(t => t.Key); } PopulateMigrations( appliedMigrations, toMigration, out var migrationsToApply, out var migrationsToRevert, out var actualTargetMigration); var builder = new IndentedStringBuilder(); if (fromMigration == Migration.InitialDatabase || string.IsNullOrEmpty(fromMigration)) { builder .Append(_historyRepository.GetCreateIfNotExistsScript()) .Append(_sqlGenerationHelper.BatchTerminator); } var transactionStarted = false; for (var i = 0; i < migrationsToRevert.Count; i++) { var migration = migrationsToRevert[i]; var previousMigration = i != migrationsToRevert.Count - 1 ? migrationsToRevert[i + 1] : actualTargetMigration; _logger.MigrationGeneratingDownScript(this, migration, fromMigration, toMigration, idempotent); foreach (var command in GenerateDownSql(migration, previousMigration, options)) { if (!noTransactions) { if (!transactionStarted && !command.TransactionSuppressed) { builder .AppendLine(_sqlGenerationHelper.StartTransaction) .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = true; } if (transactionStarted && command.TransactionSuppressed) { builder .AppendLine(_sqlGenerationHelper.Commit) .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = false; } } if (idempotent) { builder.AppendLine(_historyRepository.GetBeginIfExistsScript(migration.GetId())); using (builder.Indent()) { builder.AppendLines(command.CommandText); } builder.Append(_historyRepository.GetEndIfScript()); } else { builder.Append(command.CommandText); } builder.Append(_sqlGenerationHelper.BatchTerminator); } if (!noTransactions && transactionStarted) { builder .AppendLine(_sqlGenerationHelper.Commit) .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = false; } } foreach (var migration in migrationsToApply) { _logger.MigrationGeneratingUpScript(this, migration, fromMigration, toMigration, idempotent); foreach (var command in GenerateUpSql(migration, options)) { if (!noTransactions) { if (!transactionStarted && !command.TransactionSuppressed) { builder .AppendLine(_sqlGenerationHelper.StartTransaction) .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = true; } if (transactionStarted && command.TransactionSuppressed) { builder .AppendLine(_sqlGenerationHelper.Commit) .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = false; } } if (idempotent) { builder.AppendLine(_historyRepository.GetBeginIfNotExistsScript(migration.GetId())); using (builder.Indent()) { builder.AppendLines(command.CommandText); } builder.Append(_historyRepository.GetEndIfScript()); } else { builder.Append(command.CommandText); } builder.Append(_sqlGenerationHelper.BatchTerminator); } if (!noTransactions && transactionStarted) { builder .AppendLine(_sqlGenerationHelper.Commit) .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = false; } } return(builder.ToString()); }
public static string ConstructPropertyDocumentation(string propertyDocumentation) { var builder = new IndentedStringBuilder(" "); return(builder.AppendLine(propertyDocumentation).ToString()); }
public override void Write(IndentedStringBuilder builder) { builder.Append($" {TCLEscaping.Default.Escape(_value)}"); }
/// <summary> /// Generates Ruby code in form of string for deserializing object of given type. /// </summary> /// <param name="type">Type of object needs to be deserialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to be deserialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureDeserializeType( this IType type, IScopeProvider scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long) { return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.Double) { return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.Date) { return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.DateTime) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.UnixTime) { return builder.AppendLine("{0} = DateTime.strptime({0}.to_s, '%s') unless {0}.to_s.empty?", valueReference).ToString(); } } else if (enumType != null && !string.IsNullOrEmpty(enumType.Name)) { return builder .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference) .AppendLine( " enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}", enumType.Name, valueReference) .AppendLine( " warn 'Enum {0} does not contain ' + {1}.downcase + ', but was received from the server.' unless enum_is_valid", enumType.Name, valueReference) .AppendLine("end") .ToString(); } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureDeserializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("deserialized_{0} = []", sequence.Name.ToLower()) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized_{0}.push({1})", sequence.Name.ToLower(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = deserialized_{1}", valueReference, sequence.Name.ToLower()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureDeserializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("end") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { var compositeName = composite.Name; if(compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
public override void GenerateCode([NotNull] MigrationCodeGenerator generator, [NotNull] IndentedStringBuilder stringBuilder) { Check.NotNull(generator, "generator"); Check.NotNull(stringBuilder, "stringBuilder"); generator.Generate(this, stringBuilder); }
public override string GenerateMetadata( string migrationNamespace, Type contextType, string migrationName, string migrationId, IModel targetModel) { Check.NotEmpty(migrationNamespace, nameof(migrationNamespace)); Check.NotNull(contextType, nameof(contextType)); Check.NotEmpty(migrationName, nameof(migrationName)); Check.NotEmpty(migrationId, nameof(migrationId)); Check.NotNull(targetModel, nameof(targetModel)); var builder = new IndentedStringBuilder(); var namespaces = new List<string> { "System", "Microsoft.Data.Entity", "Microsoft.Data.Entity.Infrastructure", "Microsoft.Data.Entity.Metadata", "Microsoft.Data.Entity.Migrations", contextType.Namespace }; namespaces.AddRange(GetNamespaces(targetModel)); foreach (var n in namespaces.Distinct()) { builder .Append("using ") .Append(n) .AppendLine(";"); } builder .AppendLine() .Append("namespace ").AppendLine(_code.Namespace(migrationNamespace)) .AppendLine("{"); using (builder.Indent()) { builder .Append("[DbContext(typeof(").Append(_code.Reference(contextType)).AppendLine("))]") .Append("[Migration(").Append(_code.Literal(migrationId)).AppendLine(")]") .Append("partial class ").AppendLine(_code.Identifier(migrationName)) .AppendLine("{"); using (builder.Indent()) { builder .AppendLine("protected override void BuildTargetModel(ModelBuilder modelBuilder)") .AppendLine("{"); using (builder.Indent()) { // TODO: Optimize. This is repeated below _modelGenerator.Generate("modelBuilder", targetModel, builder); } builder.AppendLine("}"); } builder.AppendLine("}"); } builder.AppendLine("}"); return builder.ToString(); }
private async Task <SearchResult> SearchImpl(SearchOptions searchOptions, SqlSearchType searchType, string currentSearchParameterHash, CancellationToken cancellationToken) { Expression searchExpression = searchOptions.Expression; // AND in the continuation token if (!string.IsNullOrWhiteSpace(searchOptions.ContinuationToken) && !searchOptions.CountOnly) { var continuationToken = ContinuationToken.FromString(searchOptions.ContinuationToken); if (continuationToken != null) { if (string.IsNullOrEmpty(continuationToken.SortValue)) { // it's a _lastUpdated or (_type,_lastUpdated) sort optimization (SearchParameterInfo _, SortOrder sortOrder) = searchOptions.Sort.Count == 0 ? default : searchOptions.Sort[0]; FieldName fieldName; object keyValue; SearchParameterInfo parameter; if (continuationToken.ResourceTypeId == null || _schemaInformation.Current < SchemaVersionConstants.PartitionedTables) { // backwards compat parameter = SqlSearchParameters.ResourceSurrogateIdParameter; fieldName = SqlFieldName.ResourceSurrogateId; keyValue = continuationToken.ResourceSurrogateId; } else { parameter = SqlSearchParameters.PrimaryKeyParameter; fieldName = SqlFieldName.PrimaryKey; keyValue = new PrimaryKeyValue(continuationToken.ResourceTypeId.Value, continuationToken.ResourceSurrogateId); } Expression lastUpdatedExpression = sortOrder == SortOrder.Ascending ? Expression.GreaterThan(fieldName, null, keyValue) : Expression.LessThan(fieldName, null, keyValue); var tokenExpression = Expression.SearchParameter(parameter, lastUpdatedExpression); searchExpression = searchExpression == null ? tokenExpression : Expression.And(tokenExpression, searchExpression); } } else { throw new BadRequestException(Resources.InvalidContinuationToken); } } var originalSort = searchOptions.Sort; searchOptions = UpdateSort(searchOptions, searchExpression, searchType); if (searchOptions.CountOnly) { // if we're only returning a count, discard any _include parameters since included resources are not counted. searchExpression = searchExpression?.AcceptVisitor(RemoveIncludesRewriter.Instance); } SqlRootExpression expression = (SqlRootExpression)searchExpression ?.AcceptVisitor(LastUpdatedToResourceSurrogateIdRewriter.Instance) .AcceptVisitor(DateTimeEqualityRewriter.Instance) .AcceptVisitor(FlatteningRewriter.Instance) .AcceptVisitor(UntypedReferenceRewriter.Instance) .AcceptVisitor(_sqlRootExpressionRewriter) .AcceptVisitor(_partitionEliminationRewriter) .AcceptVisitor(_sortRewriter, searchOptions) .AcceptVisitor(SearchParamTableExpressionReorderer.Instance) .AcceptVisitor(MissingSearchParamVisitor.Instance) .AcceptVisitor(NotExpressionRewriter.Instance) .AcceptVisitor(_chainFlatteningRewriter) .AcceptVisitor(ResourceColumnPredicatePushdownRewriter.Instance) .AcceptVisitor(DateTimeBoundedRangeRewriter.Instance) .AcceptVisitor( (SqlExpressionRewriterWithInitialContext <object>)(_schemaInformation.Current >= SchemaVersionConstants.PartitionedTables ? StringOverflowRewriter.Instance : LegacyStringOverflowRewriter.Instance)) .AcceptVisitor(NumericRangeRewriter.Instance) .AcceptVisitor(IncludeMatchSeedRewriter.Instance) .AcceptVisitor(TopRewriter.Instance, searchOptions) .AcceptVisitor(IncludeRewriter.Instance) ?? SqlRootExpression.WithResourceTableExpressions(); using (SqlConnectionWrapper sqlConnectionWrapper = await _sqlConnectionWrapperFactory.ObtainSqlConnectionWrapperAsync(cancellationToken, true)) using (SqlCommandWrapper sqlCommandWrapper = sqlConnectionWrapper.CreateSqlCommand()) { var stringBuilder = new IndentedStringBuilder(new StringBuilder()); EnableTimeAndIoMessageLogging(stringBuilder, sqlConnectionWrapper); var queryGenerator = new SqlQueryGenerator( stringBuilder, new HashingSqlQueryParameterManager(new SqlQueryParameterManager(sqlCommandWrapper.Parameters)), _model, searchType, _schemaInformation, currentSearchParameterHash); expression.AcceptVisitor(queryGenerator, searchOptions); sqlCommandWrapper.CommandText = stringBuilder.ToString(); LogSqlCommand(sqlCommandWrapper); using (var reader = await sqlCommandWrapper.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken)) { if (searchOptions.CountOnly) { await reader.ReadAsync(cancellationToken); var searchResult = new SearchResult(reader.GetInt32(0), searchOptions.UnsupportedSearchParams); // call NextResultAsync to get the info messages await reader.NextResultAsync(cancellationToken); return(searchResult); } var resources = new List <SearchResultEntry>(searchOptions.MaxItemCount); short?newContinuationType = null; long? newContinuationId = null; bool moreResults = false; int matchCount = 0; // Currently we support only date time sort type. DateTime?sortValue = null; var isResultPartial = false; while (await reader.ReadAsync(cancellationToken)) { PopulateResourceTableColumnsToRead( reader, out short resourceTypeId, out string resourceId, out int version, out bool isDeleted, out long resourceSurrogateId, out string requestMethod, out bool isMatch, out bool isPartialEntry, out bool isRawResourceMetaSet, out string searchParameterHash, out Stream rawResourceStream); // If we get to this point, we know there are more results so we need a continuation token // Additionally, this resource shouldn't be included in the results if (matchCount >= searchOptions.MaxItemCount && isMatch) { moreResults = true; continue; } string rawResource; using (rawResourceStream) { rawResource = await CompressedRawResourceConverter.ReadCompressedRawResource(rawResourceStream); } // See if this resource is a continuation token candidate and increase the count if (isMatch) { newContinuationType = resourceTypeId; newContinuationId = resourceSurrogateId; // Keep track of sort value if this is the last row. // if we have more than 10 columns, it means sort expressions were added. if (matchCount == searchOptions.MaxItemCount - 1 && reader.FieldCount > _resourceTableColumnCount + 1) { sortValue = reader.GetValue(SortValueColumnName) as DateTime?; } matchCount++; } // as long as at least one entry was marked as partial, this resultset // should be marked as partial isResultPartial = isResultPartial || isPartialEntry; resources.Add(new SearchResultEntry( new ResourceWrapper( resourceId, version.ToString(CultureInfo.InvariantCulture), _model.GetResourceTypeName(resourceTypeId), new RawResource(rawResource, FhirResourceFormat.Json, isMetaSet: isRawResourceMetaSet), new ResourceRequest(requestMethod), new DateTimeOffset(ResourceSurrogateIdHelper.ResourceSurrogateIdToLastUpdated(resourceSurrogateId), TimeSpan.Zero), isDeleted, null, null, null, searchParameterHash), isMatch ? SearchEntryMode.Match : SearchEntryMode.Include)); } // call NextResultAsync to get the info messages await reader.NextResultAsync(cancellationToken); ContinuationToken continuationToken = moreResults ? new ContinuationToken( searchOptions.Sort.Select(s => s.searchParameterInfo.Name switch { SearchParameterNames.ResourceType => (object)newContinuationType, SearchParameterNames.LastUpdated => newContinuationId, _ => sortValue.Value.ToString("o"), }).ToArray())
/// <summary> /// Constructs blueprint of the given <paramref name="primary"/>. /// </summary> /// <param name="primary">PrimaryType for which mapper being generated.</param> /// <returns>Mapper for the <paramref name="primary"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// The below example shows possible mapper string for PrimaryType. /// type: { /// name: 'Boolean' -- This value should be one of the KnownPrimaryType /// } /// </example> private static string ContructMapperForPrimaryType(this PrimaryType primary) { if (primary == null) { throw new ArgumentNullException(nameof(primary)); } IndentedStringBuilder builder = new IndentedStringBuilder(" "); if (primary.Type == KnownPrimaryType.Boolean) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.Double) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Double'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Decimal) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.String || primary.Type == KnownPrimaryType.Uuid) { builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.ByteArray) { builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.Base64Url) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.Date) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.DateTime) { builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTime'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.DateTimeRfc1123) { builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTimeRfc1123'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.TimeSpan) { builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.UnixTime) { builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.Object) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}"); } else if (primary.Type == KnownPrimaryType.Stream) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Stream'").Outdent().AppendLine("}"); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} is not a supported primary Type for {1}.", primary.Type, primary.SerializedName)); } return builder.ToString(); }
private void WriteMacOSViewWillMoveToSuperview(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder) { var isiosView = typeSymbol.Is(_macosViewSymbol); var hasNoWillMoveToSuperviewMethod = typeSymbol .GetMethods() .Where(m => IsNotDependencyObjectGeneratorSourceFile(m)) .None(m => m.Name == "ViewWillMoveToSuperview"); var overridesWillMoveToSuperview = isiosView && hasNoWillMoveToSuperviewMethod; if (overridesWillMoveToSuperview) { builder.AppendFormatInvariant(@" public override void ViewWillMoveToSuperview(AppKit.NSView newsuper) {{ base.ViewWillMoveToSuperview(newsuper); WillMoveToSuperviewPartial(newsuper); SyncBinder(newsuper, Window); }} partial void WillMoveToSuperviewPartial(AppKit.NSView newsuper); private void SyncBinder(AppKit.NSView superview, AppKit.NSWindow window) {{ if(superview == null && window == null) {{ TemplatedParent = null; }} }} " ); } else { builder.AppendLine($"// Skipped _macosViewSymbol: {typeSymbol.Is(_macosViewSymbol)}, hasNoViewWillMoveToSuperviewMethod: {hasNoWillMoveToSuperviewMethod}"); } }
/// <summary> /// Constructs blueprint of the given <paramref name="composite"/>. /// </summary> /// <param name="composite">CompositeType for which mapper being generated.</param> /// <param name="expandComposite">Expand composite type if <c>true</c> otherwise specify class_name in the mapper.</param> /// <returns>Mapper for the <paramref name="composite"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// The below example shows possible mapper string for CompositeType. /// type: { /// name: 'Composite', /// polymorphic_discriminator: 'property_name', -- name of the property for polymorphic discriminator /// Used only when x-ms-discriminator-value applied /// uber_parent: 'parent_class_name', -- name of the topmost level class on inheritance hierarchy /// Used only when x-ms-discriminator-value applied /// class_name: 'class_name', -- name of the modeled class /// Used when <paramref name="expandComposite"/> is false /// model_properties: { -- expanded properties of the model /// Used when <paramref name="expandComposite"/> is true /// property_name : { -- name of the property of this composite type /// *** -- mapper of the IType from the type of the property /// } /// } /// } /// </example> private static string ContructMapperForCompositeType(this CompositeType composite, bool expandComposite) { if (composite == null) { throw new ArgumentNullException(nameof(composite)); } IndentedStringBuilder builder = new IndentedStringBuilder(" "); builder.AppendLine("type: {").Indent() .AppendLine("name: 'Composite',"); if (composite.PolymorphicDiscriminator != null) { builder.AppendLine("polymorphic_discriminator: '{0}',", composite.PolymorphicDiscriminator); var polymorphicType = composite; while (polymorphicType.BaseModelType != null) { polymorphicType = polymorphicType.BaseModelType; } builder.AppendLine("uber_parent: '{0}',", polymorphicType.Name); } if (!expandComposite) { builder.AppendLine("class_name: '{0}'", composite.Name).Outdent().AppendLine("}"); } else { builder.AppendLine("class_name: '{0}',", composite.Name) .AppendLine("model_properties: {").Indent(); var composedPropertyList = new List<Property>(composite.ComposedProperties); for (var i = 0; i < composedPropertyList.Count; i++) { var prop = composedPropertyList[i]; var serializedPropertyName = prop.SerializedName; if (i != composedPropertyList.Count - 1) { builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.Type.ConstructMapper(serializedPropertyName, prop, false)); } else { builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.Type.ConstructMapper(serializedPropertyName, prop, false)); } } // end of modelProperties and type builder.Outdent(). AppendLine("}").Outdent(). AppendLine("}"); } return builder.ToString(); }
private void WriteAndroidAttachedToWindow(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder) { var isAndroidView = typeSymbol.Is(_androidViewSymbol); var isAndroidActivity = typeSymbol.Is(_androidActivitySymbol); var isAndroidFragment = typeSymbol.Is(_androidFragmentSymbol); var isUnoViewGroup = typeSymbol.Is(_unoViewgroupSymbol); var implementsIFrameworkElement = typeSymbol.Interfaces.Any(t => t == _iFrameworkElementSymbol); var hasOverridesAttachedToWindowAndroid = isAndroidView && typeSymbol .GetMethods() .Where(m => IsNotDependencyObjectGeneratorSourceFile(m)) .None(m => m.Name == "OnAttachedToWindow"); if (isAndroidView || isAndroidActivity || isAndroidFragment) { if (!isAndroidActivity && !isAndroidFragment) { WriteRegisterLoadActions(typeSymbol, builder); } builder.AppendLine($@" #if {hasOverridesAttachedToWindowAndroid} //Is Android view (that doesn't already override OnAttachedToWindow) #if {isUnoViewGroup} //Is UnoViewGroup // Both methods below are implementation of abstract methods // which are called from onAttachedToWindow in Java. protected override void OnNativeLoaded() {{ _loadActions.ForEach(a => a.Item1()); BinderAttachedToWindow(); }} protected override void OnNativeUnloaded() {{ _loadActions.ForEach(a => a.Item2()); BinderDetachedFromWindow(); }} #else //Not UnoViewGroup protected override void OnAttachedToWindow() {{ base.OnAttachedToWindow(); __Store.Parent = base.Parent; #if {implementsIFrameworkElement} //Is IFrameworkElement OnLoading(); OnLoaded(); #endif _loadActions.ForEach(a => a.Item1()); BinderAttachedToWindow(); }} protected override void OnDetachedFromWindow() {{ base.OnDetachedFromWindow(); _loadActions.ForEach(a => a.Item2()); #if {implementsIFrameworkElement} //Is IFrameworkElement OnUnloaded(); #endif if(base.Parent == null) {{ __Store.Parent = null; }} BinderDetachedFromWindow(); }} #endif // IsUnoViewGroup #endif // OverridesAttachedToWindow private void BinderAttachedToWindow() {{ OnAttachedToWindowPartial(); }} private void BinderDetachedFromWindow() {{ OnDetachedFromWindowPartial(); }} /// <summary> /// A method called when the control is attached to the Window (equivalent of Loaded) /// </summary> partial void OnAttachedToWindowPartial(); /// <summary> /// A method called when the control is attached to the Window (equivalent of Unloaded) /// </summary> partial void OnDetachedFromWindowPartial(); " ); } }
private async Task <string> GetDatabaseSchemaAsync(DbConnection connection) { var builder = new IndentedStringBuilder(); var command = connection.CreateCommand(); command.CommandText = @" SELECT t.name, c.Name, TYPE_NAME(c.user_type_id), c.is_nullable, d.Definition FROM sys.objects t LEFT JOIN sys.columns c ON c.object_id = t.object_id LEFT JOIN sys.default_constraints d ON d.parent_column_id = c.column_id AND d.parent_object_id = t.object_id WHERE t.type = 'U' ORDER BY t.name, c.column_id;"; using (var reader = await command.ExecuteReaderAsync()) { var first = true; string lastTable = null; while (await reader.ReadAsync()) { var currentTable = reader.GetString(0); if (currentTable != lastTable) { if (first) { first = false; } else { builder.DecrementIndent(); } builder .AppendLine() .AppendLine(currentTable) .IncrementIndent(); lastTable = currentTable; } builder .Append(reader[1]) // Name .Append(" ") .Append(reader[2]) // Type .Append(" ") .Append(reader.GetBoolean(3) ? "NULL" : "NOT NULL"); if (!await reader.IsDBNullAsync(4)) { builder .Append(" DEFAULT ") .Append(reader[4]); } builder.AppendLine(); } } return(builder.ToString()); }
private static void WriteRegisterLoadActions(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder) { builder.AppendLine($@" // A list of actions to be executed on Load and Unload private List<(Action loaded, Action unloaded)> _loadActions = new List<(Action loaded, Action unloaded)>(2); /// <summary> /// Registers actions to be executed when the control is Loaded and Unloaded. /// </summary> /// <param name=""loaded""></param> /// <param name=""unloaded""></param> /// <returns></returns> /// <remarks>The loaded action may be executed immediately if the control is already loaded.</remarks> public IDisposable RegisterLoadActions(Action loaded, Action unloaded) {{ var actions = (loaded, unloaded); _loadActions.Add(actions); #if __ANDROID__ if(this.IsLoaded()) #elif __IOS__ || __MACOS__ if(Window != null) #else #error Unsupported platform #endif {{ loaded(); }} return Disposable.Create(() => _loadActions.Remove(actions)); }} " ); }
public virtual void GenerateConstructors([NotNull] IndentedStringBuilder sb) { Check.NotNull(sb, nameof(sb)); GenerateZeroArgConstructor(sb); }
/// <summary> /// 修改排序规则名称。 /// </summary> /// <param name="command">当前命令。</param> /// <param name="builder">SQL语句构建实例。</param> protected override void Generate(RenameSequenceCommand command, IndentedStringBuilder builder) { Check.NotNull(command, nameof(command)); Check.NotNull(builder, nameof(builder)); var separate = false; var name = command.Name; if (command.NewName != null) { var qualifiedName = new StringBuilder(); if (command.Schema != null) { qualifiedName .Append(command.Schema) .Append("."); } qualifiedName.Append(Prefix(command.Name)); Rename(qualifiedName.ToString(), Prefix(command.NewName), builder); separate = true; name = command.NewName; } if (command.NewSchema != null) { if (separate) { builder.AppendLine(Sql.BatchCommandSeparator); } Transfer(command.NewSchema, command.Schema, name, builder); } }
private void BuildServerProcessorsPaths(GeneratorExecutionContext context, IndentedStringBuilder sb) { sb.AppendLineInvariant($"[assembly: global::Uno.UI.RemoteControl.ServerProcessorsConfigurationAttribute(" + $"@\"{context.GetMSBuildPropertyValue("UnoRemoteControlProcessorsPath")}\"" + $")]"); }
/// <summary> /// Generates Ruby code in form of string for serializing object of given type. /// </summary> /// <param name="type">Type of object needs to be serialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to serialized.</param> /// <param name="defaultNamespace">Current namespace.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string SerializeType( this IType type, IScopeProvider scope, string valueReference, string defaultNamespace) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString(); } if (primary == PrimaryType.DateTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString(); } } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.SerializeType(scope, elementVar, defaultNamespace); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("if ({0})", valueReference) .Indent() .AppendLine("serialized{0} = [];", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("serialized{0}.push({1});", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = serialized{1};", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.SerializeType(scope, valueVar, defaultNamespace); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("if ({0})", valueReference) .Indent() .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("}") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder .AppendLine("unless {0}.dtype.nil?", valueReference) .Indent() .AppendLine("{0} = Class::const_get({0}.dtype.capitalize).serialize_object({0})", valueReference) .Outdent() .AppendLine("else") .Indent() .AppendLine("{0} = {1}::{2}.serialize_object({0})", valueReference, defaultNamespace + "::Models", composite.Name) .Outdent() .AppendLine("end"); return builder.ToString(); } return builder.AppendLine("if ({0})", valueReference) .Indent() .AppendLine("{0} = {1}::{2}.serialize_object({0})", valueReference, defaultNamespace + "::Models", composite.Name) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
private void WriteBinderImplementation(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder) { var virtualModifier = typeSymbol.IsSealed ? "" : "virtual"; var protectedModifier = typeSymbol.IsSealed ? "private" : "internal protected"; builder.AppendLine($@" #region DataContext DependencyProperty public object DataContext {{ get => GetValue(DataContextProperty); set => SetValue(DataContextProperty, value); }} // Using a DependencyProperty as the backing store for DataContext. This enables animation, styling, binding, etc... public static readonly DependencyProperty DataContextProperty = DependencyProperty.Register( name: nameof(DataContext), propertyType: typeof(object), ownerType: typeof({typeSymbol.Name}), typeMetadata: new FrameworkPropertyMetadata( defaultValue: null, options: FrameworkPropertyMetadataOptions.Inherits, propertyChangedCallback: (s, e) => (({typeSymbol.Name})s).OnDataContextChanged(e) ) ); {protectedModifier} {virtualModifier} void OnDataContextChanged(DependencyPropertyChangedEventArgs e) {{ OnDataContextChangedPartial(e); DataContextChanged?.Invoke(this, new DataContextChangedEventArgs(DataContext)); }} #endregion #region TemplatedParent DependencyProperty public DependencyObject TemplatedParent {{ get => (DependencyObject)GetValue(TemplatedParentProperty); set => SetValue(TemplatedParentProperty, value); }} // Using a DependencyProperty as the backing store for TemplatedParent. This enables animation, styling, binding, etc... public static readonly DependencyProperty TemplatedParentProperty = DependencyProperty.Register( name: nameof(TemplatedParent), propertyType: typeof(DependencyObject), ownerType: typeof({typeSymbol.Name}), typeMetadata: new FrameworkPropertyMetadata( defaultValue: null, options: FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.ValueDoesNotInheritDataContext | FrameworkPropertyMetadataOptions.WeakStorage, propertyChangedCallback: (s, e) => (({typeSymbol.Name})s).OnTemplatedParentChanged(e) ) ); {protectedModifier} {virtualModifier} void OnTemplatedParentChanged(DependencyPropertyChangedEventArgs e) {{ __Store.SetTemplatedParent(e.NewValue as FrameworkElement); OnTemplatedParentChangedPartial(e); }} #endregion public void SetBinding(object target, string dependencyProperty, global::Windows.UI.Xaml.Data.BindingBase binding) {{ __Store.SetBinding(target, dependencyProperty, binding); }} public void SetBinding(string dependencyProperty, global::Windows.UI.Xaml.Data.BindingBase binding) {{ __Store.SetBinding(dependencyProperty, binding); }} public void SetBinding(DependencyProperty dependencyProperty, global::Windows.UI.Xaml.Data.BindingBase binding) {{ __Store.SetBinding(dependencyProperty, binding); }} public void SetBindingValue(object value, [CallerMemberName] string propertyName = null) {{ __Store.SetBindingValue(value, propertyName); }} [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal bool IsAutoPropertyInheritanceEnabled {{ get => __Store.IsAutoPropertyInheritanceEnabled; set => __Store.IsAutoPropertyInheritanceEnabled = value; }} partial void OnDataContextChangedPartial(DependencyPropertyChangedEventArgs e); partial void OnTemplatedParentChangedPartial(DependencyPropertyChangedEventArgs e); public global::Windows.UI.Xaml.Data.BindingExpression GetBindingExpression(DependencyProperty dependencyProperty) => __Store.GetBindingExpression(dependencyProperty); public void ResumeBindings() =>__Store.ResumeBindings(); public void SuspendBindings() => __Store.SuspendBindings(); " ); }
private static void BuildEndPointAttribute(GeneratorExecutionContext context, IndentedStringBuilder sb) { var unoRemoteControlPort = context.GetMSBuildPropertyValue("UnoRemoteControlPort"); if (string.IsNullOrEmpty(unoRemoteControlPort)) { unoRemoteControlPort = "0"; } var unoRemoteControlHost = context.GetMSBuildPropertyValue("UnoRemoteControlHost"); if (string.IsNullOrEmpty(unoRemoteControlHost)) { var addresses = NetworkInterface.GetAllNetworkInterfaces() .SelectMany(x => x.GetIPProperties().UnicastAddresses) .Where(x => !IPAddress.IsLoopback(x.Address)); //This is not supported on linux yet: .Where(x => x.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred); foreach (var addressInfo in addresses) { var address = addressInfo.Address; string addressStr; if (address.AddressFamily == AddressFamily.InterNetworkV6) { address.ScopeId = 0; // remove annoying "%xx" on IPv6 addresses addressStr = $"[{address}]"; } else { addressStr = address.ToString(); } sb.AppendLineInvariant($"[assembly: global::Uno.UI.RemoteControl.ServerEndpointAttribute(\"{addressStr}\", {unoRemoteControlPort})]"); } } else { sb.AppendLineInvariant($"[assembly: global::Uno.UI.RemoteControl.ServerEndpointAttribute(\"{unoRemoteControlHost}\", {unoRemoteControlPort})]"); } }
private string Array(Type type, IEnumerable values, bool vertical = false) { var builder = new IndentedStringBuilder(); builder.Append("new"); var byteArray = type == typeof(byte); if (byteArray) { builder.Append(" byte"); } else if (type == typeof(object)) { builder.Append(" object"); } builder.Append("[]"); if (vertical) { builder.AppendLine(); } else { builder.Append(" "); } builder.Append("{"); if (vertical) { builder.AppendLine(); builder.IncrementIndent(); } else { builder.Append(" "); } var first = true; foreach (var value in values) { if (first) { first = false; } else { builder.Append(","); if (vertical) { builder.AppendLine(); } else { builder.Append(" "); } } builder.Append( byteArray ? Literal((int)(byte)value) : UnknownLiteral(value)); } if (vertical) { builder.AppendLine(); builder.DecrementIndent(); } else { builder.Append(" "); } builder.Append("}"); return(builder.ToString()); }
public virtual string BuildGroupedParameterMappings() { var builder = new IndentedStringBuilder(" "); if (InputParameterTransformation.Count > 0) { // Declare all the output paramaters outside the try block foreach (var transformation in InputParameterTransformation) { if (transformation.OutputParameter.ModelType is CompositeType && transformation.OutputParameter.IsRequired) { builder.AppendLine("var {0} = new client.models['{1}']();", transformation.OutputParameter.Name, transformation.OutputParameter.ModelType.Name); } else { builder.AppendLine("var {0};", transformation.OutputParameter.Name); } } builder.AppendLine("try {").Indent(); foreach (var transformation in InputParameterTransformation) { builder.AppendLine("if ({0})", BuildNullCheckExpression(transformation)) .AppendLine("{").Indent(); var outputParameter = transformation.OutputParameter; bool noCompositeTypeInitialized = true; if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.ModelType is CompositeType) { //required outputParameter is initialized at the time of declaration if (!transformation.OutputParameter.IsRequired) { builder.AppendLine("{0} = new client.models['{1}']();", transformation.OutputParameter.Name, transformation.OutputParameter.ModelType.Name); } noCompositeTypeInitialized = false; } foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter)); if (noCompositeTypeInitialized) { // If composite type is initialized based on the above logic then it should not be validated. builder.AppendLine(outputParameter.ModelType.ValidateType(this, outputParameter.Name, outputParameter.IsRequired)); } } builder.Outdent() .AppendLine("}"); } builder.Outdent() .AppendLine("} catch (error) {") .Indent() .AppendLine("return callback(error);") .Outdent() .AppendLine("}"); } return(builder.ToString()); }
public void Append_line_with_indent_only() { var indentedStringBuilder = new IndentedStringBuilder(); using (indentedStringBuilder.Indent()) { indentedStringBuilder.AppendLine(); } Assert.Equal(Environment.NewLine, indentedStringBuilder.ToString()); }
public abstract void Generate( [NotNull] IModel model, [NotNull] IndentedStringBuilder stringBuilder);
/// <summary> /// Generates Ruby code in form of string for serializing object of given type. /// </summary> /// <param name="type">Type of object needs to be serialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to serialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureSerializeType( this IType type, IScopeProvider scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.Type == KnownPrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.DateTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString(); } if (primary.Type == KnownPrimaryType.UnixTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%s')", valueReference).ToString(); } } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureSerializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("serialized{0} = []", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("serialized{0}.push({1})", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = serialized{1}", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureSerializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("}") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { var compositeName = composite.Name; if(compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
public abstract void GenerateModelSnapshotClass( [NotNull] string @namespace, [NotNull] string className, [NotNull] IModel model, [NotNull] IndentedStringBuilder stringBuilder);
public virtual string GenerateScript( string fromMigration = null, string toMigration = null, bool idempotent = false) { var migrations = _migrationsAssembly.Migrations; if (string.IsNullOrEmpty(fromMigration)) { fromMigration = Migration.InitialDatabase; } else if (fromMigration != Migration.InitialDatabase) { fromMigration = _migrationsAssembly.GetMigrationId(fromMigration); } if (string.IsNullOrEmpty(toMigration)) { toMigration = migrations.Keys.Last(); } else if (toMigration != Migration.InitialDatabase) { toMigration = _migrationsAssembly.GetMigrationId(toMigration); } var builder = new IndentedStringBuilder(); // If going up... if (string.Compare(fromMigration, toMigration, StringComparison.OrdinalIgnoreCase) <= 0) { var migrationsToApply = migrations.Where( m => string.Compare(m.Key, fromMigration, StringComparison.OrdinalIgnoreCase) > 0 && string.Compare(m.Key, toMigration, StringComparison.OrdinalIgnoreCase) <= 0) .Select(m => _migrationsAssembly.CreateMigration(m.Value, _activeProvider)); var checkFirst = true; foreach (var migration in migrationsToApply) { if (checkFirst) { if (migration.GetId() == migrations.Keys.First()) { builder.AppendLine(_historyRepository.GetCreateIfNotExistsScript()); builder.Append(_sqlGenerator.BatchSeparator); } checkFirst = false; } _logger.LogVerbose(RelationalStrings.GeneratingUp(migration.GetId())); foreach (var command in GenerateUpSql(migration)) { if (idempotent) { builder.AppendLine(_historyRepository.GetBeginIfNotExistsScript(migration.GetId())); using (builder.Indent()) { builder.AppendLines(command.CommandText); } builder.AppendLine(_historyRepository.GetEndIfScript()); } else { builder.AppendLine(command.CommandText); } builder.Append(_sqlGenerator.BatchSeparator); } } } else // If going down... { var migrationsToRevert = migrations .Where( m => string.Compare(m.Key, toMigration, StringComparison.OrdinalIgnoreCase) > 0 && string.Compare(m.Key, fromMigration, StringComparison.OrdinalIgnoreCase) <= 0) .OrderByDescending(m => m.Key) .Select(m => _migrationsAssembly.CreateMigration(m.Value, _activeProvider)) .ToList(); for (var i = 0; i < migrationsToRevert.Count; i++) { var migration = migrationsToRevert[i]; var previousMigration = i != migrationsToRevert.Count - 1 ? migrationsToRevert[i + 1] : null; _logger.LogVerbose(RelationalStrings.GeneratingDown(migration.GetId())); foreach (var command in GenerateDownSql(migration, previousMigration)) { if (idempotent) { builder.AppendLine(_historyRepository.GetBeginIfExistsScript(migration.GetId())); using (builder.Indent()) { builder.AppendLines(command.CommandText); } builder.AppendLine(_historyRepository.GetEndIfScript()); } else { builder.AppendLine(command.CommandText); } builder.Append(_sqlGenerator.BatchSeparator); } } } return builder.ToString(); }
/// <summary> /// Generates Ruby code in form of string for deserializing object of given type. /// </summary> /// <param name="type">Type of object needs to be deserialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to be deserialized.</param> /// <param name="namespacesToLookForClasses">List of namespaces where classes for polymorphic serialization can be found.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string DeserializeType( this IType type, IScopeProvider scope, string valueReference, List<string> namespacesToLookForClasses) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.Int || primary == PrimaryType.Long) { return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.Double) { return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.Date) { return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.DateTime) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary == PrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } } else if (enumType != null && !string.IsNullOrEmpty(enumType.Name)) { return builder .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference) .AppendLine( " enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}", enumType.Name, valueReference) .AppendLine( " fail MsRest::DeserializationError.new('Error occured while deserializing the enum', nil, nil, nil) unless enum_is_valid") .AppendLine("end") .ToString(); } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.DeserializeType(scope, elementVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("deserialized{0} = [];", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized{0}.push({1});", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = deserialized{1};", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.DeserializeType(scope, valueVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("end") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder .AppendLine("unless {0}['dtype'].nil?", valueReference) .Indent() .AppendLine("class_name = {0}['dtype'].capitalize", valueReference) .AppendLine("class_instance = Models.const_get(class_name)"); foreach (var ns in namespacesToLookForClasses) { builder .AppendLine("class_instance = {0}.const_get(class_name) if class_instance.nil?", ns); } builder .AppendLine("{0} = class_instance.deserialize_object({0})", valueReference) .Outdent() .AppendLine("else") .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end"); return builder.ToString(); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
public override string GenerateMigration( string migrationNamespace, string migrationName, IReadOnlyList<MigrationOperation> upOperations, IReadOnlyList<MigrationOperation> downOperations) { Check.NotEmpty(migrationNamespace, nameof(migrationNamespace)); Check.NotEmpty(migrationName, nameof(migrationName)); Check.NotNull(upOperations, nameof(upOperations)); Check.NotNull(downOperations, nameof(downOperations)); var builder = new IndentedStringBuilder(); var namespaces = new List<string> { "System", "System.Collections.Generic", "Microsoft.Data.Entity.Migrations" }; namespaces.AddRange(GetNamespaces(upOperations.Concat(downOperations))); foreach (var n in namespaces.Distinct()) { builder .Append("using ") .Append(n) .AppendLine(";"); } builder .AppendLine() .Append("namespace ").AppendLine(_code.Namespace(migrationNamespace)) .AppendLine("{"); using (builder.Indent()) { builder .Append("public partial class ").Append(_code.Identifier(migrationName)).AppendLine(" : Migration") .AppendLine("{"); using (builder.Indent()) { builder .AppendLine("protected override void Up(MigrationBuilder migrationBuilder)") .AppendLine("{"); using (builder.Indent()) { _operationGenerator.Generate("migrationBuilder", upOperations, builder); } builder .AppendLine("}") .AppendLine() .AppendLine("protected override void Down(MigrationBuilder migrationBuilder)") .AppendLine("{"); using (builder.Indent()) { _operationGenerator.Generate("migrationBuilder", downOperations, builder); } builder.AppendLine("}"); } builder.AppendLine("}"); } builder.AppendLine("}"); return builder.ToString(); }
/// <summary> /// Constructs blueprint of the given <paramref name="type"/>. /// </summary> /// <param name="type">Type for which mapper being generated.</param> /// <param name="serializedName">Serialized name to be used.</param> /// <param name="parameter">Parameter of the composite type to construct the parameter constraints.</param> /// <param name="expandComposite">Expand composite type if <c>true</c> otherwise specify class_name in the mapper.</param> /// <returns>Mapper for the <paramref name="type"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// One of the example of the mapper is /// { /// required: false, /// serialized_name: 'Fish', /// type: { /// name: 'Composite', /// polymorphic_discriminator: 'fishtype', /// uber_parent: 'Fish', /// class_name: 'Fish', /// model_properties: { /// species: { /// required: false, /// serialized_name: 'species', /// type: { /// name: 'String' /// } /// }, /// length: { /// required: true, /// serialized_name: 'length', /// type: { /// name: 'Double' /// } /// }, /// siblings: { /// required: false, /// serialized_name: 'siblings', /// type: { /// name: 'Sequence', /// element: { /// required: false, /// serialized_name: 'FishElementType', /// type: { /// name: 'Composite', /// polymorphic_discriminator: 'fishtype', /// uber_parent: 'Fish', /// class_name: 'Fish' /// } /// } /// } /// } /// } /// } /// } /// </example> public static string ConstructMapper(this IType type, string serializedName, IParameter parameter, bool expandComposite) { if (type == null) { throw new ArgumentNullException(nameof(type)); } var builder = new IndentedStringBuilder(" "); CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; if (enumType != null && enumType.ModelAsString) { primary = new PrimaryType(KnownPrimaryType.String); } builder.AppendLine("").Indent(); builder.AppendLine(type.AddMetaData(serializedName, parameter)); if (primary != null) { builder.AppendLine(primary.ContructMapperForPrimaryType()); } else if (enumType != null && enumType.Name != null) { builder.AppendLine(enumType.ContructMapperForEnumType()); } else if (sequence != null) { builder.AppendLine(sequence.ContructMapperForSequenceType()); } else if (dictionary != null) { builder.AppendLine(dictionary.ContructMapperForDictionaryType()); } else if (composite != null) { builder.AppendLine(composite.ContructMapperForCompositeType(expandComposite)); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} is not a supported Type.", type)); } return builder.ToString(); }
/// <summary> /// Generate code to perform required validation on a type /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <param name="constraints">Constraints</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IModelType type, IChild scope, string valueReference, Dictionary <Constraint, string> constraints) { if (scope == null) { throw new ArgumentNullException("scope"); } var model = type as CompositeTypeCs; var sequence = type as SequenceTypeCs; var dictionary = type as DictionaryTypeCs; var sb = new IndentedStringBuilder(); if (model != null && model.ShouldValidateChain()) { sb.AppendLine("{0}.Validate();", valueReference); } if (constraints != null && constraints.Any()) { AppendConstraintValidations(valueReference, constraints, sb, type); } if (sequence != null && sequence.ShouldValidateChain()) { var elementVar = scope.GetUniqueName("element"); var innerValidation = sequence.ElementType.ValidateType(scope, elementVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}"); } } else if (dictionary != null && dictionary.ShouldValidateChain()) { var valueVar = scope.GetUniqueName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1}.Values)", valueVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}").Outdent(); } } if (sb.ToString().Trim().Length > 0) { if (type.IsValueType()) { return(sb.ToString()); } else { return(CheckNull(valueReference, sb.ToString())); } } return(null); }
public abstract void GenerateEntityProperty([NotNull] IProperty property, [NotNull] IndentedStringBuilder sb);
/// <summary> /// Generates Ruby code in form of string for serializing object of given type. /// </summary> /// <param name="type">Type of object needs to be serialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to serialized.</param> /// <param name="namespacesToLookForClasses">List of namespaces where classes for polymorphic deserialization can be found.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string SerializeType( this IType type, IScopeProvider scope, string valueReference, List<string> namespacesToLookForClasses) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString(); } if (primary == PrimaryType.DateTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString(); } if (primary == PrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString(); } } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.SerializeType(scope, elementVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("serialized{0} = []", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("serialized{0}.push({1})", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = serialized{1}", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.SerializeType(scope, valueVar, namespacesToLookForClasses); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("}") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder .AppendLine("unless {0}.dtype.nil?", valueReference) .Indent() .AppendLine("class_name = {0}.dtype.capitalize", valueReference) .AppendLine("class_instance = Models.const_get(class_name)"); foreach (var ns in namespacesToLookForClasses) { builder .AppendLine("class_instance = {0}.const_get(class_name) if class_instance.nil?", ns); } builder .AppendLine("{0} = class_instance.serialize_object({0})", valueReference) .Outdent() .AppendLine("else") .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end"); return builder.ToString(); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, composite.Name) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
private static void AppendConstraintValidations(string valueReference, Dictionary <Constraint, string> constraints, IndentedStringBuilder sb, IModelType type) { foreach (var constraint in constraints.Keys) { string constraintCheck; string constraintValue = ((type as PrimaryType)?.KnownFormat == KnownFormat.@char) ?$"'{constraints[constraint]}'" : constraints[constraint]; switch (constraint) { case Constraint.ExclusiveMaximum: constraintCheck = $"{valueReference} >= {constraintValue}"; break; case Constraint.ExclusiveMinimum: constraintCheck = $"{valueReference} <= {constraintValue}"; break; case Constraint.InclusiveMaximum: constraintCheck = $"{valueReference} > {constraintValue}"; break; case Constraint.InclusiveMinimum: constraintCheck = $"{valueReference} < {constraintValue}"; break; case Constraint.MaxItems: constraintCheck = $"{valueReference}.Count > {constraintValue}"; break; case Constraint.MaxLength: constraintCheck = $"{valueReference}.Length > {constraintValue}"; break; case Constraint.MinItems: constraintCheck = $"{valueReference}.Count < {constraintValue}"; break; case Constraint.MinLength: constraintCheck = $"{valueReference}.Length < {constraintValue}"; break; case Constraint.MultipleOf: constraintCheck = $"{valueReference} % {constraintValue} != 0"; break; case Constraint.Pattern: constraintValue = ToLiteral(constraintValue); if (type is DictionaryType) { constraintCheck = $"!System.Linq.Enumerable.All({valueReference}.Values, value => System.Text.RegularExpressions.Regex.IsMatch(value, {constraintValue}))"; } else { constraintCheck = $"!System.Text.RegularExpressions.Regex.IsMatch({valueReference}, {constraintValue})"; } break; case Constraint.UniqueItems: if ("true".EqualsIgnoreCase(constraints[constraint])) { constraintCheck = $"{valueReference}.Count != {valueReference}.Distinct().Count()"; } else { constraintCheck = null; } break; default: throw new NotSupportedException("Constraint '" + constraint + "' is not supported."); } if (constraintCheck != null) { if (constraint != Constraint.UniqueItems) { sb.AppendLine("if ({0})", constraintCheck) .AppendLine("{").Indent() .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\", {2});", constraint, valueReference.Replace("this.", ""), constraintValue).Outdent() .AppendLine("}"); } else { sb.AppendLine("if ({0})", constraintCheck) .AppendLine("{").Indent() .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\");", constraint, valueReference.Replace("this.", "")).Outdent() .AppendLine("}"); } } } }
/// <summary> /// Adds metadata to the given <paramref name="type"/>. /// </summary> /// <param name="type">Type for which metadata being generated.</param> /// <param name="serializedName">Serialized name to be used.</param> /// <param name="parameter">Parameter of the composite type to construct the parameter constraints.</param> /// <returns>Metadata as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// The below example shows possible mapper string for IParameter for IType. /// required: true | false, -- whether this property is required or not /// read_only: true | false, -- whether this property is read only or not. Default is false /// is_constant: true | false, -- whether this property is constant or not. Default is false /// serialized_name: 'name' -- serialized name of the property if provided /// default_value: 'value' -- default value of the property if provided /// constraints: { -- constraints of the property /// key: value, -- constraint name and value if any /// ***: ***** /// } /// </example> private static string AddMetaData(this IType type, string serializedName, IParameter parameter) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (serializedName == null) { throw new ArgumentNullException(nameof(serializedName)); } IndentedStringBuilder builder = new IndentedStringBuilder(" "); Dictionary<Constraint, string> constraints = null; string defaultValue = null; bool isRequired = false; bool isConstant = false; bool isReadOnly = false; var property = parameter as Property; if (property != null) { isReadOnly = property.IsReadOnly; } if (parameter != null) { defaultValue = parameter.DefaultValue; isRequired = parameter.IsRequired; isConstant = parameter.IsConstant; constraints = parameter.Constraints; } CompositeType composite = type as CompositeType; if (composite != null && composite.ContainsConstantProperties && isRequired) { defaultValue = "{}"; } if (isRequired) { builder.AppendLine("required: true,"); } else { builder.AppendLine("required: false,"); } if (isReadOnly) { builder.AppendLine("read_only: true,"); } if (isConstant) { builder.AppendLine("is_constant: true,"); } if (serializedName != null) { builder.AppendLine("serialized_name: '{0}',", serializedName); } if (defaultValue != null) { builder.AppendLine("default_value: {0},", defaultValue); } if (constraints != null && constraints.Count > 0) { builder.AppendLine("constraints: {").Indent(); var keys = constraints.Keys.ToList<Constraint>(); for (int j = 0; j < keys.Count; j++) { var constraintValue = constraints[keys[j]]; if (keys[j] == Constraint.Pattern) { constraintValue = string.Format(CultureInfo.InvariantCulture, "'{0}'", constraintValue); } if (j != keys.Count - 1) { builder.AppendLine("{0}: {1},", keys[j], constraintValue); } else { builder.AppendLine("{0}: {1}", keys[j], constraintValue); } } builder.Outdent() .AppendLine("},"); } return builder.ToString(); }
private static string GetDatabaseSchemaAsync(DbConnection connection) { var builder = new IndentedStringBuilder(); var command = connection.CreateCommand(); command.CommandText = @" SELECT table_name, column_name, udt_name, is_nullable = 'YES', column_default FROM information_schema.columns WHERE table_catalog = @db AND table_schema = 'public' ORDER BY table_name, ordinal_position "; var dbName = connection.Database; command.Parameters.Add(new NpgsqlParameter { ParameterName = "db", Value = dbName }); using (var reader = command.ExecuteReader()) { var first = true; string lastTable = null; while (reader.Read()) { var currentTable = reader.GetString(0); if (currentTable != lastTable) { if (first) { first = false; } else { builder.DecrementIndent(); } builder .AppendLine() .AppendLine(currentTable) .IncrementIndent(); lastTable = currentTable; } builder .Append(reader[1]) // Name .Append(" ") .Append(reader[2]) // Type .Append(" ") .Append(reader.GetBoolean(3) ? "NULL" : "NOT NULL"); if (!reader.IsDBNull(4)) { builder .Append(" DEFAULT ") .Append(reader[4]); } builder.AppendLine(); } } return(builder.ToString()); }
/// <summary> /// Constructs blueprint of the given <paramref name="enumeration"/>. /// </summary> /// <param name="enumeration">EnumType for which mapper being generated.</param> /// <returns>Mapper for the <paramref name="enumeration"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// The below example shows possible mapper string for EnumType. /// type: { /// name: 'Enum', /// module: 'module_name' -- name of the module to be looked for enum values /// } /// </example> private static string ContructMapperForEnumType(this EnumType enumeration) { if (enumeration == null) { throw new ArgumentNullException(nameof(enumeration)); } IndentedStringBuilder builder = new IndentedStringBuilder(" "); builder.AppendLine("type: {").Indent() .AppendLine("name: 'Enum',") .AppendLine("module: '{0}'", enumeration.Name).Outdent() .AppendLine("}"); return builder.ToString(); }
public ExpressionPrinter() { _stringBuilder = new IndentedStringBuilder(); _parametersInScope = new Dictionary <ParameterExpression, string>(); _namelessParameters = new List <ParameterExpression>(); }
/// <summary> /// Constructs blueprint of the given <paramref name="dictionary"/>. /// </summary> /// <param name="dictionary">DictionaryType for which mapper being generated.</param> /// <returns>Mapper for the <paramref name="dictionary"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <example> /// The below example shows possible mapper string for DictionaryType. /// type: { /// name: 'Dictionary', /// value: { /// *** -- mapper of the IType from the value type of dictionary /// } /// } /// </example> private static string ContructMapperForDictionaryType(this DictionaryType dictionary) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } IndentedStringBuilder builder = new IndentedStringBuilder(" "); builder.AppendLine("type: {").Indent() .AppendLine("name: 'Dictionary',") .AppendLine("value: {").Indent() .AppendLine("{0}", dictionary.ValueType.ConstructMapper(dictionary.ValueType.Name + "ElementType", null, false)).Outdent() .AppendLine("}").Outdent() .AppendLine("}"); return builder.ToString(); }
public void Generate_migration_metadata_class() { var model = new Model(); var entityType = model.AddEntityType("Entity"); entityType.GetOrSetPrimaryKey(entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true)); var migration = new MigrationInfo("000000000000001_Name", "1.2.3.4") { TargetModel = model }; var codeGenerator = new CSharpMigrationCodeGenerator(new CSharpModelCodeGenerator()); var stringBuilder = new IndentedStringBuilder(); codeGenerator.GenerateMigrationMetadataClass("MyNamespace", "MyClass", migration, typeof(MyContext), stringBuilder); Assert.Equal( @"using Microsoft.Data.Entity; using Microsoft.Data.Entity.Commands.Tests.Migrations; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using System; namespace MyNamespace { [ContextType(typeof(Microsoft.Data.Entity.Commands.Tests.Migrations.CSharpMigrationCodeGeneratorTest.MyContext))] public partial class MyClass : IMigrationMetadata { string IMigrationMetadata.MigrationId { get { return ""000000000000001_Name""; } } string IMigrationMetadata.ProductVersion { get { return ""1.2.3.4""; } } IModel IMigrationMetadata.TargetModel { get { var builder = new BasicModelBuilder(); builder.Entity(""Entity"", b => { b.Property<int>(""Id""); b.Key(""Id""); }); return builder.Model; } } } }", stringBuilder.ToString()); }
public override string GetCreateIfNotExistsScript() { var builder = new IndentedStringBuilder(); builder.Append("IF OBJECT_ID(N'"); if (TableSchema != null) { builder .Append(Sql.EscapeLiteral(TableSchema)) .Append("."); } builder .Append(Sql.EscapeLiteral(TableName)) .AppendLine("') IS NULL"); using (builder.Indent()) { builder.AppendLines(GetCreateScript()); } return builder.ToString(); }
protected virtual void GenerateForeignKey( [NotNull] IForeignKey foreignKey, [NotNull] IndentedStringBuilder stringBuilder) { Check.NotNull(foreignKey, nameof(foreignKey)); Check.NotNull(stringBuilder, nameof(stringBuilder)); stringBuilder .AppendLine() .Append("b.HasOne(") .Append(_code.Literal(foreignKey.PrincipalEntityType.Name)); if (foreignKey.DependentToPrincipal != null) { stringBuilder .Append(", ") .Append(_code.Literal(foreignKey.DependentToPrincipal.Name)); } stringBuilder .Append(")") .AppendLine(); using (stringBuilder.Indent()) { if (foreignKey.IsUnique) { stringBuilder .Append(".WithOne("); if (foreignKey.PrincipalToDependent != null) { stringBuilder .Append(_code.Literal(foreignKey.PrincipalToDependent.Name)); } stringBuilder .AppendLine(")") .Append(".HasForeignKey(") .Append(_code.Literal(foreignKey.DeclaringEntityType.Name)) .Append(", ") .Append(string.Join(", ", foreignKey.Properties.Select(p => _code.Literal(p.Name)))) .Append(")"); GenerateForeignKeyAnnotations(foreignKey, stringBuilder); if (foreignKey.PrincipalKey != foreignKey.PrincipalEntityType.FindPrimaryKey()) { stringBuilder .AppendLine() .Append(".HasPrincipalKey(") .Append(_code.Literal(foreignKey.PrincipalEntityType.Name)) .Append(", ") .Append(string.Join(", ", foreignKey.PrincipalKey.Properties.Select(p => _code.Literal(p.Name)))) .Append(")"); } } else { stringBuilder .Append(".WithMany("); if (foreignKey.PrincipalToDependent != null) { stringBuilder .Append(_code.Literal(foreignKey.PrincipalToDependent.Name)); } stringBuilder .AppendLine(")") .Append(".HasForeignKey(") .Append(string.Join(", ", foreignKey.Properties.Select(p => _code.Literal(p.Name)))) .Append(")"); GenerateForeignKeyAnnotations(foreignKey, stringBuilder); if (foreignKey.PrincipalKey != foreignKey.PrincipalEntityType.FindPrimaryKey()) { stringBuilder .AppendLine() .Append(".HasPrincipalKey(") .Append(string.Join(", ", foreignKey.PrincipalKey.Properties.Select(p => _code.Literal(p.Name)))) .Append(")"); } } if (foreignKey.DeleteBehavior != DeleteBehavior.Restrict) { stringBuilder .AppendLine() .Append(".OnDelete(") .Append(_code.Literal(foreignKey.DeleteBehavior)) .Append(")"); } } stringBuilder.Append(";"); }