public void Write(ClassBuilder cb, DatabaseColumn column, string propertyName) { var netName = column.NetName ?? column.Name; //http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx _friendlyName = Regex.Replace(netName, "([A-Z]+|[0-9]+)", " $1", RegexOptions.Compiled).Trim(); if (column.IsPrimaryKey) { cb.AppendLine("[Key]"); } else if (!column.Nullable) { cb.AppendLine("[Required]"); } WriteColumnAttribute(cb, column.Name); if (column.IsAutoNumber) { cb.AppendLine($"[DatabaseGenerated(DatabaseGeneratedOption.Identity)]"); } else if (!string.IsNullOrEmpty(column.DefaultValue)) { cb.AppendLine($"[DatabaseGenerated(DatabaseGeneratedOption.Computed)]"); } if (!string.IsNullOrEmpty(column.Description) && column.Description.StartsWith("[") && column.Description.EndsWith("]")) { cb.AppendLine(column.Description); } }
public static void WriteEntryLogging(ClassBuilder classBuilder, string methodSignature) { var methodName = RegexMethodName.Match(methodSignature).Groups["methodName"].Value; classBuilder.AppendLine($"this._logger.LogTrace(\"Entering {methodName}\");"); classBuilder.AppendLine("var stopwatch = new Stopwatch();"); classBuilder.AppendLine("stopwatch.Start();"); classBuilder.BeginNest("try"); }
public static void WriteExitLogging(ClassBuilder classBuilder, string methodSignature) { var methodName = RegexMethodName.Match(methodSignature).Groups["methodName"].Value; classBuilder.EndNest(); classBuilder.BeginNest("finally"); classBuilder.AppendLine("stopwatch.Stop();"); classBuilder.AppendLine($"this._logger.LogTrace($\"Exiting {methodName}\\t\\t{{stopwatch.ElapsedMilliseconds}}\");"); classBuilder.EndNest(); }
private void WriteRiaClass(string className) { _cb.AppendLine("[MetadataType(typeof(" + className + "." + className + "Metadata))]"); using (_cb.BeginBrace("public partial class " + className)) { //write the buddy class using (_cb.BeginNest("internal sealed class " + className + "Metadata")) { WriteClassMembers(className); } } }
private static void WriteIndex(ClassBuilder cb, DatabaseColumn column) { //EF 6.1 [Index] var table = column.Table; //find all the indexes that contain this column var indexes = table.Indexes.FindAll(x => x.Columns.Contains(column)); var pk = table.PrimaryKey; foreach (var index in indexes) { if (pk != null && pk.Columns.SequenceEqual(index.Columns.Select(c => c.Name))) { //this is the primary key index continue; } var sb = new StringBuilder(); sb.Append("[Index(\"" + index.Name + "\""); var multiColumn = index.Columns.Count > 1; if (multiColumn) { var position = index.Columns.FindIndex(x => Equals(x, column)) + 1; sb.Append(", " + position); } if (index.IsUnique) { //[Index("IdAndRating", 2, IsUnique = true)] sb.Append(", IsUnique = true"); } sb.Append(")]"); cb.AppendLine(sb.ToString()); } }
private void WriteDisplayAttribute(ClassBuilder cb, string name) { if (_friendlyName != name) { cb.AppendLine("[Display(Name=\"" + _friendlyName + "\")]"); } }
public static void WriteFileHeader(ClassBuilder classBuilder) { classBuilder.AppendLine(@"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a Tool. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // // Behavior of class members defined in this file may be changed by overriding in a derived class. // </auto-generated> //------------------------------------------------------------------------------"); }
private void WriteRequiredAttribute(ClassBuilder cb) { var required = "[Required]"; var requiredErrorMessage = _codeWriterSettings.RequiredErrorMessage; if (!string.IsNullOrEmpty(requiredErrorMessage)) { required = "[Required(ErrorMessage=\"" + string.Format(CultureInfo.InvariantCulture, requiredErrorMessage, _friendlyName) + "\")]"; } cb.AppendLine(required); }
private void WriteRegisterRepositories() { using (classBuilder.BeginNest($"public static IServiceCollection AddEnterpriseDataRepositories(this IServiceCollection services)")) { foreach (var t in schema.Tables) { var interfaceName = CodeWriterUtils.GetRepositoryInterfaceName(t); var implementationName = CodeWriterUtils.GetRepositoryImplementationName(t); classBuilder.AppendLine($"services.AddTransient<{interfaceName}, {implementationName}>();"); } classBuilder.AppendLine("return services;"); } classBuilder.AppendLine(""); }
private void WriteStringLengthAttribute(ClassBuilder cb, int?length) { var stringLength = string.Format(CultureInfo.InvariantCulture, "[StringLength({0})]", length); var lengthErrorMessage = _codeWriterSettings.StringLengthErrorMessage; if (!string.IsNullOrEmpty(lengthErrorMessage)) { stringLength = stringLength.Replace(")]", ", ErrorMessage=\"" + string.Format(CultureInfo.InvariantCulture, lengthErrorMessage, length, _friendlyName) + "\")]"); } cb.AppendLine(stringLength); }
private void WriteDecimalRange(ClassBuilder cb, int max) { var maximum = new string('9', max); var range = string.Format(CultureInfo.InvariantCulture, "[Range(typeof(decimal), \"0\", \"{0}\")]", maximum); var rangeErrorMessage = _codeWriterSettings.RangeErrorMessage; if (!string.IsNullOrEmpty(rangeErrorMessage)) { range = range.Replace(")]", ", ErrorMessage=\"" + string.Format(CultureInfo.InvariantCulture, rangeErrorMessage, maximum, _friendlyName) + "\")]"); } cb.AppendLine(range); }
private string Write() { WriteUsings(); using (classBuilder.BeginNest($"namespace {codeWriterSettings.Namespace}")) { using (classBuilder.BeginNest($"public static class {className}")) { using (classBuilder.BeginNest("public static void RegisterEnumerationTypeMappings()")) { WriteMapEnumerations(); classBuilder.AppendLine("NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite();"); } } } return(classBuilder.ToString()); }
private void WriteIntegerRange(ClassBuilder cb, int max) { var maximum = new string('9', max); var range = string.Format(CultureInfo.InvariantCulture, "[Range(0, {0})]", maximum); var rangeErrorMessage = _codeWriterSettings.RangeErrorMessage; if (!string.IsNullOrEmpty(rangeErrorMessage)) { range = range.Replace(")]", ", ErrorMessage=\"" + string.Format(CultureInfo.InvariantCulture, rangeErrorMessage, maximum, _friendlyName) + "\")]"); } cb.AppendLine(range); }
private void WriteDelete() { var methodParameters = CodeWriterUtils.GetDeleteMethodParameters(table, codeWriterSettings, false, false); classBuilder.AppendLine($"{CodeWriterUtils.GetDeleteMethodSignature(table, codeWriterSettings, methodParameters)};"); }
/// <summary> /// Adds the overrides (composite key version) /// </summary> public void AddOverrides() { //if there is no pk, these won't work if (_table is DatabaseView) { _columns = _table.Columns.Where(x => !x.Nullable).ToList(); if (!_columns.Any()) { _columns = _table.Columns; } } else { if (_table.PrimaryKey == null) { return; } _columns = _table.Columns.Where(x => x.IsPrimaryKey).ToList(); } _cb.AppendLine("#region overrides"); AddToString(); AddGetHashCode(); AddEquals(); _cb.AppendLine("#endregion"); }
private void WriteStringLengthAttribute(ClassBuilder cb, int? length) { var stringLength = string.Format(CultureInfo.InvariantCulture, "[StringLength({0})]", length); var lengthErrorMessage = _codeWriterSettings.StringLengthErrorMessage; if (!string.IsNullOrEmpty(lengthErrorMessage)) { stringLength = stringLength.Replace(")]", ", ErrorMessage=\"" + string.Format(CultureInfo.InvariantCulture, lengthErrorMessage, length, _friendlyName) + "\")]"); } cb.AppendLine(stringLength); }
public void Write(ClassBuilder cb, DatabaseColumn column) { var netName = column.NetName ?? column.Name; //http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx _friendlyName = Regex.Replace(netName, "([A-Z]+|[0-9]+)", " $1", RegexOptions.Compiled).Trim(); if (_isNet4) //Display is .Net 4 and Silverlight 3 only { WriteDisplayAttribute(cb, netName); } //we won't mark primary keys as required, because they may be assigned by a ORM primary key strategy or database identity/sequence if (column.IsPrimaryKey) { //.Net 4 and Silverlight 3 only //NOTE: for EF CodeFirst generation, we also mapped fluently. //Despite the duplication, it's useful to have the key as a marker in the model if (_isNet4) cb.AppendLine("[Key]"); } else if (!column.Nullable) WriteRequiredAttribute(cb); //foreign keys will not expose the underlying type if (column.IsForeignKey) return; if (column.IsIndexed && _codeWriterSettings.CodeTarget == CodeTarget.PocoEntityCodeFirst && _codeWriterSettings.WriteCodeFirstIndexAttribute && column.Table != null) { WriteIndex(cb, column); } var dt = column.DataType; if (dt == null) { //it is a database specific type } else if (dt.IsString) { //if it's over a million characters, no point validating if (column.Length < 1073741823 && column.Length > 0) WriteStringLengthAttribute(cb, column.Length); } else if (dt.IsInt) { var max = column.Precision.GetValueOrDefault() - column.Scale.GetValueOrDefault(); if (max > 0 && max < 10) { //int.MaxValue is 2,147,483,647 (precision 10), no need to range WriteIntegerRange(cb, max); } } else if (dt.GetNetType() == typeof(decimal)) { //[Range(typeof(decimal),"0", "999")] var max = column.Precision.GetValueOrDefault() - column.Scale.GetValueOrDefault(); if (max > 0 && max < 28) { WriteDecimalRange(cb, max); } } }
private void WriteColumnAttribute(ClassBuilder cb, string name) { cb.AppendLine($"[Column(\"\\\"{name}\\\"\")]"); }
public override void WriteNamespaces(DatabaseTable table, ClassBuilder classBuilder) { classBuilder.AppendLine("using System.ComponentModel.DataAnnotations.Schema"); }
public string Write() { if (string.IsNullOrEmpty(table.NetName) && table.DatabaseSchema != null) { PrepareSchemaNames.Prepare(table.DatabaseSchema, codeWriterSettings.Namer); } CodeWriterUtils.WriteFileHeader(classBuilder); WriteUsings(); CodeWriterUtils.BeginNestNamespace(classBuilder, codeWriterSettings); classBuilder.AppendXmlSummary($"Class representing the {table.Name} table."); classBuilder.AppendLine($"[Table(\"\\\"{table.Name}\\\"\")]"); using (classBuilder.BeginNest($"public partial class {table.NetName}")) { WriteAllMembers(); } classBuilder.EndNest(); return(classBuilder.ToString()); }
public void Write(ClassBuilder cb, DatabaseColumn column) { var netName = column.NetName ?? column.Name; //http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx _friendlyName = Regex.Replace(netName, "([A-Z]+|[0-9]+)", " $1", RegexOptions.Compiled).Trim(); if (_isNet4) //Display is .Net 4 and Silverlight 3 only { WriteDisplayAttribute(cb, netName); } //we won't mark primary keys as required, because they may be assigned by a ORM primary key strategy or database identity/sequence if (column.IsPrimaryKey) { //.Net 4 and Silverlight 3 only //NOTE: for EF CodeFirst generation, we also mapped fluently. //Despite the duplication, it's useful to have the key as a marker in the model if (_isNet4) { cb.AppendLine("[Key]"); } } else if (!column.Nullable) { WriteRequiredAttribute(cb); } //foreign keys will not expose the underlying type if (column.IsForeignKey) { return; } var dt = column.DataType; if (dt == null) { //it is a database specific type } else if (dt.IsString) { //if it's over a million characters, no point validating if (column.Length < 1073741823 && column.Length > 0) { WriteStringLengthAttribute(cb, column.Length); } } else if (dt.IsInt) { var max = column.Precision.GetValueOrDefault() - column.Scale.GetValueOrDefault(); if (max > 0 && max < 10) { //int.MaxValue is 2,147,483,647 (precision 10), no need to range WriteIntegerRange(cb, max); } } else if (dt.GetNetType() == typeof(decimal)) { //[Range(typeof(decimal),"0", "999")] var max = column.Precision.GetValueOrDefault() - column.Scale.GetValueOrDefault(); if (max > 0 && max < 28) { WriteDecimalRange(cb, max); } } }
private void WriteUsings() { classBuilder.AppendLine("using NpgsqlTypes;"); classBuilder.AppendLine(""); }
public string Write() { //find first table with no dependencies (foreign keys) and a .Net name. var entity = _schema.Tables .FirstOrDefault(t => t.ForeignKeys.Count == 0 && !string.IsNullOrEmpty(t.NetName)); if (entity == null) { return(null); } //we'll also run a sproc if we find one var sproc = _schema.StoredProcedures.FirstOrDefault(p => p.ResultSets.Count > 0); ClassName = entity.NetName + "Test"; WriteNamespaces(sproc != null); using (_cb.BeginNest("namespace " + _codeWriterSettings.Namespace + ".Tests")) { _cb.AppendLine("[TestClass]"); using (_cb.BeginNest("public class " + ClassName)) { WriteStaticConstructor(entity); WriteOpenSession(); WriteGenerateString(); WriteCreateEntity(entity); WriteCrudTest(entity); WriteSproc(sproc); } } return(_cb.ToString()); }
private void WriteDelete(bool isLogicalDelete) { var methodParameters = CodeWriterUtils.GetDeleteMethodParameters(table, codeWriterSettings, false, false); if (isLogicalDelete) { WriteDeleteLogical(methodParameters); classBuilder.AppendLine(""); } WriteDeletePhysical(methodParameters); classBuilder.AppendLine(""); WriteDeleteCommon(methodParameters, isLogicalDelete); }