public ForeignKeyException(Exception inner) : base(null, inner) { Match m = indexRegex.Match(inner.Message); if (m.Success) { TableName = m.Groups["table"].Value; Field = m.Groups["field"].Value; TableType = Schema.Current.Tables .Where(kvp => kvp.Value.Name.Name == TableName) .Select(p => p.Key) .SingleOrDefaultEx(); } if (inner.Message.Contains("INSERT")) { IsInsert = true; Match m2 = referedTable.Match(inner.Message); if (m2.Success) { ReferedTableName = m2.Groups["referedTable"].Value.Split('.').Last(); ReferedTableType = Schema.Current.Tables .Where(kvp => kvp.Value.Name.Name == ReferedTableName) .Select(p => p.Key) .SingleOrDefaultEx(); ReferedTableType = EnumEntity.Extract(ReferedTableType) ?? ReferedTableType; } } }
public AttributeCollection TypeAttributes(Type entityType) { if (!typeof(Entity).IsAssignableFrom(entityType) && !typeof(IView).IsAssignableFrom(entityType)) { throw new InvalidOperationException("{0} is not an Entity or View".FormatWith(entityType.Name)); } if (entityType.IsAbstract) { throw new InvalidOperationException("{0} is abstract".FormatWith(entityType.Name)); } return(TypeAttributesCache.GetOrAdd(entityType, t => { var list = entityType.GetCustomAttributes(true).Cast <Attribute>().ToList(); var enumType = EnumEntity.Extract(entityType); if (enumType != null) { foreach (var at in enumType.GetCustomAttributes(true).Cast <Attribute>().ToList()) { list.RemoveAll(a => a.GetType() == at.GetType()); list.Add(at); } } return new AttributeCollection(AttributeTargets.Class, list, () => AssertNotIncluded(entityType)); })); }
public static TypeAllowedAndConditions GetAllowed(Type type) { if (!AuthLogic.IsEnabled || ExecutionMode.InGlobal) { return(new TypeAllowedAndConditions(TypeAllowed.Write)); } if (!TypeLogic.TypeToEntity.ContainsKey(type)) { return(new TypeAllowedAndConditions(TypeAllowed.Write)); } if (EnumEntity.Extract(type) != null) { return(new TypeAllowedAndConditions(TypeAllowed.Read)); } TypeAllowed?temp = TypeAuthLogic.GetTemporallyAllowed(type); if (temp.HasValue) { return(new TypeAllowedAndConditions(temp.Value)); } return(cache.GetAllowed(RoleEntity.Current, type)); }
public static string GetNiceName(object queryName) { return (queryName is Type t ? (EnumEntity.Extract(t) ?? t).NicePluralName() : queryName is Enum e?e.NiceToString() : queryName.ToString() !); }
internal static SchemaMapInfo GetMapInfo() { var getStats = GetRuntimeStats(); var s = Schema.Current; var nodes = (from t in s.Tables.Values where s.IsAllowed(t.Type, true) == null let type = EnumEntity.Extract(t.Type) ?? t.Type select new TableInfo { typeName = TypeLogic.GetCleanName(t.Type), niceName = type.NiceName(), tableName = t.Name.ToString(), columns = t.Columns.Count, entityData = EntityKindCache.GetEntityData(t.Type), entityKind = EntityKindCache.GetEntityKind(t.Type), entityBaseType = GetEntityBaseType(t.Type), @namespace = type.Namespace !, rows = getStats.TryGetC(t.Name)?.rows, total_size_kb = getStats.TryGetC(t.Name)?.total_size_kb, rows_history = t.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.rows), total_size_kb_history = t.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.total_size_kb), mlistTables = t.TablesMList().Select(ml => new MListTableInfo { niceName = ml.PropertyRoute.PropertyInfo !.NiceName(), tableName = ml.Name.ToString(), rows = getStats.TryGetC(ml.Name)?.rows, total_size_kb = getStats.TryGetC(ml.Name)?.total_size_kb, history_rows = ml.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.rows), history_total_size_kb = ml.SystemVersioned?.Let(sv => getStats.TryGetC(sv.TableName)?.total_size_kb), columns = ml.Columns.Count, }).ToList()
static string? GetSchemaNameName(Type type) { type = EnumEntity.Extract(type) ?? type; if (type == typeof(ColumnOptionsMode) || type == typeof(FilterOperation) || type == typeof(PaginationMode) || type == typeof(OrderType)) type = typeof(UserQueryEntity); if (type == typeof(SmtpDeliveryFormat) || type == typeof(SmtpDeliveryMethod) || type == typeof(ExchangeVersion)) type = typeof(EmailMessageEntity); if (type == typeof(DayOfWeek)) type = typeof(ScheduledTaskEntity); if (type.Assembly == typeof(ApplicationConfigurationEntity).Assembly) return null; if (type.Assembly == typeof(DashboardEntity).Assembly) { var name = type.Namespace!.Replace("Signum.Entities.", ""); name = (name.TryBefore('.') ?? name); if (name == "SMS") return "sms"; if (name == "Authorization") return "auth"; return name.FirstLower(); } if (type.Assembly == typeof(Entity).Assembly) return "framework"; throw new InvalidOperationException("Impossible to determine SchemaName for {0}".FormatWith(type.FullName)); }
public static SqlPreCommand?InsertEnumValuesScript() { return((from t in Schema.Current.Tables.Values let enumType = EnumEntity.Extract(t.Type) where enumType != null select EnumEntity.GetEntities(enumType).Select((e, i) => t.InsertSqlSync(e, suffix: t.Name.Name + i)).Combine(Spacing.Simple) ).Combine(Spacing.Double)?.PlainSqlCommand()); }
public virtual ObjectName GenerateTableName(Type type, TableNameAttribute tn) { SchemaName sn = tn != null?GetSchemaName(tn) : SchemaName.Default; string name = tn?.Name ?? EnumEntity.Extract(type)?.Name ?? Reflector.CleanTypeName(type); return(new ObjectName(sn, name)); }
public static string GetCleanName(object queryName) { if (queryName is Type) { queryName = EnumEntity.Extract((Type)queryName) ?? (Type)queryName; } return(queryName is Type ? Reflector.CleanTypeName((Type)queryName) : queryName.ToString()); }
public TypeAllowedAndConditions GetValue(Type type) { if (EnumEntity.Extract(type) != null) { return(new TypeAllowedAndConditions(TypeAllowed.Read)); } return(Allowed); }
internal static List <TypeEntity> GenerateSchemaTypes() { var list = (from tab in Schema.Current.Tables.Values let type = EnumEntity.Extract(tab.Type) ?? tab.Type select new TypeEntity { TableName = tab.Name.ToString(), CleanName = Reflector.CleanTypeName(type), Namespace = type.Namespace !, ClassName = type.Name, }).ToList();
public static string GetQueryUniqueKey(object queryName) { if (queryName is Type) { queryName = EnumEntity.Extract((Type)queryName) ?? (Type)queryName; } return (queryName is Type ? ((Type)queryName).FullName : queryName is Enum ? "{0}.{1}".FormatWith(queryName.GetType().Name, queryName.ToString()) : queryName.ToString()); }
public static string GetNiceName(object queryName, CultureInfo ci) { if (queryName is Type) { queryName = EnumEntity.Extract((Type)queryName) ?? (Type)queryName; } return (queryName is Type ? ((Type)queryName).NicePluralName() : queryName is Enum ? ((Enum)queryName).NiceToString() : queryName.ToString()); }
static Reflector() { DescriptionManager.CleanTypeName = CleanTypeName; //To allow MyEntityEntity DescriptionManager.CleanType = t => EnumEntity.Extract(t) ?? t.CleanType(); //To allow Lite<T> DescriptionManager.DefaultDescriptionOptions += DescriptionManager_IsEnumsInEntities; DescriptionManager.DefaultDescriptionOptions += DescriptionManager_IsQuery; DescriptionManager.DefaultDescriptionOptions += DescriptionManager_IsSymbolContainer; DescriptionManager.DefaultDescriptionOptions += DescriptionManager_IsIEntity; DescriptionManager.ShouldLocalizeMemeber += DescriptionManager_ShouldLocalizeMemeber; DescriptionManager.Invalidate(); }
internal static List <TypeEntity> GenerateSchemaTypes() { var list = (from tab in Schema.Current.Tables.Values let type = EnumEntity.Extract(tab.Type) ?? tab.Type select new TypeEntity { FullClassName = type.FullName, TableName = tab.Name.Name, CleanName = Reflector.CleanTypeName(type) }).ToList(); return(list); }
public TypeCaches(Schema current) { TypeToEntity = EnumerableExtensions.JoinRelaxed( Database.RetrieveAll <TypeEntity>(), current.Tables.Keys, t => t.FullClassName, t => (EnumEntity.Extract(t) ?? t).FullName, (typeEntity, type) => new { typeEntity, type }, "caching {0}".FormatWith(current.Table(typeof(TypeEntity)).Name) ).ToDictionary(a => a.type, a => a.typeEntity); EntityToType = TypeToEntity.Inverse(); TypeToId = TypeToEntity.SelectDictionary(k => k, v => v.Id); IdToType = TypeToId.Inverse(); }
public TypeHelpTS GetTypeHelp(string typeName, TypeHelpMode mode) { Type type = TypeLogic.TryGetType(typeName); if (type == null) { return(null); } var isEnum = EnumEntity.IsEnumEntity(type); var members = new List <TypeMemberHelpTS>(); if (isEnum) { var enumType = EnumEntity.Extract(type); var values = EnumEntity.GetValues(enumType).ToList(); members.AddRange(values.Select(ev => new TypeMemberHelpTS(ev))); } else { var routes = PropertyRoute.GenerateRoutes(type); var root = TreeHelper.ToTreeC(routes, a => a.Parent).SingleEx(); members = root.Children .Where(a => mode == TypeHelpMode.CSharp || ReflectionServer.InTypeScript(a.Value)) .Select(pr => new TypeMemberHelpTS(pr, mode)).ToList(); if (mode == TypeHelpMode.CSharp) { var expressions = DynamicQueryManager.Current.RegisteredExtensions.GetValue(type); members.AddRange(expressions.Values.Select(ex => new TypeMemberHelpTS(ex))); } } return(new TypeHelpTS { type = (isEnum ? EnumEntity.Extract(type).Name : type.Name), cleanTypeName = typeName, isEnum = isEnum, members = members }); }
public virtual string GenerateMListFieldName(PropertyRoute route, KindOfField kindOfField) { Type type = Lite.Extract(route.Type) ?? route.Type; switch (kindOfField) { case KindOfField.Value: case KindOfField.Embedded: return(type.Name.FirstUpper()); case KindOfField.Enum: case KindOfField.Reference: return((EnumEntity.Extract(type)?.Name ?? Reflector.CleanTypeName(type)) + "ID"); default: throw new InvalidOperationException("No field name for type {0} defined".FormatWith(type)); } }
public ForeignKeyException(Exception inner) : base(null, inner) { Match m = indexRegex.Match(inner.Message); if (m.Success) { var parts = m.Groups["parts"].Value.Split("_"); for (int i = 1; i < parts.Length; i++) { TableName = parts.Take(i).ToString("_"); ColumnName = parts.Skip(i).ToString("_"); TableType = Schema.Current.Tables .Where(kvp => kvp.Value.Name.Name == TableName) .Select(p => p.Key) .SingleOrDefaultEx(); if (TableType != null) { break; } } } if (inner.Message.Contains("INSERT") || inner.Message.Contains("UPDATE")) { IsInsert = true; Match m2 = referedTable.Match(inner.Message); if (m2.Success) { ReferedTableName = m2.Groups["referedTable"].Value.Split('.').Last(); ReferedTableType = Schema.Current.Tables .Where(kvp => kvp.Value.Name.Name == ReferedTableName) .Select(p => p.Key) .SingleOrDefaultEx(); ReferedTableType = ReferedTableType == null ? null : EnumEntity.Extract(ReferedTableType) ?? ReferedTableType; } } }
protected static Type CleanType(Type type) { type = Lite.Extract(type) ?? type; type = EnumEntity.Extract(type) ?? type; return(type); }
public static string GetKey(object queryName) { return(queryName is Type t?Reflector.CleanTypeName(EnumEntity.Extract(t) ?? t) : queryName.ToString() !); }
public override string NiceName() { var cleanType = EnumEntity.Extract(entityType) ?? entityType; return(QueryTokenMessage._0As1.NiceToString().FormatWith(Parent.ToString(), cleanType.NiceName())); }
public Dictionary <string, object> GetQueries() { return(queries.GetOrAdd(CultureInfo.CurrentCulture, ci => GetAllQueryNames().ToOmniboxPascalDictionary(qn => qn is Type t ? (EnumEntity.Extract(t) ?? t).NiceName() : QueryUtils.GetNiceName(qn), qn => qn))); }
public static Dictionary <TypeEntity, Type> TryEntityToType(Replacements replacements) { return((from dn in Administrator.TryRetrieveAll <TypeEntity>(replacements) join t in Schema.Current.Tables.Keys on dn.FullClassName equals(EnumEntity.Extract(t) ?? t).FullName select(dn, t)).ToDictionary(a => a.dn, a => a.t)); }
internal static SchemaMapInfo GetMapInfo(out List <MapColorProvider> providers) { var getStats = GetRuntimeStats(); var nodes = (from t in Schema.Current.Tables.Values let type = EnumEntity.Extract(t.Type) ?? t.Type select new TableInfo { findUrl = Finder.IsFindable(t.Type) ? Finder.FindRoute(t.Type) : null, webTypeName = Navigator.ResolveWebTypeName(t.Type), niceName = type.NiceName(), tableName = t.Name.ToString(), columns = t.Columns.Count, entityData = EntityKindCache.GetEntityData(t.Type), entityKind = EntityKindCache.GetEntityKind(t.Type), entityBaseType = GetEntityBaseType(t.Type), @namespace = type.Namespace, rows = getStats.GetOrThrow(t.Name).rows, total_size_kb = getStats.GetOrThrow(t.Name).total_size_kb, mlistTables = t.TablesMList().Select(ml => new MListTableInfo { niceName = ml.Field.Route.PropertyInfo.NiceName(), tableName = ml.Name.ToString(), rows = getStats.GetOrThrow(t.Name).rows, total_size_kb = getStats.GetOrThrow(t.Name).total_size_kb, columns = ml.Columns.Count, }).ToList() }).ToList(); providers = MapClient.GetColorProviders.GetInvocationListTyped().SelectMany(f => f()).OrderBy(a => a.Order).ToList(); var extraActions = providers.Select(a => a.AddExtra).NotNull().ToList(); if (extraActions.Any()) { foreach (var n in nodes) { foreach (var action in extraActions) { action(n); } } } var normalEdges = (from t in Schema.Current.Tables.Values from kvp in t.DependentTables() where !kvp.Value.IsCollection select new RelationInfo { fromTable = t.Name.ToString(), toTable = kvp.Key.Name.ToString(), lite = kvp.Value.IsLite, nullable = kvp.Value.IsNullable }).ToList(); var mlistEdges = (from t in Schema.Current.Tables.Values from tm in t.TablesMList() from kvp in tm.GetTables() select new RelationInfo { fromTable = tm.Name.ToString(), toTable = kvp.Key.Name.ToString(), lite = kvp.Value.IsLite, nullable = kvp.Value.IsNullable }).ToList(); return(new SchemaMapInfo { tables = nodes, relations = normalEdges.Concat(mlistEdges).ToList() }); }
static SqlPreCommand SynchronizeEnumsScript(Replacements replacements) { Schema schema = Schema.Current; List <SqlPreCommand> commands = new List <SqlPreCommand>(); foreach (var table in schema.Tables.Values) { Type enumType = EnumEntity.Extract(table.Type); if (enumType != null) { IEnumerable <Entity> should = EnumEntity.GetEntities(enumType); Dictionary <string, Entity> shouldByName = should.ToDictionary(a => a.ToString()); List <Entity> current = Administrator.TryRetrieveAll(table.Type, replacements); Dictionary <string, Entity> currentByName = current.ToDictionaryEx(a => a.toStr, table.Name.Name); string key = Replacements.KeyEnumsForTable(table.Name.Name); replacements.AskForReplacements(currentByName.Keys.ToHashSet(), shouldByName.Keys.ToHashSet(), key); currentByName = replacements.ApplyReplacementsToOld(currentByName, key); var mix = shouldByName.JoinDictionary(currentByName, (n, s, c) => new { s, c }).Where(a => a.Value.s.id != a.Value.c.id).ToDictionary(); HashSet <PrimaryKey> usedIds = current.Select(a => a.Id).ToHashSet(); Dictionary <string, Entity> middleByName = mix.Where(kvp => usedIds.Contains(kvp.Value.s.Id)).ToDictionary(kvp => kvp.Key, kvp => Clone(kvp.Value.c)); if (middleByName.Any()) { var moveToAux = SyncEnums(schema, table, currentByName.Where(a => middleByName.ContainsKey(a.Key)).ToDictionary(), middleByName); if (moveToAux != null) { commands.Add(moveToAux); } } var com = SyncEnums(schema, table, currentByName.Where(a => !middleByName.ContainsKey(a.Key)).ToDictionary(), shouldByName.Where(a => !middleByName.ContainsKey(a.Key)).ToDictionary()); if (com != null) { commands.Add(com); } if (middleByName.Any()) { var backFromAux = SyncEnums(schema, table, middleByName, shouldByName.Where(a => middleByName.ContainsKey(a.Key)).ToDictionary()); if (backFromAux != null) { commands.Add(backFromAux); } } } } return(SqlPreCommand.Combine(Spacing.Double, commands.ToArray())); }
internal protected virtual Table Include(Type type, PropertyRoute route) { if (schema.Tables.TryGetValue(type, out Table result)) { return(result); } using (HeavyProfiler.LogNoStackTrace("Include", () => type.TypeName())) { if (type.IsAbstract) { throw new InvalidOperationException(route?.Let(r => "Error on field {0}: ".FormatWith(r)) + "Impossible to include in the Schema the type {0} because is abstract".FormatWith(type)); } if (!Reflector.IsEntity(type)) { throw new InvalidOperationException(route?.Let(r => "Error on field {0}: ".FormatWith(r)) + "Impossible to include in the Schema the type {0} because is not and Entity".FormatWith(type)); } foreach (var t in type.Follow(a => a.BaseType)) { if (!t.IsSerializable) { throw new InvalidOperationException("Type {0} is not marked as serializable".FormatWith(t.TypeName())); } } string name = schema.Settings.desambiguatedNames?.TryGetC(type) ?? Reflector.CleanTypeName(EnumEntity.Extract(type) ?? type); if (schema.NameToType.ContainsKey(name)) { throw new InvalidOperationException(route?.Let(r => "Error on field {0}: ".FormatWith(r)) + "Two types have the same cleanName, desambiguate using Schema.Current.Settings.Desambiguate method: \r\n {0}\r\n {1}".FormatWith(schema.NameToType[name].FullName, type.FullName)); } try { result = new Table(type); schema.Tables.Add(type, result); schema.NameToType[name] = type; schema.TypeToName[type] = name; Complete(result); return(result); } catch (Exception) //Avoid half-cooked tables { schema.Tables.Remove(type); schema.NameToType.Remove(name); schema.TypeToName.Remove(type); throw; } } }
internal protected virtual Table Include(Type type, PropertyRoute?route) { if (schema.Tables.TryGetValue(type, out var result)) { return(result); } if (this.Schema.IsCompleted) //Below for nop includes of Views referencing lites or entities { throw new InvalidOperationException("Schema already completed"); } using (HeavyProfiler.LogNoStackTrace("Include", () => type.TypeName())) { if (type.IsAbstract) { throw new InvalidOperationException(ErrorIncluding(route) + $"Impossible to include in the Schema the type {type} because is abstract"); } if (!Reflector.IsEntity(type)) { throw new InvalidOperationException(ErrorIncluding(route) + $"Impossible to include in the Schema the type {type} because is not and Entity"); } foreach (var t in type.Follow(a => a.BaseType)) { if (!t.IsSerializable) { throw new InvalidOperationException(ErrorIncluding(route) + $"Type {t.TypeName()} is not marked as serializable"); } } string cleanName = schema.Settings.desambiguatedNames?.TryGetC(type) ?? Reflector.CleanTypeName(EnumEntity.Extract(type) ?? type); if (schema.NameToType.ContainsKey(cleanName)) { throw new InvalidOperationException(ErrorIncluding(route) + @$ "Two types have the same cleanName '{cleanName}', desambiguate using Schema.Current.Settings.Desambiguate method: {schema.NameToType[cleanName].FullName} {type.FullName}"); } try { result = new Table(type); schema.Tables.Add(type, result); schema.NameToType[cleanName] = type; schema.TypeToName[type] = cleanName; Complete(result); return(result); } catch (Exception) //Avoid half-cooked tables { schema.Tables.Remove(type); schema.NameToType.Remove(cleanName); schema.TypeToName.Remove(type); throw; } } }