Beispiel #1
0
        void Initialize()
        {
            if (Args.Contains("--help") || Args.Contains("-h"))
            {
                int width = Console.BufferWidth;
                using (var str = new StringReader(Gen.Messages.AppHelpString))
                {
                    string line = str.ReadLine();
                    if (!string.IsNullOrEmpty(line))
                    {
                        int firstChar = FirstNonSpace(line);
                    }
                }
                Console.Write(Gen.Messages.AppHelpString);
                return;
            }

            settings.FileConfig    = GetFileFromArgument("-gcfg");
            settings.FileTemplates = GetFileFromArgument("-it");
            settings.FileSchema    = GetFileFromArgument("-is");
            settings.JsonConfig    = GetFileFromArgument("-ij");
            settings.FileIn        = GetFileFromArgument("-i");
            settings.FileOut       = GetFileFromArgument("-o");

            if (Args.Contains("-db"))
            {
                settings.DatabaseName = this.GetValue(true, "-db");
            }
            else if (Args.Contains("-dbn"))
            {
                settings.DatabaseName = this.GetValue(true, "-dbn");
            }

            if (Args.Contains("-t"))
            {
                settings.TableName = this.GetValue(true, "-t");
            }
            else if (Args.Contains("-table"))
            {
                settings.TableName = this.GetValue(true, "-table");
            }
            else if (Args.Contains("-tbln"))
            {
                settings.TableName = this.GetValue(true, "-tbln");
            }

            if (Args.Contains("-tpl"))
            {
                settings.TemplateName = this.GetValue(true, "-tpl");
            }
            else if (Args.Contains("-tpln"))
            {
                settings.TemplateName = this.GetValue(true, "-tpln");
            }

            if (Args.Contains("-r"))
            {
                settings.ReplacementTag = this.GetValue(true, "-r");
            }
        }
Beispiel #2
0
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     try
     {
         var assemblyPath = Path.Combine(Path.GetDirectoryName(TargetPath), "AssemblyInfo.json");
         if (File.Exists(assemblyPath))
         {
             var content = File.ReadAllText(assemblyPath);
             jsonAssembly                = serializer.Deserialize <AssemblyInfo>(content);
             checkEmbed.IsChecked        = jsonAssembly.EmbedFiles;
             textAssemblyVersion.Text    = jsonAssembly.AssemblyVersion;
             textFileVersion.Text        = jsonAssembly.FileVersion;
             textProductName.Text        = jsonAssembly.ProductName;
             textProductDescription.Text = jsonAssembly.ProductDescription;
             textCompanyName.Text        = jsonAssembly.CompanyName;
             textCopyright.Text          = jsonAssembly.Copyright;
         }
     }
     catch { }
     if (Args.Contains("-silent"))
     {
         this.Hide();
         buttonMake_Click(buttonMake, new RoutedEventArgs());
     }
 }
        private void ValidateArgs(Cmd cmd)
        {
            if (HasAnonymousArg && cmd.Arg == null)
            {
                throw new ArgumentError("Anonymous(unnamed) argument expected");
            }
            if (!HasAnonymousArg && cmd.Arg != null)
            {
                throw new ArgumentError($"Unexpected anonymous(unnamed) argument '{cmd.Arg.Value.Lexeme}'");
            }

            foreach (var x in Required)
            {
                if (!cmd.Args.Contains(x))
                {
                    throw new ArgumentError($"Argument '{x.Lexeme}' expected");
                }
            }

            foreach (var x in cmd.Args)
            {
                if (!Args.Contains(x))
                {
                    throw new ArgumentError($"Unexpected argument '{x.Lexeme}'");
                }
            }
        }
Beispiel #4
0
 static CommandLineArgs()
 {
     IsAutoStart     = Args.Contains(NTKeyword.AutoStartCmdParameterName, StringComparer.OrdinalIgnoreCase);
     Upgrade         = PickArgument(NTKeyword.UpgradeCmdParameterName);
     Action          = PickArgument(NTKeyword.ActionCmdParameterName);
     NTMinerFileName = PickArgument("ntminerFileName=");
 }
Beispiel #5
0
        protected override void ConfigureIoC(IStyletIoCBuilder builder)
        {
            _logger.LogInformation("Configuring IoC");

            _logger.LogInformation("Setting {type}", typeof(StartupInfo).ToString());
            var startup = new StartupInfo
            {
                Args = Args
            };

            startup.StartMinmized = Args.Contains("minimized");
            builder.Bind <StartupInfo>().ToInstance(startup);

            builder.Bind <Func <Type, ILogger> >().ToInstance(_createLogger);

            builder.Bind <IEntropy>().ToInstance(new AssemblyNameEntropy());

            // Configure the IoC container in here
            foreach (StyletIoCModule item in s_iocModules)
            {
                _logger?.LogDebug("Adding {iocmodule}: '{module}'", nameof(StyletIoCModule), item.TypeName());
                builder.AddModule(item);
            }

            builder.Bind <Tick>().ToSelf().InSingletonScope();
        }
Beispiel #6
0
        public async Task RunAsync()
        {
            if (Args.Length == 1 && (Args[0] == "-h" || Args[0] == "--help"))
            {
                ShowHelp();
                return;
            }

            if (Args.Length == 0)
            {
                HandleMissingParams();
                return;
            }

            if (Args.Length == 1)
            {
                await GetIssueByKey(Args[0]);

                return;
            }

            if (Args.Length == 2 && (Args.Contains("-c") || Args.Contains("--create")))
            {
                await GetIssueAndCreateBranch(Args);

                return;
            }

            HandleUnknownParam();
        }
Beispiel #7
0
        public void Run()
        {
            if (Args.Length == 1 && (Args[0] == "-h" || Args[0] == "--help"))
            {
                ShowHelp();
                return;
            }

            GitUtils.CheckIfRepository();

            if (Args.Length == 0)
            {
                ShowUser(isGlobal: false);
                return;
            }

            if (Args.Length == 1 && (Args[0] == "-g" || Args[0] == "--global"))
            {
                ShowUser(isGlobal: true);
                return;
            }

            if (Args.Length == 1 && (Args[0] == "-p" || Args[0] == "--personal"))
            {
                SetUser(isGlobal: false, config: UserConfig.Personal);
                return;
            }

            if (Args.Length == 1 && (Args[0] == "-w" || Args[0] == "--work"))
            {
                SetUser(isGlobal: false, config: UserConfig.Work);
                return;
            }

            if (
                Args.Length == 2 &&
                (Args.Contains("-g") || Args.Contains("--global")) &&
                (Args.Contains("-p") || Args.Contains("--personal"))
                )
            {
                SetUser(isGlobal: true, config: UserConfig.Personal);
                return;
            }

            if (
                Args.Length == 2 &&
                (Args.Contains("-g") || Args.Contains("--global")) &&
                (Args.Contains("-w") || Args.Contains("--work"))
                )
            {
                SetUser(isGlobal: true, config: UserConfig.Work);
                return;
            }

            HandleUnknownParam();
        }
Beispiel #8
0
        FileInfo GetFileFromArgument(string argument)
        {
            if (!Args.Contains(argument))
            {
                return(null);
            }
            var val = GetValue(true, argument);
            var f   = new FileInfo(val);

            return(new FileInfo(val));
        }
        public static bool IsExempt(FiOSServer Server, ExemptionType ExemptType, params string[] Args)
        {
            var exemptionsEle = _config.Root.Descendants(_ns + "Exemptions");
            var exemptTypeEle = exemptionsEle.Elements().Where(x => x.Name.LocalName.ToUpper() == ExemptType.ToString().ToUpper());

            if (exemptTypeEle.Count() == 0)
            {
                return(false);
            }

            if (exemptTypeEle.Descendants().Any(x => x.Name.LocalName.ToUpper().Equals("SERVER")) && !exemptTypeEle.Descendants(_ns + "Server").Attributes("Name").Select(x => x.Value).Any(x => x.Equals(Server.HostName)))
            {
                return(false);
            }

            if (ExemptType == ExemptionType.HardDrive)
            {
                var driveLetters = exemptTypeEle.Elements(_ns + "DriveLetter").Select(x => x.Value);

                bool containsAll = true;
                foreach (var dl in driveLetters)
                {
                    if (!(Args.Contains(dl) || Args.Contains(dl + ":")) && containsAll)
                    {
                        containsAll = false;
                    }
                }
                return(containsAll);
            }
            else if (ExemptType == ExemptionType.IIS)
            {
                return(true);
            }

            return(false);
        }
Beispiel #10
0
        public PuttyStartInfo(SessionData session)
        {
            Session = session;
            string argsToLog = null;

            Executable = GetExecutable(session);

            if (session.Proto == ConnectionProtocol.Cygterm)
            {
                CygtermStartInfo cyg = new CygtermStartInfo(session);
                Args       = cyg.Args;
                WorkingDir = cyg.StartingDir;
            }
            else if (session.Proto == ConnectionProtocol.Mintty)
            {
                MinttyStartInfo mintty = new MinttyStartInfo(session);
                Args       = mintty.Args;
                WorkingDir = mintty.StartingDir;
            }
            else if (session.Proto == ConnectionProtocol.VNC)
            {
                VNCStartInfo vnc = new VNCStartInfo(session);
                Args       = vnc.Args;
                WorkingDir = vnc.StartingDir;
            }
            else
            {
                Args      = MakeArgs(session, true);
                argsToLog = MakeArgs(session, false);
            }

            // attempt to parse env vars
            Args = Args.Contains('%') ? TryParseEnvVars(Args) : Args;

            Log.InfoFormat("Putty Args: '{0}'", argsToLog ?? Args);
        }
Beispiel #11
0
        public NesGame(string path)
        {
            GamePath   = path;
            Code       = Path.GetFileNameWithoutExtension(path);
            ConfigPath = Path.Combine(path, Code + ".desktop");
            NesPath    = Path.Combine(path, Code + ".nes");
            if (File.Exists(NesPath))
            {
                Type = GameType.Cartridge;
            }
            else
            {
                var fdsPath = Path.Combine(path, Code + ".fds");
                if (File.Exists(fdsPath))
                {
                    NesPath = fdsPath;
                    Type    = GameType.FDS;
                }
                else
                {
                    throw new Exception("ROM not found: " + path);
                }
            }
            IconPath      = Path.Combine(path, Code + ".png");
            SmallIconPath = Path.Combine(path, Code + "_small.png");
            GameGeniePath = Path.Combine(path, GameGenieFileName);
            if (!File.Exists(ConfigPath))
            {
                throw new FileNotFoundException("Invalid game directory: " + path);
            }

            Name         = Code;
            Players      = 1;
            Simultaneous = false;
            ReleaseDate  = DefaultReleaseDate;
            Args         = DefaultArgs;
            Publisher    = DefaultPublisher;

            var configLines = File.ReadAllLines(ConfigPath);

            foreach (var line in configLines)
            {
                int pos = line.IndexOf('=');
                if (pos <= 0)
                {
                    continue;
                }
                var param = line.Substring(0, pos).Trim().ToLower();
                var value = line.Substring(pos + 1).Trim();
                switch (param)
                {
                case "exec":
                    Args = line;
                    if (Args.Contains(".nes"))
                    {
                        Args = Args.Substring(Args.IndexOf(".nes") + 4).Trim();
                    }
                    else if (Args.Contains(".fds"))
                    {
                        Args = Args.Substring(Args.IndexOf(".fds") + 4).Trim();
                    }
                    else
                    {
                        Args = "";
                    }
                    break;

                case "name":
                    Name = value;
                    break;

                case "players":
                    Players = byte.Parse(value);
                    break;

                case "simultaneous":
                    Simultaneous = value != "0";
                    break;

                case "releasedate":
                    ReleaseDate = value;
                    break;

                case "sortrawpublisher":
                    Publisher = value;
                    break;
                }
            }
            if (File.Exists(GameGeniePath))
            {
                GameGenie = File.ReadAllText(GameGeniePath);
            }
            hasUnsavedChanges = false;
        }
Beispiel #12
0
        private void buttonMake_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (checkSave.IsChecked == true)
                {
                    var assemblyPath = Path.Combine(Path.GetDirectoryName(TargetPath), "AssemblyInfo.json");
                    jsonAssembly                    = new AssemblyInfo();
                    jsonAssembly.EmbedFiles         = checkEmbed.IsChecked;
                    jsonAssembly.AssemblyVersion    = textAssemblyVersion.Text;
                    jsonAssembly.FileVersion        = textFileVersion.Text;
                    jsonAssembly.ProductName        = textProductName.Text;
                    jsonAssembly.ProductDescription = textProductDescription.Text;
                    jsonAssembly.CompanyName        = textCompanyName.Text;
                    jsonAssembly.Copyright          = textCopyright.Text;
                    File.WriteAllText(assemblyPath, serializer.Serialize(jsonAssembly));
                }
            }
            catch { }
            var provider       = CodeDomProvider.CreateProvider("CSharp");
            var compilerParams = new CompilerParameters();

            compilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("System.Core.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
            compilerParams.ReferencedAssemblies.Add("System.Xml.dll");
            compilerParams.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            compilerParams.GenerateExecutable = true;
            compilerParams.OutputAssembly     = Path.GetDirectoryName(TargetPath) + @"\" + Path.GetFileNameWithoutExtension(TargetPath) + ".exe";
            compilerParams.EmbeddedResources.Add(TargetPath);

            if (checkEmbed.IsChecked == true || Args.Contains("-embed"))
            {
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(TargetPath)).Where(strPath => strPath != TargetPath))
                {
                    if (Path.GetExtension(file) == ".ico")
                    {
                        compilerParams.CompilerOptions = "/win32icon:\"" + file + "\" /fullpaths";
                    }
                    compilerParams.EmbeddedResources.Add(file);
                }
            }
            var fs        = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Make_EXE.Maker.cs");
            var strScript = new StreamReader(fs).ReadToEnd();

            fs.Close();
            strScript = strScript.Replace("[assembly: System.Reflection.AssemblyVersion(\"0.0.0.0\")]", "[assembly: System.Reflection.AssemblyVersion(\"" + jsonAssembly.AssemblyVersion + "\")]");
            strScript = strScript.Replace("[assembly: System.Reflection.AssemblyFileVersion(\"0.0.0.0\")]", "[assembly: System.Reflection.AssemblyFileVersion(\"" + jsonAssembly.FileVersion + "\")]");
            strScript = strScript.Replace("[assembly: System.Reflection.AssemblyProduct(\"\")]", "[assembly: System.Reflection.AssemblyProduct(\"" + jsonAssembly.ProductName + "\")]");
            strScript = strScript.Replace("[assembly: System.Reflection.AssemblyDescription(\"\")]", "[assembly: System.Reflection.AssemblyDescription(\"" + jsonAssembly.ProductDescription + "\")]");
            strScript = strScript.Replace("[assembly: System.Reflection.AssemblyCompany(\"\")]", "[assembly: System.Reflection.AssemblyCompany(\"" + jsonAssembly.CompanyName + "\")]");
            strScript = strScript.Replace("[assembly: System.Reflection.AssemblyCopyright(\"\")]", "[assembly: System.Reflection.AssemblyCopyright(\"" + jsonAssembly.Copyright + "\")]");
            if (Args.Contains("-redirect") || checkRedirect.IsChecked == true)
            {
                strScript = strScript.Replace("static bool redirect = false;", "static bool redirect = true;");
            }
            var results = provider.CompileAssemblyFromSource(compilerParams, strScript);

            if (!Args.Contains("-silent"))
            {
                this.Hide();
                if (results.Errors.HasErrors)
                {
                    MessageBox.Show("There were errors compiling the EXE.", "Compiler Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                    foreach (CompilerError error in results.Errors)
                    {
                        MessageBox.Show("Error: " + error.ErrorNumber + ": " + error.ErrorText + "  Column: " + error.Column + "  Line: " + error.Line);
                    }
                }
                else
                {
                    MessageBox.Show("Your EXE has been packaged!  Location: " + compilerParams.OutputAssembly, "EXE Packaged", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            if (results.Errors.HasErrors)
            {
                Environment.Exit(1);
            }
            else
            {
                Environment.Exit(0);
            }
        }
Beispiel #13
0
        protected override void Execute(Args args)
        {
            var root = args.GetValue("directory");
            var server = args.GetValue("server");
            var database = args.GetValue("database");

            if (args.Contains("quiet"))
            {
                Console.WriteLine("Exctracting artefacts from {0} {1}", server, database);
            }
            else
            {
                Console.Write("Exctract artefacts from {0} {1} (y/n)? ", server, database);
                if (!Console.ReadLine().Equals("y", StringComparison.CurrentCultureIgnoreCase)) return;
            }

            var filters = new[]
                              {
                                  "^_.+$",
                                  "^(sp|fn)_.*diagram.*$",
                                  "^.+_dts_.+$",
                                  "^.+_gen_.+$",
                                  "^conv_.+$",
                                      "^IsScriptExecuted$",
                                      "^syncobj_.+$",
                                      "^sysextendedarticlesview$"
                              };
            var types = new[]
                            {
                                new TypeDef{Key = "FN", Name = "function", Dir = "Functions"},
                                new TypeDef{Key = "P",  Name = "procedure", Dir = "StoredProcedures"},
                                new TypeDef{Key = "V",  Name = "view", Dir = "Views"}
                            };

            var schemas = Database.Query<Item>("select * from sys.schemas").ToDictionary(x => x.schema_id, x => x.name);
            foreach (var type in types)
            {
                var dir = Path.Combine(root, type.Dir);
                MakeSureDirectoryExists(dir);

                var files = Directory.GetFiles(dir, "*.sql", SearchOption.AllDirectories).ToList();
                foreach (var file in files.ToList())
                {
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
                    if (!filters.Any(x => Regex.IsMatch(fileNameWithoutExtension, x, RegexOptions.IgnoreCase))) continue;
                    RemoveReadOnlyAttribute(file);
                    File.Delete(file);
                    files.Remove(file);

                }
                using (TemporaryConsoleColorError())
                    foreach (var @group in files.GroupBy(x => Path.GetFileName(x).ToLower()).Where(x => x.Count() > 1))
                    {
                        Console.WriteLine("duplicate filenames");
                        foreach (var file in @group)
                            Console.WriteLine("  " + file);
                    }

                var filesByLowerCaseFileName = files.ToDictionary(x => Path.GetFileName(x).ToLower());
                var selectItemsSql = string.Format("select name, schema_id from sys.objects where type = '{0}'", type.Key);
                foreach (var item in Database.Query<Item>(selectItemsSql))
                {
                    if (filters.Any(x => Regex.IsMatch(item.name, x, RegexOptions.IgnoreCase))) continue;
                    var schema = schemas[item.schema_id];
                    var filename = (schema == "dbo" ? item.name : schema + "." + item.name) + ".sql";
                    string targetPath;
                    if (!filesByLowerCaseFileName.TryGetValue(filename.ToLower(), out targetPath))
                        targetPath = Path.Combine(dir, filename);
                    RemoveReadOnlyAttribute(targetPath);
                    File.WriteAllText(targetPath, CreateScript(schema, item.name, type));
                    filesByLowerCaseFileName.Remove(filename.ToLower());
                }
                foreach (var file in filesByLowerCaseFileName.Values)
                {
                    RemoveReadOnlyAttribute(file);
                    File.Delete(file);
                }
            }
        }
Beispiel #14
0
 /// <summary>
 /// Checks for equality of an item with any element of an array of items.
 /// </summary>
 public static bool Is <T>(this T Item, params T[] Args) => Args.Contains(Item);
Beispiel #15
0
        public override void Execute(IEmailItem emailItem = null, int?lastExitCode = null)
        {
            ExitCode = (int)ExitCodeEnum.CommandNotRun;

            if (!AppliesTo(emailItem, lastExitCode))
            {
                return;
            }

            string exportFileName = string.Empty;

            if (Export)
            {
                if (string.IsNullOrEmpty(ExportPath))
                {
                    ExportPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                }

                var invalidPathChars = Path.GetInvalidPathChars();
                ExportPath = new string(ExportPath.Where(x => !invalidPathChars.Contains(x)).ToArray());

                if (string.IsNullOrEmpty(EmlFileName))
                {
                    var messageId = emailItem.Message.MessageId;
                    EmlFileName = !string.IsNullOrEmpty(messageId) ? string.Format("{0}.eml", messageId) : string.Format("{0}.eml", Guid.NewGuid());
                }

                EmlFileName    = new string(EmlFileName.Where(x => !invalidPathChars.Contains(x)).ToArray());
                exportFileName = Path.Combine(ExportPath, EmlFileName);

                if (null != emailItem && !emailItem.IsExported)
                {
                    Logger.Debug(@"[GenericTransportAgent] Exporting EML file to ""{1}""...", EmlFileName);
                    emailItem.Save(exportFileName);
                }
            }

            if (!string.IsNullOrEmpty(Cmd))
            {
                var process = new Process {
                    StartInfo = { FileName = Cmd, },
                };

                if (!string.IsNullOrEmpty(Args))
                {
                    if (Args.Contains("$emlfile$"))
                    {
                        Args = Args.Replace("$emlfile$", exportFileName);
                    }

                    process.StartInfo.Arguments = Args;
                }

                Logger.Debug(@"[GenericTransportAgent] Running command ""{1}"" (args: ""{2}"")...", Cmd, Args);
                process.Start();
                process.WaitForExit(Timeout);

                if (!process.HasExited)
                {
                    Logger.Debug(@"[GenericTransportAgent] - Command did not exit successfully...");
                    process.Kill();
                    ExitCode = (int)ExitCodeEnum.CommandTimedOut;
                }
                else
                {
                    ExitCode = process.ExitCode;
                    Logger.Debug(@"[GenericTransportAgent] - Command did exit successfully, exit code {1}...", ExitCode);
                }
            }

            if (null == Handlers || Handlers.Count <= 0)
            {
                return;
            }

            foreach (var handler in Handlers)
            {
                handler.Execute(emailItem, ExitCode);
            }
        }
Beispiel #16
0
        protected override void Execute(Args args)
        {
            Console.WriteLine();
            Console.WriteLine("Server   " + args.GetValue("server"));
            Console.WriteLine("Database " + args.GetValue("database"));

            const string isInitialized =
               "select * from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'dbo' and TABLE_NAME = 'ScriptLog'";
            if (!Database.Query(isInitialized).Any()) throw new ApplicationException("Database has not been intialized");

            var scriptLogEntries = ScriptLogEntry.Load(Database).ToList();
            var lastScriptLogEntry = GetLastScriptLogEntry(scriptLogEntries);
            var executedScriptFileNames = GetExecutedScriptFileNames(scriptLogEntries);

            var directory = args.GetValue("directory");
            var recursive = args.Contains("recursive");
            var scriptsNotExecuted = ScriptFile.Load(directory, recursive)
                                               .Where(x => !executedScriptFileNames.Contains(x.VersionAndNumber))
                                               .ToList();
            var obsoleteScripts =
               scriptsNotExecuted.Where(
                                        x =>
                                        x.GetComparableVersion() <
                                        lastScriptLogEntry.GetComparableVersion(IncludeScriptNumber.Yes)).ToList();
            var newScripts =
               scriptsNotExecuted.Where(
                                        x =>
                                        x.GetComparableVersion() >
                                        lastScriptLogEntry.GetComparableVersion(IncludeScriptNumber.No)).ToList();

            Console.WriteLine();
            Console.Write("Current version " + lastScriptLogEntry.Version);
            if (lastScriptLogEntry.ScriptNumber.HasValue)
                Console.Write("_" + lastScriptLogEntry.ScriptNumber);
            Console.WriteLine();

            if (obsoleteScripts.Any())
            {
                using (TemporaryConsoleColorWarning())
                {
                    Console.WriteLine();
                    Console.WriteLine("Scripts that won't be executed");
                    foreach (var scriptFile in obsoleteScripts)
                        Console.WriteLine("  {0}", scriptFile.FileName);
                }
            }

            if (!newScripts.Any())
            {
                Console.WriteLine();
                Console.WriteLine("Did not find any scripts to execute");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("Scripts that will be executed");
            foreach (var scriptFile in newScripts)
            {
                Console.Write("  {0}", scriptFile.FileName);
                if (scriptFile.Version == lastScriptLogEntry.Version &&
                    scriptFile.Number < lastScriptLogEntry.ScriptNumber.GetValueOrDefault())
                    using (TemporaryConsoleColorWarning())
                        Console.Write(" - older than current version");
                Console.WriteLine();
            }

            if (!args.Contains("quiet"))
            {
                Console.WriteLine();
                Console.Write("Continue (y/n): ");
                if (!"y".Equals(Console.ReadLine(), StringComparison.CurrentCultureIgnoreCase))
                    return;
            }

            var includesNotFound = new List<string>();
            var includesWithErrors = new Dictionary<string, IncludedScriptState>(StringComparer.CurrentCultureIgnoreCase);

            var stopwatch = Stopwatch.StartNew();
            foreach (var scriptFile in newScripts)
            {
                var scriptFileStopwatch = Stopwatch.StartNew();
                Console.WriteLine();
                Console.WriteLine("{0}", scriptFile.FileName);
                Database.Execute(x =>
                                 {
                                     foreach (var batch in scriptFile.GetBatches())
                                     {
                                         var batchStopwatch = Stopwatch.StartNew();
                                         var result = x.Execute(batch.Sql);
                                         Console.WriteLine("  lines {0}-{1} affected {2} rows, executed in {3}",
                                                           batch.FromLine,
                                                           batch.ToLine,
                                                           result,
                                                           Format(batchStopwatch.Elapsed));
                                     }

                                     foreach (var includedScript in scriptFile.GetIncludes())
                                     {
                                         try
                                         {
                                             Console.Write("  include {0}", includedScript.Path);
                                             foreach (var batch in includedScript.GetBatches())
                                                 x.Execute(batch.Sql);
                                             Console.WriteLine();
                                             if (includesWithErrors.ContainsKey(includedScript.Path))
                                                 includesWithErrors[includedScript.Path] = IncludedScriptState.Applied;
                                         }
                                         catch (Exception exception)
                                         {
                                             using (TemporaryConsoleColorWarning())
                                             {
                                                 if (exception is FileNotFoundException)
                                                 {
                                                     includesNotFound.Add(includedScript.Path);
                                                     Console.WriteLine(" not found");
                                                 }
                                                 else
                                                 {
                                                     includesWithErrors[includedScript.Path] = IncludedScriptState.NotApplied;
                                                     Console.WriteLine(" failed");
                                                     Console.WriteLine("    {0}", exception.Message);
                                                 }
                                             }
                                         }
                                     }

                                     const string sql =
                                        "insert [dbo].[ScriptLog] ([Version], [ScriptNumber], [User], [Date]) values (@version, @scriptNumber, @user, @date)";
                                     var entry = new ScriptLogEntry
                                                 {
                                                     Date = DateTimeOffset.UtcNow,
                                                     ScriptNumber = scriptFile.Number,
                                                     User = Environment.UserName,
                                                     Version = scriptFile.Version
                                                 };
                                     x.Execute(sql, entry);
                                 });

                Console.WriteLine("  script executed in {0}", Format(scriptFileStopwatch.Elapsed));
                Console.WriteLine();
            }

            if (includesNotFound.Any())
            {
                using (TemporaryConsoleColorWarning())
                {
                    Console.WriteLine("The following includes could not be found");
                    foreach (var item in includesNotFound.Distinct(StringComparer.CurrentCultureIgnoreCase))
                        Console.WriteLine("  {0}", item);
                    Console.WriteLine();
                }
            }

            if (includesWithErrors.Any())
            {
                var failedIncludes = includesWithErrors.Where(x => x.Value == IncludedScriptState.NotApplied)
                                                       .Select(x => x.Key)
                                                       .ToList();
                if (failedIncludes.Any())
                {
                    using (TemporaryConsoleColorError())
                    {
                        Console.WriteLine("The following includes could not be applied");
                        foreach (var item in failedIncludes)
                            Console.WriteLine("  {0}", item);
                        Console.WriteLine();
                    }
                }
                else
                {
                    using (TemporaryConsoleColorSuccess())
                    {
                        Console.WriteLine("All failed includes has been successfully applied by later scripts.");
                        Console.WriteLine();
                    }
                }
            }

            using (TemporaryConsoleColorSuccess())
                Console.WriteLine("Scripts executed in {0}", Format(stopwatch.Elapsed));
        }
Beispiel #17
0
 public static bool IsArgumentExists(string arg) => Args.Contains(arg);