private void loadQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LinqPadQuery query;

            using (var chooser = new OpenFileDialog())
            {
                chooser.DefaultExt = ".linq";
                chooser.Filter     = "LinqPad Queries|*.linq|All Files|*.*";

                DialogResult result = chooser.ShowDialog();
                if (result == DialogResult.OK)
                {
                    query = LinqPadQuery.CreateFrom(chooser.FileName);
                }
                else
                {
                    return;
                }
            }

            var props = new ConnectionProperties();

            this.Populate(props);
            List <string> errors = ValidateLinqQuery(query, props);

            if (errors.Count == 0)
            {
                this.mInitializationQuery = query;
                this.SetLoadedQueryName(Path.GetFileName(this.mInitializationQuery.Location));
            }
            else
            {
                DisplayErrors(errors);
            }
        }
        private void reloadFromDiskToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.mInitializationQuery == null)
            {
                return;
            }
            if (!File.Exists(this.mInitializationQuery.Location))
            {
                MessageBox.Show(string.Format("Query '{0}' no longer exists", this.mInitializationQuery.Location));
                return;
            }

            ConnectionProperties props = new ConnectionProperties();

            this.Populate(props);

            LinqPadQuery  query  = LinqPadQuery.CreateFrom(this.mInitializationQuery.Location);
            List <string> errors = this.ValidateLinqQuery(query, props);

            if (errors.Count != 0)
            {
                MessageBox.Show("Loaded query has errors: \r\n" +
                                string.Join("\r\n", errors));
                return;
            }

            this.mInitializationQuery = query;
            this.SetLoadedQueryName(Path.GetFileName(this.mInitializationQuery.Location));
        }
Example #3
0
        public static LinqPadQuery CreateFrom(string path)
        {
            LinqPadQuery retval = new LinqPadQuery();

            retval.Location = path;
            retval.Reload();

            return(retval);
        }
Example #4
0
 public bool Equals(LinqPadQuery other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(XNode.EqualityComparer.Equals(other.ConnectionInfo, this.ConnectionInfo) &&
            string.Equals(other.Location, Location, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(other.Query, Query, StringComparison.OrdinalIgnoreCase));
 }
        /// <summary>
        /// Creates the Schema which displays information about the connection to the user,
        /// and dynamically generates the driver as an assembly.
        /// </summary>
        /// <param name="cxInfo">the serialized connection properties.</param>
        /// <param name="assemblyToBuild">The location where the dynamically generated assembly should be created</param>
        /// <param name="nameSpace">The namespace of the driver class</param>
        /// <param name="typeName">The name of the driver class</param>
        /// <returns>A tree of ExplorerItem objects which is shown to the user in LinqPad's UI</returns>
        public override List <ExplorerItem> GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName)
        {
            var             props      = propsSerializer.Deserialize(cxInfo.DriverData);
            List <Assembly> assemblies =
                props.AssemblyLocations.Select(LoadAssemblySafely).ToList();

            //refresh the init query
            if (props.InitializationQuery != null)
            {
                props.InitializationQuery = LinqPadQuery.CreateFrom(props.InitializationQuery.Location);
            }

            //refresh DB collections
            MongoServer mongo = null;

            try
            {
                mongo = MongoServer.Create(props.ConnectionString);
                mongo.TrimDatabaseMappings(props.CollectionTypeMappings);
            }
            finally
            {
                if (mongo != null)
                {
                    mongo.Disconnect();
                }
            }

            var code = new[] { GenerateDynamicCode(props, assemblies, nameSpace, typeName) }
            .Concat(GetStaticCodeFiles());

            //write inner class CustomInitQuery
            if (props.InitializationQuery != null)
            {
                code = code.Concat(new[] { this.GenerateCustomInitQuery(props.InitializationQuery, nameSpace) });
            }


            BuildAssembly(props, code, assemblyToBuild, GetDriverFolder);

            return(BuildSchema(props, assemblies));
        }
        public string GenerateCustomInitQuery(LinqPadQuery query, string nameSpace)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var ns in query.Namespaces)
            {
                sb.Append("using ").Append(ns).AppendLine(";");
            }
            sb.AppendFormat(@"
namespace {1}
{{
    public class CustomInitQuery
    {{
        public CustomInitQuery()
        {{

        }}

        {0}
    }}
}}", query.Query, nameSpace);

            return(sb.ToString());
        }
        /// <summary>
        /// loads the saved connection properties into the form
        /// </summary>
        private void LoadFrom(ConnectionProperties props)
        {
            this.txtConnectionString.Text = props.ConnectionString;
            this.LoadedAssemblies         = props.AssemblyLocations.ToDictionary(loc => loc, loc =>
            {
                if (!File.Exists(loc))
                {
                    return(null);
                }
                else
                {
                    return(this.loadSafely(loc));
                }
            });
            this.LoadedTypes.Clear();
            this.LoadedTypes.AddRange(MongoDynamicDataContextDriver.CommonTypes.Values);
            var badAssemblies = new HashSet <Assembly>();

            this.LoadedTypes.AddRange(this.LoadedAssemblies.Values.Where(x => x != null)
                                      .SelectMany(ass =>
            {
                try
                {
                    return(ass.GetExportedTypes());
                }
                catch (Exception)
                {
                    badAssemblies.Add(ass);
                    return(Enumerable.Empty <Type>());
                }
            }));
            foreach (var badAssembly in badAssemblies)
            {
                var key = this.LoadedAssemblies.First(x => x.Value == badAssembly).Key;
                this.LoadedAssemblies[key] = null;
            }
            this.mDatabases = new Dictionary <string, HashSet <CollectionTypeMapping> >();
            foreach (var pair in props.CollectionTypeMappings)
            {
                this.mDatabases[pair.Key] = new HashSet <CollectionTypeMapping>(pair.Value);
            }

            this.cbDatabases.Items.Clear();
            this.cbDatabases.Items.AddRange(this.mDatabases.Keys.Cast <object>().ToArray());
            string db = this.mDatabases.Keys.FirstOrDefault();

            this.cbDatabases.SelectedItem = db;
            if (db != null)
            {
                this.dgCollectionTypes.DataSource = this.mDatabases[db].Select(m => new TypeMappingWrapper(m)).ToList();
            }
            else
            {
                this.dgCollectionTypes.DataSource = null;
            }
            if (props.SelectedDatabase != null)
            {
                this.cbDatabases.SelectedIndex = this.cbDatabases.Items.IndexOf(props.SelectedDatabase);
            }

            this.lbCustomSerializers.Items.Clear();
            this.SerializerMappings.Clear();
            if (props.CustomSerializers != null)
            {
                foreach (var pair in props.CustomSerializers)
                {
                    var keyType = this.LoadedTypes.FirstOrDefault(x => string.Equals(pair.Key, x.FullName));
                    var valType = this.LoadedTypes.FirstOrDefault(x => string.Equals(pair.Value, x.FullName));
                    if (keyType != null && valType != null)
                    {
                        this.SerializerMappings[keyType] = valType;
                    }
                }
            }
            this.lbCustomSerializers.Items.AddRange(this.SerializerMappings.Select(pair => new SerializerMappingWrapper {
                Type = pair.Key, Serializer = pair.Value
            }).Cast <object>().ToArray());

            this.mAdditionalOptions = props.AdditionalOptions;

            this.mInitializationQuery = props.InitializationQuery;
            if (this.mInitializationQuery != null)
            {
                this.SetLoadedQueryName(Path.GetFileName(this.mInitializationQuery.Location));
            }

            UpdateLoadedAssemblies();
        }
        private List <string> ValidateLinqQuery(LinqPadQuery query, ConnectionProperties props)
        {
            List <string> errors = new List <string>();

            StringBuilder sb = new StringBuilder();

            foreach (var ns in query.Namespaces)
            {
                sb.Append("using ").Append(ns).AppendLine(";");
            }
            sb.AppendFormat(@"
public class TestQuery
{{
    public TestQuery()
    {{

    }}

    {0}
}}", query.Query);

            var             driver = new MongoDynamicDataContextDriver();
            CompilerResults results;

            using (var codeProvider = new CSharpCodeProvider(new Dictionary <string, string>()
            {
                { "CompilerVersion", "v4.0" }
            }))
            {
                var assemblyNames = new HashSet <string>(query.References, new AssemblyPathEqualityComparer());

                //add additional assemblies which may or may not have been overridden
                assemblyNames.AddRange("System.dll System.Core.dll".Split());
                assemblyNames.Add(Path.Combine(driver.GetDriverFolder(), "MongoDB.Driver.dll"));
                assemblyNames.Add(Path.Combine(driver.GetDriverFolder(), "MongoDB.Bson.dll"));
                assemblyNames.Add(Path.Combine(driver.GetDriverFolder(), "LinqPadMongoDriver.dll"));

                var options = new CompilerParameters(assemblyNames.ToArray());
                options.GenerateInMemory = true;

                results = codeProvider.CompileAssemblyFromSource(options, sb.ToString());
            }
            if (results.Errors.Count > 0)
            {
                errors.AddRange(results.Errors.Cast <CompilerError>().Select(x => x.ToString()));

                return(errors);
            }

            Type       compiledType = results.CompiledAssembly.GetType("TestQuery");
            object     instance     = Activator.CreateInstance(compiledType);
            MethodInfo initMethod   = compiledType.GetMethod("Initialize", new[] { typeof(ConnectionProperties) });

            if (initMethod == null)
            {
                errors.Add(string.Format("The query must contain a method called Initialize that takes one parameter of type {0}", typeof(ConnectionProperties)));
                return(errors);
            }


            return(errors);
        }
 private void removeToolStripMenuItem_Click(object sender, EventArgs e)
 {
     this.mInitializationQuery = null;
     this.SetLoadedQueryName(null);
 }