public static string CreateManyToOneAssociation(this TableData table, TableData foreignTable, string primaryKeyName, string foreignKeyName, bool backwardReference = false) { // use the foreign table's type name as property name var propertyName = table.FindFreePropertyName(foreignTable.TypeBuilder.Name); table.PropertyAndFieldNames.Add(propertyName); // create a property of the foreign table's type in the table entity var property = table.TypeBuilder.DefineProperty(propertyName, foreignTable.TypeBuilder); // create a getter for the property var propertyGetter = table.TypeBuilder.DefineGetter(property); // obtain ResolveManyToOne method var resolveManyToOneMethod = typeof(Entity).GetMethod("ResolveManyToOne", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(property.PropertyType); // "implement" the method to obtain and return the value by calling 'ResolveManyToOne' var ilGenerator = propertyGetter.GetILGenerator(); // call the method and return the value ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldstr, property.Name); ilGenerator.Emit(OpCodes.Call, resolveManyToOneMethod); ilGenerator.Emit(OpCodes.Ret); property.SetGetMethod(propertyGetter); // add the 'AssociationAttribute' to the property property.AddAssociationAttribute(foreignKeyName, primaryKeyName, foreignTable.Name, true); // create the explorer item var explorerItem = new ExplorerItem(propertyName, ExplorerItemKind.ReferenceLink, ExplorerIcon.ManyToOne); table.ExplorerItem.Children.Add(explorerItem); return property.Name; }
static ExplorerItem ToExplorerItem(PropertyInfo p, int level) { Type t = p.PropertyType; if (t.IsEnum || t.IsPrimitive || typeof(IFormattable).IsAssignableFrom(t)) return ToSimpleExplorerItem(p); Type elementType = GetLatentSequenceElementType(t); bool isLatentSequence = elementType != null; if (elementType == null) elementType = GetEnumerableElementType(t); if (elementType != null && !elementType.Namespace.StartsWith(Linq2AzureNamespace) || elementType == null && !t.Namespace.StartsWith(Linq2AzureNamespace)) return ToSimpleExplorerItem(p); var item = new ExplorerItem( p.Name, ExplorerItemKind.QueryableObject, elementType == null ? ExplorerIcon.OneToOne : level == 0 ? ExplorerIcon.Table : ExplorerIcon.OneToMany) { ToolTipText = FormatTypeName(t), IsEnumerable = elementType != null && level == 0 }; item.DragText = item.Text + (isLatentSequence ? ".AsObservable()" : ""); if (level < 10) item.Children = GetSchema(elementType ?? t, level + 1); return item; }
public TableData(string name, ExplorerItem explorerItem, TypeBuilder typeBuilder, ISet<string> propertyAndFieldNames) { Name = name; ExplorerItem = explorerItem; TypeBuilder = typeBuilder; PropertyAndFieldNames = propertyAndFieldNames; }
public virtual List<ExplorerItem> BuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName) { var unit = new CodeCompileUnit(); var namespace2 = new CodeNamespace(nameSpace); namespace2.Imports.Add(new CodeNamespaceImport("System")); namespace2.Imports.Add(new CodeNamespaceImport("System.Linq")); namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch")); namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch.SearchTypes")); var settings = new SitecoreConnectionSettings(); var mapper = new DriverDataCxSettingsMapper(); mapper.Read(cxInfo, settings); var selectedType = settings.SearchResultType.GetSelectedType(); namespace2.Imports.Add(new CodeNamespaceImport(selectedType.Namespace)); var declaration = new CodeTypeDeclaration(typeName) { IsClass = true, TypeAttributes = TypeAttributes.Public }; namespace2.Types.Add(declaration); unit.Namespaces.Add(namespace2); var constructor = new CodeConstructor { Attributes = MemberAttributes.Public }; this.AddConstructorCode(constructor, settings); declaration.Members.Add(constructor); var indexNames = this.GetIndexNames(cxInfo); var list = new List<ExplorerItem>(); foreach (var str in indexNames) { this.AddIndexAsProperty(str, selectedType, declaration); var item = new ExplorerItem(str, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = false }; item.DragText = this.GetDragText(item, settings); list.Add(item); } var provider = new CSharpCodeProvider(); var options = new CompilerParameters(); var assemblyFilesToReference = this.GetAssemblyFilesToReference(settings); foreach (var str2 in assemblyFilesToReference) { options.ReferencedAssemblies.Add(str2); } options.GenerateInMemory = true; options.OutputAssembly = assemblyToBuild.CodeBase; var results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { unit }); if (results.Errors.Count > 0) { throw new Exception(string.Concat(new object[] { "Cannot compile typed context: ", results.Errors[0].ErrorText, " (line ", results.Errors[0].Line, ")" })); } return list; }
private static string GetItemText(LINQPad.Extensibility.DataContext.ExplorerItem item, bool sqlMode) { if (!(sqlMode && !string.IsNullOrEmpty(item.SqlName))) { return(item.Text); } string sqlName = item.SqlName; if (!string.IsNullOrEmpty(item.SqlTypeDeclaration)) { sqlName = sqlName + " (" + item.SqlTypeDeclaration + ")"; } return(sqlName); }
public ExplorerItem EmitCodeAndGetExplorerItemTree(TypeBuilder dataContextTypeBuilder) { var query = SqlHelper.LoadSql("QueryTables.sql"); var tables = connection.Query(query); var explorerItems = new List<ExplorerItem>(); foreach (var group in tables.GroupBy(t => t.TableCatalog)) { var databaseName = group.Key; var preparedTables = new List<TableData>(); foreach (var table in group.OrderBy(t => t.TableName)) { var unmodifiedTableName = (string)table.TableName; var tableName = cxInfo.GetTableName(unmodifiedTableName); var explorerItem = new ExplorerItem(tableName, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = true, Children = new List<ExplorerItem>(), DragText = tableName, SqlName = $"\"{unmodifiedTableName}\"" }; var tableData = PrepareTableEntity(cxInfo, moduleBuilder, connection, nameSpace, databaseName, unmodifiedTableName, explorerItem); preparedTables.Add(tableData); } // build the associations before the types are created BuildAssociations(connection, preparedTables); foreach (var tableData in preparedTables) { dataContextTypeBuilder.CreateAndAddType(tableData); explorerItems.Add(tableData.ExplorerItem); } } return new ExplorerItem("Tables", ExplorerItemKind.Category, ExplorerIcon.Table) { IsEnumerable = true, Children = explorerItems }; }
static ExplorerItem CreateExplorerOperation(Type serviceType, OperationBinding operation) { var method = serviceType.GetMethod(operation.Name); var parameters = method.GetParameters(); var description = operation.DocumentationElement == null ? "" : operation.DocumentationElement.InnerText; var item = new ExplorerItem(operation.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.StoredProc) { ToolTipText = description, DragText = GetMethodCallString(method.Name, from p in parameters select p.Name), Children = ( from p in parameters select new ExplorerItem(p.Name, ExplorerItemKind.Parameter, ExplorerIcon.Parameter) ).ToList() }; return item; }
private ExplorerItemNode FindExplorerItemNode(TreeNode parent, ExplorerItem item) { foreach (ExplorerItemNode node in parent.Nodes.OfType<ExplorerItemNode>()) { if (node.ExplorerItem == item) { return node; } } foreach (TreeNode node3 in parent.Nodes) { ExplorerItemNode node4 = this.FindExplorerItemNode(node3, item); if (node4 != null) { return node4; } } return null; }
public static string CreateOneToManyAssociation(this TableData table, TableData foreignTable, string primaryKeyName, string foreignKeyName) { // create an IEnumerable<> with the type of the (main) table's type builder var typedEnumerableType = typeof(IEnumerable<>).MakeGenericType(table.TypeBuilder); // use the table's explorer item text as property name var propertyName = foreignTable.FindFreePropertyName(table.ExplorerItem.Text); foreignTable.PropertyAndFieldNames.Add(propertyName); // create a property in the foreign key's target table var property = foreignTable.TypeBuilder.DefineProperty(propertyName, typedEnumerableType); // create a getter for the property var propertyGetter = foreignTable.TypeBuilder.DefineGetter(property); // obtain ResolveOneToMany method var resolveOneToManyMethod = typeof(Entity).GetMethod("ResolveOneToMany", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(table.TypeBuilder); // "implement" the method to obtain and return the value by calling 'ResolveOneToMany' var ilGenerator = propertyGetter.GetILGenerator(); // call the method and return the value ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldstr, property.Name); ilGenerator.Emit(OpCodes.Call, resolveOneToManyMethod); ilGenerator.Emit(OpCodes.Ret); property.SetGetMethod(propertyGetter); // add the 'AssociationAttribute' to the property property.AddAssociationAttribute(primaryKeyName, foreignKeyName, table.Name); // create the explorer item var explorerItem = new ExplorerItem(propertyName, ExplorerItemKind.CollectionLink, ExplorerIcon.OneToMany); foreignTable.ExplorerItem.Children.Add(explorerItem); // create 'backward' association table.CreateManyToOneAssociation(foreignTable, primaryKeyName, foreignKeyName, true); return propertyName; }
public override List<ExplorerItem> GetSchema(IConnectionInfo cxInfo, Type customType) { var result = new List<ExplorerItem>(); var logsTable = new ExplorerItem("Logs", ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = true,DragText = "Logs" }; var properties = typeof (LogEntry).GetProperties() .Select(p => new ExplorerItem(p.Name, ExplorerItemKind.Property, ExplorerIcon.Column)) .ToList(); logsTable.Children = properties; result.Add(logsTable); var filesItem = new ExplorerItem("Files", ExplorerItemKind.Category, ExplorerIcon.Box); filesItem.Children = DirectoryHelper.GetActiveFiles(new Log4jConnectionProperties(cxInfo)) .Select(f => new ExplorerItem(f, ExplorerItemKind.Schema, ExplorerIcon.Schema)).ToList(); result.Add(filesItem); result.Add(new ExplorerItem("ClearCache", ExplorerItemKind.QueryableObject, ExplorerIcon.StoredProc){DragText = "ClearCache()"}); return result; }
//----------------------------------------------------------------------------------------------------------------------------------------------------- private List<ExplorerItem> BuildSchema(IEdmModel model) { var rootItems = new List<ExplorerItem>(); var entityItemsByEntityType = new Dictionary<IEdmEntityType, ExplorerItem>(); var allEntityTypes = model.SchemaElements.OfType<IEdmEntityType>().ToArray(); foreach ( var entityType in allEntityTypes ) { var entityItem = new ExplorerItem(entityType.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table); entityItem.ToolTipText = entityType.FullTypeName(); entityItem.Children = new List<ExplorerItem>(); entityItemsByEntityType.Add(entityType, entityItem); foreach ( var property in entityType.Properties() ) { string itemText; string itemTooltip; ExplorerItemKind itemKind; ExplorerIcon itemIcon; SetPropertyItemStyle(entityType, property, out itemText, out itemTooltip, out itemKind, out itemIcon); var propertyItem = new ExplorerItem(itemText, itemKind, itemIcon); var navigationProperty = (property as IEdmNavigationProperty); if ( navigationProperty != null ) { propertyItem.Tag = navigationProperty.ToEntityType(); } propertyItem.ToolTipText = itemTooltip; entityItem.Children.Add(propertyItem); } rootItems.Add(entityItem); } FixupNavigationLinks(rootItems, entityItemsByEntityType); return rootItems; }
public List<ExplorerItem> BuildSchema() { // Create a ExplorerItem for each persistable type. List<ExplorerItem> lSchema = ( from Type lType in schema.PersistableTypes let lName = schema.TypesNameToPluralName[lType.FullName] orderby lName select new ExplorerItem(lName, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = true, // Use tag to create lookup below. Tag = lType }).ToList(); // Lookup from items to types. This helps creating links between Schema items. var lItemLookup = lSchema.ToLookup(lItem => ((Type)lItem.Tag)); foreach (ExplorerItem lItem in lSchema) { Type lType = (Type)lItem.Tag; // Create a element schema for each persistable type. ExplorerItem lElementProperties = new ExplorerItem( //schema.TypesNameToPluralName[lType.ToGenericTypeString()] + " Properties", lType.ToGenericTypeString() + " Properties", ExplorerItemKind.Schema, ExplorerIcon.Schema); lItem.Children = new List<ExplorerItem> { lElementProperties }; // Fill the element schema with ExplorerItems based on // fields and properties of Type. lElementProperties.Children = SchemaExtractor.GetDataMembers(lType) .OrderBy(lChildMember => lChildMember.Name) .Select(lChildMember => GetChildItem(lItemLookup, lType, lChildMember)) .OrderBy(lChildItem => lChildItem.Kind) .ToList(); } return lSchema; }
private ExplorerItem CreateNamespace(string name, List<ExplorerItem> root) { ExplorerItem item = null; List<ExplorerItem> currentScope = root; string[] tokens = name.Split('.'); for (int i = 1; i < tokens.Length; i++) { string token = tokens[i]; item = currentScope.FirstOrDefault(ei => ei.Text == token); if (item == null) { item = new ExplorerItem(token, ExplorerItemKind.Schema, ExplorerIcon.Schema); item.Children = new List<ExplorerItem>(); currentScope.Add(item); } currentScope = item.Children; } return item; }
private List<ExplorerItem> CreateTree(Dictionary<Type, long> stat) { var result = new List<ExplorerItem>(); KeyValuePair<Type, long>[] x = (from pair in stat orderby pair.Key.Namespace, pair.Key.Name select pair).ToArray(); string currentNamespace = null; ExplorerItem scope = null; foreach (var pair in x) { if (pair.Key.Namespace != currentNamespace) { scope = CreateNamespace(pair.Key.Namespace, result); currentNamespace = pair.Key.Namespace; } ; var eventType = new ExplorerItem(pair.Key.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table); eventType.ToolTipText = "Occurences: " + pair.Value + "\n"; foreach (object a in pair.Key.GetCustomAttributes(false).OrderBy(a => a.GetType().Name)) { eventType.ToolTipText += '\n' + a.ToString() + '\n'; } eventType.DragText = "playback.GetObservable<" + pair.Key.FullName + ">()"; eventType.Children = new List<ExplorerItem>(); scope.Children.Add(eventType); foreach (PropertyInfo p in pair.Key.GetProperties()) { var field = new ExplorerItem(p.Name, ExplorerItemKind.Property, ExplorerIcon.Column); eventType.Children.Add(field); field.ToolTipText = p.PropertyType.Name; } } return result; }
private static ExplorerItem GetStructuralChildItem(IEdmEntityType parentType, IEdmStructuralProperty property) { var icon = parentType.HasDeclaredKeyProperty(property) ? ExplorerIcon.Key : ExplorerIcon.Column; var name = $"{property.Name} ({property.Type.GetTypeName()})"; var item = new ExplorerItem(name, ExplorerItemKind.Property, icon) { DragText = property.Name }; return item; }
private static TableData PrepareTableEntity(IConnectionInfo cxInfo, ModuleBuilder moduleBuilder, IDbConnection dbConnection, string nameSpace, string databaseName, string tableName, ExplorerItem tableExplorerItem) { // get primary key columns var primaryKeyColumns = dbConnection.GetPrimaryKeyColumns(tableName); var typeName = $"{nameSpace}.{cxInfo.GetTypeName(tableName)}"; // ToDo make sure tablename can be used var typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public, typeof(Entity)); // add the table attribute to the class typeBuilder.AddTableAttribute(tableName); var query = SqlHelper.LoadSql("QueryColumns.sql"); var propertyAndFieldNames = new HashSet<string>(); var columns = dbConnection.Query(query, new { DatabaseName = databaseName, TableName = tableName }); foreach (var column in columns) { var columnName = cxInfo.GetColumnName((string)column.ColumnName); var isPrimaryKeyColumn = primaryKeyColumns.Contains((string)column.ColumnName); // always use the unmodified column name var columnDefault = (string)column.ColumnDefault; // always make primary key columns nullable (otherwise auto increment can't be used with an insert) var fieldType = (Type)SqlHelper.MapDbTypeToType(column.DataType, column.UdtName, "YES".Equals(column.Nullable, StringComparison.InvariantCultureIgnoreCase), cxInfo.UseAdvancedTypes()); string text; if (fieldType != null) { // ToDo make sure name can be used var fieldBuilder = typeBuilder.DefineField(columnName, fieldType, FieldAttributes.Public); fieldBuilder.AddColumnAttribute((string)column.ColumnName); // always use the unmodified column name if (isPrimaryKeyColumn) { // check if the column is an identity column if (!string.IsNullOrEmpty(columnDefault) && columnDefault.ToLower().StartsWith("nextval")) { fieldBuilder.AddIdentityAttribute(); } fieldBuilder.AddPrimaryKeyAttribute(); } text = $"{columnName} ({fieldType.GetTypeName()})"; propertyAndFieldNames.Add(columnName); } else { // field type is not mapped text = $"{columnName} (unsupported - {column.DataType})"; } var explorerItem = new ExplorerItem(text, ExplorerItemKind.Property, ExplorerIcon.Column) { SqlTypeDeclaration = column.DataType, DragText = columnName }; tableExplorerItem.Children.Add(explorerItem); } return new TableData(tableName, tableExplorerItem, typeBuilder, propertyAndFieldNames); }
protected virtual string GetDragText(ExplorerItem item, ISitecoreConnectionSettings settings) { var builder = new StringBuilder(); builder.AppendLine(string.Format("var index = ContentSearchManager.GetIndex(\"{0}\");", item.Text)); builder.AppendLine("using (var context = index.CreateSearchContext())"); builder.AppendLine("{"); var type = settings.SearchResultType.GetSelectedType(); var typeName = settings.NamespacesToAdd.Contains(type.Namespace) ? type.Name : type.FullName; builder.AppendLine(string.Format("\tcontext.GetQueryable<{0}>()", typeName)); var whereClauses = new HashSet<string>(); var selectAssignments = new HashSet<string>(); var nameProperty = GetPropertyNameForLinqExpression(type, "_name"); var languageProperty = GetPropertyNameForLinqExpression(type, "_language"); var itemIdProperty = GetPropertyNameForLinqExpression(type, "_group"); if (! string.IsNullOrEmpty(nameProperty)) { whereClauses.Add(string.Format("item.{0} == \"Home\"", nameProperty)); selectAssignments.Add(string.Format("Name = item.{0}", nameProperty)); } if (! string.IsNullOrEmpty(languageProperty)) { whereClauses.Add(string.Format("item.{0} == \"en\"", languageProperty)); } if (! string.IsNullOrEmpty(itemIdProperty)) { selectAssignments.Add(string.Format("Id = item.{0}.ToString()", itemIdProperty)); } foreach (var clause in whereClauses) { builder.AppendFormat("\t\t.Where(item => {0})\n", clause); } builder.AppendFormat("\t\t\t\t.Select(item => new {{{0}}} )\n", string.Join(", ", selectAssignments.ToArray())); builder.AppendLine("\t\t\t\t\t.Dump();"); builder.AppendLine("}"); return builder.ToString(); }
/// <summary> /// Create schema tree that appears on the left pane below the driver connection name. /// </summary> /// <param name="stat"> Available event types and statistics. </param> /// <returns> Tree of available types and their statistics. </returns> private List<ExplorerItem> CreateEventTree(Dictionary<Type, EventStatistics> stat) { var result = new List<ExplorerItem>(); KeyValuePair<Type, EventStatistics>[] eventTypes = (from pair in stat orderby pair.Key.Name select pair).ToArray(); ExplorerItem scope = null; string currentName = null; foreach (var eventType in eventTypes) { if (eventType.Key.Name == currentName) { continue; } if (scope == null) { scope = new ExplorerItem(eventType.Key.Name, ExplorerItemKind.Schema, ExplorerIcon.Schema) { Children = new List<ExplorerItem>() }; result.Add(scope); currentName = eventType.Key.Name; } result = scope.Children; } // Defining the features for each event type. foreach (var pair in eventTypes) { ExplorerItem eventType; if (pair.Value.EventsPerSecond == 0 && pair.Value.AverageByteSize == 0) { eventType = new ExplorerItem(pair.Key.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { ToolTipText = "Statistics " + "\n" + "Occurences: " + pair.Value.EventCount + "\n" + "ByteSize: " + pair.Value.ByteSize + "\n", DragText = "playback.GetObservable<" + pair.Key.Name + ">()", Children = new List<ExplorerItem>(), IsEnumerable = true }; } else { eventType = new ExplorerItem(pair.Key.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { ToolTipText = "Statistics " + "\n" + "Occurences: " + pair.Value.EventCount + "\n" + "Events per second: " + pair.Value.EventsPerSecond + "\n" + "ByteSize: " + pair.Value.ByteSize + "\n" + "Average Byte Size: " + pair.Value.AverageByteSize + "\n", DragText = "playback.GetObservable<" + pair.Key.Name + ">()", Children = new List<ExplorerItem>(), IsEnumerable = true }; } scope.Children.Add(eventType); // Get the nested properties (columns) for each event type. foreach (var property in pair.Key.GetProperties()) { var propertyType = new ExplorerItem(property.Name, ExplorerItemKind.Property, ExplorerIcon.Column) { ToolTipText = "Property Type: " + property.PropertyType.Name, DragText = property.Name, Children = new List<ExplorerItem>(), IsEnumerable = true }; eventType.Children.Add(propertyType); if (!(property.PropertyType.IsPrimitive || property.PropertyType.Namespace.Contains("System"))) { this.AddNestedPropertyToTree(property.PropertyType.GetProperties(), propertyType); } } } return result; }
private void GetChildProperties(Type t, List<ExplorerItem> childItems) { var publicProperties = t.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); for (int j = 0; j < publicProperties.Length; j++) { PropertyInfo info = publicProperties[j]; if (info.PropertyType.IsClass) { var item = new ExplorerItem(info.Name, ExplorerItemKind.Property, ExplorerIcon.Column); item.ToolTipText = info.PropertyType.Name; childItems.Add(item); if (info.PropertyType.Name.StartsWith("Bson")) // don't add properties of bson documents { continue; } var ienunerable = info.PropertyType.GetInterface("IEnumerable"); if (ienunerable != null) { item.IsEnumerable = true; } item.Children = new List<ExplorerItem>(); GetChildProperties(info.PropertyType, item.Children); } else { childItems.Add(new ExplorerItem(info.Name, ExplorerItemKind.Property, ExplorerIcon.Column)); } } }
internal ExplorerItemNode FindExplorerItemNode(ExplorerItem item) { return this.FindExplorerItemNode(this, item); }
private static List<ExplorerItem> GetSchema(CassandraKeyspaceSchema schema) { var families = new List<ExplorerItem>(); foreach (var familyDef in schema.ColumnFamilies) { var family = new ExplorerItem(familyDef.FamilyName, ExplorerItemKind.QueryableObject, ExplorerIcon.Table); family.IsEnumerable = true; family.Children = new List<ExplorerItem>(); family.Children.Add(new ExplorerItem(familyDef.KeyName.GetValue<string>(), ExplorerItemKind.Property, ExplorerIcon.Key)); foreach (var colDef in familyDef.Columns) { var col = new ExplorerItem(colDef.Name.GetValue<string>(), ExplorerItemKind.Property, ExplorerIcon.Column); family.Children.Add(col); } families.Add(family); } return families; }
static ExplorerItem ToExplorerItem(MethodInfo m, int level) { var item = new ExplorerItem(m.Name, ExplorerItemKind.Property, ExplorerIcon.ScalarFunction) { ToolTipText = FormatTypeName(m.ReturnType), DragText = m.Name + "()" }; item.Children = m.GetParameters() .Select(p => new ExplorerItem(FormatTypeName (p.ParameterType) + " " + p.Name, ExplorerItemKind.Parameter, ExplorerIcon.Parameter)) .ToList(); return item; }
internal List<ExplorerItem> GetExplorerSchema(bool isSqlServer, string dbPrefix, bool flattenSchema) { List<ExplorerItem> objectsAsExplorerItems = this.GetObjectsAsExplorerItems(isSqlServer, dbPrefix); Dictionary<object, ExplorerItem> dictionary = (from o in objectsAsExplorerItems where o.Icon == ExplorerIcon.Table select o).ToDictionary<ExplorerItem, object, ExplorerItem>(o => o.Tag, o => o); foreach (ExplorerItem item in objectsAsExplorerItems) { foreach (ExplorerItem item2 in item.Children) { if ((item2.Tag != null) && dictionary.ContainsKey(item2.Tag)) { item2.HyperlinkTarget = dictionary[item2.Tag]; } } } var typeArray = (from <>h__TransparentIdentifier1d in from item in objectsAsExplorerItems select new { item = item, so = (SchemaObject) item.Tag } group <>h__TransparentIdentifier1d.item by (string.IsNullOrEmpty(<>h__TransparentIdentifier1d.so.SchemaName) || (<>h__TransparentIdentifier1d.so.SchemaName.ToLowerInvariant() == "dbo")) ? ((IEnumerable<<>f__AnonymousType23<string, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>>>) "") : ((IEnumerable<<>f__AnonymousType23<string, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>, IGrouping<ExplorerIcon, ExplorerItem>>>) <>h__TransparentIdentifier1d.so.SchemaName) into g orderby g.Key let iconGroups = from i in g group i by i.Icon select new { SchemaName = g.Key, Tables = iconGroups.FirstOrDefault<IGrouping<ExplorerIcon, ExplorerItem>>(ig => ((ExplorerIcon) ig.Key) == ExplorerIcon.Table), Views = iconGroups.FirstOrDefault<IGrouping<ExplorerIcon, ExplorerItem>>(ig => ((ExplorerIcon) ig.Key) == ExplorerIcon.View), StoredProcs = iconGroups.FirstOrDefault<IGrouping<ExplorerIcon, ExplorerItem>>(ig => ((ExplorerIcon) ig.Key) == ExplorerIcon.StoredProc), ScalarFunctions = iconGroups.FirstOrDefault<IGrouping<ExplorerIcon, ExplorerItem>>(ig => ((ExplorerIcon) ig.Key) == ExplorerIcon.ScalarFunction), TableFunctions = iconGroups.FirstOrDefault<IGrouping<ExplorerIcon, ExplorerItem>>(ig => ((ExplorerIcon) ig.Key) == ExplorerIcon.TableFunction) }).ToArray(); List<ExplorerItem> list2 = new List<ExplorerItem>(); foreach (var type in typeArray) { List<ExplorerItem> list3; if ((type.SchemaName == "") || flattenSchema) { list3 = list2; } else { ExplorerItem item3 = new ExplorerItem(type.SchemaName, ExplorerItemKind.Schema, ExplorerIcon.Schema) { SqlName = type.SchemaName }; list2.Add(item3); list3 = item3.Children = new List<ExplorerItem>(); } if (type.Tables != null) { list3.AddRange(type.Tables); } if (type.Views != null) { ExplorerItem item4 = new ExplorerItem("Views", ExplorerItemKind.Category, ExplorerIcon.View) { Children = type.Views.ToList<ExplorerItem>() }; list3.Add(item4); } if (type.StoredProcs != null) { ExplorerItem item5 = new ExplorerItem("Stored Procs", ExplorerItemKind.Category, ExplorerIcon.StoredProc) { Children = type.StoredProcs.ToList<ExplorerItem>() }; list3.Add(item5); } if ((type.ScalarFunctions != null) || (type.TableFunctions != null)) { ExplorerItem item6 = new ExplorerItem("Functions", ExplorerItemKind.Category, ExplorerIcon.ScalarFunction) { Children = new List<ExplorerItem>() }; if (type.ScalarFunctions != null) { item6.Children.AddRange(type.ScalarFunctions); } if (type.TableFunctions != null) { item6.Children.AddRange(type.TableFunctions); } list3.Add(item6); } } foreach (Database database in this.LinkedDatabases) { ExplorerItem item7 = new ExplorerItem(database.ClrName + ((database.ServerName == null) ? "" : (" (in " + database.ServerName + ')')), ExplorerItemKind.Schema, (database.SystemSchema == null) ? ExplorerIcon.LinkedDatabase : ExplorerIcon.Box) { Children = database.GetExplorerSchema(isSqlServer, database.ClrName, database.SystemSchema != null) }; list2.Add(item7); } return list2; }
private static IEnumerable <ExplorerItem> GetTables(Type contextType) { var source = (from pi in contextType.GetProperties() where pi.PropertyType.IsGenericType where typeof(ObjectQuery <>).IsAssignableFrom(pi.PropertyType.GetGenericTypeDefinition()) || typeof(ObjectSet <>).IsAssignableFrom(pi.PropertyType.GetGenericTypeDefinition()) let genArg = pi.PropertyType.GetGenericArguments() where genArg.Length == 1 orderby pi.Name.ToUpperInvariant() let tableProps = (from p in genArg[0].GetProperties() select new { Name = p.Name, MemberType = p.PropertyType, Attributes = p.GetCustomAttributes(true) }).Union(from f in genArg[0].GetFields() select new { Name = f.Name, MemberType = f.FieldType, Attributes = f.GetCustomAttributes(true) }) select new { TableType = genArg[0], MemberInfo = new ExplorerItem { Text = pi.Name, ToolTipText = pi.PropertyType.FormatTypeName(), DragText = pi.Name, Kind = ExplorerItemKind.QueryableObject, Icon = ExplorerIcon.Table, IsEnumerable = true, Children = (from col in tableProps let colAtt = col.Attributes.OfType <EdmScalarPropertyAttribute>().FirstOrDefault <EdmScalarPropertyAttribute>() where colAtt != null select new ExplorerItem { Text = col.Name + " (" + col.MemberType.FormatTypeName() + ")", DragText = col.Name, Icon = colAtt.EntityKeyProperty ? ExplorerIcon.Key : ExplorerIcon.Column, Kind = ExplorerItemKind.Property }).ToList <ExplorerItem>() }, AssociatedChildren = (from col in tableProps let assAtt = col.Attributes.OfType <EdmRelationshipNavigationPropertyAttribute>().FirstOrDefault <EdmRelationshipNavigationPropertyAttribute>() where assAtt != null orderby col.MemberType.IsGenericType select new { MemberType = col.MemberType.IsGenericType ? col.MemberType.GetGenericArguments()[0] : col.MemberType, AssociationName = assAtt.RelationshipName, MemberInfo = new ExplorerItem { Text = col.Name, DragText = col.Name, ToolTipText = col.MemberType.FormatTypeName(), Icon = col.MemberType.IsGenericType ? ExplorerIcon.OneToMany : ExplorerIcon.ManyToOne, Kind = col.MemberType.IsGenericType ? ExplorerItemKind.CollectionLink : ExplorerItemKind.ReferenceLink } }).ToList() }).ToList(); ILookup <Type, ExplorerItem> lookup = source.ToLookup(m => m.TableType, m => m.MemberInfo); HashSet <string> set = new HashSet <string>(from c in from t in source select t.AssociatedChildren where c.MemberInfo.Kind == ExplorerItemKind.ReferenceLink group c by c.AssociationName into g where g.Count() > 1 select g.Key); HashSet <string> set2 = new HashSet <string>(from c in from t in source select t.AssociatedChildren where c.MemberInfo.Kind == ExplorerItemKind.CollectionLink group c by c.AssociationName into g where g.Count() > 1 select g.Key); foreach (var typee in source) { foreach (var typed in typee.AssociatedChildren) { if (lookup.Contains(typed.MemberType)) { typed.MemberInfo.HyperlinkTarget = lookup[typed.MemberType].First <ExplorerItem>(); } if (set.Contains(typed.AssociationName)) { typed.MemberInfo.Icon = ExplorerIcon.OneToOne; ExplorerItem memberInfo = typed.MemberInfo; memberInfo.ToolTipText = memberInfo.ToolTipText + " (1:1 relationship)"; } else if (set2.Contains(typed.AssociationName)) { typed.MemberInfo.Icon = ExplorerIcon.ManyToMany; ExplorerItem local2 = typed.MemberInfo; local2.ToolTipText = local2.ToolTipText + " (many:many relationship)"; } } } foreach (var typee in source) { typee.MemberInfo.Children.AddRange(from c in typee.AssociatedChildren select c.MemberInfo); } return(from t in source select t.MemberInfo); }
public ExplorerItemNode(Repository r, LINQPad.Extensibility.DataContext.ExplorerItem m) : base(GetItemText(m, UseSqlMode(r))) { this._repository = r; this._explorerItem = m; this._sqlMode = UseSqlMode(r); base.ImageKey = base.SelectedImageKey = m.Icon.ToString(); base.ToolTipText = m.ToolTipText; if (m.HyperlinkTarget != null) { base.NodeFont = SchemaTree.UnderlineFont; } else if (m.Kind == ExplorerItemKind.Parameter) { base.NodeFont = SchemaTree.ItalicFont; } else if (m.Kind != ExplorerItemKind.QueryableObject) { base.NodeFont = SchemaTree.BaseFont; } if (m.Kind == ExplorerItemKind.Category) { base.ForeColor = (SystemColors.Window.GetBrightness() < 0.5f) ? Color.FromArgb(120, 0xff, 0xff) : Color.FromArgb(0, 120, 120); } else if (m.Kind == ExplorerItemKind.CollectionLink) { base.ForeColor = (SystemColors.Window.GetBrightness() < 0.5f) ? Color.LightGreen : Color.Green; } else if (m.Kind == ExplorerItemKind.Parameter) { base.ForeColor = (SystemColors.Window.GetBrightness() < 0.5f) ? Color.FromArgb(110, 140, 0xff) : Color.FromArgb(60, 80, 150); } else if (m.Kind == ExplorerItemKind.Property) { if (SystemColors.Window.GetBrightness() > 0.8f) { base.ForeColor = Color.FromArgb(40, 40, 40); } } else if (m.Kind == ExplorerItemKind.ReferenceLink) { base.ForeColor = (SystemColors.Window.GetBrightness() < 0.5f) ? Color.RoyalBlue : Color.Blue; } else if (m.Kind == ExplorerItemKind.Schema) { base.ForeColor = (SystemColors.Window.GetBrightness() < 0.5f) ? Color.Orchid : Color.Purple; } if (m.Icon == ExplorerIcon.Inherited) { base.ForeColor = Color.FromArgb(base.ForeColor.R + ((0xff - base.ForeColor.R) / 3), base.ForeColor.G + ((0xff - base.ForeColor.G) / 3), base.ForeColor.B + ((0xff - base.ForeColor.B) / 3)); } bool flag = m.Kind == ExplorerItemKind.QueryableObject; if (m.Children != null) { foreach (LINQPad.Extensibility.DataContext.ExplorerItem item in m.Children) { if (flag) { this._dormantChildren = true; } else { base.Nodes.Add(new ExplorerItemNode(this._repository, item)); } } } if (this._dormantChildren) { base.Nodes.Add(" "); } }
//private void GetChildProperties(Type t, List<ExplorerItem> childItems) //{ // var publicProperties = t.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); // for (int j = 0; j < publicProperties.Length; j++) // { // PropertyInfo info = publicProperties[j]; // if (info.PropertyType.Name.StartsWith("Bson")) // ignore bson documents // continue; // if (info.PropertyType.IsClass) // { // var item = new ExplorerItem(info.Name, ExplorerItemKind.Property, ExplorerIcon.Column); // var ienunerable = info.PropertyType.GetInterface("IEnumerable"); // if (ienunerable != null) // { // item.IsEnumerable = true; // } // item.Children = new List<ExplorerItem>(); // childItems.Add(item); // GetChildProperties(info.PropertyType, item.Children); // } // else // { // childItems.Add(new ExplorerItem(info.Name, ExplorerItemKind.Property, ExplorerIcon.Column)); // } // } //} private List<ExplorerItem> BuildExplorerItems() { var result = new List<ExplorerItem>(); var item = new ExplorerItem("Entities", ExplorerItemKind.Category, ExplorerIcon.Schema); item.Children = new List<ExplorerItem>(); result.Add(item); for (int i = 0; i < _entityTypes.Count; i++) { Type t = _entityTypes[i].Item1; string collectionName = _entityTypes[i].Item2; var typeItem = new ExplorerItem(collectionName, ExplorerItemKind.QueryableObject, ExplorerIcon.Table); item.Children.Add(typeItem); typeItem.IsEnumerable = true; typeItem.ToolTipText = string.Format("{0} Entity", collectionName); typeItem.Children = new List<ExplorerItem>(); GetChildProperties(t, typeItem.Children); } return result; }
List<ExplorerItem> BuildColumnExplorerItems(IList<TableFieldSchema> fields) { return fields.Select(x => { var isNullable = x.Mode == "NULLABLE"; var isArray = x.Mode == "REPEATED"; var suffix = isNullable ? "?" : isArray ? "[]" : ""; var item = new ExplorerItem($"{x.Name} ({x.Type}{suffix})", ExplorerItemKind.Property, ExplorerIcon.Column) { ToolTipText = x.Description }; return item; }) .ToList(); }
private void AddNestedPropertyToTree(PropertyInfo[] property, ExplorerItem propertyType) { if (property == null) { throw new ArgumentNullException("property"); } if (propertyType == null) { throw new ArgumentNullException("propertyType"); } var oldPropertyType = propertyType; foreach (var prop in property) { propertyType = new ExplorerItem(prop.Name, ExplorerItemKind.Property, ExplorerIcon.Column) { ToolTipText = "Property Type: " + prop.PropertyType.Name, DragText = prop.Name, Children = new List<ExplorerItem>(), IsEnumerable = true }; oldPropertyType.Children.Add(propertyType); if (!(prop.PropertyType.IsPrimitive || prop.PropertyType.Namespace.Contains("System"))) { this.AddNestedPropertyToTree(prop.PropertyType.GetProperties(), propertyType); } } }
private static ExplorerItem GetNavigationChildItem(IEdmNavigationProperty property, List<ExplorerItem> schema) { var partnerType = property.ToEntityType(); var backReferenceType = partnerType.DeclaredNavigationProperties() .FirstOrDefault(o => o.ToEntityType() == property.DeclaringEntityType()); var isCollection = property.Type.IsCollection(); var kind = isCollection ? ExplorerItemKind.CollectionLink : ExplorerItemKind.ReferenceLink; ExplorerIcon icon; if (backReferenceType == null) icon = ExplorerIcon.Column; else if (isCollection) icon = backReferenceType.Type.IsCollection() ? ExplorerIcon.ManyToMany : ExplorerIcon.OneToMany; else icon = backReferenceType.Type.IsCollection() ? ExplorerIcon.ManyToOne : ExplorerIcon.OneToOne; var item = new ExplorerItem(property.Name, kind, icon) { ToolTipText = partnerType.Name, HyperlinkTarget = schema.FirstOrDefault(a => (IEdmEntityType)a.Tag == partnerType), DragText = property.Name }; return item; }
private ExplorerItem CreateFunctionExplorerItem(FunctionData func, List<FunctionArgumentInfo> paramTypes) { var paramExplorerItems = paramTypes.Select(x => { var itemText = $"{x.Name} ({x.Type?.Name ?? $"unknown type: {x.DbTypeName}"})"; return new ExplorerItem(itemText, ExplorerItemKind.Parameter, ExplorerIcon.Parameter); }).ToList(); var funcType = func.IsMultiValueReturn ? ExplorerIcon.TableFunction : ExplorerIcon.ScalarFunction; var explorerItem = new ExplorerItem(func.Name, ExplorerItemKind.QueryableObject, funcType) { IsEnumerable = true, Children = paramExplorerItems }; return explorerItem; }
public List<ExplorerItem> BuildExplorerItems(BuildCodeResult[] generatedCodes) { var tableRangeLookupDictionary = generatedCodes .Where(x => x.IsTablePrefix) .Distinct(x => x.MetaTableSchema) .ToDictionary(x => x.MetaTableSchema); var tableLookupDictionary = generatedCodes .Where(x => x.IsTableName) .Distinct(x => x.MetaTableSchema) .ToDictionary(x => x.MetaTableSchema); var matchTableRange = new Regex(@"\d{8}$"); var list = new List<ExplorerItem>(); foreach (var dataset in this.Schemas) { var root = new ExplorerItem(dataset.DatasetName, ExplorerItemKind.Category, ExplorerIcon.Box); // regularTable = 1, view = 2, tableRange = 3 var lookup = dataset.GroupedMetaTableSchemas.ToLookup(x => { return (x.IsGrouped) ? 3 : x.MetaTableSchemas.First().TableInfo.type; }); // View/Table = this.From<T>() // Range = this.FromDateRange<T>() var tableRanges = new ExplorerItem("Ranges", ExplorerItemKind.Category, ExplorerIcon.Schema) { Children = lookup[3].Select(g => { var x = g.MetaTableSchemas.First(); var groupingChild = new ExplorerItem($"Tables ({g.MetaTableSchemas.Length})", ExplorerItemKind.Category, ExplorerIcon.Table) { Children = g.MetaTableSchemas.Select(y => { var className = tableLookupDictionary.GetOrDefault(y)?.ClassName ?? y.ToClassName(false); return new ExplorerItem(y.TableInfo.table_id, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { DragText = $"From<{className}>()", ToolTipText = y.TableInfo.ToFullTableName(), }; }).ToList() }; var propertyList = new List<ExplorerItem> { groupingChild }; propertyList.AddRange(BuildColumnExplorerItems(x.Fields)); var classNameCheck = tableRangeLookupDictionary.GetOrDefault(x)?.ClassName ?? x.ToClassName(true); var item = new ExplorerItem(g.ShortTablePrefix, ExplorerItemKind.QueryableObject, ExplorerIcon.Schema) { DragText = $"FromDateRange<{classNameCheck}>()", ToolTipText = x.TableInfo.ToFullTableName(), Children = propertyList }; return item; }).ToList() }; var views = new ExplorerItem("Views", ExplorerItemKind.Category, ExplorerIcon.View) { Children = lookup[2].Select(g => { var x = g.MetaTableSchemas.First(); var className = tableLookupDictionary.GetOrDefault(x)?.ClassName ?? x.ToClassName(false); var item = new ExplorerItem(x.TableInfo.table_id, ExplorerItemKind.QueryableObject, ExplorerIcon.View) { DragText = $"From<{className}>()", ToolTipText = x.TableInfo.ToFullTableName(), Children = BuildColumnExplorerItems(x.Fields) }; return item; }).ToList() }; var tables = new ExplorerItem("Tables", ExplorerItemKind.Category, ExplorerIcon.Table) { Children = lookup[1].Select(g => { var x = g.MetaTableSchemas.First(); var className = tableLookupDictionary.GetOrDefault(x)?.ClassName ?? x.ToClassName(false); var item = new ExplorerItem(x.TableInfo.table_id, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { DragText = $"From<{className}>()", ToolTipText = x.TableInfo.ToFullTableName(), Children = BuildColumnExplorerItems(x.Fields) }; return item; }).ToList() }; // RangeTables root.Children = new List<ExplorerItem> { tableRanges, views, tables }; list.Add(root); } return list; }
/// <summary> /// Builds the Schema tree for display to the user /// </summary> /// <param name="props">The deserialized Connection Properties</param> /// <param name="assemblies">The already-loaded assemblies.</param> /// <returns>A tree of ExplorerItem objects which is shown to the user in LinqPad's UI</returns> public List<ExplorerItem> BuildSchema(ConnectionProperties props, List<Assembly> assemblies) { List<ExplorerItem> ret = new List<ExplorerItem>(); List<ExplorerItem> UntypedCollections = new List<ExplorerItem>(); List<ExplorerItem> TypedCollections = new List<ExplorerItem>(); ret.Add(new ExplorerItem("db", ExplorerItemKind.QueryableObject, ExplorerIcon.LinkedDatabase)); foreach (var ctm in props.CollectionTypeMappings[props.SelectedDatabase]) { ExplorerItem coll = null; Type type = null; if (!string.IsNullOrEmpty(ctm.CollectionType)) { type = this.TryLoadType(assemblies, ctm.CollectionType); } if (type != null) { var name = DoPluralize(ctm.CollectionName); coll = new ExplorerItem(name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = true, DragText = name, ToolTipText = String.Format("Queryable of {0}", type.Name) }; foreach (PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { //ignore BSON ignored properties if (info.GetCustomAttributes(typeof(BsonIgnoreAttribute), true).Any()) continue; if (coll.Children == null) coll.Children = new List<ExplorerItem>(); coll.Children.Add(new ExplorerItem(info.Name, ExplorerItemKind.Property, ExplorerIcon.Column)); } ret.Add(coll); var tColl = new ExplorerItem(name + "Collection", ExplorerItemKind.CollectionLink, ExplorerIcon.View) { IsEnumerable = true, DragText = name + "Collection", ToolTipText = String.Format("MongoCollection of {0}", type.Name) }; tColl.Children = coll.Children; TypedCollections.Add(tColl); } else { UntypedCollections.Add(new ExplorerItem(ctm.CollectionName, ExplorerItemKind.Category, ExplorerIcon.Blank)); } } if (TypedCollections.Count > 0) { var item = new ExplorerItem("Collections", ExplorerItemKind.Category, ExplorerIcon.Box); item.Children = TypedCollections; ret.Add(item); } if(UntypedCollections.Count > 0) { var item = new ExplorerItem("Untyped Collections", ExplorerItemKind.Category, ExplorerIcon.Box); item.Children = UntypedCollections; ret.Add(item); } if (ret.Count == 0) throw new Exception("No databases mapped to types"); return ret; }