public void BuildAssembly(string cSharpSourceCode, string outputFile) { IList <string> assembliesToReference = #if NETCORE // GetCoreFxReferenceAssemblies is helper method that returns the full set of .NET Core reference assemblies. // (There are more than 100 of them.) DataContextDriver.GetCoreFxReferenceAssemblies().ToList(); #else // .NET Framework - here's how to get the basic Framework assemblies: new List <string>() { typeof(int).Assembly.Location, // mscorlib typeof(Uri).Assembly.Location, // System typeof(Enumerable).Assembly.Location, // System.Core }; #endif assembliesToReference.Add(Assembly.GetExecutingAssembly().Location); var compileResult = DataContextDriver.CompileSource(new CompilationInput { FilePathsToReference = assembliesToReference.ToArray(), OutputPath = outputFile, SourceCode = new[] { cSharpSourceCode } }); if (compileResult.Errors.Any()) { throw new Exception("Cannot compile typed context: " + compileResult.Errors[0]); } }
void ChooseType(object sender, RoutedEventArgs e) { if (_model != null) { var oldCursor = Cursor; try { Cursor = Cursors.Wait; _model.CustomAssemblyPath = _model.CustomAssemblyPath.Trim(); var assembly = DataContextDriver.LoadAssemblySafely(_model.CustomAssemblyPath); var customTypes = assembly.GetExportedTypes().Where(IsDataConnection).Select(t => t.FullName).Cast <object>().ToArray(); Cursor = oldCursor; var result = (string)Dialogs.PickFromList("Choose Custom Type", customTypes); if (result != null) { _model.CustomTypeName = result; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Assembly load error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { Cursor = oldCursor; } } }
private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) { try { string assemblyname = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll"; string driverDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); IEnumerable <string> assemblies = Directory.EnumerateFiles(driverDir, assemblyname); foreach (string path in assemblies) { return(DataContextDriver.LoadAssemblySafely(path)); } string root = Path.Combine(Path.GetTempPath(), @"LINQPad\"); assemblies = Directory.EnumerateFiles(root, assemblyname, SearchOption.AllDirectories); foreach (string path in assemblies) { return(DataContextDriver.LoadAssemblySafely(path)); } } catch (Exception error) { TxEventSource.Log.TraceError(error.ToString()); } return(null); }
protected ObjectNode(ObjectNode parent, object value, int maxDepth, DataContextDriver dcDriver) { this.Parent = parent; this.ObjectValue = value; this.MaxDepth = maxDepth; this.DCDriver = dcDriver; if (Util.IsMetaGraphNode(value)) { this.NestingDepth--; } while (parent != null) { if (!Util.IsMetaGraphNode(parent.ObjectValue)) { this.NestingDepth++; } if (IsSame(value, parent.ObjectValue)) { this.CyclicReference = parent; } if (parent.ObjectValue is Process) { this._containsProcess = true; } parent = parent.Parent; } }
public Type[] GetAvailableTypes(string targetDir, string[] traces, string[] metadaFiles) { Assembly[] assemblies = (from file in GetAssemblies(targetDir, traces, metadaFiles) select DataContextDriver.LoadAssemblySafely(file)).ToArray(); var types = (from a in assemblies from t in a.GetTypes() where t.IsPublic select t).ToArray(); return(types); }
/// <summary> /// Obtains the and set entity assembly namespaces. /// </summary> /// <param name="cxInfo">The cx info.</param> private void ObtainAndSetEntityAssemblyNamespaces(IConnectionInfo cxInfo) { var entityAssemblyFilename = CxInfoHelper.GetEntityAssemblyFilename(cxInfo, CxInfoHelper.GetTemplateGroup(cxInfo)); if (string.IsNullOrEmpty(entityAssemblyFilename)) { return; } var assembly = DataContextDriver.LoadAssemblySafely(entityAssemblyFilename); var namespaces = assembly.GetTypes().Select(t => t.Namespace).Distinct().ToArray(); CxInfoHelper.SetDriverDataElement(cxInfo, DriverDataElements.EntityAssemblyNamespacesElement, String.Join(",", namespaces)); }
public static void Compile(string cSharpSourceCode, string outputFile, string[] referencedAssemblies) { var compileResult = DataContextDriver.CompileSource(new CompilationInput { FilePathsToReference = DataContextDriver.GetCoreFxReferenceAssemblies().Concat(referencedAssemblies).ToArray(), OutputPath = outputFile, SourceCode = new[] { cSharpSourceCode } }); if (compileResult.Errors.Length > 0) { throw new Exception("Cannot compile typed context: " + compileResult.Errors[0]); } }
protected QueryCompiler(QueryCore query, bool addReferences) { this.IsMyExtensions = query.IsMyExtensions; if (this.IsMyExtensions) { MyExtensions.UpdateAdditionalRefs(query); } if (GacResolver.IsEntityFrameworkAvailable) { this.References.Add("System.Data.Entity.dll"); } DataContextDriver driver = query.GetDriver(true); if ((query.Repository != null) && (driver != null)) { this.ImportedNamespaces.RemoveRange(driver.GetNamespacesToRemoveInternal(query.Repository)); this.ImportedNamespaces.AddRange(driver.GetNamespacesToAddInternal(query.Repository)); if (addReferences) { this.References.AddRange(query.Repository.GetDriverAssemblies()); } } if (addReferences) { this.References.AddRange(PluginAssembly.GetCompatibleAssemblies(query.IsMyExtensions)); } this.ImportedNamespaces.AddRange(query.AdditionalNamespaces); if (!string.IsNullOrEmpty(query.QueryBaseClassNamespace)) { this.ImportedNamespaces.Add(query.QueryBaseClassNamespace); } if (addReferences) { this.References.AddRange(query.AllFileReferences); foreach (string str in query.AdditionalGACReferences) { string item = GacResolver.FindPath(str); if (item != null) { this.References.Add(item); } } this.References.AddRange(query.GetStaticSchemaSameFolderReferences()); if (!this.IsMyExtensions) { this.References.AddRange(MyExtensions.AdditionalRefs); } } }
static CompilationOutput Compile(string cSharpSourceCode, string outputFile) { File.WriteAllText(@"C:\Users\jom252\Desktop\pdf\fileOut.txt", cSharpSourceCode); var compileResult = DataContextDriver.CompileSource(new CompilationInput { FilePathsToReference = AssembliesToReference(), OutputPath = outputFile, SourceCode = new[] { cSharpSourceCode } }); if (compileResult.Errors.Length > 0) { throw new Exception("Cannot compile typed context: " + compileResult.Errors[0]); } return(compileResult); }
/// <summary> /// Initializes the context for adapter. The 'context' is an ILinqMetaData instance. /// </summary> /// <param name="cxInfo">The cx info.</param> /// <param name="context">The context.</param> /// <param name="executionManager">The execution manager.</param> private void InitializeContextAdapter(IConnectionInfo cxInfo, object context, QueryExecutionManager executionManager) { ILinqMetaData contextAsLinqMetaData = context as ILinqMetaData; if (contextAsLinqMetaData == null) { throw new InvalidOperationException("'context' isn't an ILinqMetaData typed object"); } string adapterAssemblyFilename = CxInfoHelper.GetDriverDataElementValue(cxInfo, DriverDataElements.AdapterDBSpecificAssemblyFilenameElement); var adapterAssembly = DataContextDriver.LoadAssemblySafely(adapterAssemblyFilename); if (adapterAssembly == null) { throw new InvalidOperationException(string.Format("The file '{0}' isn't a valid assembly.", adapterAssemblyFilename)); } var adapterType = adapterAssembly.GetTypes().Where(t => typeof(IDataAccessAdapter).IsAssignableFrom(t)).FirstOrDefault(); if (adapterType == null) { throw new InvalidOperationException(string.Format("The assembly '{0}' doesn't contain an implementation of IDataAccessAdapter.", adapterAssemblyFilename)); } IDataAccessAdapter adapterInstance = null; string connectionString = CxInfoHelper.GetDriverDataElementValue(cxInfo, DriverDataElements.ConnectionStringElementName); if (string.IsNullOrEmpty(connectionString)) { // use normal empty ctor adapterInstance = Activator.CreateInstance(adapterType) as IDataAccessAdapter; } else { // use ctor which specifies the ctor adapterInstance = Activator.CreateInstance(adapterType, connectionString) as IDataAccessAdapter; } if (adapterInstance == null) { throw new InvalidOperationException(string.Format("Couldn't create an instance of adapter type '{0}' from assembly '{1}'.", adapterType.FullName, adapterAssemblyFilename)); } var adapterToUseProperty = contextAsLinqMetaData.GetType().GetProperty("AdapterToUse"); if (adapterToUseProperty == null) { throw new InvalidOperationException(string.Format("The type '{0}' doesn't have a property 'AdapterToUse'.", context.GetType().FullName)); } adapterToUseProperty.SetValue(contextAsLinqMetaData, adapterInstance, null); }
private static string[] BuildAssembly(string code, AssemblyName name) { var referencedAssemblies = DataContextDriver.GetCoreFxReferenceAssemblies().Concat(new [] { typeof(SchemaBuilder).Assembly.Location, typeof(CsvReader).Assembly.Location }); var result = DataContextDriver.CompileSource(new CompilationInput { FilePathsToReference = referencedAssemblies.ToArray(), OutputPath = name.CodeBase, SourceCode = new[] { code } }); return(result.Successful ? new string[0] : result.Errors); }
private static IEnumerable <ExplorerItem> GetRoutines(Type contextType) { // This looks for stored proc methods on the sub-typed EM. Unlike the EF driver, it does not group the procs into an SP category. // The logic is actually stolen somewhat from the EF driver. // Sprocs currently return nothing (ignored here) or an IEnumerable of entity type, complex type, or nullable scalar primitive. // It's too slow to load metadata to check if entity/complex type, so we instead check for a nullable<t> return type, which indicates a scalar. var procs = ( from mi in contextType.GetMethods() where mi.DeclaringType.FullName != "IdeaBlade.EntityModel.EntityManager" where mi.ReturnType.IsGenericType where typeof(IEnumerable <>).IsAssignableFrom(mi.ReturnType.GetGenericTypeDefinition()) orderby mi.Name let rettype = mi.ReturnType.GetGenericArguments()[0] let scalartype = rettype.IsGenericType && rettype.GetGenericTypeDefinition() == typeof(Nullable <>) select new ExplorerItem(mi.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.StoredProc) { ToolTipText = mi.Name, DragText = mi.Name + "(" + (mi.GetParameters().Any <ParameterInfo>() ? "..." : "") + ")", Children = // Get parms (from param in mi.GetParameters() select new ExplorerItem(param.Name + " (" + DataContextDriver.FormatTypeName(param.ParameterType, false) + ")", ExplorerItemKind.Parameter, ExplorerIcon.Parameter) ) // And regular properties (if a complex or entity type) .Union (from col in rettype.GetProperties(BindingFlags.Instance | BindingFlags.Public) where scalartype == false where !EntityMemberProvider.IsAspect(col) select new ExplorerItem(col.Name, ExplorerItemKind.Property, ExplorerIcon.Column) ) // And a really screwy way to include a scalar return property. .Union (from t in new[] { rettype } where scalartype == true select new ExplorerItem(DataContextDriver.FormatTypeName(t, false), ExplorerItemKind.Property, ExplorerIcon.Column) ) .ToList() }).ToList(); return(procs); }
protected ParameterDescriptor[] GetContextConstructorParams(DataContextDriver driver, Repository r) { ParameterDescriptor[] descriptorArray2; try { descriptorArray2 = driver.GetContextConstructorParameters(r) ?? new ParameterDescriptor[0]; } catch (Exception exception) { if (driver.IsBuiltIn) { throw; } Log.Write(exception, "GetContextConstructorParameters"); throw new DisplayToUserException(exception.Message); } return(descriptorArray2); }
public override string GetHeader(QueryCore q) { StringBuilder builder = new StringBuilder(); if (q.QueryKind == QueryLanguage.FSharpExpression) { builder.AppendLine("namespace global\r\n"); } builder.AppendLine(string.Join("\r\n", (from n in base.ImportedNamespaces select "open " + n).ToArray <string>())); builder.AppendLine("open LINQPad.FSharpExtensions"); if (q.QueryKind == QueryLanguage.FSharpProgram) { builder.AppendLine("let Dump = Extensions.Dump"); } DataContextDriver driver = q.GetDriver(true); StringBuilder builder2 = new StringBuilder(); if (q.QueryKind == QueryLanguage.FSharpExpression) { builder.Append("\r\ntype UserQuery("); if ((driver != null) && (q.QueryKind == QueryLanguage.FSharpExpression)) { builder2.Append(" inherit " + q.QueryBaseClassName + "("); ParameterDescriptor[] contextConstructorParams = base.GetContextConstructorParams(driver, q.Repository); builder.Append(string.Join(", ", (from p in contextConstructorParams select p.ParameterName + " : " + p.FullTypeName).ToArray <string>())); builder.Append(") as this "); builder2.Append(string.Join(", ", (from p in contextConstructorParams select p.ParameterName).ToArray <string>())); builder2.Append(")"); } else { builder.Append(")"); } builder.AppendLine(" = class"); if (builder2.Length > 0) { builder.AppendLine(builder2.ToString()); } builder.AppendLine(" member private dc.RunUserAuthoredQuery() ="); builder.AppendLine(" ("); } return(builder.ToString()); }
public static List <ExplorerItem> GetSchema(IConnectionInfo cxInfo, Type customType) { // Return the objects with which to populate the Schema Explorer by reflecting over customType. // We'll start by retrieving all the properties of the custom type that implement IEnumerable<T>: var topLevelProps = ( from prop in customType.GetProperties() where prop.PropertyType != typeof(string) // Display all properties of type IEnumerable<T> (except for string!) let ienumerableOfT = prop.PropertyType.GetInterface("System.Collections.Generic.IEnumerable`1") where ienumerableOfT != null orderby prop.Name select new ExplorerItem(prop.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { IsEnumerable = true, ToolTipText = DataContextDriver.FormatTypeName(prop.PropertyType, false), // Store the entity type to the Tag property. We'll use it later. Tag = ienumerableOfT.GetGenericArguments()[0] } ).ToList(); // Create a lookup keying each element type to the properties of that type. This will allow // us to build hyperlink targets allowing the user to click between associations: var elementTypeLookup = topLevelProps.ToLookup(tp => (Type)tp.Tag); // Populate the columns (properties) of each entity: foreach (ExplorerItem table in topLevelProps) { table.Children = ((Type)table.Tag) .GetProperties() .Select(childProp => GetChildItem(elementTypeLookup, childProp)) .OrderBy(childItem => childItem.Kind) .ToList(); } return(topLevelProps); }
public override string GetHeader(QueryCore query) { StringBuilder builder = new StringBuilder("#Const LINQPAD = True\r\n"); builder.AppendLine(string.Join("\r\n", (from n in base.ImportedNamespaces select "Imports " + n).ToArray <string>())); builder.AppendLine(); if (query.IncludePredicateBuilder) { builder.AppendLine("Public Module PredicateBuilder\r\n <System.Runtime.CompilerServices.Extension> _\r\n Public Function [And](Of T)(ByVal expr1 As Expression(Of Func(Of T, Boolean)), ByVal expr2 As Expression(Of Func(Of T, Boolean))) As Expression(Of Func(Of T, Boolean))\r\n Dim invokedExpr As Expression = Expression.Invoke(expr2, expr1.Parameters.Cast(Of Expression)())\r\n Return Expression.Lambda(Of Func(Of T, Boolean))(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters)\r\n End Function\r\n\r\n Public Function [False](Of T)() As Expression(Of Func(Of T, Boolean))\r\n Return Function(f) False\r\n End Function\r\n\r\n <System.Runtime.CompilerServices.Extension> _\r\n Public Function [Or](Of T)(ByVal expr1 As Expression(Of Func(Of T, Boolean)), ByVal expr2 As Expression(Of Func(Of T, Boolean))) As Expression(Of Func(Of T, Boolean))\r\n Dim invokedExpr As Expression = Expression.Invoke(expr2, expr1.Parameters.Cast(Of Expression)())\r\n Return Expression.Lambda(Of Func(Of T, Boolean))(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters)\r\n End Function\r\n\r\n Public Function [True](Of T)() As Expression(Of Func(Of T, Boolean))\r\n Return Function(f) True\r\n End Function\r\n\r\nEnd Module\r\n"); } builder.AppendLine("Public Class UserQuery"); if (query.QueryBaseClassName != null) { builder.AppendLine(" Inherits " + query.QueryBaseClassName); } builder.AppendLine(); builder.AppendLine(); DataContextDriver driver = query.GetDriver(true); if (driver != null) { ParameterDescriptor[] contextConstructorParams = base.GetContextConstructorParams(driver, query.Repository); builder.Append(" Public Sub New ("); builder.Append(string.Join(", ", (from p in contextConstructorParams select "ByVal " + p.ParameterName + " As " + p.FullTypeName).ToArray <string>())); builder.AppendLine(")"); builder.Append(" MyBase.New("); builder.Append(string.Join(", ", (from p in contextConstructorParams select p.ParameterName).ToArray <string>())); builder.AppendLine(")"); builder.AppendLine(" End Sub"); builder.AppendLine(); } builder.AppendLine(" Private Sub RunUserAuthoredQuery()"); if (query.QueryKind == QueryLanguage.VBExpression) { builder.Append("Dim linqPadQuery = "); } else if (query.QueryKind == QueryLanguage.VBProgram) { builder.AppendLine(" Main\r\nEnd Sub"); } return(builder.ToString()); }
private static ExplorerItem GetChildItem(ILookup <Type, ExplorerItem> elementTypeLookup, PropertyInfo childProp) { // If the property's type is in our list of entities, then it's a Many:1 (or 1:1) reference. // We'll assume it's a Many:1 (we can't reliably identify 1:1s purely from reflection). if (elementTypeLookup.Contains(childProp.PropertyType)) { return new ExplorerItem(childProp.Name, ExplorerItemKind.ReferenceLink, ExplorerIcon.ManyToOne) { HyperlinkTarget = elementTypeLookup[childProp.PropertyType].First(), // FormatTypeName is a helper method that returns a nicely formatted type name. ToolTipText = DataContextDriver.FormatTypeName(childProp.PropertyType, true) } } ; // Is the property's type a collection of entities? Type ienumerableOfT = childProp.PropertyType.GetInterface("System.Collections.Generic.IEnumerable`1"); if (ienumerableOfT != null) { Type elementType = ienumerableOfT.GetGenericArguments()[0]; if (elementTypeLookup.Contains(elementType)) { return new ExplorerItem(childProp.Name, ExplorerItemKind.CollectionLink, ExplorerIcon.OneToMany) { HyperlinkTarget = elementTypeLookup[elementType].First(), ToolTipText = DataContextDriver.FormatTypeName(elementType, true) } } ; } // Ordinary property: var isKey = childProp.GetCustomAttributes(false).Any(a => a.GetType().Name == "KeyAttribute"); return(new ExplorerItem(childProp.Name + " (" + DataContextDriver.FormatTypeName(childProp.PropertyType, false) + ")", ExplorerItemKind.Property, isKey ? ExplorerIcon.Key : ExplorerIcon.Column) { DragText = childProp.Name }); }
public DataRowNode(ObjectNode parent, DataRow item, int maxDepth, DataContextDriver dcDriver) : base(parent, item, maxDepth, dcDriver) { base.Name = "DataRow"; if (base.IsAtNestingLimit()) { base.GraphTruncated = true; } else { foreach (DataColumn column in item.Table.Columns) { object obj2 = item[column]; base.Members.Add(new MemberData(column.ColumnName, column.DataType, ObjectNode.Create(this, obj2, maxDepth, dcDriver))); } if ((base.Members.Count > 50) && (base.NestingDepth > 1)) { base.InitiallyHidden = true; } } }
private void RoslynCompile(string[] sources, string assemblyName, string driverFolder) { var referencedAssemblies = DataContextDriver.GetCoreFxReferenceAssemblies().Concat(new[] { typeof(ArchiveReader).Assembly.Location, }).ToArray(); var result = DataContextDriver.CompileSource(new CompilationInput() { FilePathsToReference = referencedAssemblies, SourceCode = sources, OutputPath = Path.Combine(driverFolder, assemblyName) }); if (!result.Successful) { var message = string.Join(' ', result.Errors); throw new Exception($"Compilation failed! {message.ToString()}"); } }
public override string GetHeader(QueryCore q) { StringBuilder builder = new StringBuilder("#define LINQPAD\r\n"); builder.AppendLine(string.Join("\r\n", (from n in base.ImportedNamespaces select "using " + n + ";").ToArray <string>())); if (q.IncludePredicateBuilder) { builder.AppendLine("public static class PredicateBuilder\r\n{\r\n\tpublic static System.Linq.Expressions.Expression<Func<T, bool>> True<T> () { return f => true; }\r\n\tpublic static System.Linq.Expressions.Expression<Func<T, bool>> False<T> () { return f => false; }\r\n\r\n\tpublic static System.Linq.Expressions.Expression<Func<T, bool>> Or<T> (this System.Linq.Expressions.Expression<Func<T, bool>> expr1, System.Linq.Expressions.Expression<Func<T, bool>> expr2)\r\n\t{\r\n\t\tSystem.Linq.Expressions.Expression invokedExpr = System.Linq.Expressions.Expression.Invoke (\r\n\t\t expr2, expr1.Parameters.Cast<System.Linq.Expressions.Expression> ());\r\n\r\n\t\treturn System.Linq.Expressions.Expression.Lambda<Func<T, bool>> (\r\n\t\t System.Linq.Expressions.Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);\r\n\t}\r\n\r\n\tpublic static System.Linq.Expressions.Expression<Func<T, bool>> And<T> (this System.Linq.Expressions.Expression<Func<T, bool>> expr1, System.Linq.Expressions.Expression<Func<T, bool>> expr2)\r\n\t{\r\n\t\tSystem.Linq.Expressions.Expression invokedExpr = System.Linq.Expressions.Expression.Invoke (\r\n\t\t expr2, expr1.Parameters.Cast<System.Linq.Expressions.Expression> ());\r\n\r\n\t\treturn System.Linq.Expressions.Expression.Lambda<Func<T, bool>> (\r\n\t\t System.Linq.Expressions.Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);\r\n\t}\r\n}"); } builder.Append("\r\npublic partial class UserQuery"); if (q.QueryBaseClassName != null) { builder.Append(" : " + q.QueryBaseClassName); } builder.AppendLine("\r\n{"); DataContextDriver driver = q.GetDriver(true); if (driver != null) { builder.Append(" public UserQuery ("); ParameterDescriptor[] contextConstructorParams = base.GetContextConstructorParams(driver, q.Repository); builder.Append(string.Join(", ", (from p in contextConstructorParams select p.FullTypeName + " " + p.ParameterName).ToArray <string>())); builder.Append(") : base ("); builder.Append(string.Join(", ", (from p in contextConstructorParams select p.ParameterName).ToArray <string>())); builder.AppendLine(") { }"); } builder.AppendLine("\r\n [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]"); builder.AppendLine(" void RunUserAuthoredQuery()"); builder.AppendLine(" {"); if (q.QueryKind == QueryLanguage.Expression) { builder.AppendLine(" LINQPad.Extensions.Dump<object> ("); } else if (q.QueryKind == QueryLanguage.Program) { builder.AppendLine(" Main();"); builder.AppendLine("}"); } return(builder.ToString()); }
/// <summary> /// Enables the ORM profiler. /// </summary> /// <param name="cxInfo">The cx info.</param> private void EnableORMProfiler(IConnectionInfo cxInfo) { var interceptorLocation = CxInfoHelper.GetDriverDataElementValue(cxInfo, DriverDataElements.ORMProfilerInterceptorLocationElement); if (!File.Exists(interceptorLocation)) { throw new InvalidOperationException(string.Format("The ORM Profiler interceptor isn't found at '{0}'", interceptorLocation)); } var interceptorAssembly = DataContextDriver.LoadAssemblySafely(interceptorLocation); if (interceptorAssembly == null) { throw new InvalidOperationException(string.Format("Couldn't load the ORM Profiler interceptor assembly '{0}'", interceptorLocation)); } Type interceptor = interceptorAssembly.GetType("SD.Tools.OrmProfiler.Interceptor.InterceptorCore"); interceptor.InvokeMember("Initialize", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, null, null, new[] { GetConnectionDescription(cxInfo) }, System.Globalization.CultureInfo.CurrentUICulture); }
public ParserRegistry() { string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); IEnumerable <Type> types = from file in Directory.GetFiles(dir, "Tx*.dll") from t in DataContextDriver.LoadAssemblySafely(file).GetTypes() where t.IsPublic select t; IEnumerable <MethodInfo> methods = from t in types from m in t.GetMethods() where m.GetCustomAttribute <FileParserAttribute>() != null select m; _addFiles = methods.ToArray(); methods = from t in types from m in t.GetMethods() where m.GetCustomAttribute <RealTimeFeedAttribute>() != null select m; _addSessions = methods.ToArray(); }
public void Compile(string code, AssemblyName name, IEnumerable <string> assemblyLocations) { var platformAssemblies = DataContextDriver.GetCoreFxReferenceAssemblies(); var references = platformAssemblies.Concat(assemblyLocations).Select(l => MetadataReference.CreateFromFile(l)); var parseOptions = new CSharpParseOptions().WithPreprocessorSymbols("NETCORE"); var compilation = CSharpCompilation.Create( name.Name, references: references, syntaxTrees: new SyntaxTree[] { CSharpSyntaxTree.ParseText(code, parseOptions) }, options: this.Options ); using var fileStream = File.OpenWrite(name.CodeBase); var results = compilation.Emit(fileStream); if (!results.Success) { throw new ArgumentException(string.Format(Exceptions.CannotCompileCode, results.Diagnostics[0].GetMessage(), results.Diagnostics[0].Location.GetLineSpan())); } }
//public static List<ExplorerItem> GetSchemaAndBuildAssembly(ConnectionData connectionData, AssemblyName assemblyName, // ref string nameSpace, ref string typeName) //{ // var code = GenerateCode(connectionData); // CompileCode(code, assemblyName); //} internal static List <ExplorerItem> GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName name, ref string nameSpace, ref string typeName) { //using (var progress = new ProgressIndicatorHost( 5, true)) { //progress.SetStatus(1, "Fetching entities (slow)..."); // Generate the code using the ADO.NET Data Services classes: var code = GenerateCode(new ConnectionData(cxInfo), nameSpace); //progress.SetStatus(2, "Compiling assemblies..."); // Compile the code into the assembly, using the assembly name provided: BuildAssembly(code, name); //progress.SetStatus(3, "Loading assemblies..."); var assembly = DataContextDriver.LoadAssemblySafely(name.CodeBase); var a = assembly.GetType(nameSpace + ".TypedDataContext"); //progress.SetStatus(4, "Calculating schema..."); // Use the schema to populate the Schema Explorer: List <ExplorerItem> schema = GetSchema(cxInfo, a); return(schema); } }
/// <summary> /// Generate Schema information. /// </summary> /// <param name="cxInfo">IConnectionInfo</param> /// <param name="customType">Context Type</param> /// <returns>Schema Information.</returns> public override List <ExplorerItem> GetSchema(IConnectionInfo cxInfo, Type customType) { // Instantiate CrmProperties. CrmProperties props = new CrmProperties(cxInfo); // Instantiate ExplorerItem list. List <ExplorerItem> schema = new List <ExplorerItem>(); // Create Tables for Schema. foreach (PropertyInfo prop in customType.GetRuntimeProperties()) { // If property is not Generic Type or IQueryable, then ignore. if (!prop.PropertyType.IsGenericType || prop.PropertyType.Name != "DataServiceQuery`1") { continue; } // Create ExploreItem with Table icon as this is top level item. ExplorerItem item = new ExplorerItem(prop.Name, ExplorerItemKind.QueryableObject, ExplorerIcon.Table) { // Store Entity Type to Tag. Tag = prop.PropertyType.GenericTypeArguments[0].Name, IsEnumerable = true, Children = new List <ExplorerItem>() }; schema.Add(item); } schema = schema.OrderBy(x => x.Text).ToList <ExplorerItem>(); // Then create columns for each table. Loop through tables again. foreach (PropertyInfo prop in customType.GetRuntimeProperties()) { // Obtain Table item from table lists. var item = schema.Where(x => x.Text == prop.Name).FirstOrDefault(); if (item == null) { continue; } // Get all property from Entity for the table. (i.e. Account for AccountSet) foreach (PropertyInfo childprop in customType.Module.GetTypes().Where(x => x.Name == prop.PropertyType.GenericTypeArguments[0].Name).First().GetRuntimeProperties()) { // If property is IEnumerable type, then it is 1:N or N:N relationship field. // Need to find a way to figure out if this is 1:N or N:N. At the moment, I just make them as OneToMany type. if (childprop.PropertyType.IsGenericType && childprop.PropertyType.Name == "IEnumerable`1") { // Try to get LinkTarget. ExplorerItem linkTarget = schema.Where(x => x.Tag.ToString() == childprop.PropertyType.GetGenericArguments()[0].Name).FirstOrDefault(); if (linkTarget == null) { continue; } // Create ExplorerItem as Colleciton Link. item.Children.Add( new ExplorerItem( childprop.Name, ExplorerItemKind.CollectionLink, ExplorerIcon.OneToMany) { HyperlinkTarget = linkTarget, ToolTipText = DataContextDriver.FormatTypeName(childprop.PropertyType, false) }); } else { // Try to get LinkTarget to check if this field is N:1. ExplorerItem linkTarget = schema.Where(x => x.Tag.ToString() == childprop.PropertyType.Name).FirstOrDefault(); // If no linkTarget exists, then this is normal field. if (linkTarget == null) { // Create ExplorerItem as Column. item.Children.Add( new ExplorerItem( childprop.Name + " (" + DataContextDriver.FormatTypeName(childprop.PropertyType, false) + ")", ExplorerItemKind.Property, ExplorerIcon.Column) { ToolTipText = DataContextDriver.FormatTypeName(childprop.PropertyType, false) }); } else { // Otherwise, create ExploreItem as N:1 item.Children.Add( new ExplorerItem( childprop.Name + " (" + DataContextDriver.FormatTypeName(childprop.PropertyType, false) + ")", ExplorerItemKind.ReferenceLink, ExplorerIcon.ManyToOne) { HyperlinkTarget = linkTarget, ToolTipText = DataContextDriver.FormatTypeName(childprop.PropertyType, false) }); } } // Order Fields item.Children = item.Children.OrderBy(x => x.Text).ToList <ExplorerItem>(); } } // Order Entities. schema = schema.OrderBy(x => x.Text).ToList <ExplorerItem>(); return(schema); }
public static bool ShowConnectionDialog(DataContextDriver driver, IConnectionInfo cxInfo, bool isNewConnection, bool isDynamic) { var model = new ConnectionViewModel(); var providerName = isNewConnection ? ProviderName.SqlServer : (string)cxInfo.DriverData.Element("providerName"); if (providerName != null) { model.SelectedProvider = model.Providers.FirstOrDefault(p => p.Name == providerName); } model.Name = cxInfo.DisplayName; model.IsDynamic = isDynamic; model.CustomAssemblyPath = cxInfo.CustomTypeInfo.CustomAssemblyPath; model.CustomTypeName = cxInfo.CustomTypeInfo.CustomTypeName; model.AppConfigPath = cxInfo.AppConfigPath; model.CustomConfiguration = cxInfo.DriverData.Element("customConfiguration")?.Value; model.Persist = cxInfo.Persist; model.IsProduction = cxInfo.IsProduction; model.EncryptConnectionString = cxInfo.DatabaseInfo.EncryptCustomCxString; model.Pluralize = !cxInfo.DynamicSchemaOptions.NoPluralization; model.Capitalize = !cxInfo.DynamicSchemaOptions.NoCapitalization; model.IncludeRoutines = cxInfo.DriverData.Element("excludeRoutines")?.Value.ToLower() != "true"; model.IncludeFKs = cxInfo.DriverData.Element("excludeFKs")?.Value.ToLower() != "true"; model.ConnectionString = cxInfo.DatabaseInfo.CustomCxString.IsNullOrWhiteSpace() ? (string)cxInfo.DriverData.Element("connectionString") : cxInfo.DatabaseInfo.CustomCxString; model.IncludeSchemas = cxInfo.DriverData.Element("includeSchemas")?.Value; model.ExcludeSchemas = cxInfo.DriverData.Element("excludeSchemas")?.Value; model.IncludeCatalogs = cxInfo.DriverData.Element("includeCatalogs")?.Value; model.ExcludeCatalogs = cxInfo.DriverData.Element("excludeCatalogs")?.Value; //model.NormalizeNames = cxInfo.DriverData.Element("normalizeNames") ?.Value.ToLower() == "true"; model.AllowMultipleQuery = cxInfo.DriverData.Element("allowMultipleQuery")?.Value.ToLower() == "true"; model.UseProviderSpecificTypes = cxInfo.DriverData.Element("useProviderSpecificTypes")?.Value.ToLower() == "true"; model.UseCustomFormatter = cxInfo.DriverData.Element("useCustomFormatter")?.Value.ToLower() == "true"; model.CommandTimeout = cxInfo.DriverData.ElementValueOrDefault("commandTimeout", str => str.ToInt32() ?? 0, 0); model.OptimizeJoins = cxInfo.DriverData.Element("optimizeJoins") == null || cxInfo.DriverData.Element("optimizeJoins")?.Value.ToLower() == "true"; if (ConnectionDialog.Show(model, isDynamic ? (Func <ConnectionViewModel, Exception>)TestConnection : null)) { providerName = model.SelectedProvider?.Name; cxInfo.DriverData.SetElementValue("providerName", providerName); cxInfo.DriverData.SetElementValue("connectionString", null); cxInfo.DriverData.SetElementValue("excludeRoutines", !model.IncludeRoutines ? "true" : "false"); cxInfo.DriverData.SetElementValue("excludeFKs", !model.IncludeFKs ? "true" : "false"); cxInfo.DriverData.SetElementValue("includeSchemas", model.IncludeSchemas.IsNullOrWhiteSpace() ? null : model.IncludeSchemas); cxInfo.DriverData.SetElementValue("excludeSchemas", model.ExcludeSchemas.IsNullOrWhiteSpace() ? null : model.ExcludeSchemas); cxInfo.DriverData.SetElementValue("includeCatalogs", model.IncludeCatalogs.IsNullOrWhiteSpace() ? null : model.IncludeSchemas); cxInfo.DriverData.SetElementValue("excludeCatalogs", model.ExcludeCatalogs.IsNullOrWhiteSpace() ? null : model.ExcludeSchemas); cxInfo.DriverData.SetElementValue("optimizeJoins", model.OptimizeJoins ? "true" : "false"); cxInfo.DriverData.SetElementValue("allowMultipleQuery", model.AllowMultipleQuery ? "true" : "false"); //cxInfo.DriverData.SetElementValue("normalizeNames", model.NormalizeNames ? "true" : null); cxInfo.DriverData.SetElementValue("useProviderSpecificTypes", model.UseProviderSpecificTypes ? "true" : null); cxInfo.DriverData.SetElementValue("useCustomFormatter", model.UseCustomFormatter ? "true" : null); cxInfo.DriverData.SetElementValue("commandTimeout", model.CommandTimeout.ToString()); var providerInfo = ProviderHelper.GetProvider(providerName); cxInfo.DatabaseInfo.Provider = providerInfo.GetConnectionNamespace(); try { var provider = ProviderHelper.GetProvider(model.SelectedProvider.Name).GetDataProvider(model.ConnectionString); using (var db = new DataConnection(provider, model.ConnectionString)) { db.CommandTimeout = model.CommandTimeout; cxInfo.DatabaseInfo.Provider = db.Connection.GetType().Namespace; cxInfo.DatabaseInfo.Server = ((DbConnection)db.Connection).DataSource; cxInfo.DatabaseInfo.Database = db.Connection.Database; cxInfo.DatabaseInfo.DbVersion = ((DbConnection)db.Connection).ServerVersion; } } catch { } cxInfo.DriverData.SetElementValue("customConfiguration", model.CustomConfiguration.IsNullOrWhiteSpace() ? null : model.CustomConfiguration); cxInfo.CustomTypeInfo.CustomAssemblyPath = model.CustomAssemblyPath; cxInfo.CustomTypeInfo.CustomTypeName = model.CustomTypeName; cxInfo.AppConfigPath = model.AppConfigPath; cxInfo.DatabaseInfo.CustomCxString = model.ConnectionString; cxInfo.DatabaseInfo.EncryptCustomCxString = model.EncryptConnectionString; cxInfo.DynamicSchemaOptions.NoPluralization = !model.Pluralize; cxInfo.DynamicSchemaOptions.NoCapitalization = !model.Capitalize; cxInfo.DynamicSchemaOptions.ExcludeRoutines = !model.IncludeRoutines; cxInfo.Persist = model.Persist; cxInfo.IsProduction = model.IsProduction; cxInfo.DisplayName = model.Name.IsNullOrWhiteSpace() ? null : model.Name; return(true); } return(false); }
private void CompileAndRun(DataContextInfo dcInfo) { try { object obj2; QueryCore core; lock ((obj2 = this._locker)) { core = this._query; if ((core == null) || this._cancelRequest) { return; } } if ((dcInfo != null) && (dcInfo.Error != null)) { this.OnQueryCompleted("Connection error", dcInfo.Error); } else { DataContextDriver driver = core.GetDriver(true); if ((driver != null) && (driver.AssembliesToAddError != null)) { this.OnQueryCompleted("Error loading custom driver assemblies", driver.AssembliesToAddError.Message); } else { QueryCompiler c = null; if (((this._lastCompilation != null) && (this._lastCompilation.AssemblyDLL != null)) && File.Exists(this._lastCompilation.AssemblyDLL.FullPath)) { c = this._lastCompilation.Compiler; if (!((((dcInfo != null) || (this._lastCompilation.DataContextDLL == null)) && ((dcInfo == null) || (this._lastCompilation.DataContextDLL != null))) ? (((dcInfo == null) || (this._lastCompilation.DataContextDLL == null)) || (dcInfo.AssemblyPath == this._lastCompilation.DataContextDLL)) : false)) { c = null; } } bool flag2 = false; if (c == null) { this._executionProgress = LINQPad.ExecutionModel.ExecutionProgress.Compiling; c = QueryCompiler.Create(core, true); lock ((obj2 = this._locker)) { if (this._cancelRequest) { return; } } c.Compile(this._source, core, (dcInfo == null) ? null : dcInfo.AssemblyPath); lock ((obj2 = this._locker)) { if (this._cancelRequest) { return; } if (c.Errors.HasErrors) { this._executionProgress = LINQPad.ExecutionModel.ExecutionProgress.Finished; this.QueryCompleted = null; this.PluginsReady = null; this.CustomClickComplete = null; } } this.OnQueryCompiled(new QueryCompilationEventArgs(c, (dcInfo == null) ? null : dcInfo.AssemblyPath, this._partialSource)); flag2 = true; } lock ((obj2 = this._locker)) { if ((this._cancelRequest || c.Errors.HasErrors) || this._compileOnly) { this._executionProgress = LINQPad.ExecutionModel.ExecutionProgress.Finished; return; } } Server server = this._serverGenerator(this); if (server != null) { lock ((obj2 = this._locker)) { if (this._cancelRequest) { return; } if (this._server != server) { this.ClearServer(); } this._server = server; this._executionProgress = LINQPad.ExecutionModel.ExecutionProgress.Executing; } bool flag7 = c.References.Any <string>(r => r.EndsWith(".winmd", StringComparison.InvariantCultureIgnoreCase)); server.WriteResultsToGrids = core.ToDataGrids; server.ExecuteClrQuery(this, core.Repository, c.OutputFile.FullPath, c.LineOffset, c.References.ToArray <string>(), Program.MTAMode || flag7, flag2 && c.Errors.HasWarnings, core.FilePath, core.Name, this._pluginWinManager, !UserOptionsLive.Instance.ExecutionTrackingDisabled); } } } } catch (Exception exception) { try { this.OnQueryCompleted("Unable to execute query", ""); } catch { } Program.ProcessException(exception); } }
public ClrMemberNode(ObjectNode parent, object item, int maxDepth, DataContextDriver dcDriver) : base(parent, item, maxDepth, dcDriver) { base.Name = item.GetType().FormatTypeName(); Type type = item.GetType(); if (!((base.CyclicReference != null) || base.IsAtNestingLimit())) { base.InitiallyHidden = ((((item is MemberInfo) || (item is RuntimeMethodHandle)) || ((item is CultureInfo) || (item is ProcessModule))) || (((item is Uri) || (item is Version)) || ((type.Namespace == "Microsoft.SqlServer.Types") || (type.FullName == "System.Data.EntityKey")))) || ((type.Namespace != null) && (type.Namespace.StartsWith("System.Reflection", StringComparison.Ordinal) || type.Namespace.StartsWith("System.IO", StringComparison.Ordinal))); } if (item is Type) { base.Name = "typeof(" + ((Type)item).Name + ")"; } if (!base.Name.StartsWith("{", StringComparison.Ordinal)) { if ((item is MethodBase) && (((MethodBase)item).DeclaringType != null)) { MethodBase base2 = (MethodBase)item; string[] strArray = new string[] { base2.DeclaringType.FormatTypeName(), ".", base2.Name, " (", string.Join(", ", (from p in base2.GetParameters() select p.ParameterType.FormatTypeName() + " " + p.Name).ToArray <string>()), ")" }; base.Summary = string.Concat(strArray); } else { try { base.Summary = item.ToString(); } catch { } } } if (base.Summary.Length > 150) { base.Summary = base.Summary.Substring(0, 150) + "..."; } FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); if (((fields.Length != 0) || (properties.Length != 0)) && (base.CyclicReference == null)) { if (!((!base.IsAtNestingLimit() || Util.IsMetaGraphNode(item)) || (base.Parent is ListNode))) { base.GraphTruncated = true; } else { object obj2; bool isAnonType = base.IsAnonType; Func <object> getter = null; foreach (FieldInfo fi in fields) { if (isAnonType || (((fi.GetCustomAttributes(typeof(AssociationAttribute), true).Length == 0) && !fi.FieldType.FullName.StartsWith("System.Data.Objects.DataClasses.EntityReference")) && !IsUnloadedEntityAssociation(item, fi))) { if (getter == null) { getter = () => fi.GetValue(item); } obj2 = this.GetValue(fi, getter, isAnonType); base.Members.Add(new MemberData(fi.Name, fi.FieldType, ObjectNode.Create(this, obj2, item is Exception, maxDepth, dcDriver))); } } foreach (PropertyInfo pi in properties) { if ((pi.GetIndexParameters().Length == 0) && (isAnonType || ((((pi.GetCustomAttributes(typeof(AssociationAttribute), true).Length == 0) && !pi.PropertyType.FullName.StartsWith("System.Data.Objects.DataClasses.EntityReference")) && ((pi.PropertyType.FullName != "System.Data.EntityKey") && (pi.PropertyType.FullName != "System.Data.EntityState"))) && !IsUnloadedEntityAssociation(item, pi)))) { bool exceptionThrown = false; obj2 = this.GetValue(pi, () => this.GetPropValue(pi, item, out exceptionThrown), isAnonType); bool flag2 = exceptionThrown && ((item is Exception) || ((parent != null) && (parent.ObjectValue is Exception))); base.Members.Add(new MemberData(pi.Name, pi.PropertyType, ObjectNode.Create(this, obj2, item is Exception, flag2 ? 1 : maxDepth, dcDriver))); } } if ((base.Members.Count > 50) && (base.NestingDepth > 1)) { base.InitiallyHidden = true; } } } }
public MemberNode(ObjectNode parent, object item, int maxDepth, DataContextDriver dcDriver) : base(parent, item, maxDepth, dcDriver) { this.Members = new List <MemberData>(); this.Summary = ""; }
private static string[] AssembliesToReference() { return(DataContextDriver.GetCoreFxReferenceAssemblies() .Append(typeof(TargetObjectBuilder).Assembly.Location).ToArray()); }