private static void BuildSettingsFile(string file, NpgsqlConnection connection, string pgroutinerSettingsFile) { try { File.WriteAllText(file, BuildFormatedSettings(connection: connection)); Program.WriteLine(""); Program.Write(ConsoleColor.Yellow, $"Settings file "); Program.Write(ConsoleColor.Cyan, pgroutinerSettingsFile); Program.WriteLine(ConsoleColor.Yellow, $" successfully created!", ""); Program.Write(ConsoleColor.Yellow, "- Run "); Program.Write(ConsoleColor.Cyan, $"pgroutiner {SettingsArgs.Alias}"); Program.Write(ConsoleColor.Yellow, " or "); Program.Write(ConsoleColor.Cyan, $"pgroutiner {SettingsArgs.Name}"); Program.WriteLine(ConsoleColor.Yellow, " to see current settings and switches."); Program.Write(ConsoleColor.Yellow, "- Run "); Program.Write(ConsoleColor.Cyan, $"pgroutiner {HelpArgs.Alias}"); Program.Write(ConsoleColor.Yellow, " or "); Program.Write(ConsoleColor.Cyan, $"pgroutiner {HelpArgs.Name}"); Program.WriteLine(ConsoleColor.Yellow, " to see help on available commands.", ""); } catch (Exception e) { Program.DumpError($"File {pgroutinerSettingsFile} could not be written: {e.Message}"); } }
public static bool WriteFile(string path, string content) { if (Settings.Value.Dump) { Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(content); Console.ResetColor(); return(true); } try { var dir = Path.GetDirectoryName(path); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllText(path, content); return(true); } catch (Exception e) { Program.DumpError($"File {path} could not be written: {e.Message}"); return(false); } }
public void RunAsShellExecute() { try { using var process = new Process(); process.StartInfo.FileName = settings.PsqlCommand; process.StartInfo.Arguments = $"{baseArg} {(settings.PsqlOptions ?? "")}"; process.StartInfo.CreateNoWindow = false; process.StartInfo.UseShellExecute = true; process.StartInfo.RedirectStandardInput = false; process.StartInfo.RedirectStandardOutput = false; process.StartInfo.RedirectStandardError = false; process.Start(); if (!OperatingSystem.IsWindows()) { process.WaitForExit(); } } catch (Exception e) { Program.DumpError(e.Message); } }
public static IConfigurationRoot ParseSettings(string[] args, string pgroutinerSettingsFile) { var argsList = args.ToList(); void ParseSwitches(object instance, bool setValue = false) { foreach (var prop in instance.GetType().GetProperties()) { if (prop.PropertyType != typeof(bool)) { continue; } Arg argNames; var argField = typeof(Settings).GetField($"{prop.Name}Args"); if (argField != null) { argNames = (Arg)argField.GetValue(null); } else { argNames = new Arg($"--{prop.Name.ToLower()}", prop.Name); } if (Program.ArgsInclude(args, argNames)) { prop.SetValue(instance, true); argsList.Remove(argNames.Alias); argsList.Remove(argNames.Name); if (setValue) { argsList.Add(argNames.Name); argsList.Add("True"); } } } } ParseSwitches(Switches.Value); ParseSwitches(Value, true); var pgroutinerFile = Path.Join(Program.CurrentDir, pgroutinerSettingsFile); var settingsFile = Path.Join(Program.CurrentDir, "appsettings.json"); var devSettingsFile = Path.Join(Program.CurrentDir, "appsettings.Development.json"); var files = new List <string>(); if (File.Exists(pgroutinerFile)) { files.Add(" " + Path.GetFileName(pgroutinerFile)); } if (File.Exists(devSettingsFile)) { files.Add(" " + Path.GetFileName(devSettingsFile)); } if (File.Exists(settingsFile)) { files.Add(" " + Path.GetFileName(settingsFile)); } IConfigurationRoot config; try { var configBuilder = new ConfigurationBuilder() .AddJsonFile(pgroutinerFile, optional: true, reloadOnChange: false) .AddJsonFile(settingsFile, optional: true, reloadOnChange: false) .AddJsonFile(devSettingsFile, optional: true, reloadOnChange: false); config = configBuilder.Build(); config.GetSection("PgRoutiner").Bind(Value); config.Bind(Value); if (!string.IsNullOrEmpty(Value.ConfigPath)) { Value.ConfigPath = Path.Join(Program.CurrentDir, Value.ConfigPath); if (File.Exists(settingsFile)) { files.Add(" " + Path.GetFileName(Value.ConfigPath)); } configBuilder = new ConfigurationBuilder() .AddJsonFile(pgroutinerFile, optional: true, reloadOnChange: false) .AddJsonFile(settingsFile, optional: true, reloadOnChange: false) .AddJsonFile(devSettingsFile, optional: true, reloadOnChange: false) .AddJsonFile(Value.ConfigPath, optional: true, reloadOnChange: false); config = configBuilder.Build(); config.GetSection("PgRoutiner").Bind(Value); config.Bind(Value); } Dictionary <string, string> switchMappings = new(); foreach (var f in typeof(Settings).GetFields()) { if (f.FieldType != typeof(Arg)) { continue; } var arg = (Arg)f.GetValue(null); switchMappings[arg.Alias] = arg.Original; } new ConfigurationBuilder() .AddCommandLine(argsList.ToArray(), switchMappings) .Build() .Bind(Value); } catch (Exception e) { Program.DumpError($"Failed to bind configuration: {e.Message}"); return(null); } if (files.Count > 0) { Program.WriteLine("", "Using configuration files: "); Program.WriteLine(ConsoleColor.Cyan, files.ToArray()); } foreach (var prop in typeof(Settings).GetProperties()) { if (prop.PropertyType != typeof(string)) { continue; } var value = prop.GetValue(Value) as string; if (value == "") { prop.SetValue(Value, null); } } if (Value.Mapping != null && Value.Mapping.Values.Count > 0) { foreach (var(key, value) in Value.Mapping) { DefaultTypeMapping[key] = value; } Value.Mapping = DefaultTypeMapping; } else { Value.Mapping = DefaultTypeMapping; } #if DEBUG Program.ParseProjectSetting(Value); #endif if (Value.Execute != null || Value.Psql || Value.CommitMd) { Value.DbObjects = false; Value.SchemaDump = false; Value.DataDump = false; Value.Diff = false; Value.Routines = false; Value.UnitTests = false; Value.Markdown = false; } if (!new string[] { "Single", "SingleOrDefault", "First", "FirstOrDefault" }.Contains(Value.ReturnMethod)) { Program.DumpError($"ReturnMethod setting must be one of the allowed values: Single, SingleOrDefault, First or FirstOrDefault"); return(null); } return(config); }
public static IConfigurationRoot ParseSettings(string[] args) { var settingsFile = Path.Join(Program.CurrentDir, "appsettings.json"); var devSettingsFile = Path.Join(Program.CurrentDir, "appsettings.Development.json"); var files = new List <string>(); if (File.Exists(devSettingsFile)) { files.Add(" " + Path.GetFileName(devSettingsFile)); } if (File.Exists(settingsFile)) { files.Add(" " + Path.GetFileName(settingsFile)); } if (files.Count() > 0) { Program.WriteLine("", "Using config files: "); Program.WriteLine(ConsoleColor.Cyan, files.ToArray()); } var configBuilder = new ConfigurationBuilder() .AddJsonFile(settingsFile, optional: true, reloadOnChange: false) .AddJsonFile(devSettingsFile, optional: true, reloadOnChange: false); var config = configBuilder.Build(); config.GetSection("PgRoutiner").Bind(Value); var cmdLineConfigBuilder = new ConfigurationBuilder().AddCommandLine(args); var cmdLine = cmdLineConfigBuilder.Build(); cmdLine.Bind(Value); if (Value.SimilarTo == "") { Value.SimilarTo = null; } if (Value.NotSimilarTo == "") { Value.NotSimilarTo = null; } if (Value.ModelDir == "") { Value.ModelDir = null; } if (Value.Mapping != null) { foreach (var(key, value) in Value.Mapping) { DefaultTypeMapping[key] = value; } Value.Mapping = DefaultTypeMapping; } else { Value.Mapping = DefaultTypeMapping; // new Dictionary<string, string>(); } if (!string.IsNullOrEmpty(Value.Connection)) { if (!string.IsNullOrEmpty(config.GetConnectionString(Value.Connection))) { return(config); } Program.DumpError($"Connection name {Value.Connection} could not be found in settings, exiting..."); return(null); } if (!config.GetSection("ConnectionStrings").GetChildren().Any()) { Program.DumpError($"Connection setting is not set and ConnectionStrings section doesn't contain any values, exiting..."); return(null); } Value.Connection = config.GetSection("ConnectionStrings").GetChildren().First().Key; return(config); }
private string ParseConnStringInternal(string connectionStr) { string user = null; string pass = null; string server = null; string port = null; string database = null; string addition = null; try { if (connectionStr.StartsWith("postgresql://")) { connectionStr = connectionStr.Remove(0, "postgresql://".Length); var parts = connectionStr.Split('@'); var first = parts.First(); var second = parts.Last(); var firstParts = first.Split(':'); user = firstParts.First(); pass = firstParts.Last(); var secondParts = second.Split('/'); var host = secondParts.First(); database = secondParts.Last(); var hostParts = host.Split(':'); server = hostParts.First(); port = hostParts.Last(); if (!string.IsNullOrEmpty(server)) { server = $"Server={server};"; } if (!string.IsNullOrEmpty(port)) { port = $"Port={port};"; } if (!string.IsNullOrEmpty(database)) { database = $"Db={database};"; } if (!string.IsNullOrEmpty(user)) { user = $"User Id={user};"; } if (!string.IsNullOrEmpty(pass)) { pass = $"Password={pass};"; } } else { foreach (var part in connectionStr.Split(';')) { var parts = part.Split('=', 2); var first = parts.First().ToLower(); var second = parts.Last(); if (string.IsNullOrEmpty(first)) { continue; } if (string.Equals(first, "user id") || string.Equals(first, "user") || string.Equals(first, "username")) { user = $"User Id={second};"; continue; } if (string.Equals(first, "password")) { pass = $"Password={second};"; continue; } if (string.Equals(first, "server") || string.Equals(first, "host")) { server = $"Server={second};"; continue; } if (string.Equals(first, "port")) { port = $"Port={second};"; continue; } if (string.Equals(first, "db") || string.Equals(first, "database")) { database = $"Db={second};"; continue; } if (!string.IsNullOrEmpty(part)) { addition = string.Concat(addition == null ? "" : $"{addition};", part); } } } } catch { Program.DumpError($"Connection string \"{connectionStr}\" is malformed."); return(null); } if (string.IsNullOrEmpty(server)) { server = GetServer(Settings.Value.SkipConnectionPrompt); } if (string.IsNullOrEmpty(port)) { port = GetPort(Settings.Value.SkipConnectionPrompt); } if (string.IsNullOrEmpty(database)) { database = GetDatabase(Settings.Value.SkipConnectionPrompt); } if (string.IsNullOrEmpty(user)) { user = GetUser(Settings.Value.SkipConnectionPrompt); } if (string.IsNullOrEmpty(pass)) { pass = GetPassword(Settings.Value.SkipConnectionPrompt); } return($"{server}{database}{port}{user}{pass}{addition}"); }
public NpgsqlConnection ParseConnectionString() { if (!string.IsNullOrEmpty(name)) { var connectionStr = config.GetConnectionString(name); if (string.IsNullOrEmpty(connectionStr)) { connectionStr = ParseConnStringInternal(name); } else { connectionStr = ParseConnStringInternal(connectionStr); } if (connectionStr == null) { return(null); } try { return(CreateAndOpen(connectionStr)); } catch (Exception e) { Program.DumpError($"Could not open {name}{Environment.NewLine}{e.Message}{Environment.NewLine}Exiting..."); return(null); } } else { var configKey = GetConnStringConfigKey(); if (configKey != null) { typeof(Settings).GetProperty(connectionKey).SetValue(Settings.Value, configKey); var connectionStr = ParseConnStringInternal(config.GetConnectionString(configKey)); if (connectionStr == null) { return(null); } try { return(CreateAndOpen(connectionStr)); } catch (Exception e) { Program.DumpError($"Could not open {name}{Environment.NewLine}{e.Message}{Environment.NewLine}Exiting..."); return(null); } } else { var connectionStr = GetConnectionString(); try { return(CreateAndOpen(connectionStr)); } catch (Exception e) { Program.DumpError($"Could not open {connectionStr}{Environment.NewLine}{e.Message}{Environment.NewLine}Exiting..."); return(null); } } } }
private static void UpdateProjectReferences(Project project) { if (project.NpgsqlIncluded == false) { if (!Value.SkipUpdateReferences) { Program.DumpError($"Npgsql package package is required."); if (Program.Ask("Add Npgsql reference? [Y/N]", ConsoleKey.Y, ConsoleKey.N) == ConsoleKey.Y) { Program.RunProcess("dotnet", "add package Npgsql"); } } } if (!Value.SkipAsyncMethods && project.AsyncLinqIncluded == false) { if (!Value.SkipUpdateReferences) { Program.DumpError($"To be able to use async methods, System.Linq.Async package is required."); if (Program.Ask("Add System.Linq.Async package reference? [Y/N]", ConsoleKey.Y, ConsoleKey.N) == ConsoleKey.Y) { Program.RunProcess("dotnet", "add package System.Linq.Async"); } } } if (string.IsNullOrEmpty(project.NormVersion)) { if (!Value.SkipUpdateReferences) { Program.DumpError($"Norm.net package package is required."); if (Program.Ask("Add Norm.net reference? [Y/N]", ConsoleKey.Y, ConsoleKey.N) == ConsoleKey.Y) { Program.RunProcess("dotnet", "add package Norm.net"); project.NormVersion = Value.MinNormVersion; } } } var minNormVersion = Convert.ToInt32(Value.MinNormVersion.Replace(".", "")); try { var version = Convert.ToInt32(project.NormVersion.Replace(".", "")); if (version < minNormVersion) { throw new Exception(); } } catch (Exception) { if (!Value.SkipUpdateReferences) { Program.DumpError($"Minimum version for Norm.net package is {Settings.Value.MinNormVersion}. Current version in project is {project.NormVersion}."); if (Program.Ask("Update Norm.net package? [Y/N]", ConsoleKey.Y, ConsoleKey.N) == ConsoleKey.Y) { Program.RunProcess("dotnet", "add package Norm.net"); } } } }
private static Project ParseProjectFile() { string projectFile = null; #if DEBUG var projectSetting = Value.Project; #else string projectSetting = null; #endif if (!string.IsNullOrEmpty(projectSetting)) { projectFile = Path.Combine(Program.CurrentDir, Path.GetFileName(projectSetting)); if (!File.Exists(projectFile)) { Program.DumpError($"Couldn't find a project to run. Ensure that a {Path.GetFullPath(projectFile)} project exists, or pass the path to the project in a first argument (pgroutiner path)"); return(null); } } else { foreach (var file in Directory.EnumerateFiles(Program.CurrentDir, "*.csproj", SearchOption.TopDirectoryOnly)) { if (Path.GetExtension(file)?.ToLower() == ".csproj") { projectFile = file; break; } } if (projectFile == null) { Program.DumpError($"Couldn't find a project to run. Ensure a project exists in {Path.GetFullPath(Program.CurrentDir)}, or pass the path to the project in a first argument (pgroutiner path)"); return(null); } } Program.WriteLine("", "Using project file: "); Program.WriteLine(ConsoleColor.Cyan, " " + Path.GetFileName(projectFile)); var ns = Path.GetFileNameWithoutExtension(projectFile); Project result = new Project { ProjectFile = projectFile }; using (var fileStream = File.OpenText(projectFile)) { using var reader = XmlReader.Create(fileStream, new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true }); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "RootNamespace") { if (reader.Read()) { ns = reader.Value; } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "PackageReference") { if (reader.GetAttribute("Include") == "Norm.net") { result.NormVersion = reader.GetAttribute("Version"); } if (reader.GetAttribute("Include") == "System.Linq.Async") { result.AsyncLinqIncluded = true; } if (reader.GetAttribute("Include") == "Npgsql") { result.NpgsqlIncluded = true; } } } } if (string.IsNullOrEmpty(Value.Namespace)) { Value.Namespace = ns; } return(result); }