Пример #1
0
 public void LockViewPortStart()
 {
     CommandLineHelper.Command("-vports", "Lock", "ON");
     Logger.Info(System.Reflection.MethodBase.GetCurrentMethod().Name);
 }
Пример #2
0
        public void TestGetValueStringError()
        {
            var obj = new CommandLineHelperTests();

            Assert.Throws <ArgumentException>(() => CommandLineHelper.GetValueString(obj));
        }
Пример #3
0
 public void TestNameWithoutLeadingUppercaseCharacter()
 {
     Assert.Throws <ArgumentException>(() => CommandLineHelper.CreateArgString("dateFrom", "2014-01-01"));
 }
Пример #4
0
        private static int Main()
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            ConsoleHelper.FixEncoding();

            List <string> assemblyFileNames = new List <string>();

            CommandLineHelper cmdLine = new CommandLineHelper();
            var debugOption           = cmdLine.RegisterOption("debug").Alias("d");
            var helpOption            = cmdLine.RegisterOption("help").Alias("h", "?");
            var noGzOption            = cmdLine.RegisterOption("nogz");
            var noNamesOption         = cmdLine.RegisterOption("nonames");
            var optimizeOption        = cmdLine.RegisterOption("optimize").Alias("opt");
            var outFileOption         = cmdLine.RegisterOption("outfile", 1).Alias("o");
            var srcBaseOption         = cmdLine.RegisterOption("srcbase", 1);

            try
            {
                cmdLine.Parse();
            }
            catch (Exception ex)
            {
                return(ConsoleHelper.ExitError(ex.Message, 1));
            }

            if (helpOption.IsSet)
            {
                ShowHelp();
                return(0);
            }

            try
            {
                foreach (var arg in cmdLine.FreeArguments)
                {
                    if (arg.IndexOfAny(new[] { '?', '*' }) != -1)
                    {
                        foreach (string foundFile in Directory.GetFiles(Path.GetDirectoryName(arg), Path.GetFileName(arg)))
                        {
                            CheckAddAssemblyFile(assemblyFileNames, foundFile);
                        }
                    }
                    else
                    {
                        CheckAddAssemblyFile(assemblyFileNames, arg);
                    }
                }
            }
            catch (Exception ex)
            {
                return(ConsoleHelper.ExitError("Cannot load input files. " + ex.Message, 5));
            }

            if (assemblyFileNames.Count == 0)
            {
                return(ConsoleHelper.ExitError("Missing argument: Input assembly file name", 2));
            }

            if (debugOption.IsSet)
            {
                ConsoleHelper.WriteLine("Input assemblies:", ConsoleColor.DarkGray);
                foreach (string fileName in assemblyFileNames)
                {
                    ConsoleHelper.WriteLine("  " + fileName, ConsoleColor.DarkGray);
                }
            }

            XmlDocument doc    = new XmlDocument();
            XmlWriter   xw     = doc.CreateNavigator().AppendChild();
            PdbReader   reader = new PdbReader(assemblyFileNames, xw);

            if (srcBaseOption.IsSet)
            {
                reader.SourceBasePath = Path.GetFullPath(srcBaseOption.Value);
            }
            try
            {
                reader.Convert();
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                if (ex.LoaderExceptions != null)
                {
                    ConsoleHelper.WriteLine("ReflectionTypeLoadException.LoaderExceptions:", ConsoleColor.Red);
                    foreach (var ex2 in ex.LoaderExceptions)
                    {
                        ConsoleHelper.WriteWrapped("- " + ex2.Message);
                    }
                }
                return(ConsoleHelper.ExitError("Cannot convert symbols. " + ex.Message, 3));
            }
            catch (Exception ex)
            {
                return(ConsoleHelper.ExitError("Cannot convert symbols. " + ex.Message, 3));
            }
            xw.Close();

            if (optimizeOption.IsSet)
            {
                // Reduce multiple subsequent "hidden" sequence points to the first of them
                doc.SelectNodes("/symbols/module/methods/method/sequencePoints/entry[@hidden='true'][preceding-sibling::entry[1][@hidden='true']]")
                .OfType <XmlNode>()
                .ForEachSafe(n => n.ParentNode.RemoveChild(n));

                // Remove sequence points if they are all hidden
                doc.SelectNodes("/symbols/module/methods/method/sequencePoints[not(entry[@startLine])]")
                .OfType <XmlNode>()
                .ForEachSafe(n => n.ParentNode.RemoveChild(n));

                // Remove all methods with no sequence points
                doc.SelectNodes("/symbols/module/methods/method[not(sequencePoints)]")
                .OfType <XmlNode>()
                .ForEachSafe(n => n.ParentNode.RemoveChild(n));

                // Remove all files with no remaining methods
                doc.SelectNodes("/symbols/module/files/file")
                .OfType <XmlNode>()
                .ForEachSafe(n =>
                {
                    if (n.SelectNodes("../../methods/method/sequencePoints/entry[@fileRef='" + n.Attributes["id"].Value + "']").Count == 0)
                    {
                        n.ParentNode.RemoveChild(n);
                    }
                });
            }

            if (noNamesOption.IsSet)
            {
                // Remove all name attributes from methods
                doc.SelectNodes("/symbols/module/methods/method")
                .OfType <XmlNode>()
                .ForEachSafe(n => n.Attributes.RemoveNamedItem("name"));
            }

            string xmlFileName =
                outFileOption.Value ??
                Path.ChangeExtension(
                    assemblyFileNames.OrderBy(a => Path.GetExtension(a).Equals(".dll", StringComparison.OrdinalIgnoreCase)).First(),
                    (noGzOption.IsSet ? ".pdb.xml" : ".pdbx"));

            if (debugOption.IsSet)
            {
                ConsoleHelper.WriteLine("Output file:", ConsoleColor.DarkGray);
                ConsoleHelper.WriteLine("  " + xmlFileName, ConsoleColor.DarkGray);
            }

            try
            {
                if (!noGzOption.IsSet)
                {
                    using (FileStream fileStream = new FileStream(xmlFileName, FileMode.Create))
                        using (GZipStream gzStream = new GZipStream(fileStream, CompressionMode.Compress))
                        {
                            doc.Save(gzStream);
                        }
                }
                else
                {
                    doc.Save(xmlFileName);
                }
            }
            catch (Exception ex)
            {
                return(ConsoleHelper.ExitError("Cannot save XML file. " + ex.Message, 4));
            }
            return(0);
        }
Пример #5
0
        static void Main(string[] args)
        {
            CommandLineArguments arguments = null;

            try
            {
                arguments = CommandLineHelper.Parse <CommandLineArguments>(args);
            }
            catch (Exception)
            {
                return;
            }

            /*try
             * {*/
            var gameStateManager = new GameStateManager();
            var blockSimples     = new[]
            {
                new Tuple <byte, string, bool>(1, "Stone", true),
                new Tuple <byte, string, bool>(2, "Grass block", true),
                new Tuple <byte, string, bool>(3, "Dirt", true),
                new Tuple <byte, string, bool>(4, "Cobblestone", true),
                new Tuple <byte, string, bool>(5, "Wooden planks", true),
                new Tuple <byte, string, bool>(7, "Bedrock", true),
                new Tuple <byte, string, bool>(12, "Sand", true),
                new Tuple <byte, string, bool>(13, "Gravel", true),
                new Tuple <byte, string, bool>(14, "Gold Ore", true),
                new Tuple <byte, string, bool>(15, "Iron Ore", true),
                new Tuple <byte, string, bool>(16, "Coal Ore", true),
                new Tuple <byte, string, bool>(17, "Oak Wood", true),
                new Tuple <byte, string, bool>(24, "Sandstone", true),
                new Tuple <byte, string, bool>(31, "Grass", false),
                new Tuple <byte, string, bool>(35, "Wool", true),
            };
            var blocksProvider = new BlocksProvider();
            var blockSelector  = new BlockSelector();

            for (int i = 0; i < blockSimples.Length; i++)
            {
                blocksProvider.RegisterBlock(blockSimples[i].Item1, new BlockSimple(blockSimples[i].Item2, blockSimples[i].Item3));
                blockSelector.AddSelectableBlock(blockSimples[i].Item1);
            }

            var chunkManager     = new ChunkManager();
            var chunkGenerator   = new ChunkGeneratorSurface(chunkManager);
            var worldManager     = new WorldManager(blocksProvider, chunkManager, chunkGenerator);
            var chunkPartManager = new ChunkPartManager(worldManager, chunkManager, blocksProvider);

            var world  = new World("world", (arguments?.Seed ?? 0) != 0 ? arguments.Seed : new Random().Next());
            var window = new MainWindow(gameStateManager, world);

            gameStateManager.SetGameState(new GameStatePlay(gameStateManager, worldManager, chunkManager, chunkPartManager, blockSelector, blocksProvider, world));
            window.Run(60);
            worldManager.Clean(world);

            /*}
             * catch (Exception exception)
             * {
             *  Console.Error.WriteLine($"Une exception de type {exception.GetType()} est survenue, message : {exception.Message}");
             *  Console.Error.WriteLine($"Stacktrace:");
             *  Console.Error.WriteLine(exception.StackTrace);
             *  Console.WriteLine("Sortie...");
             *  Environment.Exit(1);
             * }*/
        }
Пример #6
0
        /// <summary>
        /// Wrapped main program, uses <see cref="ConsoleException"/> as return code in case of
        /// error and does not wait at the end.
        /// </summary>
        private static void MainWrapper()
        {
            CommandLineHelper cmdLine        = new CommandLineHelper();
            var showHelpOption               = cmdLine.RegisterOption("help").Alias("h", "?");
            var showVersionOption            = cmdLine.RegisterOption("version").Alias("ver");
            var debugOption                  = cmdLine.RegisterOption("debug");
            var patchAssemblyInfoOption      = cmdLine.RegisterOption("patch");
            var restorePatchedFilesOption    = cmdLine.RegisterOption("restore");
            var simpleAttributeOption        = cmdLine.RegisterOption("simple");
            var informationalAttributeOption = cmdLine.RegisterOption("info");
            var allAttributesOption          = cmdLine.RegisterOption("all");
            var formatOption                 = cmdLine.RegisterOption("format", 1);
            var revisionOnlyOption           = cmdLine.RegisterOption("revonly");
            var requireVcsOption             = cmdLine.RegisterOption("require", 1);
            var rejectModifiedOption         = cmdLine.RegisterOption("rejectmod").Alias("rejectmodified");
            var rejectMixedOption            = cmdLine.RegisterOption("rejectmix").Alias("rejectmixed");
            var multiProjectOption           = cmdLine.RegisterOption("multi");
            var scanRootOption               = cmdLine.RegisterOption("root");
            var decodeRevisionOption         = cmdLine.RegisterOption("decode", 1);
            var predictRevisionsOption       = cmdLine.RegisterOption("predict");

            try
            {
                //cmdLine.ReadArgs(Environment.CommandLine, true);   // Alternative split method, should have the same result
                cmdLine.Parse();
                showDebugOutput = debugOption.IsSet;
                if (showDebugOutput)
                {
                    ShowDebugMessage(
                        "Command line: " +
                        Environment.GetCommandLineArgs()
                        .Select(s => "[" + s + "]")
                        .Aggregate((a, b) => a + " " + b));
                }
            }
            catch (Exception ex)
            {
                throw new ConsoleException(ex.Message, ExitCodes.CmdLineError);
            }

            // Handle simple text output options
            if (showHelpOption.IsSet)
            {
                ShowHelp();
                return;
            }
            if (showVersionOption.IsSet)
            {
                ShowVersion();
                return;
            }

            // Check for environment variable from PowerShell build framework.
            // If psbuild has set this variable, it is using NetRevisionTool itself in multi-project
            // mode and pre/postbuild actions in individual projects should not do anything on their
            // own.
            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("SuppressNetRevisionTool")))
            {
                ShowDebugMessage("SuppressNetRevisionTool environment variable is set. Quitting…");
                return;
            }

            // Find all directories
            string path = GetWorkPath(cmdLine);

            string[] projectDirs = null;
            if (multiProjectOption.IsSet)
            {
                // Read solution file and collect all projects
                projectDirs = GetProjectsFromSolution(path);

                // From now on, work with the solution directory as default path to get the revision of
                if (Path.GetExtension(path).ToLowerInvariant() == ".sln")
                {
                    path = Path.GetDirectoryName(path);
                }
            }
            else
            {
                if (!Directory.Exists(path))
                {
                    throw new ConsoleException("The specified project directory does not exist.", ExitCodes.FileNotFound);
                }

                projectDirs = new[] { path };
            }

            // Restoring doesn't need more info, do it now
            if (restorePatchedFilesOption.IsSet)
            {
                // Restore AssemblyInfo file(s)
                foreach (string projectDir in projectDirs)
                {
                    var aih = new AssemblyInfoHelper(projectDir, true);
                    aih.RestoreFile();
                }
                return;
            }

            // Analyse working directory
            RevisionData data = ProcessDirectory(path, scanRootOption.IsSet, requireVcsOption.Value);

            data.Normalize();

            // Check for required VCS
            if (requireVcsOption.IsSet)
            {
                if (data.VcsProvider == null ||
                    !data.VcsProvider.Name.Equals(requireVcsOption.Value, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ConsoleException("Required VCS \"" + requireVcsOption.Value + "\" not present.", ExitCodes.RequiredVcs);
                }
            }

            // Check for reject modifications/mixed revisions
            if (rejectModifiedOption.IsSet && data.IsModified)
            {
                throw new ConsoleException("The working directory contains uncommitted modifications.", ExitCodes.RejectModified);
            }
            if (rejectMixedOption.IsSet && data.IsMixed)
            {
                throw new ConsoleException("The working directory contains mixed revisions.", ExitCodes.RejectMixed);
            }

            // Determine revision ID format, in case we need one here
            string format = null;

            if (formatOption.IsSet && !string.IsNullOrWhiteSpace(formatOption.Value))
            {
                // Take from command-line option
                format = formatOption.Value;
                ShowDebugMessage("Format specified: " + format);
            }
            else
            {
                // None or empty specified. Search in AssemblyInfo file(s) in the project(s)
                ShowDebugMessage("No format specified, searching AssemblyInfo source file.");
                AssemblyInfoHelper aih = null;
                foreach (string projectDir in projectDirs)
                {
                    aih = new AssemblyInfoHelper(projectDir, false);
                    if (aih.FileExists)
                    {
                        format = aih.GetRevisionFormat();
                        if (format != null)
                        {
                            if (projectDirs.Length > 1)
                            {
                                ShowDebugMessage("Found format in project \"" + projectDir + "\".");
                            }
                            break;
                        }
                    }
                    else
                    {
                        ShowDebugMessage("  AssemblyInfo source file not found.", 2);
                    }
                }
                if (format != null)
                {
                    ShowDebugMessage("Found format: " + format);
                }
            }

            if (format == null)
            {
                if (data.RevisionNumber > 0)
                {
                    ShowDebugMessage("No format available, using default format for revision number.");
                    format = "{revnum}";
                }
                else if (!string.IsNullOrEmpty(data.CommitHash) && !Regex.IsMatch(data.CommitHash, "^0+$"))
                {
                    ShowDebugMessage("No format available, using default format for commit hash.");
                    format = "{chash:8}";
                }
                else
                {
                    ShowDebugMessage("No format available, using empty format.");
                    format = "";
                }
            }

            if (decodeRevisionOption.IsSet)
            {
                // Decode specified revision ID
                RevisionFormat.ShowDecode(format, decodeRevisionOption.Value);
            }
            else if (predictRevisionsOption.IsSet)
            {
                // Predict next revision IDs
                RevisionFormat.PredictValue(format);
            }
            else if (patchAssemblyInfoOption.IsSet)
            {
                // Patch AssemblyInfo file(s)
                bool noAttrSet              = !simpleAttributeOption.IsSet && !informationalAttributeOption.IsSet;
                bool simpleAttributes       = simpleAttributeOption.IsSet || noAttrSet;
                bool informationalAttribute = informationalAttributeOption.IsSet || noAttrSet;

                foreach (string projectDir in projectDirs)
                {
                    var aih = new AssemblyInfoHelper(projectDir, true);
                    aih.PatchFile(format, data, simpleAttributes, informationalAttribute, revisionOnlyOption.IsSet);
                }
            }
            else
            {
                // Just display revision ID
                var rf = new RevisionFormat();
                rf.RevisionData = data;
                Console.WriteLine(rf.Resolve(format));
            }
        }
Пример #7
0
            public void Parse_The_Last_Quoted_Argument_Even_When_The_Quote_Mark_Is_Not_Closed()
            {
                var arguments = CommandLineHelper.Parse("install \"c:\\Users\\alexander.fernandez\\Documents\\Visual Studio 2012\\Projects\\Catel\\src\\Catel.sln");

                Assert.AreEqual("c:\\Users\\alexander.fernandez\\Documents\\Visual Studio 2012\\Projects\\Catel\\src\\Catel.sln", arguments[1]);
            }
Пример #8
0
        /// <summary>
        /// Parse the commandline arguments.
        /// </summary>
        /// <param name="args">Commandline arguments.</param>
        public string[] Parse(string[] args)
        {
            List <string> unprocessed = new List <string>();

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];
                if (String.IsNullOrEmpty(arg)) // skip blank arguments
                {
                    continue;
                }

                if (1 == arg.Length) // treat '-' and '@' as filenames when by themselves.
                {
                    unprocessed.Add(arg);
                }
                else if ('-' == arg[0] || '/' == arg[0])
                {
                    string parameter = arg.Substring(1);
                    if (parameter.Equals("b", StringComparison.Ordinal))
                    {
                        if (!CommandLineHelper.IsValidArg(args, ++i))
                        {
                            break;
                        }

                        var bindPath = BindPath.Parse(args[i]);

                        this.BindPaths.Add(bindPath);
                    }
                    else if (parameter.StartsWith("cultures:", StringComparison.Ordinal))
                    {
                        string culturesString = arg.Substring(10).ToLower(CultureInfo.InvariantCulture);

                        // When null is used treat it as if cultures wasn't specified.
                        // This is needed for batching over the light task when using MSBuild which doesn't
                        // support empty items
                        if (culturesString.Equals("null", StringComparison.OrdinalIgnoreCase))
                        {
                            this.Cultures = null;
                        }
                        else
                        {
                            this.Cultures = culturesString.Split(';', ',');

                            for (int c = 0; c < this.Cultures.Length; ++c)
                            {
                                // Neutral is different from null. For neutral we still want to do WXL filtering.
                                // Set the culture to the empty string = identifier for the invariant culture
                                if (this.Cultures[c].Equals("neutral", StringComparison.OrdinalIgnoreCase))
                                {
                                    this.Cultures[c] = String.Empty;
                                }
                            }
                        }
                    }
                    else if (parameter.StartsWith("dcl:", StringComparison.Ordinal))
                    {
                        string defaultCompressionLevel = arg.Substring(5);

                        if (String.IsNullOrEmpty(defaultCompressionLevel))
                        {
                            break;
                        }
                        else if (Enum.TryParse(defaultCompressionLevel, true, out CompressionLevel compressionLevel))
                        {
                            this.DefaultCompressionLevel = compressionLevel;
                        }
                    }
                    else if (parameter.StartsWith("d", StringComparison.Ordinal))
                    {
                        parameter = arg.Substring(2);
                        string[] value = parameter.Split("=".ToCharArray(), 2);

                        string preexisting;
                        if (1 == value.Length)
                        {
                            this.Messaging.Write(ErrorMessages.ExpectedWixVariableValue(value[0]));
                        }
                        else if (this.Variables.TryGetValue(value[0], out preexisting))
                        {
                            this.Messaging.Write(ErrorMessages.WixVariableCollision(null, value[0]));
                        }
                        else
                        {
                            this.Variables.Add(value[0], value[1]);
                        }
                    }
                    else if (parameter.Equals("ext", StringComparison.Ordinal))
                    {
                        if (!CommandLineHelper.IsValidArg(args, ++i))
                        {
                            this.Messaging.Write(ErrorMessages.TypeSpecificationForExtensionRequired("-ext"));
                            break;
                        }

                        this.Extensions.Add(args[i]);
                    }
                    else if (parameter.Equals("loc", StringComparison.Ordinal))
                    {
                        string locFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);
                        if (String.IsNullOrEmpty(locFile))
                        {
                            break;
                        }

                        this.LocalizationFiles.Add(locFile);
                    }
                    else if (parameter.Equals("nologo", StringComparison.Ordinal))
                    {
                        this.ShowLogo = false;
                    }
                    else if (parameter.Equals("notidy", StringComparison.Ordinal))
                    {
                        this.Tidy = false;
                    }
                    else if ("o" == parameter || "out" == parameter)
                    {
                        this.OutputFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);
                        if (String.IsNullOrEmpty(this.OutputFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("pedantic", StringComparison.Ordinal))
                    {
                        this.ShowPedanticMessages = true;
                    }
                    else if (parameter.Equals("sloc", StringComparison.Ordinal))
                    {
                        this.SuppressLocalization = true;
                    }
                    else if (parameter.Equals("usf", StringComparison.Ordinal))
                    {
                        this.UnreferencedSymbolsFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.UnreferencedSymbolsFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("xo", StringComparison.Ordinal))
                    {
                        this.OutputXml = true;
                    }
                    else if (parameter.Equals("cc", StringComparison.Ordinal))
                    {
                        this.CabCachePath = CommandLineHelper.GetDirectory(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.CabCachePath))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("ct", StringComparison.Ordinal))
                    {
                        if (!CommandLineHelper.IsValidArg(args, ++i))
                        {
                            this.Messaging.Write(ErrorMessages.IllegalCabbingThreadCount(String.Empty));
                            break;
                        }

                        int ct = 0;
                        if (!Int32.TryParse(args[i], out ct) || 0 >= ct)
                        {
                            this.Messaging.Write(ErrorMessages.IllegalCabbingThreadCount(args[i]));
                            break;
                        }

                        this.CabbingThreadCount = ct;
                        this.Messaging.Write(VerboseMessages.SetCabbingThreadCount(this.CabbingThreadCount.ToString()));
                    }
                    else if (parameter.Equals("cub", StringComparison.Ordinal))
                    {
                        string cubeFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(cubeFile))
                        {
                            break;
                        }

                        this.CubeFiles.Add(cubeFile);
                    }
                    else if (parameter.StartsWith("ice:", StringComparison.Ordinal))
                    {
                        this.Ices.Add(parameter.Substring(4));
                    }
                    else if (parameter.Equals("intermediatefolder", StringComparison.OrdinalIgnoreCase))
                    {
                        this.IntermediateFolder = CommandLineHelper.GetDirectory(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.IntermediateFolder))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("contentsfile", StringComparison.Ordinal))
                    {
                        this.ContentsFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.ContentsFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("outputsfile", StringComparison.Ordinal))
                    {
                        this.OutputsFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.OutputsFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("builtoutputsfile", StringComparison.Ordinal))
                    {
                        this.BuiltOutputsFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.BuiltOutputsFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("wixprojectfile", StringComparison.Ordinal))
                    {
                        this.WixprojectFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.WixprojectFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.Equals("pdbout", StringComparison.Ordinal))
                    {
                        this.PdbFile = CommandLineHelper.GetFile(parameter, this.Messaging, args, ++i);

                        if (String.IsNullOrEmpty(this.PdbFile))
                        {
                            break;
                        }
                    }
                    else if (parameter.StartsWith("sice:", StringComparison.Ordinal))
                    {
                        this.SuppressIces.Add(parameter.Substring(5));
                    }
                    else if (parameter.Equals("sl", StringComparison.Ordinal))
                    {
                        this.SuppressLayout = true;
                    }
                    else if (parameter.Equals("spdb", StringComparison.Ordinal))
                    {
                        this.SuppressWixPdb = true;
                    }
                    else if (parameter.Equals("sacl", StringComparison.Ordinal))
                    {
                        this.SuppressAclReset = true;
                    }
                    else if (parameter.Equals("sval", StringComparison.Ordinal))
                    {
                        this.SuppressValidation = true;
                    }
                    else if ("sv" == parameter)
                    {
                        this.SuppressVersionCheck = true;
                    }
                    else if (parameter.StartsWith("sw", StringComparison.Ordinal))
                    {
                        string paramArg = parameter.Substring(2);
                        if (0 == paramArg.Length)
                        {
                            this.Messaging.SuppressAllWarnings = true;
                        }
                        else
                        {
                            int suppressWarning = 0;
                            if (!Int32.TryParse(paramArg, out suppressWarning) || 0 >= suppressWarning)
                            {
                                this.Messaging.Write(ErrorMessages.IllegalSuppressWarningId(paramArg));
                            }
                            else
                            {
                                this.Messaging.SuppressWarningMessage(suppressWarning);
                            }
                        }
                    }
                    else if (parameter.StartsWith("wx", StringComparison.Ordinal))
                    {
                        string paramArg = parameter.Substring(2);
                        if (0 == paramArg.Length)
                        {
                            this.Messaging.WarningsAsError = true;
                        }
                        else
                        {
                            int elevateWarning = 0;
                            if (!Int32.TryParse(paramArg, out elevateWarning) || 0 >= elevateWarning)
                            {
                                this.Messaging.Write(ErrorMessages.IllegalWarningIdAsError(paramArg));
                            }
                            else
                            {
                                this.Messaging.ElevateWarningMessage(elevateWarning);
                            }
                        }
                    }
                    else if ("v" == parameter)
                    {
                        this.Messaging.ShowVerboseMessages = true;
                    }
                    else if ("?" == parameter || "help" == parameter)
                    {
                        this.ShowHelp = true;
                        break;
                    }
                    else
                    {
                        unprocessed.Add(arg);
                    }
                }
                else if ('@' == arg[0])
                {
                    string[] parsedArgs   = CommandLineResponseFile.Parse(arg.Substring(1));
                    string[] unparsedArgs = this.Parse(parsedArgs);
                    unprocessed.AddRange(unparsedArgs);
                }
                else
                {
                    unprocessed.Add(arg);
                }
            }

            return(unprocessed.ToArray());
        }
Пример #9
0
        private void ExecuteTask()
        {
            // 单元测试结果文件,包含通过率数据
            // 为了防止项目同名,单元测试生成的结果文件和项目文件保存在一起,而不是直接保存到临时目录
            string resultFile = Path.Combine(Path.GetDirectoryName(_projectFile), @"TestResult.xml");
            string coverFile  = Path.Combine(Path.GetDirectoryName(_projectFile), @"CoverResult.dcvr");

            int retryTime = 0;

            while (retryTime <= 3)
            {
                if (File.Exists(resultFile))
                {
                    File.Delete(resultFile);
                }

                if (File.Exists(coverFile))
                {
                    File.Delete(coverFile);
                }


                CoverageParams cp = new CoverageParams();
                cp.TargetExecutable = _nunitPath;
                cp.TargetArguments  = string.Format("\"{0}\" --result \"{1}\"  --inprocess", _projectFile, resultFile);
                cp.TargetWorkingDir = Path.Combine(Path.GetDirectoryName(_projectFile), "bin");
                cp.Output           = coverFile;

                string argFileName = string.Format("UnitTest-cover-args-{0}.xml",
                                                   Path.GetFileNameWithoutExtension(_projectFile).Replace(".", "_"));
                string args1File = _context.WriteTempFile(cp, argFileName);

                // 调用 ReSharper dotCover ,执行单元测试,并生成代码覆盖率快照文件
                ExecuteResult result = CommandLineHelper.Execute(_dotCoverPath, string.Format("cover \"{0}\"", args1File));
                ConsoleWrite(result.ToString());

                result.FillBaseInfo();      // 设置日志的时间,当前机器名
                _context.WriteTempFile(result, "UnitTest-RunCover-Console-" + Path.GetFileNameWithoutExtension(_projectFile) + ".txt");


                // ReSharper dotCover 时常会出现BUG,现象为不能生成代码覆盖率快照文件,例如下面的执行消息:

                //Results (nunit3) saved as D:\TFS\10_5_10_96\Prod\ERP-V1.0\40_成本系统\01_主干-开发分支\88 公共类库\Mysoft.Cbxt.Common.UnitTest\TestResult.xml
                //[JetBrains dotCover] Coverage session finished [2018/1/3 6:06:05]
                //[JetBrains dotCover] Coverage session finished but no snapshots were created.

                // 目前的解决方法是,运行 dotCover 之后再检查是否已生成快照文件,如果文件没有生成就重新执行
                // 重试的最大次数为 3

                if (File.Exists(coverFile))
                {
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                    retryTime++;
                }
            }



            System.Threading.Thread.Sleep(3000);    // 等待文件写入

            if (File.Exists(resultFile))
            {
                NunitTestResult testResult = XmlHelper.XmlDeserializeFromFile <NunitTestResult>(resultFile);

                this.Result = new UnitTestResult {
                    ProjectName = Path.GetFileNameWithoutExtension(_projectFile),
                    Total       = testResult.Total,
                    Passed      = testResult.Passed
                };

                ConsoleWrite($"{Path.GetFileNameWithoutExtension(_projectFile)}: {testResult.Passed} / {testResult.Total}");

                // 将单元测试结果复制到临时目录。
                string tempFileName = string.Format("UnitTest-Result-{0}.xml", Path.GetFileNameWithoutExtension(_projectFile));

                try {
                    string text = File.ReadAllText(resultFile, Encoding.UTF8);
                    _context.WriteTempFile(text, tempFileName);
                }
                catch { /* 如果有异常发生,就忽略  */ }
            }
            else
            {
                ConsoleWrite(resultFile + " NOT FOUND!");
            }
        }
Пример #10
0
        /// <summary>
        /// Copies a file to a folder, creates folder if it doesn't exist. Folder name is based on test flight data. If logs are
        /// uploaded, the appropriate testflight data is updated
        /// </summary>
        /// <param name="flight"></param>
        /// <param name="fileNames"></param>
        /// <param name="workingPath"></param>
        /// <returns></returns>
        public void TransferFile(TestFlight flight, string filePath, string workingPath)
        {
            // create a path from the working directory and the flight name and data
            var fileStoragePath = System.IO.Path.Combine(_dataPath, workingPath);

            // verify if the directory exists
            if (!System.IO.Directory.Exists(fileStoragePath))
            {
                // create it if it doens't exist
                System.IO.Directory.CreateDirectory(fileStoragePath);
            }

            // get the filename of the file
            var fileNameWithoutPath = System.IO.Path.GetFileName(filePath);

            // Parse logs to update test flight with proper wing ID
            // the file that ends with "_ACEeprom.text" contains Wing ID
            if (fileNameWithoutPath.EndsWith("_ACEeprom.text"))
            {
                // get flight data from log
                var type = File.ReadAllLines(filePath).Where(line => line.Contains("acType")).FirstOrDefault().Substring(7).PadLeft(4, '0');
                flight.WingId = type + File.ReadAllLines(filePath).Where(line => line.Contains("acSerNr")).FirstOrDefault().Substring(8).PadLeft(6, '0');
            }

            // Parse logs to update test flight with proper ebox ID
            // the file that ends with "_eBoxEeprom.text" contains ebox ID
            if (fileNameWithoutPath.EndsWith("_eBoxEeprom.text"))
            {
                // get flight data from log
                flight.EboxId = "EBX" + File.ReadAllLines(filePath).Where(line => line.Contains("eBoxSerNr")).FirstOrDefault().Substring(10).PadLeft(5, '0');
            }

            // Parse logs to update test flight data with Elevator, Aileron and ShutterCommands values
            // the file that ends with "_prodlog.text" contains Elevator, Aileron, Samples and Shutter Commands
            if (fileNameWithoutPath.EndsWith("_prodlog.text"))
            {
                // get flight data from log
                var flightData = File.ReadAllLines(filePath)[0].Split(' ');

                flight.Elevator        = Convert.ToInt32(flightData[0]);
                flight.Aileron         = Convert.ToInt32(flightData[1]);
                flight.Samples         = Convert.ToInt32(flightData[2]);
                flight.ShutterCommands = Convert.ToInt32(flightData[3]);
            }

            // Parse logs to update test flight data with undershoot
            if (fileNameWithoutPath.EndsWith(".txt"))
            {
                var flightData = File.ReadAllLines(filePath).Where(line => line != string.Empty).ToArray();

                for (var i = 0; i < flightData.Count(); i++)
                {
                    var speed  = Convert.ToInt32(flightData[i].Split(' ')[26]);
                    var height = Convert.ToInt32(flightData[i].Split(' ')[32]);
                    var status = Convert.ToInt32(flightData[i].Split(' ')[22]);
                    var deltaZ = Convert.ToInt32(flightData[i].Split(' ')[33]);

                    // change these values to fine tune
                    if (speed < 40 && height < 2 && status == 157 && deltaZ > -5 && deltaZ < 5)
                    {
                        // determine actual landing location
                        var latitude         = Double.Parse(flightData[i].Split(' ')[25], System.Globalization.NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"));
                        var longitude        = Double.Parse(flightData[i].Split(' ')[24], System.Globalization.NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"));
                        var actualLandingLoc = new GeoCoordinate(latitude, longitude);

                        // determine a reference position a little earlier in the AC's current path, this will be used to differentiate between under and overshoot
                        latitude  = Double.Parse(flightData[i - 5].Split(' ')[25], System.Globalization.NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"));
                        longitude = Double.Parse(flightData[i - 5].Split(' ')[24], System.Globalization.NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"));
                        var referenceLoc = new GeoCoordinate(latitude, longitude);

                        // calculate distance from actual landing to programmed landing
                        var distance = GetDistanceBetween(_programmedLandingLocation.Latitude, _programmedLandingLocation.Longitude, actualLandingLoc.Latitude, actualLandingLoc.Longitude);

                        // calculate if its an overshoot or an undershoot:
                        // if the distance between reference and programmed is smaller than the distance between actual and programmed then it's an overshoot
                        var distanceBetweenReferenceAndProgrammed = GetDistanceBetween(referenceLoc, _programmedLandingLocation);
                        if (distanceBetweenReferenceAndProgrammed < distance)
                        {
                            distance = distance * -1;
                        }

                        // assign the calculated undershoot to the flight property
                        flight.Undershoot = Convert.ToInt32(Math.Round(distance, 0));

                        break;
                    }
                }
            }

            if (fileNameWithoutPath.EndsWith("T04"))
            {
                // run the T04 file parser app
                var commandLineHelper = new CommandLineHelper();
                commandLineHelper.Run("T01App.exe", filePath);

                // retrieve event number from result
                var record19Value = Convert.ToInt32(commandLineHelper.Output
                                                    .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
                                                    .Where(line => line.IndexOf("Record  19 :") > -1)
                                                    .FirstOrDefault()
                                                    .Substring(12));

                // store the retrieved number of events in the testflight object
                flight.GBoxEvents = record19Value;
            }

            // Create a directory name
            var newFileName = System.IO.Path.Combine(fileStoragePath, fileNameWithoutPath);

            // Copy file
            using (FileStream SourceStream = File.Open(filePath, FileMode.Open))
                using (FileStream DestinationStream = File.Create(newFileName))
                    SourceStream.CopyTo(DestinationStream);

            // delete T04 file
            if (fileNameWithoutPath.EndsWith("T04"))
            {
                File.Delete(filePath);
            }

            // if _doDeleteAfterCopy is true, clean up images after copying
            if (_doDeleteAfterCopy && (fileNameWithoutPath.ToLower().EndsWith("jpg") || fileNameWithoutPath.ToLower().EndsWith("jpeg")))
            {
                File.Delete(filePath);
            }
        }
Пример #11
0
        protected override void OnStartup(StartupEventArgs args)
        {
            base.OnStartup(args);

            // Fix WPF's built-in themes
            if (OSInfo.IsWindows8OrNewer)
            {
                ReAddResourceDictionary("/Resources/RealWindows8.xaml");
            }

            // Initialise and show the main window

            CommandLineHelper cmdLine = new CommandLineHelper();
            var scanOption            = cmdLine.RegisterOption("scan", 1).Alias("s");

            try
            {
                cmdLine.Parse();
            }
            catch (Exception ex)
            {
                App.ErrorMessage("Command line error.", ex, "Parsing command line");
                Application.Current.Shutdown();
            }

            List <string> filesToLoad = new List <string>();
            bool          error       = false;

            foreach (string fileNameArg in cmdLine.FreeArguments)
            {
                if (!string.IsNullOrWhiteSpace(fileNameArg))
                {
                    // File name
                    if (File.Exists(fileNameArg))
                    {
                        // File exists, open it
                        string fileName = fileNameArg;
                        if (!Path.IsPathRooted(fileName))
                        {
                            fileName = Path.GetFullPath(fileName);
                        }
                        filesToLoad.Add(fileName);
                    }
                    else if (Directory.Exists(fileNameArg))
                    {
                        // Directory specified, collect all files
                        foreach (string fileName in Directory.GetFiles(fileNameArg, "*.txd"))
                        {
                            filesToLoad.Add(fileName);
                        }
                        if (filesToLoad.Count == 0)
                        {
                            // Nothing found, try older XML file names
                            foreach (string fileName in Directory.GetFiles(fileNameArg, "*.xml"))
                            {
                                if (FileNameHelper.GetCulture(fileName) != null)
                                {
                                    filesToLoad.Add(fileName);
                                }
                            }
                        }
                    }
                    else
                    {
                        FL.Error("File/directory not found", fileNameArg);
                        error = true;
                    }
                }
            }
            if (error)
            {
                App.ErrorMessage("At least one of the files or directories specified at the command line could not be found.");
            }

            // Scan for other files near the selected files
            // (Currently only active if a single file is specified)
            //if (filesToLoad.Count == 1)
            //{
            //    foreach (string fileName in filesToLoad.Distinct().ToArray())
            //    {
            //        if (fileName.ToLowerInvariant().EndsWith(".txd") && File.Exists(fileName))
            //        {
            //            // Existing .txd file
            //            // Scan same directory for other .txd files
            //            string[] otherFiles = Directory.GetFiles(Path.GetDirectoryName(fileName), "*.txd");
            //            // otherFiles should contain fileName and may contain additional files
            //            if (otherFiles.Length > 1)
            //            {
            //                if (App.YesNoQuestion("Other Tx dictionary files are located in the same directory as the selected file. Should they also be loaded?"))
            //                {
            //                    // Duplicates will be removed later
            //                    filesToLoad.AddRange(otherFiles);
            //                }
            //            }
            //        }
            //    }
            //}
            // NOTE: Loading multiple txd files is not supported. (Only scan for more cultures of version 1 files. - Done)

            if (!FileNameHelper.FindOtherCultures(filesToLoad))
            {
                Application.Current.Shutdown();
            }

            // Create main window and view model
            var view      = new MainWindow();
            var viewModel = new MainViewModel();

            if (filesToLoad.Count == 0 && scanOption.IsSet)
            {
                viewModel.ScanDirectory = scanOption.Value;
            }

            view.DataContext = viewModel;

            // Load selected files
            if (filesToLoad.Count > 0)
            {
                viewModel.LoadFiles(filesToLoad);
            }

            // Show the main window
            view.Show();
        }
Пример #12
0
        /// <summary>
        /// Run the pre/conversion/post processes.  The guts of the whole thing!
        /// </summary>
        private void runProcesses()
        {
            logger.Debug("Running PreProcessor if required");
            // if required, run the preprocessor command:
            if (XMLTV2MXF_WPF.Properties.Settings.Default.usePreProcessor)
            {
                try
                {
                    //           // Run the command
                    string cmd = XMLTV2MXF_WPF.Properties.Settings.Default.preProcessorCommand;
                    // substitue $INPUTFILE for the chosen input file
                    cmd = cmd.Replace("$INPUTFILE", XMLTV2MXF_WPF.Properties.Settings.Default.inputXMLTVfile);

                    logger.Debug("preProcessor set, trying to execute: " + cmd);

                    //          Process pr = new Process();
                    int    application_split = cmd.IndexOf(".exe") + 4;
                    string FileName          = cmd.Substring(0, application_split);
                    string Arguments         = cmd.Substring(application_split, cmd.Length - application_split).Trim();

                    logger.Info("Executing preProcessor command:");

                    // Display Progress Bar
                    //ProgressBar1.Visibility = System.Windows.Visibility.Visible;

                    logger.Info(CommandLineHelper.Run(FileName, Arguments));
                }
                catch (Exception e)
                {
                    logger.Error("Error running preProcessor! Check settings", e);
                    return;
                }
            }

            logger.Info("Performing Conversion:");
            XMLTV2MXF_Main.doProcessing();

            logger.Debug("Running PostProcessor if required");
            // if required, run the postprocessor command:
            if (XMLTV2MXF_WPF.Properties.Settings.Default.usePostProcessor)
            {
                try
                {
                    //           // Run the command
                    string cmd = XMLTV2MXF_WPF.Properties.Settings.Default.postProcessorCommand;
                    // substitue $INPUTFILE for the chosen input file
                    cmd = cmd.Replace("$OUTPUTFILE", XMLTV2MXF_WPF.Properties.Settings.Default.outputMXFfile);

                    logger.Debug("postProcessor set, trying to execute: " + cmd);

                    //          Process pr = new Process();
                    int    application_split = cmd.IndexOf(".exe") + 4;
                    string FileName          = cmd.Substring(0, application_split);
                    string Arguments         = cmd.Substring(application_split, cmd.Length - application_split).Trim();

                    logger.Info("Executing postProcessor command:");

                    // Display Progress Bar
                    //ProgressBar1.Visibility = System.Windows.Visibility.Visible;

                    logger.Info(CommandLineHelper.Run(FileName, Arguments));
                }
                catch (Exception e)
                {
                    logger.Error("Error running postProcessor! Check settings", e);
                    return;
                }
            }
        }
Пример #13
0
        public static void DrawText(ref RegionMassProperties aRms, string dU, string mU, Database db)
        {
            #region scale

            var scale           = "mm";
            var scaleUnitsValue = UnitsValue.Millimeters;
            var sysUnits        =
                Application.GetSystemVariable("INSUNITS").ToString();
            switch (sysUnits)
            {
            case "1":
                scale           = "inch";
                scaleUnitsValue = UnitsValue.Inches;
                break;

            case "2":
                scale           = "feet";
                scaleUnitsValue = UnitsValue.Feet;
                break;

            case "4":
                scale           = "mm";
                scaleUnitsValue = UnitsValue.Millimeters;
                break;

            case "5":
                scale           = "cm";
                scaleUnitsValue = UnitsValue.Centimeters;
                break;

            case "6":
                scale           = "m";
                scaleUnitsValue = UnitsValue.Meters;
                break;

            case "14":
                scale           = "dm";
                scaleUnitsValue = UnitsValue.Decimeters;
                break;

            default:
                MessageBox.Show("\nUnits to scale inserted content: UNRECOGNIZED ?!", "units E R R O R");
                break;
            }

            var format       = "f5";
            var mTextMessage = "";

            #endregion

            mTextMessage += AssemblyText(
                "Area",
                aRms.Area * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.AreaUnit), 2),
                aRms.AreaUnit,
                "2",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Iy",
                aRms.Iy * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.IyUnit), 4),
                aRms.IyUnit,
                "4",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Wy_Upper",
                aRms.WyUpper * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.WyUpperUnit), 3),
                aRms.WyUpperUnit,
                "3",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Wy_Lower",
                aRms.WyLower * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.WyLowerUnit), 3),
                aRms.WyLowerUnit,
                "3",
                scale,
                format);
            mTextMessage += AssemblyText(
                "D_Upper",
                aRms.DUpper * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.DUpperUnit), 1),
                aRms.DUpperUnit,
                "",
                scale,
                format);
            mTextMessage += AssemblyText(
                "D_Lower",
                aRms.DLower * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.DLowerUnit), 1),
                aRms.DLowerUnit,
                "",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Iyy",
                aRms.Iyy * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.IyyUnit), 1),
                aRms.IyyUnit,
                "",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Iz",
                aRms.Iz * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.IzUnit), 4),
                aRms.IzUnit,
                "4",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Wz_Right",
                aRms.WzRight * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.WzRightUnit), 3),
                aRms.WzRightUnit,
                "3",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Wz_Left",
                aRms.WzLeft * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.WzLeftUnit), 3),
                aRms.WzLeftUnit,
                "3",
                scale,
                format);
            mTextMessage += AssemblyText(
                "D_Right",
                aRms.DRight * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.DRightUnit), 1),
                aRms.DRightUnit,
                "",
                scale,
                format);
            mTextMessage += AssemblyText(
                "D_Left",
                aRms.DLeft * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.DLeftUnit), 1),
                aRms.DLeftUnit,
                "",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Izz",
                aRms.Izz * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.IzzUnit), 1),
                aRms.IzzUnit,
                "",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Imin",
                aRms.Imin * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.IminUnit), 4),
                aRms.IminUnit,
                "4",
                scale,
                format);
            mTextMessage += AssemblyText(
                "Imax",
                aRms.Imax * Math.Pow(UnitsConverter.GetConversionFactor(scaleUnitsValue, aRms.ImaxUnit), 4),
                aRms.ImaxUnit,
                "4",
                scale,
                format);

            // Density
            var density = aRms.Density * UnitsConverter.GetConversionFactor(UnitsValue.Millimeters, aRms.DensityUnit);
            mTextMessage += "{\\A0Density:\\~" + density.ToString(scale != "m" ? format : "") + "\\~" + dU +
                            "\\S3;}\\P\n";

            // weight G
            var g = aRms.G * UnitsConverter.GetConversionFactor(UnitsValue.Millimeters, aRms.GUnit);
            mTextMessage += "{\\A0G:\\~" + g.ToString(scale != "m" ? format : "") + "\\~" + mU + "}\\P\n";
            Ed.WriteMessage(mTextMessage);

            // draw message
            using (var tr = db.TransactionManager.StartTransaction())
            {
                var bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                var btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                if (!_textId.IsNull && !_textId.IsErased)
                {
                    var regoinTextEnt = (Entity)tr.GetObject(_textId, OpenMode.ForWrite);
                    regoinTextEnt.Erase(true);
                }

                var regionText = new MText();
                regionText.SetDatabaseDefaults();
                regionText.Location = aRms.TextInsertionPoint;
                regionText.Width    = 1000;
                regionText.Height   = 1.2;
                regionText.Contents = mTextMessage + "\n";
                btr.AppendEntity(regionText);
                _textId = regionText.ObjectId;
                tr.AddNewlyCreatedDBObject(regionText, true);
                tr.Commit();
            }

            CommandLineHelper.Command("_REGEN");
        }
Пример #14
0
        static void Main(string[] args)
        {
            Dictionary <string, string> aliases = new Dictionary <string, string>();

            aliases.Add("-s", "--symtab");
            aliases.Add("-o", "--output");
            aliases.Add("-lf", "--list-file");
            aliases.Add("-f", "--format");
            aliases.Add("-a", "--append-deck");
            aliases.Add("-pp", "--pretty-print");
            aliases.Add("-?", "--help");
            aliases.Add("-h", "--help");

            Dictionary <string, string> cmdLine = CommandLineHelper.SplitCommandLine(Environment.CommandLine, aliases, true);

            Console.Error.WriteLine("MIXAL Assembler, (c) 2009 George Tryfonas");

            string inFile = GetInputFile(cmdLine);

            if (string.IsNullOrEmpty(inFile))
            {
                Console.Error.WriteLine("No input file specified.");
                Environment.Exit(-1);
            }

            string outFile = GetOutputFile(cmdLine);

            try
            {
                MIXAssembler assembler = new MIXAssembler(inFile, outFile);

                if (cmdLine.ContainsKey("--format"))
                {
                    switch (cmdLine["--format"])
                    {
                    case "binary":
                        assembler = new MIXAssembler(inFile, outFile, Format.Binary);
                        break;

                    case "card":
                        assembler = new MIXAssembler(inFile, outFile, Format.Card);
                        break;

                    default:
                        Console.Error.WriteLine(string.Format("Unknown output format: '{0}'", cmdLine["--format"]));
                        System.Environment.Exit(-1);
                        break;
                    }
                }
                else
                {
                    assembler = new MIXAssembler(inFile, outFile);
                }

                if (cmdLine.ContainsKey("--symtab"))
                {
                    assembler.MakeSymbolTable = true;
                    assembler.SymbolTableFile = cmdLine["--symtab"];
                }

                if (cmdLine.ContainsKey("--list-file"))
                {
                    assembler.ListingFile = cmdLine["--list-file"];
                }

                Console.Error.WriteLine(string.Format("Output file is: '{0}'\nOutput format is: {1}",
                                                      string.IsNullOrEmpty(assembler.OutputFile) ? "CONSOLE" : assembler.OutputFile, assembler.OutputFormat));

                int wordCount = assembler.Assemble();
                if (assembler.Errors.Count() > 0)
                {
                    foreach (var e in assembler.Errors)
                    {
                        Console.Error.WriteLine(string.Format("Error at {0},{1}: {2}", e.Line, e.Column, e.Text));
                    }
                    Console.Error.WriteLine("Assembly did not complete due to errors.");
                }
                else
                {
                    Console.Error.WriteLine(string.Format("{0} word(s) assembled.", wordCount));
                    if (assembler.Warnings.Count() > 0)
                    {
                        foreach (var e in assembler.Warnings)
                        {
                            Console.Error.WriteLine(string.Format("Error at {0},{1}: {2}", e.Line, e.Column, e.Text));
                        }
                        Console.Error.WriteLine("Assembly completed with warnings.");
                    }
                    else
                    {
                        Console.Error.WriteLine("Assembly completed successfully.");
                    }

                    if (assembler.OutputFormat == Format.Card && cmdLine.ContainsKey("--append-deck"))
                    {
                        string deckFile = cmdLine["--append-deck"];
                        Console.Error.WriteLine(string.Format("Appending deck file: '{0}'", deckFile));
                        StreamReader reader = new StreamReader(deckFile);
                        string       deck   = reader.ReadToEnd();
                        reader.Close();
                        StreamWriter writer = new StreamWriter(assembler.OutputFile == null ? Console.OpenStandardOutput() : new FileStream(assembler.OutputFile, FileMode.Append));
                        writer.Write(deck);
                        writer.Close();
                    }

                    if (cmdLine.ContainsKey("--pretty-print"))
                    {
                        assembler.PrettyPrinter = new TeXPrinter(assembler.InputFile);
                    }

                    assembler.MakeOther();
                }
            }
            catch (IOException e)
            {
                Console.Error.WriteLine("Input/output error: " + e.Message);
                Environment.Exit(-1);
            }
        }
Пример #15
0
        private async void StartWithArguments()
        {
            CommandlineArgs args = CommandLineHelper.GetCommandlineArguments();

            switch (args.Argument)
            {
            case CommandLineHelper.Argument.Autostart:
                //Tray with Hotkeys
                await StartTray.Initialize(this);

                break;

            case CommandLineHelper.Argument.Gif:
                //GIF Recording Capture
                using (GifWindow window = new GifWindow())
                    window.ShowDialog();
                break;

            case CommandLineHelper.Argument.Snipe:
                //Normal Image Capture
                if (ConfigHelper.FreezeScreen)
                {
                    using (ScreenshotWindowFreeze window = new ScreenshotWindowFreeze())
                        window.ShowDialog();
                }
                else
                {
                    using (ScreenshotWindow window = new ScreenshotWindow())
                        window.ShowDialog();
                }
                break;

            case CommandLineHelper.Argument.Upload:
                //Context Menu Instant Upload
                if (args.UploadFiles.Count > 1)
                {
                    //1 or more files
                    //TODO: Implement "%1" more than 1
                    await StartUpload.UploadMultiple(args.UploadFiles);
                }
                else if (args.UploadFiles.Count == 1)
                {
                    //1 File
                    await StartUpload.UploadSingle(args.UploadFiles[0]);
                }
                else
                {
                    //No Image File detected
                    await Statics.ShowNotificationAsync(Properties.strings.notAnImage, NotificationWindow.NotificationType.Error);
                }
                break;
            }

            //Wait for every Notification to close
            if (NotificationWindow.IsShown)
            {
                await Task.Delay(NotificationWindow.ShowDuration);
            }

            Application.Current.Shutdown();
        }
Пример #16
0
        static void Main(string[] args)
        {
            var sw = new Stopwatch();

            sw.Start();
            try
            {
                var isHelp = CommandLineHelper.HasParameterByName(args, "--help") ||
                             CommandLineHelper.HasParameterByName(args, "-H") ||
                             args.Length == 0;

                const string defaultNamespace = "Project.Name";
                const string defaultContext   = "DatabaseContext";
                const string defaultModels    = "Models";

                if (isHelp)
                {
                    Console.WriteLine("Scaffold DF core model from database (MSSQL)");
                    Console.WriteLine();
                    Console.WriteLine("Usage:");
                    Console.WriteLine("-H,--help - display this help");
                    Console.WriteLine($"-N,--namespace <Namespace> - specifies namespace for generated classes, default is '{defaultNamespace}'");
                    Console.WriteLine($"-C,--context <Name> - name for context, default is '{defaultContext}'");
                    Console.WriteLine($"-M,--models <Path> - path for models, default is '{defaultModels}'");
                    Console.WriteLine("-S,--schema <Schema> - comma-separated list of schema to include, default is not defined, meaning is to include all");
                    Console.WriteLine("-SP,--stored-procedures - comma-separated list of SPs to include, if list is empty - all are generated");
                    //TODO: Console.WriteLine("-TVF,--table-value-functions - comma-separated list of TVFs to include, if list is empty - all are generated");
                    Console.WriteLine("-IT,--ignore-tables <Tables> - comma-separated list of tables to exclude. Example: '[dbo].Table1,[master].Table2'");
                    Console.WriteLine("-IV,--ignore-views <Views> - comma-separated list of view to exclude. Example: '[dbo].View1,[master].View2'");
                    Console.WriteLine("-FR,--foreign-key-regex <regex> - Regex to extract foreign property name. Example: 'FK_([a-zA-Z]+)_(?<PropertyName>.+)'");
                    Console.WriteLine("-CS,--connectionString <ConnectionString> - Connection string to the db, example: Data Source=.;Initial Catalog=Database;integrated security=SSPI");
                    Console.WriteLine("-TD,--templates-directory <Path> - Path with template fies set.hbs and context.hbs");
                    Console.WriteLine("-ETN,--extended-property-type-name <Name> - Extended property name to read model property type from, default is 'TypeName'. If column does not have extended property then model property type is inferred from the database column type.");
                    Console.WriteLine("-V,--verbose <Schema> - Show messages during execution");
                    Console.WriteLine("-CSD,--custom-settings-json <Path> - Path to custom settings json file");
                    Console.WriteLine("-AT,--allowed-tables <Tables> - comma-separated list of tables to include, if list is empty - all are generated, except ignore-tables. Example: '[dbo].[Table1],[master].[Table2]'");
                    Console.WriteLine("-ISP,--ignore-stored-procedures - comma-separated list of SPs to exclude. Example: '[dbo].[sp1],[master].[sp2]'");
                    Console.WriteLine("-AMTM,--allow-many-to-many - default is not supported");
                    Console.WriteLine("-IFOMTM,--ignore-for-objects-many-to-many - comma-separated list of tables to exclude many-to-many relationships. Example: '[dbo].[Table1],[master].[Table2]'");

                    return;
                }

                var @namespace = CommandLineHelper.GetParameterByName(args, "--namespace")
                                 ?? CommandLineHelper.GetParameterByName(args, "-N")
                                 ?? defaultNamespace;

                var contextName = CommandLineHelper.GetParameterByName(args, "--context")
                                  ?? CommandLineHelper.GetParameterByName(args, "-C")
                                  ?? defaultContext;

                var models = CommandLineHelper.GetParameterByName(args, "--models")
                             ?? CommandLineHelper.GetParameterByName(args, "-M")
                             ?? defaultModels;

                var schemas = CommandLineHelper.GetParameterByName(args, "--schema")
                              ?? CommandLineHelper.GetParameterByName(args, "-S")
                              ?? string.Empty;

                var excludeTables = CommandLineHelper.GetParameterByName(args, "--ignore-tables")
                                    ?? CommandLineHelper.GetParameterByName(args, "-IT")
                                    ?? string.Empty;

                var excludeViews = CommandLineHelper.GetParameterByName(args, "--ignore-views")
                                   ?? CommandLineHelper.GetParameterByName(args, "-IV")
                                   ?? string.Empty;

                var cleanUp = (CommandLineHelper.GetParameterByName(args, "--clean-up")
                               ?? CommandLineHelper.GetParameterByName(args, "-CU")) != null;

                var generateStoredProcedures = CommandLineHelper.HasParameterByName(args, "--stored-procedures") ||
                                               CommandLineHelper.HasParameterByName(args, "-SP");

                var ignoreStoredProcedures = CommandLineHelper.GetParameterByName(args, "--ignore-stored-procedures")
                                             ?? CommandLineHelper.GetParameterByName(args, "-ISP")
                                             ?? string.Empty;

                var generateTableValueFunctions = CommandLineHelper.HasParameterByName(args, "--table-valued-functions") ||
                                                  CommandLineHelper.HasParameterByName(args, "-TVF");

                var ignoreTableValuedFunctions = CommandLineHelper.GetParameterByName(args, "--ignore-table-valued-functions")
                                                 ?? CommandLineHelper.GetParameterByName(args, "-ITVF")
                                                 ?? string.Empty;

                var fkPropertyRegex = CommandLineHelper.GetParameterByName(args, "--foreign-key-regex")
                                      ?? CommandLineHelper.GetParameterByName(args, "-FR")
                                      ?? string.Empty;

                var connectionString = CommandLineHelper.GetParameterByName(args, "--connectionString")
                                       ?? CommandLineHelper.GetParameterByName(args, "-SC")
                                       ?? string.Empty;

                var templatesDirectory = CommandLineHelper.GetParameterByName(args, "--templates-directory")
                                         ?? CommandLineHelper.GetParameterByName(args, "-TD")
                                         ?? Environment.CurrentDirectory;

                var extendedPropertyTypeName = CommandLineHelper.GetParameterByName(args, "--extended-property-type-name")
                                               ?? CommandLineHelper.GetParameterByName(args, "-ETN")
                                               ?? "TypeName";

                var isVerbose = CommandLineHelper.HasParameterByName(args, "--verbose") ||
                                CommandLineHelper.HasParameterByName(args, "-V");

                var customSettingsJsonPath = CommandLineHelper.GetParameterByName(args, "--custom-settings-json")
                                             ?? CommandLineHelper.GetParameterByName(args, "-CSD")
                                             ?? string.Empty;

                var allowedTables = CommandLineHelper.GetParameterByName(args, "--allowed-tables")
                                    ?? CommandLineHelper.GetParameterByName(args, "-AT")
                                    ?? string.Empty;

                var allowManyToMany = CommandLineHelper.HasParameterByName(args, "--allow-many-to-many") ||
                                      CommandLineHelper.HasParameterByName(args, "-AMTM");

                var ignoreForObjectsManyToMany = CommandLineHelper.GetParameterByName(args, "--ignore-for-objects-many-to-many")
                                                 ?? CommandLineHelper.GetParameterByName(args, "-IFOMTM")
                                                 ?? string.Empty;

                var includeSchemas = schemas.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                     .Select(x => x.ToLower())
                                     .ToList();
                var excludeTablesList = excludeTables.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(x => x.ToLower())
                                        .ToList();
                var excludeViewsList = excludeViews.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                       .Select(x => x.ToLower())
                                       .ToList();
                var excludeStoredProceduresList = ignoreStoredProcedures.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                  .Select(x => x.ToLower())
                                                  .ToList();
                var excludeTableValuedFunctionsList = ignoreTableValuedFunctions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                      .Select(x => x.ToLower())
                                                      .ToList();
                var allowedTablesList = allowedTables.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(x => x.ToLower())
                                        .ToList();
                var excludeObjectsForManyToMany = ignoreForObjectsManyToMany.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                  .Select(x => x.ToLower())
                                                  .ToList();

                var directory = Environment.CurrentDirectory;

                var options = new ScaffoldOptions
                {
                    ConnectionString             = connectionString,
                    Directory                    = directory,
                    TemplatesDirectory           = templatesDirectory,
                    ModelsPath                   = models,
                    Schemas                      = includeSchemas,
                    IgnoreTables                 = excludeTablesList,
                    IgnoreViews                  = excludeViewsList,
                    GenerateStoredProcedures     = generateStoredProcedures,
                    IgnoreStoredProcedure        = excludeStoredProceduresList,
                    GenerateTableValuedFunctions = generateTableValueFunctions,
                    IgnoreTableValuedFunctions   = excludeTableValuedFunctionsList,
                    Namespace                    = @namespace,
                    ForeignPropertyRegex         = fkPropertyRegex,
                    ContextName                  = contextName,
                    IsVerbose                    = isVerbose,
                    ExtendedPropertyTypeName     = extendedPropertyTypeName,
                    CleanUp                      = cleanUp,
                    CustomSettingsJsonPath       = customSettingsJsonPath,
                    AllowedTables                = allowedTablesList,
                    AllowManyToMany              = allowManyToMany,
                    IgnoreObjectsForManyToMany   = excludeObjectsForManyToMany
                };
                var scaffolder = new Scaffolder(options);
                scaffolder.Generate();
            }
            finally
            {
                sw.Stop();
                Console.WriteLine($"Done in {sw.ElapsedMilliseconds} ms.");
                ConsoleHelper.ConsoleReadLineWithTimeout(TimeSpan.FromSeconds(10));
            }
        }
Пример #17
0
        private int Run(string[] args)
        {
            try
            {
                NameValueCollection nameValueArgs = CommandLineParser.Parse(args);
                WriteHeader();
                CommandLineHelper.TraceWriteArguments(args, nameValueArgs);
                if (CommandLineHelper.ArgSpecified(nameValueArgs, "Debug"))
                {
                    nameValueArgs.Remove("Debug");
                    CommandLineHelper.ConsoleWriteArguments(nameValueArgs);
                }
                Command command = CommandFactory.Create(nameValueArgs);
                bool    flag2   = CommandLineHelper.ArgSpecified(nameValueArgs, "?") || CommandLineHelper.ArgSpecified(nameValueArgs, "Help");
                if ((nameValueArgs.Count == 0) || flag2)
                {
                    using (new ConsoleColorChanger(ConsoleColorManager.GetInstance().GetColor(TraceLevel.Info)))
                    {
                        command.WriteUsage();
                        goto Label_02F4;
                    }
                }
                if (command is HelpCommand)
                {
                    command.Execute();
                    this.errors   += command.Result.ErrorCount;
                    this.warnings += command.Result.WarningCount;
                    this.WriteCommandSummary();
                    return(this.errors);
                }
                List <CommandLineArgumentException> list = command.ValidateArgs();
                if (list.Count > 0)
                {
                    foreach (CommandLineArgumentException exception in list)
                    {
                        this.errors   += (exception.Severity == TraceLevel.Error) ? 1 : 0;
                        this.warnings += (exception.Severity == TraceLevel.Warning) ? 1 : 0;
                        using (new ConsoleColorChanger(ConsoleColorManager.GetInstance().GetColor(exception.Severity)))
                        {
                            Console.WriteLine(exception.Severity.ToString() + ": " + exception.Message);
                            Console.WriteLine(string.Empty);
                            continue;
                        }
                    }
                }
                if (this.errors == 0)
                {
                    command.Execute();
                    this.errors   += command.Result.ErrorCount;
                    this.warnings += command.Result.WarningCount;
                    this.WriteCommandSummary();
                }
                else
                {
                    using (new ConsoleColorChanger(ConsoleColorManager.GetInstance().GetColor(TraceLevel.Info)))
                    {
                        command.WriteUsageHint();
                    }
                }
            }
            catch (Exception exception2)
            {
                Trace.WriteLine(exception2.ToString());
                this.errors++;
                using (new ConsoleColorChanger(ConsoleColorManager.GetInstance().GetColor(TraceLevel.Error)))
                {
                    Console.WriteLine(exception2.Message);
                }
                if ((exception2 is OutOfMemoryException) || (exception2 is StackOverflowException))
                {
                    throw;
                }
            }
            finally
            {
                string formattedString = StringResources.GetFormattedString(StringResources.ResourceID.CommandCompleted, new object[] { this.errors.ToString(CultureInfo.InvariantCulture), this.warnings.ToString(CultureInfo.InvariantCulture) });
                Trace.WriteLine(string.Empty);
                Trace.WriteLine(formattedString);
            }
Label_02F4:
            return(this.errors);
        }
Пример #18
0
        private static void Main(string[] args)
        {
            Console.InputEncoding  = Encoding.UTF8;
            Console.OutputEncoding = Encoding.UTF8;

            try { Line = CommandLineHelper.Parse <CommandLine>(args); }
            catch { Line = new CommandLine {
                        ShowHelp = true
                    }; }

            if (Line != null)
            {
                if (Line.ShowHelp || Line.IsValid == false)
                {
                    Line.WriteHelp(Console.Out);
                }
                else
                {
                    TinyDefinition definition = new TinyDefinition();
                    TextReader     definitionReader;

                    try
                    {
                        // separate try catch block for file issues for compatibility reasons
                        definitionReader = new StreamReader(Line.InputFile, Encoding.UTF8, true);
                    }
                    catch
                    {
                        Console.WriteLine("Cannot open '{0}'!", Line.InputFile);
                        return;
                    }

                    try
                    {
                        definition.Load(definitionReader);
                    }
                    catch (Exception e)
                    {
                        // the TFConvert exception messages correspond to the native error strings
                        Console.WriteLine(e.Message);
                        return;
                    }

                    try
                    {
                        definition.Validate();
                    }
                    catch (KeyNotFoundException)
                    {
                        // currently the only required command
                        Console.WriteLine("SelectFont command not found in .FNTDEF file");
                        return;
                    }

                    definitionReader.Close();

                    TinyFont font = TFConvert.Convert(definition);
                    DumpFont(definition, font, Console.Out);

                    try
                    {
                        font.Save(Line.OutputFile);
                    }
                    catch
                    {
                        Console.WriteLine("Cannot open '{0}' for writing!", Line.OutputFile);
                        return;
                    }
                }
            }
        }
Пример #19
0
            public void Ignores_The_Trailing_Spaces()
            {
                var arguments = CommandLineHelper.Parse("   install \"c:\\Users\\alexander.fernandez\\Documents\\Visual Studio 2012\\Projects\\Catel\\src\\Catel.sln\" -outputDirectory \"c:\\Users\\alexander.fernandez\\Documents\\Visual Studio 2012\\Projects\\Catel\\lib\" -source https://nuget.org/api/v2/      ");

                Assert.AreEqual("https://nuget.org/api/v2/", arguments[5]);
            }
        /// <summary>更新组织的名称</summary>
        static void UpdateOrganizationName(SqlCommand command, string parentId)
        {
            IList <IOrganizationInfo> list = MembershipManagement.Instance.OrganizationService.FindAllByParentId(parentId);

            foreach (IOrganizationInfo item in list)
            {
                // [暂时取消]过滤禁用的
                // if (item.Status == 0)
                //    continue;

                // 过滤名称为空的信息
                if (string.IsNullOrEmpty(item.Name))
                {
                    continue;
                }

                // 过滤全局名称为空的信息
                if (string.IsNullOrEmpty(item.GlobalName))
                {
                    continue;
                }

                command.CommandText = string.Format("SELECT OrgName, OrgGlobalName FROM Orgs WHERE MappingToken = '{0}' ", item.Id);

                string originalName = null;

                string originalGlobalName = null;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        originalName = reader.GetString(0);

                        originalGlobalName = reader.GetString(1);

                        if (ActiveDirectoryManagement.Instance.Group.IsExistName(originalGlobalName))
                        {
                            ActiveDirectoryManagement.Instance.Group.Rename(originalGlobalName, item.GlobalName);

                            ActiveDirectoryManagement.Instance.Organization.Rename(originalName,
                                                                                   MembershipManagement.Instance.OrganizationService.GetActiveDirectoryOUPathByOrganizationId(parentId),
                                                                                   item.Name);
                        }
                    }
                }

                if (!string.IsNullOrEmpty(originalGlobalName))
                {
                    //command.CommandText = string.Format("UPDATE Orgs SET OrgName = '{0}', OrgGlobalName = '{1}', ActionDate = GetDate() WHERE MappingToken = '{2}' ", item.Name, item.GlobalName, item.Id);

                    //command.ExecuteNonQuery();

                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.Yellow);
                    Console.WriteLine("组织名称【{0}({1})】已更新为【{2}({3})】。", originalName, originalGlobalName, item.Name, item.GlobalName);
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                }

                UpdateOrganizationName(command, item.Id);
            }
        }
Пример #21
0
            public void Parse_The_Right_Count_Of_Arguments()
            {
                var arguments = CommandLineHelper.Parse("install \"c:\\Users\\alexander.fernandez\\Documents\\Visual Studio 2012\\Projects\\Catel\\src\\Catel.sln\" -outputDirectory \"c:\\Users\\alexander.fernandez\\Documents\\Visual Studio 2012\\Projects\\Catel\\lib\" -source https://nuget.org/api/v2/");

                Assert.AreEqual(6, arguments.Count());
            }
        /// <summary>更新角色的名称</summary>
        static void UpdateRoleName(Options options)
        {
            IList <IRoleInfo> list = MembershipManagement.Instance.RoleService.FindAll();

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LH_BDM"].ConnectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.Connection  = connection;

                    foreach (IRoleInfo item in list)
                    {
                        // 根据用户中心的的角色
                        // 更具

                        // [暂时取消]过滤禁用的
                        // if (item.Status == 0)
                        //    continue;

                        // 过滤名称为空的信息
                        if (string.IsNullOrEmpty(item.Name))
                        {
                            continue;
                        }

                        // 过滤全局名称为空的信息
                        if (string.IsNullOrEmpty(item.GlobalName))
                        {
                            continue;
                        }

                        command.CommandText = string.Format("SELECT PostName FROM Posts WHERE MappingToken = '{0}' ", item.Id);

                        string originalGlobalName = null;

                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                originalGlobalName = reader.GetString(0);

                                if (ActiveDirectoryManagement.Instance.Group.IsExistName(originalGlobalName))
                                {
                                    ActiveDirectoryManagement.Instance.Group.Rename(originalGlobalName, item.GlobalName);
                                    ActiveDirectoryManagement.Instance.Group.MoveTo(item.GlobalName,
                                                                                    MembershipManagement.Instance.OrganizationService.GetActiveDirectoryOUPathByOrganizationId(item.OrganizationId));
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(originalGlobalName))
                        {
                            //command.CommandText = string.Format("UPDATE Posts SET PostName = '{0}', ActionDate = GetDate() WHERE MappingToken = '{1}' ", item.GlobalName, item.Id);

                            //command.ExecuteNonQuery();

                            CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.Yellow);
                            Console.WriteLine("角色名称【{0}】已更新为【{1}】。", originalGlobalName, item.GlobalName);
                            CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                        }
                    }
                }

                connection.Close();
            }
        }
Пример #23
0
 public NetworkHelper(CommandLineHelper cmdHelper)
 {
     _cmdHelper = cmdHelper;
 }
        /// <summary>初始化组织结构</summary>
        static void CheckUsers(Options options)
        {
            IList <IAccountInfo> list = MembershipManagement.Instance.AccountService.FindAll();

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LH_BDM"].ConnectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.Connection  = connection;

                    foreach (IAccountInfo item in list)
                    {
                        // [暂时取消]过滤禁用的
                        // if (item.Status == 0)
                        //    continue;

                        // 过滤登录名为空的信息
                        if (string.IsNullOrEmpty(item.LoginName))
                        {
                            continue;
                        }

                        // 过滤全局名称为空的信息
                        if (string.IsNullOrEmpty(item.GlobalName))
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(item.GlobalName))
                        {
                            CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                            Console.WriteLine("用户【{0}({1})】的全局名称为空,请设置相关配置。",
                                              item.Name,
                                              item.LoginName);
                            CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                            Console.ReadLine();
                        }
                        else if (ActiveDirectoryManagement.Instance.User.IsExistLoginName(item.LoginName))
                        {
                            command.CommandText = string.Format("UPDATE Users SET MappingToken = '{1}' WHERE LoginId = '{0}' ",
                                                                item.LoginName, item.Id);

                            int rowsAffected = command.ExecuteNonQuery();

                            if (rowsAffected == 0)
                            {
                                CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                                Console.WriteLine("系统【门户系统】没有用户【{0}({1})】。", item.Name, item.LoginName);
                                CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                            }
                        }
                        else
                        {
                            if (ActiveDirectoryManagement.Instance.User.IsExist(item.LoginName, item.GlobalName))
                            {
                                CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                                Console.WriteLine("用户【{0}({1})】的全局名称已被其他人创建,唯一名称:{2}。",
                                                  item.Name,
                                                  item.LoginName,
                                                  MembershipManagement.Instance.AccountService.CombineDistinguishedName(item.GlobalName));
                                CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                                Console.ReadLine(); // "用户【${Name}(${LoginName})】的全局名称已被其他人创建,请设置相关配置。
                            }
                            else
                            {
                                CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                                Console.WriteLine("用户【{0}({1})】不存在,唯一名称:{2}。",
                                                  item.Name,
                                                  item.LoginName,
                                                  MembershipManagement.Instance.AccountService.CombineDistinguishedName(item.GlobalName));
                                CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                                Console.ReadLine();
                            }
                        }
                    }
                }

                connection.Close();
            }
        }
Пример #25
0
            // Creates a ProcessInfo object from the IEndpointInfo. Attempts to get the command line using event pipe
            // if the endpoint information doesn't provide it. The cancelation token can be used to timebox this fallback
            // mechansim.
            public static async Task <ProcessInfo> FromEndpointInfoAsync(IEndpointInfo endpointInfo, CancellationToken extendedInfoCancellationToken)
            {
                if (null == endpointInfo)
                {
                    throw new ArgumentNullException(nameof(endpointInfo));
                }

                var client = new DiagnosticsClient(endpointInfo.Endpoint);

                string commandLine = endpointInfo.CommandLine;

                if (string.IsNullOrEmpty(commandLine))
                {
                    try
                    {
                        var infoSettings = new EventProcessInfoPipelineSettings
                        {
                            Duration = Timeout.InfiniteTimeSpan,
                        };

                        await using var pipeline = new EventProcessInfoPipeline(client, infoSettings,
                                                                                (cmdLine, token) => { commandLine = cmdLine; return(Task.CompletedTask); });

                        await pipeline.RunAsync(extendedInfoCancellationToken);
                    }
                    catch
                    {
                    }
                }

                string processName = null;

                if (!string.IsNullOrEmpty(commandLine))
                {
                    // Get the process name from the command line
                    bool isWindowsProcess = false;
                    if (string.IsNullOrEmpty(endpointInfo.OperatingSystem))
                    {
                        // If operating system is null, the process is likely .NET Core 3.1 (which doesn't have the GetProcessInfo command).
                        // Since the underlying diagnostic communication channel used by the .NET runtime requires that the diagnostic process
                        // must be running on the same type of operating system as the target process (e.g. dotnet-monitor must be running on Windows
                        // if the target process is running on Windows), then checking the local operating system should be a sufficient heuristic
                        // to determine the operating system of the target process.
                        isWindowsProcess = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    }
                    else
                    {
                        isWindowsProcess = ProcessOperatingSystemWindowsValue.Equals(endpointInfo.OperatingSystem, StringComparison.OrdinalIgnoreCase);
                    }

                    string processPath = CommandLineHelper.ExtractExecutablePath(commandLine, isWindowsProcess);
                    if (!string.IsNullOrEmpty(processPath))
                    {
                        processName = Path.GetFileName(processPath);
                        if (isWindowsProcess)
                        {
                            // Remove the extension on Windows to match the behavior of Process.ProcessName
                            processName = Path.GetFileNameWithoutExtension(processName);
                        }
                    }
                }

                // The GetProcessInfo command will return "unknown" for values for which it does
                // not know the value, such as operating system and process architecture if the
                // process is running on one that is not predefined. Mimic the same behavior here
                // when the extra process information was not provided.
                return(new ProcessInfo(
                           endpointInfo,
                           processName ?? ProcessFieldUnknownValue));
            }
        /// <summary>初始化组织结构</summary>
        static void SyncUsers(Options options)
        {
            IList <IAccountInfo> list = MembershipManagement.Instance.AccountService.FindAll();

            foreach (IAccountInfo item in list)
            {
                // 过滤禁用的
                if (item.Status == 0)
                {
                    continue;
                }

                // 过滤登录名为空的信息
                if (string.IsNullOrEmpty(item.LoginName))
                {
                    continue;
                }

                // 过滤全局名称为空的信息
                if (string.IsNullOrEmpty(item.GlobalName))
                {
                    continue;
                }

                int result = MembershipManagement.Instance.AccountService.SyncToActiveDirectory(item);

                if (result == 0)
                {
                    string accountId = item.Id;

                    if (!string.IsNullOrEmpty(accountId))
                    {
                        foreach (IRoleInfo role in item.Roles)
                        {
                            MembershipManagement.Instance.RoleService.AddRelation(accountId, role.Id);

                            MembershipManagement.Instance.OrganizationService.AddRelation(accountId, role.OrganizationId);

                            MembershipManagement.Instance.OrganizationService.AddParentRelations(accountId, role.OrganizationId);
                        }
                    }
                }

                switch (result)
                {
                case 0:
                    Console.WriteLine("用户【{0}({1})】同步成功。", item.Name, item.LoginName);
                    break;

                case 1:
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                    Console.WriteLine("用户【{0}({1})】登录名为空,请设置相关配置。",
                                      item.Name,
                                      item.LoginName,
                                      MembershipManagement.Instance.AccountService.CombineDistinguishedName(item.GlobalName));
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                    Console.ReadLine();
                    break;

                case 2:
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                    Console.WriteLine("用户【{0}({1})】全局名称为空,请设置相关配置。",
                                      item.Name,
                                      item.LoginName);
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                    Console.ReadLine();
                    break;

                case 3:
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.LightRed);
                    Console.WriteLine("用户【{0}({1})】的全局名称【{2}】已被其他人创建,请设置相关配置。",
                                      item.Name,
                                      item.LoginName,
                                      item.GlobalName);
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                    Console.ReadLine();
                    break;

                case 4:
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.DarkGray);
                    Console.WriteLine("用户【{0}({1})】的帐号为【禁用】状态,如果需要创建 Active Directory 帐号,请设置相关配置。",
                                      item.Name,
                                      item.LoginName);
                    CommandLineHelper.SetTextColor(CommandLineHelper.Foreground.White);
                    Console.ReadLine();
                    break;
                }
            }
        }
Пример #27
0
 public void TestEmptyArgumentName()
 {
     Assert.Throws <ArgumentException>(() => CommandLineHelper.CreateArgString("", "value"));
 }
Пример #28
0
        public void Clear()
        {
            if (isClean)
            {
                return;
            }

            WebBrowserHelper.ResetBatch(wBrowser);

            if (UpdatesManager.IsNewVersion && !CommandLineHelper.IsCommandSwitchSet("skipchangelog"))
            {
                UpdatesManager.IsNewVersion = false;
                string url = Constants.ChangeLogPageUrlBase;
                if (FreeCL.RTL.LangPack.CurrentLanguage == "Ukrainian")
                {
                    url += "uk.html";
                }
                else if (FreeCL.RTL.LangPack.CurrentLanguage == "Russian")
                {
                    url += "ru.html";
                }
                else
                {
                    url += "en.html";
                }
                url          += "?ver=" + FreeCL.RTL.ApplicationInfo.ProductVersion;
                forceCleaning = true;
                wBrowser.Navigate(url);
                return;
            }

            if (WebBrowserHelper.GetDocument(wBrowser) != null && !forceCleaning)
            {
                Wait();

                if (WebBrowserHelper.GetDocument(wBrowser) != null)
                {
                    if (!HtmlHelper.ClearTranslations(wBrowser))
                    {                           //possible disabled javascript or error
                        forceCleaning = true;
                    }
                    else
                    {
                        WebBrowserHelper.StartBatch(wBrowser);
                        isClean = true;                         //avoid double cleaning
                    }
                }
                else
                {
                    forceCleaning = true;
                }
            }

            if (WebBrowserHelper.GetDocument(wBrowser) == null || forceCleaning)
            {
                //Console.WriteLine("Clear Result");
                forceCleaning  = false;
                navigateCalled = true;
                wBrowser.Navigate(new Uri(WebUI.ResultsWebServer.Uri, "Default.aspx"));
                WebBrowserHelper.StartBatch(wBrowser);
            }
            RecalcSizes();
            isClean = true;
        }
Пример #29
0
 public void TestNullValue()
 {
     Assert.Throws <ArgumentException>(() => CommandLineHelper.CreateArgString("DateFrom", null));
 }
Пример #30
0
        private string BuildPayload(Notification notification)
        {
            // Get some more data about this commit via "svnlook"
            notification.CommitMessage = CommandLineHelper.ExecuteProcess(ConfigurationHelper.SVNLookProcessPath, string.Format("log -r {0} {1}", notification.Revision, notification.RepositoryPath));
            notification.CommitAuthor  = CommandLineHelper.ExecuteProcess(ConfigurationHelper.SVNLookProcessPath, string.Format("author -r {0} {1}", notification.Revision, notification.RepositoryPath));
            notification.CommitChange  = CommandLineHelper.ExecuteProcess(ConfigurationHelper.SVNLookProcessPath, string.Format("changed --copy-info -r {0} {1}", notification.Revision, notification.RepositoryPath));

            // Ensure valid formatting of message
            if (notification.CommitMessage.Contains("\""))
            {
                notification.CommitMessage = notification.CommitMessage.Replace("\"", "\\\"");
            }
            if (notification.CommitAuthor.Contains("\""))
            {
                notification.CommitAuthor = notification.CommitAuthor.Replace("\"", "\\\"");
            }
            if (notification.CommitChange.Contains("\""))
            {
                notification.CommitChange = notification.CommitChange.Replace("\"", "\\\"");
            }
            // Trim off unnecessary trailing CRLFs
            notification.CommitMessage = notification.CommitMessage.TrimEnd(new char[] { '\r', '\n' });
            notification.CommitAuthor  = notification.CommitAuthor.TrimEnd(new char[] { '\r', '\n' });
            notification.CommitChange  = notification.CommitChange.TrimEnd(new char[] { '\r', '\n' });

            // Use advanced message formatting for incoming webhooks
            var payloadBody = new StringBuilder();

            payloadBody.Append("{");    // begin payload
            payloadBody.Append(" \"username\" : \"VisualSVN Server\", ");
            payloadBody.Append(" \"icon_url\" : \"http://s3.amazonaws.com/scs-public/visualsvn_96.png\", ");
            if (!string.IsNullOrEmpty(notification.Channel))
            {
                payloadBody.Append(string.Format(" \"channel\" : \"{0}\", ", notification.Channel));
            }
            payloadBody.Append(" \"attachments\" : [ { ");  // begin attachments
            if (!string.IsNullOrEmpty(notification.RepositoryName))
            {
                payloadBody.Append(string.Format(" \"fallback\" : \"[{0}] New commit by {1}: r{2}: {3}\n\n{4}\", ", notification.RepositoryName, notification.CommitAuthor, notification.Revision, notification.CommitMessage, notification.CommitChange));
                payloadBody.Append(string.Format(" \"pretext\" : \"[{0}] New commit by {1}\", ", notification.RepositoryName, notification.CommitAuthor));
            }
            else
            {
                payloadBody.Append(string.Format(" \"fallback\" : \"New commit by {0}: r{1}: {2}\n\n{3}\", ", notification.CommitAuthor, notification.Revision, notification.CommitMessage, notification.CommitChange));
                payloadBody.Append(string.Format(" \"pretext\" : \"New commit by {0}\", ", notification.CommitAuthor));
            }
            if (!string.IsNullOrEmpty(notification.RepositoryURL))
            {
                if (notification.RepositoryURL.Contains("/svn/"))
                {
                    notification.RepositoryURL = notification.RepositoryURL.Replace("/svn/", "/!/#");
                }
                notification.RepositoryURL += "/commit/r" + notification.Revision;
                payloadBody.Append(string.Format(" \"text\" : \"<{0}|r{1}>: {2}\n\n{3}\", ", notification.RepositoryURL, notification.Revision, notification.CommitMessage, notification.CommitChange));
            }
            else
            {
                payloadBody.Append(string.Format(" \"text\" : \"r{0}: {1}\n\n{2}\", ", notification.Revision, notification.CommitMessage, notification.CommitChange));
            }
            payloadBody.Append(" \"color\" : \"#3886C0\" ");
            payloadBody.Append("} ]"); // end attachments
            payloadBody.Append("}");   // end payload

            return(payloadBody.ToString());
        }