private void GenerateFunctionStub(Function function, FunctionModel model) { var paramStrings = function.Parameters .Select(p => $"{code.Reference(p.ClrType())} {p.Name}"); var identifier = GenerateIdentifierName(function, model); _sb.AppendLine(); _sb.AppendLine($"[DbFunction(\"{function.Name}\", \"{function.Schema}\")]"); var returnType = paramStrings.First(); var parameters = string.Empty; if (function.Parameters.Count > 1) { parameters = string.Join(", ", paramStrings.Skip(1)); } _sb.AppendLine($"public static {returnType}{identifier}({parameters})"); _sb.AppendLine("{"); using (_sb.Indent()) { _sb.AppendLine("throw new NotSupportedException(\"This method can only be called from Entity Framework Core queries\");"); } _sb.AppendLine("}"); }
private void GenerateProperties(List <ModuleResultElement> resultElements, bool nullableReferences) { foreach (var property in resultElements.OrderBy(e => e.Ordinal)) { var propertyNames = GeneratePropertyName(property.Name); if (!string.IsNullOrEmpty(propertyNames.Item2)) { _sb.AppendLine(propertyNames.Item2); } var propertyType = property.ClrType(); string nullableAnnotation = string.Empty; string defaultAnnotation = string.Empty; if (nullableReferences && !propertyType.IsValueType) { if (property.Nullable) { nullableAnnotation = "?"; } else { defaultAnnotation = $" = default!;"; } } _sb.AppendLine($"public {code.Reference(propertyType)}{nullableAnnotation} {propertyNames.Item1} {{ get; set; }}{defaultAnnotation}"); } }
/// <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> protected virtual void GenerateProperties(IEntityType entityType) { foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrder() ?? -1)) { GenerateComment(property.GetComment()); if (_useDataAnnotations) { GeneratePropertyDataAnnotations(property); } _sb.AppendLine( !_useNullableReferenceTypes || property.ClrType.IsValueType ? $"public {_code.Reference(property.ClrType)} {property.Name} {{ get; set; }}" : property.IsNullable ? $"public {_code.Reference(property.ClrType)}? {property.Name} {{ get; set; }}" : $"public {_code.Reference(property.ClrType)} {property.Name} {{ get; set; }} = null!;"); } }
/// <summary> /// Code writer /// </summary> /// <param name="type"></param> /// <param name="namespace"></param> /// <param name="useDataAnnotations"></param> /// <returns></returns> public override string WriteCode(IEntityType type, string @namespace, bool useDataAnnotations) { string code = base.WriteCode(type, @namespace, useDataAnnotations); code = CustomHelpers.commentedClass(code, string.Format("Elements of the table '{0}'", type.GetTableName()), type.GetComment()); // Pluralizer issue code = code.Replace("MessageSeenBies", "MessagesSeenBy"); string constr = string.Format("public {0}()", type.Name); code = code.Replace(constr, "/// <summary>\r\n\t\t/// Entity constructor\r\n\t\t/// </summary>\r\n\t\t" + constr); foreach (var p in type.GetProperties()) { string decl = "public " + _code.Reference(p.ClrType) + " " + p.Name; StringBuilder comment = new StringBuilder(); comment.Append("\r\n\t\t/// <summary>"); comment.Append("\r\n\t\t/// Column '" + p.GetColumnName() + "'"); if (!string.IsNullOrWhiteSpace(p.GetComment())) { comment.Append(":\r\n\t\t/// " + p.GetComment()); } comment.Append("\r\n\t\t/// </summary>"); comment.Append("\r\n\t\t/// <remarks>Original field type: " + p.GetColumnType() + "</remarks>"); comment.Append("\r\n\t\t" + decl); code = code.Replace(decl, comment.ToString()); } var navi = type.GetNavigations().ToList(); if (navi.Any()) { foreach (var n in navi) { string ntype = n.IsCollection() ? $"ICollection<{n.GetTargetType().DisplayName()}>" : n.GetTargetType().DisplayName(); string decl = $"public virtual {ntype} {n.Name}"; StringBuilder comment = new StringBuilder(); comment.Append("\r\n\t\t/// <summary>"); comment.Append("\r\n\t\t/// " + n.ForeignKey); comment.Append("\r\n\t\t/// </summary>"); comment.Append("\r\n\t\t" + decl); code = code.Replace(decl, comment.ToString()); } } return(CustomHelpers.copyrightNotice + code); }
/// <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> protected virtual void GenerateProperties([NotNull] IEntityType entityType) { Check.NotNull(entityType, nameof(entityType)); foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal())) { GenerateComment(property.GetComment()); if (_useDataAnnotations) { GeneratePropertyDataAnnotations(property); } _sb.AppendLine($"public {_code.Reference(property.ClrType)} {property.Name} {{ get; set; }}"); } }
private void GenerateSequence(ISequence sequence) { var methodName = nameof(RelationalModelBuilderExtensions.HasSequence); if (sequence.ClrType != Sequence.DefaultClrType) { methodName += $"<{_code.Reference(sequence.ClrType)}>"; } var parameters = _code.Literal(sequence.Name); if (string.IsNullOrEmpty(sequence.Schema) && sequence.Model.Relational().DefaultSchema != sequence.Schema) { parameters += $", {_code.Literal(sequence.Schema)}"; } var lines = new List <string> { $"modelBuilder.{methodName}({parameters})" }; if (sequence.StartValue != Sequence.DefaultStartValue) { lines.Add($".{nameof(SequenceBuilder.StartsAt)}({sequence.StartValue})"); } if (sequence.IncrementBy != Sequence.DefaultIncrementBy) { lines.Add($".{nameof(SequenceBuilder.IncrementsBy)}({sequence.IncrementBy})"); } if (sequence.MinValue != Sequence.DefaultMinValue) { lines.Add($".{nameof(SequenceBuilder.HasMin)}({sequence.MinValue})"); } if (sequence.MaxValue != Sequence.DefaultMaxValue) { lines.Add($".{nameof(SequenceBuilder.HasMax)}({sequence.MaxValue})"); } if (sequence.IsCyclic != Sequence.DefaultIsCyclic) { lines.Add($".{nameof(SequenceBuilder.IsCyclic)}()"); } if (lines.Count == 2) { lines = new List <string> { lines[0] + lines[1] }; } _sb.AppendLine(); _sb.Append(lines[0]); using (_sb.Indent()) { foreach (var line in lines.Skip(1)) { _sb.AppendLine(); _sb.Append(line); } } _sb.AppendLine(";"); }
private void GenerateProcedure(Procedure procedure) { using (_sb.Indent()) { _sb.AppendLine(); var inParams = procedure.Parameters.Where(p => !p.Output); var outParams = procedure.Parameters.Where(p => p.Output); var paramStrings = inParams .Select(p => $"{code.Reference(p.ClrType())} {p.Name}"); var outParamStrings = outParams .Select(p => $"OutputParameter<{code.Reference(p.ClrType())}> {p.Name}"); string line; if (procedure.ResultElements.Count == 0) { line = $"public async Task<int> {GenerateIdentifierName(procedure.Name)}({string.Join(',', paramStrings)}"; } else { line = $"public async Task<{GenerateIdentifierName(procedure.Name)}Result[]> {GenerateIdentifierName(procedure.Name)}({string.Join(',', paramStrings)}"; } if (outParamStrings.Count() > 0) { line += $", {string.Join(',', outParamStrings)}"; } _sb.AppendLine($"{line})"); _sb.AppendLine("{"); using (_sb.Indent()) { foreach (var parameter in procedure.Parameters) { GenerateParameters(parameter); } var paramNames = procedure.Parameters .Select(p => $"parameter{p.Name}"); var paramProcNames = inParams .Select(p => $"@{p.Name}"); var outparamProcNames = outParams .Select(p => $"@{p.Name} OUTPUT"); var outProcs = outparamProcNames.Count() > 0 ? "," : string.Empty; if (procedure.ResultElements.Count == 0) { if (procedure.Parameters.Count == 0) { _sb.AppendLine($"return await _context.Database.ExecuteSqlRawAsync(\"EXEC [{procedure.Schema}].[{procedure.Name}]\");"); } else { _sb.AppendLine($"return await _context.Database.ExecuteSqlRawAsync(\"EXEC [{procedure.Schema}].[{procedure.Name}] {string.Join(',', paramProcNames)}{outProcs} {string.Join(',', outparamProcNames)} \",{string.Join(',', paramNames)});"); } } else { if (procedure.Parameters.Count == 0) { _sb.AppendLine($"var result = await _context.SqlQuery<{GenerateIdentifierName(procedure.Name)}Result>(\"EXEC [{procedure.Schema}].[{procedure.Name}]\");"); } else { _sb.AppendLine($"var result = await _context.SqlQuery<{GenerateIdentifierName(procedure.Name)}Result>(\"EXEC [{procedure.Schema}].[{procedure.Name}] {string.Join(',', paramProcNames)}{outProcs} {string.Join(',', outparamProcNames)} \",{string.Join(',', paramNames)});"); } _sb.AppendLine(); } foreach (var parameter in outParams) { _sb.AppendLine($"{parameter.Name}.SetValueInternal(parameter{parameter.Name}.Value);"); } if (procedure.ResultElements.Count > 0) { _sb.AppendLine($"return result;"); } } _sb.AppendLine("}"); } }
private void GenerateProcedure(Procedure procedure, ProcedureModel model) { var paramStrings = procedure.Parameters.Where(p => !p.Output) .Select(p => $"{code.Reference(p.ClrType())} {p.Name}"); var outParams = procedure.Parameters.Where(p => p.Output).ToList(); var retValueName = outParams.Last().Name; outParams.RemoveAt(outParams.Count - 1); var outParamStrings = outParams .Select(p => $"OutputParameter<{code.Reference(p.ClrType())}> {p.Name}") .ToList(); string fullExec = GenerateProcedureStatement(procedure, retValueName); var identifier = GenerateIdentifierName(procedure, model); var line = GenerateMethodSignature(procedure, outParams, paramStrings, retValueName, outParamStrings, identifier); using (_sb.Indent()) { _sb.AppendLine(); _sb.AppendLine($"{line})"); _sb.AppendLine("{"); using (_sb.Indent()) { foreach (var parameter in procedure.Parameters) { GenerateParameters(parameter); } if (procedure.ResultElements.Count == 0) { _sb.AppendLine($"var _ = await _context.Database.ExecuteSqlRawAsync({fullExec});"); } else { _sb.AppendLine($"var _ = await _context.SqlQueryAsync<{identifier}Result>({fullExec});"); } _sb.AppendLine(); foreach (var parameter in outParams) { _sb.AppendLine($"{parameter.Name}.SetValue(parameter{parameter.Name}.Value);"); } _sb.AppendLine($"{retValueName}?.SetValue(parameter{retValueName}.Value);"); _sb.AppendLine(); _sb.AppendLine("return _;"); } _sb.AppendLine("}"); } }
private void GenerateProcedure(Procedure procedure, ProcedureModel model) { var paramStrings = procedure.Parameters.Where(p => !p.Output) .Select(p => $"{code.Reference(p.ClrType())} {p.Name}"); var paramNames = procedure.Parameters .Select(p => $"parameter{p.Name}"); var paramProcNames = procedure.Parameters.Where(p => !p.Output) .Select(p => $"@{p.Name}"); var outParams = procedure.Parameters.Where(p => p.Output).ToList(); var retValueName = outParams.Last().Name; outParams.RemoveAt(outParams.Count - 1); var outparamProcNames = outParams .Select(p => $"@{p.Name} OUTPUT"); var outParamStrings = outParams .Select(p => $"OutputParameter<{code.Reference(p.ClrType())}> {p.Name}") .ToList(); var outProcs = outparamProcNames.Count() > 0 ? "," : string.Empty; var fullExec = $"\"EXEC @{retValueName} = [{procedure.Schema}].[{procedure.Name}] {string.Join(", ", paramProcNames)}{outProcs} {string.Join(", ", outparamProcNames)}\", {string.Join(", ", paramNames)}".Replace(" \"", "\""); var identifier = GenerateIdentifierName(procedure, model); var line = GenerateMethodSignature(procedure, outParams, paramStrings, retValueName, outParamStrings, identifier); using (_sb.Indent()) { _sb.AppendLine(); _sb.AppendLine($"{line})"); _sb.AppendLine("{"); using (_sb.Indent()) { foreach (var parameter in procedure.Parameters) { GenerateParameters(parameter); } if (procedure.ResultElements.Count == 0) { _sb.AppendLine($"var result = await _context.Database.ExecuteSqlRawAsync({fullExec});"); } else { _sb.AppendLine($"var result = await _context.SqlQuery<{identifier}Result>({fullExec});"); } _sb.AppendLine(); foreach (var parameter in outParams) { _sb.AppendLine($"{parameter.Name}.SetValue(parameter{parameter.Name}.Value);"); } _sb.AppendLine($"{retValueName}?.SetValue(parameter{retValueName}.Value);"); _sb.AppendLine(); _sb.AppendLine("return result;"); } _sb.AppendLine("}"); } }
public string Generate(Type serviceType) { var namespaces = new List <string> { "System.Diagnostics", "System", "XrmFramework" }; namespaces.AddRange(serviceType.GetNamespaces()); if (serviceType.BaseType != null) { namespaces.Add(serviceType.BaseType.Namespace); } namespaces.AddRange(serviceType.GetInterfaces().Select(i => i.Namespace)); namespaces.AddRange(GetNamespaces(serviceType.GetMethods())); namespaces.AddRange(serviceType.GetProperties() .SelectMany(p => p.PropertyType.GetNamespaces() .Concat(GetAttributeNamespaces(p.CustomAttributes)))); var isIService = serviceType.FullName == "XrmFramework.IService"; if (!isIService) { namespaces.Add("XrmFramework.LoggedServices"); } var builder = new IndentedStringBuilder(); foreach (var ns in namespaces.Where(n => !string.IsNullOrEmpty(n)).OrderBy(n => n).Distinct()) { builder .Append("using ") .Append(ns) .AppendLine(";"); } builder .AppendLine() .Append("namespace ") .AppendLine(_code.Namespace(serviceType.Namespace, "LoggedServices")) .AppendLine("{"); using (builder.Indent()) { var className = $"Logged{serviceType.Name.Substring(1)}"; builder .Append("public class ") .Append(_code.Identifier(className)) .Append(" : ") .Append(!isIService ? "LoggedService, " : "LoggedServiceBase, ") .AppendLine(_code.Reference(serviceType)) .AppendLine("{"); using (builder.Indent()) { if (!isIService) { builder .Append("protected new ") .Append(_code.Reference(serviceType)) .Append(" Service => (") .Append(_code.Reference(serviceType)) .AppendLine(") base.Service;"); } builder .AppendLine() .AppendLine("#region .ctor") .Append("public ").Append(_code.Identifier(className)) .Append("(IServiceContext context, ") .Append(_code.Reference(serviceType)) .AppendLine(" service) : base(context, service)"); builder .AppendLine("{") .AppendLine("}") .AppendLine("#endregion"); foreach (var method in serviceType.GetMethods()) { GenerateMethod(method, builder); } } builder.AppendLine("}"); } builder.AppendLine("}"); return(builder.ToString()); }
private void GenerateProcedure(Procedure procedure, ProcedureModel model, bool returnList) { var paramStrings = procedure.Parameters.Where(p => !p.Output) .Select(p => $"{code.Reference(p.ClrType())} {p.Name}") .ToList(); var allOutParams = procedure.Parameters.Where(p => p.Output).ToList(); var outParams = allOutParams.SkipLast(1).ToList(); var retValueName = allOutParams.Last().Name; var outParamStrings = outParams .Select(p => $"OutputParameter<{code.Reference(p.ClrType())}> {p.Name}") .ToList(); string fullExec = GenerateProcedureStatement(procedure, retValueName); var identifier = GenerateIdentifierName(procedure, model); var line = GenerateMethodSignature(procedure, outParams, paramStrings, retValueName, outParamStrings, identifier, returnList); using (_sb.Indent()) { _sb.AppendLine(); _sb.AppendLine(line); _sb.AppendLine("{"); using (_sb.Indent()) { foreach (var parameter in allOutParams) { GenerateParameterVar(parameter); } _sb.AppendLine(); _sb.AppendLine("var sqlParameters = new []"); _sb.AppendLine("{"); using (_sb.Indent()) { foreach (var parameter in procedure.Parameters) { if (parameter.Output) { _sb.Append($"{parameterPrefix}{parameter.Name}"); } else { GenerateParameter(parameter); } _sb.AppendLine(","); } } _sb.AppendLine("};"); if (procedure.HasValidResultSet && procedure.ResultElements.Count == 0) { _sb.AppendLine($"var _ = await _context.Database.ExecuteSqlRawAsync({fullExec});"); } else if (returnList) { _sb.AppendLine($"var _ = await _context.SqlQueryToListAsync<{identifier}Result>({fullExec});"); } else { _sb.AppendLine($"var _ = await _context.SqlQueryAsync<{identifier}Result>({fullExec});"); } _sb.AppendLine(); foreach (var parameter in outParams) { _sb.AppendLine($"{parameter.Name}.SetValue({parameterPrefix}{parameter.Name}.Value);"); } _sb.AppendLine($"{retValueName}?.SetValue({parameterPrefix}{retValueName}.Value);"); _sb.AppendLine(); _sb.AppendLine("return _;"); } _sb.AppendLine("}"); } }
public static void Generate(string loggedServiceFolder, IEnumerable <Type> types, Type iServiceType, Type defaultServiceType, Type iLoggedServiceType) { var namespaceSet = new HashSet <string> { "BoDi" }; var sb = new IndentedStringBuilder(); List <(Type serviceType, Type implementationType)> listServices = new(); var allTypes = iServiceType.Assembly.GetModules().SelectMany(m => m.GetTypes()).ToList(); foreach (var t in types) { namespaceSet.Add(t.Namespace); namespaceSet.Add(Code.Namespace(t.Namespace, "LoggedServices")); foreach (var type in allTypes) { if (t.IsAssignableFrom(type) && !type.IsAbstract && type.IsClass && !iLoggedServiceType.IsAssignableFrom(type) && (t == iServiceType && type == defaultServiceType || t != iServiceType)) { namespaceSet.Add(type.Namespace); listServices.Add((t, type)); } } } foreach (var ns in namespaceSet.OrderBy(n => n)) { sb .Append("using ") .Append(ns) .AppendLine(";"); } sb .AppendLine() .AppendLine("namespace XrmFramework") .AppendLine("{"); using (sb.Indent()) { sb .AppendLine("partial class InternalDependencyProvider") .AppendLine("{"); using (sb.Indent()) { sb .AppendLine("static partial void RegisterServices(IObjectContainer container)") .AppendLine("{"); using (sb.Indent()) { foreach (var service in listServices) { sb .Append("container.RegisterTypeAs<") .Append(Code.Reference(service.implementationType)) .Append(", ") .Append(Code.Reference(service.implementationType)) .AppendLine(">();") .AppendLine() .Append("container.RegisterFactoryAs<") .Append(Code.Reference(service.serviceType)) .AppendLine(">(objectContainer =>") .AppendLine("{"); using (sb.Indent()) { sb .AppendLine("var context = objectContainer.Resolve<IServiceContext>();") .Append("var service = objectContainer.Resolve<") .Append(Code.Reference(service.implementationType)) .AppendLine(">();") .Append("return new ") .Append(GetLogServiceName(service.serviceType.Name)) .AppendLine("(context, service);") .AppendLine(); } sb.AppendLine("});"); } } sb.AppendLine("}"); } sb.AppendLine("}"); } sb.AppendLine("}"); var fileName = Path.Combine(loggedServiceFolder, "InternalDependencyProvider.cs"); File.WriteAllText(fileName, sb.ToString()); }