public async static Task SqlAsync(RunnerArgs args, IConnectionFactory factory)
        {
            if (factory == null)
            {
                throw new RunnerException("Invalid factory object.");
            }

            if (string.IsNullOrWhiteSpace(args.Connection))
            {
                throw new RunnerException("Please specify a connection string using the -c|--connection argument.");
            }

            int numberOfInputs = 0;

            using (DbConnection connection = await GetOpenConnectionAsync(args, factory))
            {
                foreach (ToolOption option in args.Options)
                {
                    if (IsSqlInput(option))
                    {
                        string sqlText = string.Join("\r\n", option.Values);

                        await ExecuteSqlAsync(connection, sqlText);

                        numberOfInputs++;
                    }
                    else if (IsFileInput(option))
                    {
                        ResponseSettings settings = new ResponseSettings()
                        {
                            IgnoreWhitespace = false,
                        };
                        string[] expanded = ResponseFile.ExpandFiles(option.Values, settings).ToArray();
                        string   sqlText  = string.Join("\r\n", expanded);

                        await ExecuteSqlAsync(connection, sqlText);

                        numberOfInputs++;
                    }
                    else if (IsRawInput(option))
                    {
                        string sqlText = string.Join("", option.Values.Select(File.ReadAllText));

                        await ExecuteSqlAsync(connection, sqlText);

                        numberOfInputs++;
                    }
                }
            }

            if (numberOfInputs == 0)
            {
                throw new RunnerException("Please specify at least one SQL input with the --sql, --file or --raw arguments.");
            }

            async Task ExecuteSqlAsync(DbConnection connection, string sqlText)
            {
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = sqlText;

                    if (!string.IsNullOrWhiteSpace(command.CommandText))
                    {
                        if (args.Verbose)
                        {
                            DotNetJerryHost.WriteLine($"Executing...", ConsoleColor.Yellow);
                            DotNetJerryHost.WriteLine(sqlText, ConsoleColor.Blue);
                        }
                        else
                        {
                            DotNetJerryHost.WriteLine($"Executing '{GetSqlPreviewText(sqlText)}'...", ConsoleColor.Yellow);
                        }

                        int affectedRows = await command.ExecuteNonQueryAsync();

                        string rowsMoniker = affectedRows + " " + (affectedRows == 1 ? "row" : "rows");

                        DotNetJerryHost.WriteLine($"OK. {rowsMoniker} affected.", ConsoleColor.Green);
                    }
                    else
                    {
                        DotNetJerryHost.WriteLine($"Skipped. SQL text is empty.", ConsoleColor.Yellow);
                    }
                }
            }

            string GetSqlPreviewText(string sqlText)
            {
                StringBuilder builder = new StringBuilder();

                for (int i = 0; i < sqlText.Length && builder.Length <= 30; i++)
                {
                    if (!char.IsWhiteSpace(sqlText[i]))
                    {
                        builder.Append(sqlText[i]);
                    }
                    else if (builder.Length > 0 && !char.IsWhiteSpace(builder[builder.Length - 1]))
                    {
                        builder.Append(' ');
                    }
                }

                return(builder.ToString());
            }

            bool IsRawInput(ToolOption option) => (option.Name == "raw" || option.ShortName == "r");
            bool IsSqlInput(ToolOption option) => (option.Name == "sql" || option.ShortName == "s");
            bool IsFileInput(ToolOption option) => (option.Name == "file" || option.ShortName == "f");
        }
Exemplo n.º 2
0
        public static ResponseFile ExportSitePackage(Context context, SiteSettings ss)
        {
            if (!Parameters.SitePackage.Export ||
                !context.CanManageSite(ss: ss))
            {
                return(null);
            }
            var    useIndentOption           = context.QueryStrings.Bool("UseIndentOption");
            var    includeSitePermission     = context.QueryStrings.Bool("IncludeSitePermission");
            var    includeRecordPermission   = context.QueryStrings.Bool("IncludeRecordPermission");
            var    includeColumnPermission   = context.QueryStrings.Bool("IncludeColumnPermission");
            string sitePackagesSelectableAll = Regex.Replace(
                context.QueryStrings.Data("SitePackagesSelectableAll"),
                @"[^0-9-,(true|false)]", "");
            var sites = new List <SelectedSite>();

            sitePackagesSelectableAll.Split(',')
            .ForEach(e =>
                     sites.Add(new SelectedSite()
            {
                SiteId      = e.Split_1st('-').ToLong(),
                IncludeData = e.Split_2nd('-').ToBool()
            }));
            if (ExceededExportLimit(
                    context: context,
                    sites: sites))
            {
                return(null);
            }
            foreach (var site in sites)
            {
                var currentSs = ss.SiteId == site.SiteId
                    ? ss
                    : SiteSettingsUtilities.Get(
                    context: context,
                    siteId: site.SiteId);
                if (site.IncludeData &&
                    (context.ContractSettings.Export == false ||
                     !context.CanExport(ss: currentSs)))
                {
                    return(null);
                }
            }
            var sitePackage = new SitePackage(
                context: context,
                siteList: sites,
                includeSitePermission: includeSitePermission,
                includeRecordPermission: includeRecordPermission,
                includeColumnPermission: includeColumnPermission);
            var file = new ResponseFile(
                fileContent: sitePackage.RecordingJson(
                    context: context,
                    formatting: useIndentOption
                        ? Formatting.Indented
                        : Formatting.None),
                fileDownloadName: ExportUtilities.FileName(
                    context: context,
                    sitePackage.Sites.FirstOrDefault()?.Title,
                    extension: "json"));

            return(file);
        }
Exemplo n.º 3
0
        public bool ProcessArguments(string[] args)
        {
            try
            {
                CommandLine = args;
                for (int i = 0; i < args.Length; i++)
                {
                    var opt  = getOption(args[i]);
                    var full = getFullOption(args[i]);

                    #region switch process each argument type
                    switch (opt)
                    {
                    case "/c":
                        HasDashC = true;
                        break;

                    case "/o":
                        return(NotSupported("/o"));

                    case "/D":
                        if (opt == full)
                        {
                            // define value is next argument...
                            i++;
                        }
                        break;

                    case "/I":
                        if (opt == full)
                        {
                            // include path is next argument..
                            // microsoft really dont know how to do command line!
                            i++;
                            if (i > args.Length)
                            {
                                return(NotSupported("-I has no path!"));
                            }
                            full = "/I" + args[i];
                            goto default;
                        }
                        break;

                    case "/Z7":
                        GeneratePdb = false;
                        PdbFile     = null;
                        break;

                    case "/Yu":
                        PrecompiledHeaders = true;
                        return(NotSupported("pre-compiler headers {0}", opt));

                    case "/FI":
                        return(NotSupported(opt));

                    case "/Zi":
                        GeneratePdb = true;
                        break;

                    case "/Fd":
                        PdbFile = Path.Combine(WorkingDirectory, full.Substring(3));
                        // openssl gives us a posix path here..
                        PdbFile = PdbFile.Replace('/', '\\');
                        if (!PdbFile.ToLower().EndsWith(".pdb") && !PdbFile.EndsWith("\\"))
                        {
                            PdbFile = PdbFile + ".pdb";
                        }
                        break;

                    case "/Fo":
                        ObjectTarget = Path.Combine(WorkingDirectory, full.Substring(3));
                        if (!Path.GetFileName(ObjectTarget).Contains("."))
                        {
                            ObjectTarget += ".obj";
                        }
                        break;

                    case "/Tp":
                    case "/Tc":
                        var srcfile = full.Substring(3);
                        if (!Path.IsPathRooted(srcfile))
                        {
                            srcfile = Path.Combine(WorkingDirectory, srcfile);
                        }

                        if (FileUtils.Exists(srcfile))
                        {
                            srcs.Add(srcfile);
                        }
                        else
                        {
                            return(NotSupported("cant find file for {0}", full));
                        }
                        break;

                    case "/E":
                        return(NotSupported(opt));

                    case "/EP":
                        return(NotSupported(opt));

                    default:
                        #region positional or other flag options

                        if (full == "/link")
                        {
                            Linking = true;
                            return(NotSupported("/link"));
                        }

                        if (opt.StartsWith("@"))
                        {
                            #region response file
                            ResponseFile = full.Substring(1);

                            if (ResponseFile.EndsWith(InternalResponseFileSuffix))
                            {
                                Logging.Emit("cclash misshelper internal response file");
                                return(false);
                            }

                            if (!Path.IsPathRooted(ResponseFile))
                            {
                                ResponseFile = Path.Combine(WorkingDirectory, ResponseFile);
                            }
                            string rsptxt = File.ReadAllText(ResponseFile);
                            if (rsptxt.Length < 2047)
                            // windows max command line, this is why they invented response files
                            {
                                Logging.Emit("response data [{0}]", rsptxt);
                                if (args.Length == 1)
                                {
                                    // this only works if it is the one and only arg!
                                    args = FixupArgs(CommandLineToArgs(rsptxt).Skip(1)).ToArray();
                                    i    = -1;
                                    // replace the command line with the response file content
                                    // and restart parsing. This does go wrong if the response text is huge
                                    continue;
                                }
                            }
                            else
                            {
                                Logging.Emit("response file too large");
                            }

                            return(NotSupported("response file error"));

                            #endregion
                        }

                        if (!full.StartsWith("/"))
                        {
                            // NOTE, if we ever cache -link calls this will also match input objects and libs
                            var file = full;
                            if (!Path.IsPathRooted(file))
                            {
                                file = Path.Combine(WorkingDirectory, file);
                            }

                            if (FileUtils.Exists(file))
                            {
                                srcs.Add(file);
                                continue;
                            }
                        }
                        if (full.StartsWith("/I"))
                        {
                            var d = full.Substring(2);
                            if (d == ".")
                            {
                                d = WorkingDirectory;
                            }
                            if (d == "..")
                            {
                                d = Path.GetDirectoryName(WorkingDirectory);
                            }

                            if (!Path.IsPathRooted(d))
                            {
                                d = Path.Combine(WorkingDirectory, d);
                            }

                            if (Directory.Exists(d))
                            {
                                cliincs.Add(d);
                                continue;
                            }
                        }
                        #endregion

                        break;
                    }
                    #endregion
                }

                if (SingleSource)
                {
                    if (ObjectTarget == null)
                    {
                        var f = Path.GetFileNameWithoutExtension(SingleSourceFile) + ".obj";
                        if (Path.IsPathRooted(f))
                        {
                            ObjectTarget = f;
                        }
                        else
                        {
                            ObjectTarget = Path.Combine(WorkingDirectory, f);
                        }
                    }

                    if (GeneratePdb)
                    {
                        if (Settings.ConvertObjPdbToZ7)
                        {
                            bool doconvert = false;
                            if (PdbFile == null)
                            {
                                doconvert = true;
                            }
                            else
                            {
                                if (PdbFile.EndsWith("\\"))
                                {
                                    doconvert = true;
                                }
                                else
                                {
                                    if (!FileUtils.Exists(PdbFile))
                                    {
                                        if (WorkingDirectory.Contains("openssl"))
                                        {
                                            doconvert = true;
                                        }
                                    }
                                }
                            }

                            if (doconvert)
                            {
                                Logging.Emit("converting pdb request to Z7 embedded debug {0}:{1}", WorkingDirectory, Path.GetFileName(ObjectTarget));
                                // append /Z7 to the arg list
                                var newargs = new List <string>();
                                foreach (var a in args)
                                {
                                    if (!(a.StartsWith("/Zi") || a.StartsWith("/Fd")))
                                    {
                                        newargs.Add(a);
                                    }
                                }
                                newargs.Add("/Z7");
                                AttemptPdb       = false;
                                PdbFile          = null;
                                GeneratePdb      = false;
                                PdbExistsAlready = false;
                                args             = newargs.ToArray();
                            }
                        }
                    }

                    if (GeneratePdb)
                    {
                        return(NotSupported("PDB file requested"));
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
                return(NotSupported("option parser exception '{0}'", e));
            }
            CompileArgs = args.ToArray();
            return(IsSupported);
        }
 public void Upload(ResponseFile response)
 {
     Task.Run(async() => await _serviceExecutor.Execute(s => s.WcfUploadFile(response)));
 }