Exemple #1
0
        /// <summary>
        /// Returns the QueryFirst config for a given query file. Values specified directly in
        /// the query's qfconfig.json file will override values specified in the project and install qfconfig.json files.
        ///
        /// If the config specifies a QfDefaultConnection but no QfDefaultConnectionProviderName, "System.Data.SqlClient"
        /// will be used.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="queryText"></param>
        /// <returns></returns>
        public State Go(State state, QfConfigModel outerConfig)
        {
            // read the config file if there is one.
            var queryConfig = ConfigFileReader.GetQueryConfig(state._1SourceQueryFullPath) ?? new QfConfigModel();



            // to do perhaps. Do we want to make this work again?
            //// if the query defines a QfDefaultConnection, use it.
            //var match = Regex.Match(state._2InitialQueryText, "^--QfDefaultConnection(=|:)(?<cstr>[^\r\n]*)", RegexOptions.Multiline);
            //if (match.Success)
            //{
            //    queryConfig.DefaultConnection = match.Groups["cstr"].Value;
            //    var matchProviderName = Regex.Match(state._2InitialQueryText, "^--QfDefaultConnectionProviderName(=|:)(?<pn>[^\r\n]*)", RegexOptions.Multiline);
            //    if (matchProviderName.Success)
            //    {
            //        queryConfig.Provider = matchProviderName.Groups["pn"].Value;
            //    }
            //    else
            //    {
            //        queryConfig.Provider = "System.Data.SqlClient";
            //    }

            //}
            state._3Config = ConfigBuilder.Resolve2Configs(outerConfig, queryConfig);
            return(state);
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            // parse args
            var startupOptions = DefineAndParseOptions(args);

            // check we have a file (should never be empty because if nothing provided we take the current directory.)
            if (!string.IsNullOrEmpty(startupOptions.SourcePath) && !File.Exists(startupOptions.SourcePath) && !Directory.Exists(startupOptions.SourcePath))
            {
                QfConsole.WriteLine($@"The file or directory {startupOptions.SourcePath} does not exist. Exiting...");
                return;
            }
            // fetch config query/project/install
            var configFileReader = new ConfigFileReader();
            var projectConfig    = configFileReader.GetProjectConfig(startupOptions.SourcePath);
            var installConfig    = configFileReader.GetInstallConfig();

            var projectType = new ProjectType().DetectProjectType();

            // build config project-install
            var configBuilder = new ConfigBuilder();
            var outerConfig   = configBuilder.Resolve2Configs(projectConfig, configBuilder.GetInstallConfigForProjectType(installConfig, projectType));

            // register types
            RegisterTypes.Register(outerConfig.HelperAssemblies);

            // New Config
            if (startupOptions.CreateConfig.GetValueOrDefault())
            {
                var fileToCreate = Path.Join(Environment.CurrentDirectory, "qfconfig.json");
                if (File.Exists(fileToCreate))
                {
                    Console.WriteLine($"QueryFirst: {fileToCreate} exists already. Skipping.");
                }
                File.WriteAllText(fileToCreate,
                                  $@"{{
  ""defaultConnection"": ""Server = localhost\\SQLEXPRESS; Database = NORTHWND; Trusted_Connection = True; "",
  ""provider"": ""System.Data.SqlClient"",
  ""namespace"": ""MyNamespaceForCodeGeneration""
}}
            "
                                  );
            }
            // New Runtime Connection
            if (startupOptions.CreateRuntimeConnection.GetValueOrDefault())
            {
                var fileToCreate = Path.Join(Environment.CurrentDirectory, "QfRuntimeConnection.cs");
                if (File.Exists(fileToCreate))
                {
                    Console.WriteLine($"QueryFirst: {fileToCreate} exists already. Skipping.");
                }
                File.WriteAllText(fileToCreate,
                                  $@"using Microsoft.Data.SqlClient;
using System.Data;

    class QfRuntimeConnection
    {{
        public static IDbConnection GetConnection()
        {{
            return new SqlConnection(""Server=localhost\\SQLEXPRESS;Database=NORTHWND;Trusted_Connection=True;"");
        }}
    }}
"
                                  );
            }
            // New query
            if (!string.IsNullOrEmpty(startupOptions.NewQueryName))
            {
                if (!startupOptions.NewQueryName.EndsWith(".sql"))
                {
                    startupOptions.NewQueryName = startupOptions.NewQueryName + ".sql";
                }
                if (File.Exists(startupOptions.NewQueryName))
                {
                    Console.WriteLine($"QueryFirst: {startupOptions.NewQueryName} exists already. Exiting");
                    return;
                }
                File.WriteAllText(startupOptions.NewQueryName,
                                  @"/* .sql query managed by QueryFirst */
-- designTime - put parameter declarations and design time initialization here
-- endDesignTime"
                                  );
                return;
            }

            // C'est pas beau. If we've created a file or shown help, we'll do nothing else...
            if (startupOptions.CreateConfig.GetValueOrDefault() ||
                startupOptions.CreateRuntimeConnection.GetValueOrDefault() ||
                !string.IsNullOrEmpty(startupOptions.NewQueryName) ||
                startupOptions.DidShowHelp
                )
            {
                return;
            }

            // Process one file
            if (File.Exists(startupOptions.SourcePath))
            {
                if (startupOptions.Watch)
                {
                    // watch for changes or renaming of the specified file. (VS renames a temp file after deleting the original file)
                    using (FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(startupOptions.SourcePath), Path.GetFileName(startupOptions.SourcePath)))
                    {
                        watcher.NotifyFilter = NotifyFilters.LastAccess
                                               | NotifyFilters.LastWrite
                                               | NotifyFilters.FileName
                                               | NotifyFilters.DirectoryName;


                        watcher.Changed += (source, e) =>
                        {
                            try
                            {
                                var conductor = new Conductor().BuildUp();
                                conductor.ProcessOneQuery(startupOptions.SourcePath, outerConfig);
                            }
                            catch (Exception ex)
                            {
                                Console.Write(ex.TellMeEverything());
                            }
                        };
                        //watcher.Deleted += OnChanged;
                        watcher.Renamed += (source, e) =>
                        {
                            try
                            {
                                var conductor = new Conductor().BuildUp();
                                conductor.ProcessOneQuery(startupOptions.SourcePath, outerConfig);
                            }
                            catch (Exception ex)
                            {
                                Console.Write(ex.TellMeEverything());
                            }
                        };
                        watcher.EnableRaisingEvents = true;
                        Console.WriteLine("Press 'q' to stop watching.");
                        while (Console.Read() != 'q')
                        {
                            ;
                        }
                    }
                }
                else
                {
                    var conductor = new Conductor().BuildUp();
                    conductor.ProcessOneQuery(startupOptions.SourcePath, outerConfig);
                }
            }
            // Process a folder
            if (Directory.Exists(startupOptions.SourcePath))
            {
                if (startupOptions.Watch)
                {
                    // watch for changes or renaming of .sql files in the specified folder.
                    using (FileSystemWatcher watcher = new FileSystemWatcher(startupOptions.SourcePath, "*.sql"))
                    {
                        watcher.NotifyFilter = NotifyFilters.LastAccess
                                               | NotifyFilters.LastWrite
                                               | NotifyFilters.FileName
                                               | NotifyFilters.DirectoryName;

                        watcher.IncludeSubdirectories = true;


                        watcher.Changed += (source, e) =>
                        {
                            try
                            {
                                if (e.FullPath.ToLower().EndsWith(".sql"))
                                {
                                    var conductor = new Conductor().BuildUp();
                                    conductor.ProcessOneQuery(e.FullPath, outerConfig);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.Write(ex.TellMeEverything());
                            }
                        };
                        //watcher.Deleted += OnChanged;
                        watcher.Renamed += (source, e) =>
                        {
                            try
                            {
                                if (e.FullPath.ToLower().EndsWith(".sql"))
                                {
                                    var conductor = new Conductor().BuildUp();
                                    conductor.ProcessOneQuery(e.FullPath, outerConfig);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.Write(ex.TellMeEverything());
                            }
                        };
                        watcher.EnableRaisingEvents = true;
                        Console.WriteLine($"Press 'q' to stop watching in ${startupOptions.SourcePath}");
                        while (Console.Read() != 'q')
                        {
                            ;
                        }
                    }
                }
                else
                {
                    ProcessDirectory(startupOptions.SourcePath, outerConfig);
                }

                if (keepOpen)
                {
                    Console.ReadKey();
                }
            }
        }