Ejemplo n.º 1
0
        public void Should_choose_the_greediest_one()
        {
            string subject = "Hello, World";

            var p = new StringParser();

            Parser<string, string> first = from x in p.String("Hello")
                                           select x;

            Assert.IsTrue(first.ParseString(subject).HasValue, "First did not match");

            Parser<string, string> second = from x in p.String("Hello")
                                            from y in p.Char(',')
                                            from ws in p.Whitespace()
                                            from z in p.String("World")
                                            select x + z;

            Assert.IsTrue(second.ParseString(subject).HasValue, "Second did not match");

            Parser<string, string> parser = p.Longest(first, second);

            Result<string, string> result = parser.ParseString(subject);

            Assert.IsTrue(result.HasValue, "Neither matched");

            Assert.AreEqual("HelloWorld", result.Value, "Longest parser should have matched");
        }
Ejemplo n.º 2
0
        public HelloStringParsing()
        {
            var sp = new StringParser();

            _parser = from x in sp.String("Hello")
                      select x;
        }
Ejemplo n.º 3
0
        public static UdpStatistics CreateUdpIPv4Statistics()
        {
            LinuxUdpStatistics stats = new LinuxUdpStatistics();
            string fileContents = File.ReadAllText(NetworkFiles.SnmpV4StatsFile);
            int firstUdpHeader = fileContents.IndexOf("Udp:");
            int secondUdpHeader = fileContents.IndexOf("Udp:", firstUdpHeader + 1);
            int endOfSecondLine = fileContents.IndexOf(Environment.NewLine, secondUdpHeader);
            string tcpData = fileContents.Substring(secondUdpHeader, endOfSecondLine - secondUdpHeader);
            StringParser parser = new StringParser(tcpData, ' ');

            // NOTE: Need to verify that this order is consistent. Otherwise, we need to parse the first-line header
            // to determine the order of information contained in the file.

            parser.MoveNextOrFail(); // Skip Udp:

            stats._inDatagrams = parser.ParseNextInt32();
            stats._noPorts = parser.ParseNextInt32();
            stats._inErrors = parser.ParseNextInt32();
            stats._outDatagrams = parser.ParseNextInt32();
            stats._rcvbufErrors = parser.ParseNextInt32();
            stats._sndbufErrors = parser.ParseNextInt32();
            stats._inCsumErrors = parser.ParseNextInt32();

            // Parse the number of active connections out of /proc/net/sockstat
            string sockstatFile = File.ReadAllText(NetworkFiles.SockstatFile);
            int indexOfUdp = sockstatFile.IndexOf("UDP:");
            int endOfUdpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfUdp + 1);
            string udpLineData = sockstatFile.Substring(indexOfUdp, endOfUdpLine - indexOfUdp);
            StringParser sockstatParser = new StringParser(udpLineData, ' ');
            sockstatParser.MoveNextOrFail(); // Skip "UDP:"
            sockstatParser.MoveNextOrFail(); // Skip: "inuse"
            stats._udpListeners = sockstatParser.ParseNextInt32();

            return stats;
        }
Ejemplo n.º 4
0
        public static UdpStatistics CreateUdpIPv6Statistics()
        {
            LinuxUdpStatistics stats = new LinuxUdpStatistics();

            string fileContents = File.ReadAllText(NetworkFiles.SnmpV6StatsFile);

            RowConfigReader reader = new RowConfigReader(fileContents);

            stats._inDatagrams = reader.GetNextValueAsInt32("Udp6InDatagrams");
            stats._noPorts = reader.GetNextValueAsInt32("Udp6NoPorts");
            stats._inErrors = reader.GetNextValueAsInt32("Udp6InErrors");
            stats._outDatagrams = reader.GetNextValueAsInt32("Udp6OutDatagrams");
            stats._rcvbufErrors = reader.GetNextValueAsInt32("Udp6RcvbufErrors");
            stats._sndbufErrors = reader.GetNextValueAsInt32("Udp6SndbufErrors");
            stats._inCsumErrors = reader.GetNextValueAsInt32("Udp6InCsumErrors");

            // Parse the number of active connections out of /proc/net/sockstat6
            string sockstatFile = File.ReadAllText(NetworkFiles.Sockstat6File);
            int indexOfUdp = sockstatFile.IndexOf("UDP6:");
            int endOfUdpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfUdp + 1);
            string udpLineData = sockstatFile.Substring(indexOfUdp, endOfUdpLine - indexOfUdp);
            StringParser sockstatParser = new StringParser(udpLineData, ' ');
            sockstatParser.MoveNextOrFail(); // Skip "UDP6:"
            sockstatParser.MoveNextOrFail(); // Skip: "inuse"
            stats._udpListeners = sockstatParser.ParseNextInt32();

            return stats;
        }
 internal static StringLiteralToken Read(ILexerStream stream)
 {
     var extent = new SourceExtent(stream);
     var sourceChars = new List<char>();
     // read the first character
     sourceChars.Add(stream.ReadChar('"'));
     // read the remaining characters
     var parser = new StringParser();
     while (!stream.Eof)
     {
         var peek = stream.Peek();
         sourceChars.Add(peek);
         if ((peek == '"') && !parser.IsEscaped)
         {
             parser.ConsumeEof();
             break;
         }
         else
         {
             parser.ConsumeChar(stream.Read());
         }
     }
     // read the last character
     sourceChars.Add(stream.ReadChar('"'));
     // process any escape sequences in the string
     var unescaped = parser.OutputString.ToString();
     // return the result
     extent = extent.WithText(sourceChars);
     return new StringLiteralToken(extent, unescaped);
 }
Ejemplo n.º 6
0
            public CommandLineParser()
            {
                var p = new StringParser();

                Id = from ws in p.SkipWhitespace()
                     from c in p.Char(char.IsLetter)
                     from cs in p.Char(char.IsLetterOrDigit).ZeroOrMore()
                     select new string(c, 1) + new string(cs);

                Key = from ws in p.SkipWhitespace()
                     from c in p.Char(char.IsLetter)
                     from cs in (p.Char(char.IsLetterOrDigit).Or(p.Char('.'))).ZeroOrMore()
                     select new string(c, 1) + new string(cs);

                //                Value = from v in (p.Char(x => !char.IsWhiteSpace(x))).ZeroOrMore()
                //                        select new string(v);
                Value = from v in (p.Char().Except(p.Whitespace())).ZeroOrMore()
                        select new string(v);

                Definition = (from ws in p.SkipWhitespace()
                              from c in p.Char('-', '/')
                              from id in Id
                              from eq in p.Char(':', '=')
                              from v in Value
                              select new Definition(id, v));
            }
        // /proc/net/route contains some information about gateway addresses,
        // and separates the information about by each interface.
        internal static List<GatewayIPAddressInformation> ParseGatewayAddressesFromRouteFile(string filePath, string interfaceName)
        {
            if (!File.Exists(filePath))
            {
                throw ExceptionHelper.CreateForInformationUnavailable();
            }

            List<GatewayIPAddressInformation> collection = new List<GatewayIPAddressInformation>();
            // Columns are as follows (first-line header):
            // Iface  Destination  Gateway  Flags  RefCnt  Use  Metric  Mask  MTU  Window  IRTT
            string[] fileLines = File.ReadAllLines(filePath);
            foreach (string line in fileLines)
            {
                if (line.StartsWith(interfaceName))
                {
                    StringParser parser = new StringParser(line, '\t', skipEmpty: true);
                    parser.MoveNext();
                    parser.MoveNextOrFail();
                    string gatewayIPHex = parser.MoveAndExtractNext();
                    long addressValue = Convert.ToInt64(gatewayIPHex, 16);
                    IPAddress address = new IPAddress(addressValue);
                    collection.Add(new SimpleGatewayIPAddressInformation(address));
                }
            }

            return collection;
        }
Ejemplo n.º 8
0
        public void TestStringOne()
        {
            var matcher = new StringParser();

            var match = matcher.GetMatch(StrList1, matcher.One);
            Assert.IsTrue(match.Success);
            Assert.AreEqual(1, match.Result);
        }
Ejemplo n.º 9
0
        public void TestStringPi()
        {
            var matcher = new StringParser();

            var match = matcher.GetMatch(StrListPi, matcher.Pi);
            Assert.IsTrue(match.Success);
            Assert.AreEqual(314, match.Result);
        }
Ejemplo n.º 10
0
        public Hello_StringParsing()
        {
            var sp = new StringParser();

            _parser = from x in sp.String("Hello")
                      from y in sp.Char(',')
                      select x;
        }
        public HelloOrHello_StringParsing()
        {
            var sp = new StringParser();

            _parser = (from hello in sp.String("Hello") select hello)
                .Longest(from hello in sp.String("Hello")
                         from comma in sp.Char(',')
                         select hello);
        }
Ejemplo n.º 12
0
        public void Count_Returns_Number_Of_Tokens()
        {
            Int32 EXPECTED = 2;
            StringParser target = new StringParser("unit test", ' ', StringSplitOptions.RemoveEmptyEntries);
            Assert.AreEqual(EXPECTED, target.Count);

            target = new StringParser(" unit  test ", " ", StringSplitOptions.RemoveEmptyEntries);
            Assert.AreEqual(EXPECTED, target.Count);
        }
        public void TestParserWithNoEndingSeparatorWithSkipEmpty()
        {
            string buffer = ",,,Str|ing,,123";
            char separator = ',';

            StringParser sp = new StringParser(buffer, separator, true);
            Assert.Equal("Str|ing", sp.MoveAndExtractNext());
            Assert.Equal(123, sp.ParseNextInt32());
        }
Ejemplo n.º 14
0
        public Hello__StringParsing()
        {
            var sp = new StringParser();

            _parser = from x in sp.String("Hello")
                      from y in sp.Char(',')
                      from z in sp.Whitespace()
                      select x;
        }
        public Hello__WorldStringParsing()
        {
            var sp = new StringParser();

            _parser = from hello in sp.String("Hello")
                      from comma in sp.Char(',')
                      from ws in sp.Whitespace()
                      from world in sp.String("World")
                      select hello;
        }
        private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting

        internal static int ParseNumSocketConnections(string filePath, string protocolName)
        {
            // Parse the number of active connections out of /proc/net/sockstat
            string sockstatFile = File.ReadAllText(filePath);
            int indexOfTcp = sockstatFile.IndexOf(protocolName);
            int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1);
            string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp);
            StringParser sockstatParser = new StringParser(tcpLineData, ' ');
            sockstatParser.MoveNextOrFail(); // Skip "<name>:"
            sockstatParser.MoveNextOrFail(); // Skip: "inuse"
            return sockstatParser.ParseNextInt32();
        }
        public Hello__World___StringParsing()
        {
            var sp = new StringParser();

            _parser = from hello in sp.String("Hello")
                      from comma in sp.Char(',')
                      from ws in sp.Whitespace()
                      from world in sp.String("World")
                      from period in sp.Char('.')
                      from nl in sp.NewLine()
                      select hello;
        }
        public void TestParserWithNoEndingSeparatorWithNoSkipEmpty()
        {
            string buffer = ",,Str|ing,,123";
            char separator = ',';

            StringParser sp = new StringParser(buffer, separator, false);
            sp.MoveNextOrFail();
            sp.MoveNextOrFail();
            Assert.Equal("Str|ing", sp.MoveAndExtractNext());
            Assert.Throws<InvalidDataException>(() => sp.ParseNextInt32());
            Assert.Equal(123, sp.ParseNextInt32());
        }
Ejemplo n.º 19
0
        public void Should_return_the_position_that_did_not_match()
        {
            var sp = new StringParser();

            var parser = from x in sp.String("Hello World")
                         select x;

            var result = parser.ParseString("Hello");

            Assert.IsFalse(result.HasValue);

            Assert.AreEqual(0, result.Next.Offset);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            Person jon = new Person("Jon");
            Person derek = new Person("Derek");

            StringParser jonVoice = new StringParser(jon.Say);
            StringParser derekVoice = new StringParser(derek.Say);
            StringParser backgroundMessage = new StringParser(BackgroundMessage.Show);

            jonVoice("Hello, Derek! How are you?");
            derekVoice.Invoke("I am fine, Jon. Thanks for asking.");
            backgroundMessage("and happiness was in the air");
        }
Ejemplo n.º 21
0
        public void Should_select_all_whitespace_before_value()
        {
            string subject = "   \t\r\n\tHello";

            var p = new StringParser();

            var parser = from ws in p.Whitespace()
                         from value in p.String("Hello")
                         select value;

            var result = parser.ParseString(subject);

            Assert.IsTrue(result.HasValue);
        }
Ejemplo n.º 22
0
 internal static int ParseDefaultTtlFromFile(string filePath)
 {
     // snmp6 does not include Default TTL info. Read it from snmp.
     string snmp4FileContents = File.ReadAllText(filePath);
     int firstIpHeader = snmp4FileContents.IndexOf("Ip:", StringComparison.Ordinal);
     int secondIpHeader = snmp4FileContents.IndexOf("Ip:", firstIpHeader + 1, StringComparison.Ordinal);
     int endOfSecondLine = snmp4FileContents.IndexOf(Environment.NewLine, secondIpHeader, StringComparison.Ordinal);
     string ipData = snmp4FileContents.Substring(secondIpHeader, endOfSecondLine - secondIpHeader);
     StringParser parser = new StringParser(ipData, ' ');
     parser.MoveNextOrFail(); // Skip Ip:
     // According to RFC 1213, "1" indicates "acting as a gateway". "2" indicates "NOT acting as a gateway".
     parser.MoveNextOrFail(); // Skip forwarding
     return parser.ParseNextInt32();
 }
Ejemplo n.º 23
0
        public void Should_be_convertable_to_a_string()
        {
            const string subject = "Hello World";

            var sp = new StringParser();

            var parser = from x in sp.Chars('H', 'e', 'l', 'l', 'o').String()
                         select x;

            var result = parser.ParseString(subject);

            Assert.IsTrue(result.HasValue);

            Assert.AreEqual("Hello", result.Value);
        }
Ejemplo n.º 24
0
        public void Should_return_the_greediest_position_that_did_not_match_including_whitespace()
        {
            var sp = new StringParser();

            var parser = from x in sp.String("Hello")
                         from _ in sp.Whitespace()
                         from y in sp.String("World")
                         select y;

            var result = parser.ParseString("Hello\t W0rld");

            Assert.IsFalse(result.HasValue);

            Assert.AreEqual(7, result.Next.Offset);
        }
Ejemplo n.º 25
0
        public void Should_skip_until_the_longest_is_found()
        {
            string subject = "Hello World";

            var p = new StringParser();

            Parser<string, string> parser = from x in p.SkipUntil(p.Longest(p.String("Hello"), p.String("Hello World")))
                                           select x;

            var result = parser.ParseString(subject);

            Assert.IsTrue(result.HasValue);

            Assert.AreEqual("Hello World", result.Value);
        }
Ejemplo n.º 26
0
        public void Should_match_valid_numerics()
        {
            string text = "12345";

            var p = new StringParser();

            Parser<string, int> parser = from n in p.Int32()
                                         select n;

            Result<string, int> result = parser.ParseString(text);

            Assert.IsTrue(result.HasValue);

            Assert.AreEqual(12345, result.Value);
        }
Ejemplo n.º 27
0
        public void Should_capture_sequential_items()
        {
            string subject = "Hello World";

            var p = new StringParser();

            Parser<string, string> parser = from x in p.String("Hello")
                                           from y in p.Whitespace().Then(p.String("World"))
                                           select x + y;

            var result = parser.ParseString(subject);

            Assert.IsTrue(result.HasValue);

            Assert.AreEqual("HelloWorld", result.Value);
        }
Ejemplo n.º 28
0
        public void Should_not_match_if_the_peeked_value_not_matched()
        {
            string subject = "0123456789";

            var p = new StringParser();

            var parser = from ws in p.String("01")
                         from peeked in p.String("789").Peek()
                         from value in p.String("234")
                         select new {peeked, value};

            var result = parser.ParseString(subject);

            Assert.IsFalse(result.HasValue, "Pattern should not matched");

            Assert.AreEqual(2, result.Next.Offset);
        }
Ejemplo n.º 29
0
        public void Should_not_advance_the_input_itself()
        {
            string subject = "0123456789";

            var p = new StringParser();

            var parser = from ws in p.String("01")
                         from peeked in p.String("234").Peek()
                         from value in p.String("234")
                         select new {peeked, value};

            var result = parser.ParseString(subject);

            Assert.IsTrue(result.HasValue);

            Assert.AreEqual(result.Value.peeked, result.Value.value);
        }
        private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting

        internal static int ParseNumSocketConnections(string filePath, string protocolName)
        {
            if (!File.Exists(filePath))
            {
                throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
            }

            // Parse the number of active connections out of /proc/net/sockstat
            string sockstatFile = File.ReadAllText(filePath);
            int indexOfTcp = sockstatFile.IndexOf(protocolName, StringComparison.Ordinal);
            int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1, StringComparison.Ordinal);
            string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp);
            StringParser sockstatParser = new StringParser(tcpLineData, ' ');
            sockstatParser.MoveNextOrFail(); // Skip "<name>:"
            sockstatParser.MoveNextOrFail(); // Skip: "inuse"
            return sockstatParser.ParseNextInt32();
        }
Ejemplo n.º 31
0
 public QuickInsert(string name, string text)
 {
     Name = StringParser.Parse(name);
     Text = text;
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Removes the selected category.
        /// </summary>
        private void btnSubtract_Click(object sender, EventArgs e)
        {
            var cat = (ILabelCategory)lbCategories.SelectedItem;

            if (cat == null)
            {
                return;
            }

            if (lbCategories.Items.Count == 1)
            {
                MessageBox.Show(this, StringParser.Parse("${res:GIS.Common.Dialogs.SymbologyFormsMessageStrings.LabelSetup_OneCategoryNeededErr}"), StringParser.Parse("${res:GIS.Common.Dialogs.SymbologyFormsMessageStrings.LabelSetup_OneCategoryNeededErrCaption}"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _ignoreUpdates = true;
            lbCategories.Items.Remove(cat);
            _layer.Symbology.Categories.Remove(cat);
            if (lbCategories.Items.Count > 0)
            {
                lbCategories.SelectedIndex = 0;
            }
            _ignoreUpdates = false;

            UpdateControls();
        }
Ejemplo n.º 33
0
        public EbnfGrammar(EbnfStyle style)
            : base("ebnf")
        {
            Style = style;
            DefineCommonNonTerminals = true;
            GenerateSpecialSequences();

            // terminals
            var comment         = style.HasFlag(EbnfStyle.BracketComments) ? new GroupParser("(*", "*)") : new GroupParser("/*", "*/");
            var ows             = -(Terminals.WhiteSpace | comment);
            var rws             = +(Terminals.WhiteSpace | comment);
            var hex_character   = ("#x" & +Terminals.HexDigit);
            var character       = (("\\" & Terminals.AnyChar) | hex_character | Terminals.AnyChar.Except("]")).WithName("character");
            var character_range = (character & "-" & character).WithName("character range");
            var character_set   = ("[" & ~(Parser)"^" & +(character_range | character) & "]").WithName("character set");
            var terminal_string = new StringParser {
                QuoteCharacters = new [] { '\"', '\'', '’' }, Name = "terminal string"
            };
            var special_sequence         = ("?" & (+Terminals.AnyChar).Until("?").WithName("name") & "?").WithName("special sequence");
            var meta_identifier_terminal = Terminals.Letter & -(Terminals.LetterOrDigit | '_');
            var integer = new NumberParser().WithName("integer");

            // nonterminals
            var    definition_list   = new RepeatParser(0).WithName("definition list");
            var    single_definition = new RepeatParser(1).WithName("single definition");
            var    term            = new SequenceParser().WithName("term");
            var    primary         = new AlternativeParser().WithName("primary");
            var    exception       = new UnaryParser("exception");
            var    factor          = new SequenceParser().WithName("factor");
            var    meta_identifier = new RepeatParser(1).WithName("meta identifier");
            var    syntax_rule     = new SequenceParser().WithName("syntax rule");
            var    rule_equals     = new AlternativeParser().WithName("equals");
            Parser meta_reference  = meta_identifier;

            Parser grouped_sequence = ("(" & ows & definition_list & ows & ")").WithName("grouped sequence");

            if (style.HasFlag(EbnfStyle.SquareBracketAsOptional))
            {
                primary.Add(("[" & ows & definition_list & ows & "]").WithName("optional sequence"));
            }

            if (!style.HasFlag(EbnfStyle.CardinalityFlags))
            {
                var repeated_sequence = ("{" & ows & definition_list & ows & "}").WithName("repeated sequence");
                primary.Add(repeated_sequence);
            }

            // rules
            meta_identifier.Inner     = meta_identifier_terminal;
            meta_identifier.Separator = +(Terminals.SingleLineWhiteSpace);
            if (!style.HasFlag(EbnfStyle.CommaSeparator))
            {
                // w3c identifiers must be a single word
                meta_identifier.Maximum = 1;
                meta_reference          = meta_reference.NotFollowedBy(ows & rule_equals);
            }
            primary.Add(grouped_sequence, meta_reference, terminal_string, special_sequence);
            if (style.HasFlag(EbnfStyle.CharacterSets) && !style.HasFlag(EbnfStyle.SquareBracketAsOptional))
            {
                // w3c supports character sets
                primary.Add(hex_character.Named("hex character"));
                primary.Add(character_set);
            }
            if (style.HasFlag(EbnfStyle.NumericCardinality))
            {
                factor.Add(~(integer & ows & "*" & ows));
            }
            factor.Add(primary);
            if (style.HasFlag(EbnfStyle.CardinalityFlags))
            {
                // w3c defines cardinality at the end of a factor
                var flags = style.HasFlag(EbnfStyle.SquareBracketAsOptional) ? "*+" : "?*+";
                factor.Add(~(ows & Terminals.Set(flags).WithName("cardinality")));
            }
            term.Add(factor, ~(ows & "-" & ows & exception));
            exception.Inner             = term;
            single_definition.Inner     = term;
            single_definition.Separator = style.HasFlag(EbnfStyle.CommaSeparator) ? (Parser)(ows & "," & ows) : ows;
            definition_list.Inner       = single_definition;
            definition_list.Separator   = ows & "|" & ows;
            rule_equals.Add(style.HasFlag(EbnfStyle.DoubleColonEquals) ? "::=" : "=", ":=");
            syntax_rule.Add(meta_identifier, ows, rule_equals, ows, definition_list);
            if (style.HasFlag(EbnfStyle.SemicolonTerminator))
            {
                syntax_rule.Add(ows, ";");                 // iso rules are terminated by a semicolon
            }
            var syntax_rules = +syntax_rule;

            syntax_rules.Separator = style.HasFlag(EbnfStyle.SemicolonTerminator) ? ows : rws;

            Inner = ows & syntax_rules & ows;

            AttachEvents();
        }
Ejemplo n.º 34
0
		public NewResourceCodeCompletionItem(IResourceFileContent content, IOutputAstVisitor outputVisitor, string preEnteredName)
			: base(StringParser.Parse("${res:Hornung.ResourceToolkit.CodeCompletion.AddNewEntry}"), String.Format(CultureInfo.CurrentCulture, StringParser.Parse("${res:Hornung.ResourceToolkit.CodeCompletion.AddNewDescription}"), content.FileName), outputVisitor)
		{
			this.content = content;
			this.preEnteredName = preEnteredName;
		}
Ejemplo n.º 35
0
        protected IEnumerable <FileProjectItem> AddExistingItems()
        {
            DirectoryNode node = ProjectBrowserPad.Instance.ProjectBrowserControl.SelectedDirectoryNode;

            if (node == null)
            {
                return(null);
            }
            node.Expanding();
            node.Expand();

            List <FileProjectItem> addedItems = new List <FileProjectItem>();

            using (OpenFileDialog fdiag = new OpenFileDialog()) {
                fdiag.AddExtension = true;
                var fileFilters = ProjectService.GetFileFilters();

                fdiag.InitialDirectory = node.Directory;
                fdiag.FilterIndex      = GetFileFilterIndex(node.Project, fileFilters);
                fdiag.Filter           = String.Join("|", fileFilters);
                fdiag.Multiselect      = true;
                fdiag.CheckFileExists  = true;
                fdiag.Title            = StringParser.Parse("${res:ProjectComponent.ContextMenu.AddExistingFiles}");

                if (fdiag.ShowDialog(ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.MainWin32Window) == DialogResult.OK)
                {
                    List <KeyValuePair <string, string> > fileNames = new List <KeyValuePair <string, string> >(fdiag.FileNames.Length);
                    foreach (string fileName in fdiag.FileNames)
                    {
                        fileNames.Add(new KeyValuePair <string, string>(fileName, ""));
                    }
                    bool addedDependentFiles = false;
                    foreach (string fileName in fdiag.FileNames)
                    {
                        foreach (string additionalFile in FindAdditionalFiles(fileName))
                        {
                            if (!fileNames.Exists(delegate(KeyValuePair <string, string> pair) {
                                return(FileUtility.IsEqualFileName(pair.Key, additionalFile));
                            }))
                            {
                                addedDependentFiles = true;
                                fileNames.Add(new KeyValuePair <string, string>(additionalFile, Path.GetFileName(fileName)));
                            }
                        }
                    }



                    string copiedFileName = Path.Combine(node.Directory, Path.GetFileName(fileNames[0].Key));
                    if (!FileUtility.IsEqualFileName(fileNames[0].Key, copiedFileName))
                    {
                        int res = MessageService.ShowCustomDialog(
                            fdiag.Title, "${res:ProjectComponent.ContextMenu.AddExistingFiles.Question}",
                            0, 2,
                            "${res:ProjectComponent.ContextMenu.AddExistingFiles.Copy}",
                            "${res:ProjectComponent.ContextMenu.AddExistingFiles.Link}",
                            "${res:Global.CancelButtonText}");
                        if (res == 1)
                        {
                            // Link
                            foreach (KeyValuePair <string, string> pair in fileNames)
                            {
                                string          fileName        = pair.Key;
                                string          relFileName     = FileUtility.GetRelativePath(node.Project.Directory, fileName);
                                FileNode        fileNode        = new FileNode(fileName, FileNodeStatus.InProject);
                                FileProjectItem fileProjectItem = new FileProjectItem(node.Project, node.Project.GetDefaultItemType(fileName), relFileName);
                                fileProjectItem.SetEvaluatedMetadata("Link", Path.Combine(node.RelativePath, Path.GetFileName(fileName)));
                                fileProjectItem.DependentUpon = pair.Value;
                                addedItems.Add(fileProjectItem);
                                fileNode.ProjectItem = fileProjectItem;
                                fileNode.InsertSorted(node);
                                ProjectService.AddProjectItem(node.Project, fileProjectItem);
                            }
                            node.Project.Save();
                            if (addedDependentFiles)
                            {
                                node.RecreateSubNodes();
                            }
                            return(addedItems.AsReadOnly());
                        }
                        if (res == 2)
                        {
                            // Cancel
                            return(addedItems.AsReadOnly());
                        }
                        // only continue for res==0 (Copy)
                    }
                    bool replaceAll = false;
                    foreach (KeyValuePair <string, string> pair in fileNames)
                    {
                        copiedFileName = Path.Combine(node.Directory, Path.GetFileName(pair.Key));
                        if (!replaceAll && File.Exists(copiedFileName) && !FileUtility.IsEqualFileName(pair.Key, copiedFileName))
                        {
                            ReplaceExistingFile res = ShowReplaceExistingFileDialog(fdiag.Title, Path.GetFileName(pair.Key), true);
                            if (res == ReplaceExistingFile.YesToAll)
                            {
                                replaceAll = true;
                            }
                            else if (res == ReplaceExistingFile.No)
                            {
                                continue;
                            }
                            else if (res == ReplaceExistingFile.Cancel)
                            {
                                break;
                            }
                        }
                        FileProjectItem item = CopyFile(pair.Key, node, true);
                        if (item != null)
                        {
                            addedItems.Add(item);
                            item.DependentUpon = pair.Value;
                        }
                    }
                    node.Project.Save();
                    if (addedDependentFiles)
                    {
                        node.RecreateSubNodes();
                    }
                }
            }

            return(addedItems.AsReadOnly());
        }
Ejemplo n.º 36
0
        public override bool ExecuteAction(ActionProgramRun ap)
        {
            string res;

            if (ap.Functions.ExpandString(UserData, out res) != Functions.ExpandResult.Failed)
            {
                HistoryList  hl     = (ap.ActionController as ActionController).HistoryList;
                StringParser sp     = new StringParser(res);
                string       prefix = "EC_";

                string cmdname = sp.NextWordLCInvariant(" ");

                if (cmdname != null && cmdname.Equals("prefix"))
                {
                    prefix = sp.NextWord();

                    if (prefix == null)
                    {
                        ap.ReportError("Missing name after Prefix in Event");
                        return(true);
                    }

                    cmdname = sp.NextWordLCInvariant(" ");
                }

                int jidindex = -1;

                if (cmdname != null && (cmdname.Equals("from") || cmdname.Equals("thpos")))
                {
                    long?jid;

                    if (cmdname.Equals("thpos"))
                    {
                        HistoryEntry he = (ap.ActionController as ActionController).DiscoveryForm.PrimaryCursor.GetCurrentHistoryEntry;

                        if (he == null)
                        {
                            ReportEntry(ap, null, 0, prefix);
                            return(true);
                        }

                        jid = he.Journalid;
                    }
                    else
                    {
                        jid = sp.NextWord().InvariantParseLongNull();
                        if (!jid.HasValue)
                        {
                            ap.ReportError("Non integer JID after FROM in Event");
                            return(true);
                        }
                    }

                    jidindex = hl.GetIndex(jid.Value);

                    if (jidindex == -1)
                    {
                        ReportEntry(ap, null, 0, prefix);
                        return(true);
                    }

                    cmdname = sp.NextWordLCInvariant(" ");
                }

                if (cmdname == null)
                {
                    if (jidindex != -1)
                    {
                        ReportEntry(ap, hl.EntryOrder(), jidindex, prefix);
                    }
                    else
                    {
                        ap.ReportError("No commands in Event");
                    }

                    return(true);
                }

                bool fwd  = cmdname.Equals("forward") || cmdname.Equals("first");
                bool back = cmdname.Equals("backward") || cmdname.Equals("last");

                if (fwd || back)
                {
                    List <string> eventnames = sp.NextOptionallyBracketedList();                                                  // single entry, list of events

                    bool not = eventnames.Count == 1 && eventnames[0].Equals("NOT", StringComparison.InvariantCultureIgnoreCase); // if it goes NOT

                    if (not)
                    {
                        eventnames = sp.NextOptionallyBracketedList();     // then get another list
                    }
                    // is it "WHERE"
                    bool whereasfirst = eventnames.Count == 1 && eventnames[0].Equals("WHERE", StringComparison.InvariantCultureIgnoreCase);

                    ConditionLists cond = new ConditionLists();
                    string         nextword;

                    // if WHERE cond, or eventname WHERE cond
                    if (whereasfirst || ((nextword = sp.NextWord()) != null && nextword.Equals("WHERE", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        if (whereasfirst)       // clear out event names if it was WHERE cond..
                        {
                            eventnames.Clear();
                        }

                        string resc = cond.Read(sp.LineLeft);       // rest of it is the condition..
                        if (resc != null)
                        {
                            ap.ReportError(resc + " in Where of Event");
                            return(true);
                        }
                    }

                    List <HistoryEntry> hltest;

                    if (jidindex == -1)           // if no JID given..
                    {
                        hltest = hl.EntryOrder(); // the whole list
                    }
                    else if (fwd)
                    {
                        hltest = hl.EntryOrder().GetRange(jidindex + 1, hl.Count - (jidindex + 1));       // cut down list, excluding this entry
                    }
                    else
                    {
                        hltest = hl.EntryOrder().GetRange(0, jidindex);
                    }

                    if (eventnames.Count > 0)       // screen out event names
                    {
                        hltest = (from h in hltest where eventnames.Contains(h.journalEntry.EventTypeStr, StringComparer.OrdinalIgnoreCase) == !not select h).ToList();
                    }

                    if (cond.Count > 0)                                                                            // if we have filters, apply, filter out, true only stays
                    {
                        hltest = UserControls.HistoryFilterHelpers.CheckFilterTrue(hltest, cond, new Variables()); // apply filter..
                    }
                    if (fwd)
                    {
                        ReportEntry(ap, hltest, 0, prefix);
                    }
                    else
                    {
                        ReportEntry(ap, hltest, hltest.Count - 1, prefix);
                    }

                    return(true);
                }
                else
                {
                    if (jidindex == -1)
                    {
                        ap.ReportError("Valid JID must be given for command " + cmdname + " in Event");
                    }
                    else
                    {
                        HistoryEntry he = hl.EntryOrder()[jidindex];
                        ap[prefix + "JID"] = jidindex.ToStringInvariant();

                        if (cmdname.Equals("action"))
                        {
                            var ctrl  = (ap.ActionController as ActionController);
                            int count = ctrl.ActionRunOnEntry(he, Actions.ActionEventEDList.EventCmd(he), now: true);
                            ap[prefix + "Count"] = count.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (cmdname.Equals("edsm"))
                        {
                            EliteDangerousCore.EDSM.EDSMClass edsm = new EliteDangerousCore.EDSM.EDSMClass();
                            string url = edsm.GetUrlCheckSystemExists(he.System.Name);

                            ap[prefix + "URL"] = url;

                            if (url.Length > 0)         // may pass back empty string if not known, this solves another exception
                            {
                                BaseUtils.BrowserInfo.LaunchBrowser(url);
                            }
                        }
                        else if (cmdname.Equals("ross"))
                        {
                            ap.ReportError("Not implemented");
                        }
                        else if (cmdname.Equals("eddb"))
                        {
                            string url = Properties.Resources.URLEDDBSystemName + System.Web.HttpUtility.UrlEncode(he.System.Name);
                            BaseUtils.BrowserInfo.LaunchBrowser(url);
                            ap[prefix + "URL"] = url;
                        }
                        else if (cmdname.Equals("info"))
                        {
                            ActionVars.SystemVarsFurtherInfo(ap, hl, he.System, prefix);
                            ActionVars.ShipModuleInformation(ap, he.ShipInformation, prefix);       // protected against SI being null
                        }
                        else if (cmdname.Equals("missions"))
                        {
                            ActionVars.MissionInformation(ap, hl.MissionListAccumulator.GetMissionList(he.MissionList), prefix);
                        }
                        else if (cmdname.Equals("setstartmarker"))
                        {
                            he.journalEntry.SetStartFlag();
                        }
                        else if (cmdname.Equals("setstopmarker"))
                        {
                            he.journalEntry.SetEndFlag();
                        }
                        else if (cmdname.Equals("clearstartstopmarker"))
                        {
                            he.journalEntry.ClearStartEndFlag();
                        }
                        else if (cmdname.Equals("note"))
                        {
                            string note = sp.NextQuotedWord();
                            if (note != null && sp.IsEOL)
                            {
                                he.SetJournalSystemNoteText(note, true, EDCommander.Current.SyncToEdsm);
                                (ap.ActionController as ActionController).DiscoveryForm.NoteChanged(this, he, true);
                            }
                            else
                            {
                                ap.ReportError("Missing note text or unquoted text in Event NOTE");
                            }
                        }
                        else
                        {
                            ap.ReportError("Unknown command " + cmdname + " in Event");
                        }
                    }
                }
            }
            else
            {
                ap.ReportError(res);
            }

            return(true);
        }
Ejemplo n.º 37
0
 public void ShowNoRootDirectoryFoundMessage()
 {
     ShowErrorMessage(StringParser.Parse("${res:ICSharpCode.WixBinding.PackageFilesView.NoRootDirectoryFoundMessage}"));
 }
 public StringParserTests()
 {
     _service = new StringParser();
 }
Ejemplo n.º 39
0
 public Category(string name, int sortOrder) : base(StringParser.Parse(name))
 {
     this.Name      = StringParser.Parse(name);
     ImageIndex     = 1;
     this.sortOrder = sortOrder;
 }
Ejemplo n.º 40
0
        protected void MyInitializeComponents()
        {
            InitializeComponent();

            foreach (Control ctl in Controls.GetRecursive())
            {
                ctl.Text = StringParser.Parse(ctl.Text);
            }
            this.Text = StringParser.Parse(this.Text);

            ImageList imglist = new ImageList();

            imglist.ColorDepth = ColorDepth.Depth32Bit;
            imglist.Images.Add(IconService.GetBitmap("Icons.16x16.OpenFolderBitmap"));
            imglist.Images.Add(IconService.GetBitmap("Icons.16x16.ClosedFolderBitmap"));
            categoryTreeView.ImageList = imglist;

            templateListView.SelectedIndexChanged += new EventHandler(SelectedIndexChange);
            categoryTreeView.AfterSelect          += new TreeViewEventHandler(CategoryChange);
            categoryTreeView.BeforeSelect         += new TreeViewCancelEventHandler(OnBeforeExpand);
            categoryTreeView.BeforeExpand         += new TreeViewCancelEventHandler(OnBeforeExpand);
            categoryTreeView.BeforeCollapse       += new TreeViewCancelEventHandler(OnBeforeCollapse);
            solutionNameTextBox.TextChanged       += new EventHandler(PathChanged);
            nameTextBox.TextChanged     += new EventHandler(PathChanged);
            locationTextBox.TextChanged += new EventHandler(PathChanged);

            if (createNewSolution)
            {
                createDirectoryForSolutionCheckBox.Checked         = CreateDirectoryForSolution;
                createDirectoryForSolutionCheckBox.CheckedChanged += delegate {
                    CreateDirectoryForSolution = createDirectoryForSolutionCheckBox.Checked;
                };
            }
            else
            {
                solutionNameTextBox.Visible = false;
                solutionNameLabel.Visible   = false;
                createDirectoryForSolutionCheckBox.Visible = false;
                bottomPanel.Height -= solutionNameTextBox.Height;

                createDirectoryForSolutionCheckBox.Checked = false;
            }

            largeIconsRadioButton.Checked         = PropertyService.Get("Dialogs.NewProjectDialog.LargeImages", true);
            largeIconsRadioButton.CheckedChanged += new EventHandler(IconSizeChange);
            largeIconsRadioButton.Image           = IconService.GetBitmap("Icons.16x16.LargeIconsIcon");

            smallIconsRadioButton.Checked         = !PropertyService.Get("Dialogs.NewProjectDialog.LargeImages", true);
            smallIconsRadioButton.CheckedChanged += new EventHandler(IconSizeChange);
            smallIconsRadioButton.Image           = IconService.GetBitmap("Icons.16x16.SmallIconsIcon");

            openButton.Click   += new EventHandler(OpenEvent);
            browseButton.Click += new EventHandler(BrowseDirectories);
            createDirectoryForSolutionCheckBox.CheckedChanged += new EventHandler(PathChanged);

            ToolTip tooltip = new ToolTip();

            tooltip.SetToolTip(largeIconsRadioButton, StringParser.Parse("${res:Global.LargeIconToolTip}"));
            tooltip.SetToolTip(smallIconsRadioButton, StringParser.Parse("${res:Global.SmallIconToolTip}"));
            tooltip.Active = true;

            IconSizeChange(this, EventArgs.Empty);
        }
Ejemplo n.º 41
0
 protected virtual void InitializeTemplates()
 {
     foreach (ProjectTemplate template in ProjectTemplate.ProjectTemplates)
     {
         if (template.ProjectDescriptor == null && createNewSolution == false)
         {
             // Do not show solution template when added a new project to existing solution
             continue;
         }
         TemplateItem titem = new TemplateItem(template);
         if (titem.Template.Icon != null)
         {
             icons[titem.Template.Icon] = 0;                     // "create template icon"
         }
         if (template.NewProjectDialogVisible == true)
         {
             Category cat = GetCategory(StringParser.Parse(titem.Template.Category), StringParser.Parse(titem.Template.Subcategory));
             cat.Templates.Add(titem);
             if (cat.Templates.Count == 1)
             {
                 titem.Selected = true;
             }
         }
         alltemplates.Add(titem);
     }
 }
 private void InitBlock()
 {
     stringParser     = new StringParser();
     remarkNodeParser = new RemarkNodeParser();
     nextParsedNode   = new NodeList();
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Löst das <see cref="E:System.Windows.Forms.ListBox.DrawItem" />-Ereignis aus.
        /// </summary>
        /// <param name="e">Ein <see cref="T:System.Windows.Forms.DrawItemEventArgs" />, das die Ereignisdaten enthält.</param>
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            //base.OnDrawItem(e);

            debug("TraceGuiListBox.OnDrawItem()");

            const TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter;

            if (e.Index >= 0)
            {
                TraceGuiListItem item = (TraceGuiListItem)Items[e.Index];

                string codeLineText = item.CodeLine;
                string dataText     = "";

                string arrayText            = StringParser.getInstance().byteArray2HexString(item.DataArray, ' ');
                string wordDataText         = "Data: ";
                string wordByteWordLongText = "";

                switch (item.Type)
                {
                default:
                    wordDataText = "";
                    break;

                case TraceType.BYTE:
                    wordByteWordLongText = "Byte: ";
                    dataText             = string.Format("{0}", item.DataByte);
                    break;

                case TraceType.WORD:
                    wordByteWordLongText = "Word: ";
                    dataText             = string.Format("{0}", item.DataWord);
                    break;

                case TraceType.LONG:
                    wordByteWordLongText = "Long: ";
                    dataText             = string.Format("{0}", item.DataLong);
                    break;

                case TraceType.ARRAY:
                    break;
                }

                var codeLineRect = e.Bounds;
                codeLineRect.Height = 15;
                codeLineRect.Width  = this.Size.Width;

                var wordDataRect = e.Bounds;
                wordDataRect.Y     += codeLineRect.Height;
                wordDataRect.Height = 15;
                wordDataRect.Width  = 30;

                var wordByteWordLongRect = e.Bounds;
                wordByteWordLongRect.Y     += codeLineRect.Height + wordDataRect.Height;
                wordByteWordLongRect.X      = wordDataRect.X;
                wordByteWordLongRect.Height = wordDataRect.Height;
                wordByteWordLongRect.Width  = 30;

                var arrayDataRect = e.Bounds;
                arrayDataRect.Y     += codeLineRect.Height;
                arrayDataRect.X     += wordDataRect.Width;
                arrayDataRect.Height = 15;
                arrayDataRect.Width  = this.Width > wordDataRect.Width ? this.Width - wordDataRect.Width : 100;

                var valueDataRect = e.Bounds;
                valueDataRect.Y     += codeLineRect.Height + arrayDataRect.Height;
                valueDataRect.X     += wordByteWordLongRect.Width;
                valueDataRect.Height = 15;
                valueDataRect.Width  = this.Width > wordByteWordLongRect.Width ? this.Width - wordByteWordLongRect.Width : 100;


                //fileNameRect.X += codeLineRect.Width;
                //fileNameRect.Width = e.Bounds.Width - codeLineRect.Width;
                //fileNameRect.Height = codeLineRect.Height;

                var codeLineFont = new Font("Lucida Console", e.Font.Size + 1, FontStyle.Regular, e.Font.Unit);
                var wordFont     = new Font(e.Font.Name, e.Font.Size - 2, FontStyle.Regular, e.Font.Unit);
                var dataFont     = new Font(e.Font.Name, e.Font.Size, FontStyle.Regular, e.Font.Unit);

                Color backgroundColor = e.BackColor;

                e = new DrawItemEventArgs(e.Graphics,
                                          e.Font,
                                          e.Bounds,
                                          e.Index,
                                          e.State,
                                          e.ForeColor,
                                          backgroundColor);//Choose the color

                e.DrawBackground();
                TextRenderer.DrawText(e.Graphics, codeLineText, codeLineFont, codeLineRect, e.ForeColor, flags);
                TextRenderer.DrawText(e.Graphics, wordDataText, wordFont, wordDataRect, Color.DeepSkyBlue, flags);
                TextRenderer.DrawText(e.Graphics, wordByteWordLongText, wordFont, wordByteWordLongRect, Color.DeepSkyBlue, flags);
                TextRenderer.DrawText(e.Graphics, arrayText, dataFont, arrayDataRect, Color.DeepSkyBlue, flags);
                TextRenderer.DrawText(e.Graphics, dataText, dataFont, valueDataRect, Color.DeepSkyBlue, flags);
                e.DrawFocusRectangle();



                /*
                 * string dateText = string.Format("{0}:{1}:{2}:{3}", item.Timestamp.Hour, item.Timestamp.Minute, item.Timestamp.Second, item.Timestamp.Millisecond);
                 * string itemText = string.Format("{0} : {1}", item.CommandName, item.AnswerStatus);
                 * string hexStringText = string.Format("Command: \t {0}\nAsnwer: \t {1}", item.CommandHexString, item.AnswerHexString);
                 *
                 * var timestampRect = e.Bounds;
                 * timestampRect.Height = 15;
                 * timestampRect.Width = 75;
                 *
                 * var itemRect = e.Bounds;
                 * itemRect.X += timestampRect.Width;
                 * itemRect.Width = e.Bounds.Width - timestampRect.Width;
                 * itemRect.Height = timestampRect.Height;
                 *
                 * var hexStringRect = e.Bounds;
                 * hexStringRect.X = itemRect.X;
                 * hexStringRect.Y += itemRect.Height;
                 * hexStringRect.Width = itemRect.Width;
                 * hexStringRect.Height = e.Bounds.Height - itemRect.Height;
                 *
                 * var itemFont = new Font(e.Font.Name, e.Font.Size + 1, FontStyle.Bold, e.Font.Unit);
                 * var hexStringFont = new Font(e.Font.Name, e.Font.Size - 1, FontStyle.Regular, e.Font.Unit);
                 *
                 * Color backgroundColor = e.BackColor;
                 *
                 * switch (item.SuccessState)
                 * {
                 *  default:
                 *  case CommandAnswerListElement.SUCCESS_STATE.SUCCESS: backgroundColor = Color.LightGreen; break;
                 *  case CommandAnswerListElement.SUCCESS_STATE.WARNING: backgroundColor = Color.Yellow; break;
                 *  case CommandAnswerListElement.SUCCESS_STATE.FAILURE: backgroundColor = Color.LightCoral; break;
                 * }
                 *
                 * e = new DrawItemEventArgs(e.Graphics,
                 *                e.Font,
                 *                e.Bounds,
                 *                e.Index,
                 *                e.State,
                 *                e.ForeColor,
                 *                backgroundColor);//Choose the color
                 *
                 * e.DrawBackground();
                 * TextRenderer.DrawText(e.Graphics, dateText, e.Font, timestampRect, e.ForeColor, flags);
                 * TextRenderer.DrawText(e.Graphics, itemText, itemFont, itemRect, e.ForeColor, flags);
                 * TextRenderer.DrawText(e.Graphics, hexStringText, hexStringFont, hexStringRect, e.ForeColor, flags);
                 * e.DrawFocusRectangle();
                 */
            }
        }
 void InitStrings()
 {
     fileNameColumnHeader.Text = StringParser.Parse("${res:CompilerResultView.FileText}");
 }
Ejemplo n.º 45
0
        public void FullIntegration()
        {
            File.WriteAllText(Constants.FILE_NAME, null);

            var updateParser  = new UpdateParser();
            var stringParser  = new StringParser();
            var reader        = new Reader();
            var writer        = new Writer(reader);
            var lockManager   = new LockManager(writer, reader);
            var schemaFetcher = new SchemaFetcher(reader);

            var interpreter = new Interpreter(
                new SelectParser(),
                new InsertParser(schemaFetcher),
                updateParser,
                schemaFetcher,
                new GeneralParser(),
                new CreateParser(),
                stringParser,
                lockManager,
                reader,
                new PredicateParser());

            string identityTable = @"create table Skateboards (
                                            SkateBoardId int Identity,
                                            Name varchar(100),
                                            Price decimal
                                       )";

            Random rd = new Random();

            interpreter.ProcessStatement(identityTable);

            var emptySkateboardRows = (List <List <IComparable> >)interpreter.ProcessStatement("select * from skateboards where Name = 'bob'");

            for (int i = 0; i < 500; i++)
            {
                string insertIdentity = "insert into Skateboards values ('HotSauce', " + rd.Next() + ")";

                interpreter.ProcessStatement(insertIdentity);
            }



            string readAllSkateboards = @"select * from Skateboards";


            var skateboardRows = (List <List <IComparable> >)interpreter.ProcessStatement(readAllSkateboards);

            string readSkateboardByName = @"select * from Skateboards where name = 'HotSauce'";


            var readSkateboardByNameRows = (List <List <IComparable> >)interpreter.ProcessStatement(readSkateboardByName);


            string createHousesTable = @"create table houses (
                                            Address varchar(100),
                                            Price decimal,
                                            SqFeet bigint,
                                            IsListed bool,
                                            NumBedrooms int,
                                       )";

            interpreter.ProcessStatement(createHousesTable);



            for (int i = 0; i < 200; i++)
            {
                string insertStatement = @"insert into houses values ('" + CreateString(10) + "'," +
                                         rd.Next().ToString() + "," + rd.Next().ToString() + "," + "true," + rd.Next().ToString() + ")";

                interpreter.ProcessStatement(insertStatement);
            }

            string insertStatement2 = @"insert into houses values ('" + "450 Adams St" + "'," +
                                      "320000" + "," + "2300" + "," + "false," + "3" + ")";

            interpreter.ProcessStatement(insertStatement2);


            string createToolsTable = @"create table tools (
                                            Name varchar(30),
                                            Price decimal,
                                            NumInStock bigint,
                                            IsWooden bool,
                                            Manufacturer varchar(50)
                                       )";

            interpreter.ProcessStatement(createToolsTable);


            for (int i = 0; i < 500; i++)
            {
                string insertStatement = @"insert into tools values ('" + CreateString(10) + "'," +
                                         rd.Next().ToString() + "," + rd.Next().ToString() + "," + "true," + CreateString(10) + ")";

                interpreter.ProcessStatement(insertStatement);
            }


            string insertStatement3 = @"insert into tools values ('" + "hammer" + "'," +
                                      "23.99" + "," + "67" + "," + "false," + "'craftsman'" + ")";

            interpreter.ProcessStatement(insertStatement3);

            for (int i = 0; i < 200; i++)
            {
                string insertStatement = @"insert into houses values ('" + CreateString(10) + "'," +
                                         rd.Next().ToString() + "," + rd.Next().ToString() + "," + "true," + rd.Next().ToString() + ")";

                interpreter.ProcessStatement(insertStatement);
            }


            string insertStatement6 = @"insert into houses values ('" + "999 Adams St" + "'," +
                                      "269000" + "," + "2300" + "," + "false," + "3" + ")";

            interpreter.ProcessStatement(insertStatement6);

            string insertStatement7 = @"insert into houses values ('" + "999 Adams St" + "'," +
                                      "270000" + "," + "2300" + "," + "false," + "3" + ")";

            interpreter.ProcessStatement(insertStatement7);

            string insertStatement4 = @"insert into tools values ('" + "drill" + "'," +
                                      "45.99" + "," + "90" + "," + "false," + "'dewalt'" + ")";

            interpreter.ProcessStatement(insertStatement4);


            for (int i = 0; i < 250; i++)
            {
                string insertStatement = @"insert into tools values ('" + CreateString(10) + "'," +
                                         rd.Next().ToString() + "," + rd.Next().ToString() + "," + "true," + CreateString(10) + ")";

                interpreter.ProcessStatement(insertStatement);
            }

            string selectInOperator = "select * from tools where name in (select name from tools)";

            var selectInOperatorRows = (List <List <IComparable> >)interpreter.ProcessStatement(selectInOperator);

            //houses count should be: 1401

            //tools count should be: 752

            string readAllHouses = @"select * from houses";


            var rows = (List <List <IComparable> >)interpreter.ProcessStatement(readAllHouses);

            bool rowCountCorrect    = rows.Count() == 403;
            bool columnCountCorrect = rows[0].Count() == 5;


            string readAllTools = @"select price, numInstock from tools";


            var tools = (List <List <IComparable> >)interpreter.ProcessStatement(readAllTools);

            bool rowCountCorrect2    = tools.Count() == 752;
            bool columnCountCorrect2 = tools[0].Count() == 2;


            string querySearchHousesByName = @"select * from houses where address = '450 Adams St'";


            var result = (List <List <IComparable> >)interpreter.ProcessStatement(querySearchHousesByName);

            bool resultCountCorrect = result.Count() == 1;

            string querySearchHousesByNameAndPrice = @"select * 
                                                    from houses 
                                                     where address = '450 Adams St'
                                                      AND price > 315000";


            var result2 = (List <List <IComparable> >)interpreter.ProcessStatement(querySearchHousesByNameAndPrice);

            bool resultCountCorrect2 = result2.Count() == 1;

            string subQueryTools = @"select * from tools 
                                        where name = (select name from tools where price = 45.99 )";

            var toolsSubQueryResult = (List <List <IComparable> >)interpreter.ProcessStatement(subQueryTools);


            var toolSubQueryCompare = ((string)toolsSubQueryResult[0][0]).Trim() == "drill" && (decimal)toolsSubQueryResult[0][1]
                                      == 45.99m && (bool)toolsSubQueryResult[0][3] == false;


            string toolsInClause = @"select * from tools 
                                        where name IN ('drill', 'hammer' )";

            var toolsInClauseResults = (List <List <IComparable> >)interpreter.ProcessStatement(toolsInClause);

            var compare = toolsInClauseResults.Count() == 2;


            string selectWithPredicatesAndOrderBy = @"select * from houses
                                                      where address != '98765 ABC str'
                                                       AND Price > 269000
                                                        order by price";

            var predicatesAndOrderResults = (List <List <IComparable> >)interpreter.ProcessStatement(selectWithPredicatesAndOrderBy);

            bool colCountCorrect = ((int)predicatesAndOrderResults[0].Count()) == 5;

            bool orderIsCorrect = ((decimal)predicatesAndOrderResults[1][1]) > ((decimal)predicatesAndOrderResults[0][1]) &&
                                  ((decimal)predicatesAndOrderResults[15][1]) > ((decimal)predicatesAndOrderResults[6][1]) &&
                                  ((decimal)predicatesAndOrderResults[90][1]) > ((decimal)predicatesAndOrderResults[89][1]) &&
                                  ((decimal)predicatesAndOrderResults[100][1]) > ((decimal)predicatesAndOrderResults[98][1]) &&
                                  ((decimal)predicatesAndOrderResults[120][1]) > ((decimal)predicatesAndOrderResults[118][1]) &&
                                  ((decimal)predicatesAndOrderResults[150][1]) > ((decimal)predicatesAndOrderResults[145][1]);


            //*******group by tests

            string createTable = @"create table houses2( Price int, NumBedRooms int, NumBathrooms int )";

            interpreter.ProcessStatement(createTable);

            string insert1 = "insert into houses2 values (300000, 3, 2)";

            interpreter.ProcessStatement(insert1);

            string insert2 = "insert into houses2 values (300000, 4, 3)";

            interpreter.ProcessStatement(insert2);

            string insert3 = "insert into houses2 values (300000, 5, 4)";

            interpreter.ProcessStatement(insert3);

            string insert4 = "insert into houses2 values (330000, 6, 5)";

            interpreter.ProcessStatement(insert4);

            string insert5 = "insert into houses2 values (330000, 7, 6)";

            interpreter.ProcessStatement(insert5);



            string select = @"select Price, Max(NumBedRooms), Min(NumBathrooms)
                             from houses2
                                GROUP BY PRICE";

            var groupedRows = (List <List <IComparable> >)interpreter.ProcessStatement(select);

            var groupedCountCorrect = groupedRows.Count() == 2;

            var groupedValuesCorrect = (int)groupedRows[0][0] == 300000 &&
                                       (int)groupedRows[0][1] == 5 &&
                                       (int)groupedRows[0][2] == 2 &&
                                       (int)groupedRows[1][0] == 330000 &&
                                       (int)groupedRows[1][1] == 7 &&
                                       (int)groupedRows[1][2] == 5;


            //parallel tests
            interpreter.ProcessStatement(@"create table house4 (
                                                    NumBedrooms int,
                                                    NumBath int,
                                                    Price decimal,
                                                    IsListed bool,
                                                    Address varchar(50)
                                      )");


            var allHouses = new List <List <List <IComparable> > >();

            interpreter.ProcessStatement("insert into house4 values (5,3,295000,true,'800 Wormwood Dr')");

            Parallel.For(0, 200, i =>
            {
                interpreter.ProcessStatement("insert into house4 values (5,3,295000,true,'800 Wormwood Dr')");

                var houses = (List <List <IComparable> >)interpreter.ProcessStatement("select * FROM house4");

                allHouses.Add(houses);
            });

            var housesOut = (List <List <IComparable> >)interpreter.ProcessStatement("select * FROM house4");

            allHouses.Add(housesOut);

            var allHousesCountCorrect = allHouses.Count() == 201;

            var insertCountCorrect = allHouses[200].Count() == 201;

            //UPDATE TESTS

            string createTable9 = @"create table houses9( Price int, NumBedRooms int, NumBathrooms int )";

            interpreter.ProcessStatement(createTable9);

            string insert19 = "insert into houses9 values (300000, 3, 2)";

            interpreter.ProcessStatement(insert19);

            string insert29 = "insert into houses9 values (310000, 4, 3)";

            interpreter.ProcessStatement(insert29);

            string insert39 = "insert into houses9 values (300000, 5, 4)";

            interpreter.ProcessStatement(insert39);

            string insert49 = "insert into houses9 values (330000, 6, 5)";

            interpreter.ProcessStatement(insert49);

            string insert59 = "insert into houses9 values (330000, 7, 6)";

            interpreter.ProcessStatement(insert59);

            string updateStatement = @"update houses9 Set Price = 440000, NumBathrooms = 90 where Numbedrooms = 7";

            interpreter.ProcessStatement(updateStatement);

            var updatedRows = (List <List <IComparable> >)interpreter.ProcessStatement("select * from houses9");

            bool updatedOneCorrect = (int)updatedRows[4][0] == 440000;

            bool updatedTwoCorrect = (int)updatedRows[4][2] == 90;

            bool updatedRowsCountCorrect = updatedRows.Count() == 5;

            string createTable10 = @"create table houses10( Price int, NumBedRooms int, NumBathrooms int, DateListed DateTime)";

            interpreter.ProcessStatement(createTable10);

            string insert60 = "insert into houses10 values (300000, 5, 4, '10/15/2021 9:03:37 pm')";

            interpreter.ProcessStatement(insert60);

            var housesWithDateTime = (List <List <IComparable> >)interpreter.ProcessStatement("select * from houses10 where DateListed > '10/15/2021 9:00:00 pm' ");

            bool housesWithDateTimeCount = housesWithDateTime.Count == 1;

            Assert.AreEqual(true, rowCountCorrect);
            Assert.AreEqual(true, columnCountCorrect);
            Assert.AreEqual(true, rowCountCorrect2);
            Assert.AreEqual(true, columnCountCorrect2);
            Assert.AreEqual(true, resultCountCorrect2);
            Assert.AreEqual(true, resultCountCorrect);
            Assert.AreEqual(true, toolSubQueryCompare);
            Assert.AreEqual(true, compare);
            Assert.AreEqual(true, groupedCountCorrect);
            Assert.AreEqual(true, groupedValuesCorrect);
            Assert.AreEqual(true, colCountCorrect);
            Assert.AreEqual(true, orderIsCorrect);
            Assert.AreEqual(true, insertCountCorrect);
            Assert.AreEqual(true, updatedOneCorrect);
            Assert.AreEqual(true, updatedTwoCorrect);
            Assert.AreEqual(true, updatedRowsCountCorrect);
            Assert.AreEqual(true, housesWithDateTimeCount);
        }
Ejemplo n.º 46
0
        public override bool ExecuteAction(ActionProgramRun ap)
        {
            string res;

            if (ap.functions.ExpandString(UserData, out res) != Functions.ExpandResult.Failed)
            {
                StringParser p = new StringParser(res);

                string cmd;
                while ((cmd = p.NextWordLCInvariant(" ")) != null)
                {
                    if (cmd.Equals("dumpvars"))
                    {
                        string rest = p.NextQuotedWord();

                        if (rest != null && rest.Length > 0)
                        {
                            Variables filtered = ap.variables.FilterVars(rest);
                            foreach (string key in filtered.NameEnumuerable)
                            {
                                ap.actioncontroller.LogLine(key + "=" + filtered[key]);
                            }
                        }
                        else
                        {
                            ap.ReportError("Missing variable wildcard after Pragma DumpVars");
                            return(true);
                        }
                    }
                    else if (cmd.Equals("log"))
                    {
                        string rest = p.NextQuotedWord(replaceescape: true);

                        if (rest != null)
                        {
                            ap.actioncontroller.LogLine(rest);
                        }
                        else
                        {
                            ap.ReportError("Missing string after Pragma Log");
                            return(true);
                        }
                    }
                    else if (cmd.Equals("debug"))
                    {
                        string rest = p.NextQuotedWord(replaceescape: true);

                        if (rest != null)
                        {
#if DEBUG
                            ap.actioncontroller.LogLine(rest);
#endif
                        }
                        else
                        {
                            ap.ReportError("Missing string after Debug");
                        }
                        return(true);
                    }
                    else if (cmd.Equals("ignoreerrors"))
                    {
                        ap.SetContinueOnErrors(true);
                    }
                    else if (cmd.Equals("allowerrors"))
                    {
                        ap.SetContinueOnErrors(false);
                    }
                    else if (cmd.Equals("disableasync"))
                    {
                        ap.actioncontroller.AsyncMode = false;
                    }
                    else if (cmd.Equals("enableasync"))
                    {
                        ap.actioncontroller.AsyncMode = false;
                    }
                    else if (cmd.Equals("enabletrace"))
                    {
                        string file = p.NextQuotedWord();
                        ap.actioncontroller.DebugTrace(file == null, file);
                    }
                    else if (cmd.Equals("disabletrace"))
                    {
                        ap.actioncontroller.DebugTrace(false);
                    }
                    else if (!ap.actioncontroller.Pragma(cmd))
                    {
                        ap.ReportError("Unknown pragma");
                    }
                }
            }
            else
            {
                ap.ReportError(res);
            }

            return(true);
        }
Ejemplo n.º 47
0
        void SetOptions()
        {
            Get <ComboBox>("find").Text = SearchOptions.FindPattern;
            Get <ComboBox>("find").Items.Clear();

            Get <ComboBox>("find").Text = SearchOptions.FindPattern;
            Get <ComboBox>("find").Items.Clear();
            foreach (string findPattern in SearchOptions.FindPatterns)
            {
                Get <ComboBox>("find").Items.Add(findPattern);
            }

            if (searchAndReplaceMode == SearchAndReplaceMode.Replace)
            {
                Get <ComboBox>("replace").Text = SearchOptions.ReplacePattern;
                Get <ComboBox>("replace").Items.Clear();
                foreach (string replacePattern in SearchOptions.ReplacePatterns)
                {
                    Get <ComboBox>("replace").Items.Add(replacePattern);
                }
            }

            Get <ComboBox>("lookIn").Text = SearchOptions.LookIn;
            foreach (string lookInText in typeof(SearchTarget).GetFields().SelectMany(f => f.GetCustomAttributes(false).OfType <DescriptionAttribute>()).Select(da => da.Description))
            {
                Get <ComboBox>("lookIn").Items.Add(StringParser.Parse(lookInText));
            }
            Get <ComboBox>("lookIn").Items.Add(SearchOptions.LookIn);
            Get <ComboBox>("lookIn").SelectedIndexChanged += new EventHandler(LookInSelectedIndexChanged);

            if (IsMultipleLineSelection(SearchManager.GetActiveTextEditor()))
            {
                SearchTarget = SearchTarget.CurrentSelection;
            }
            else
            {
                if (SearchOptions.SearchTarget == SearchTarget.CurrentSelection)
                {
                    SearchOptions.SearchTarget = SearchTarget.CurrentDocument;
                }
                SearchTarget = SearchOptions.SearchTarget;
            }

            Get <ComboBox>("fileTypes").Text           = SearchOptions.LookInFiletypes;
            Get <CheckBox>("matchCase").Checked        = SearchOptions.MatchCase;
            Get <CheckBox>("matchWholeWord").Checked   = SearchOptions.MatchWholeWord;
            Get <CheckBox>("includeSubFolder").Checked = SearchOptions.IncludeSubdirectories;

            Get <ComboBox>("use").Items.Clear();
            Get <ComboBox>("use").Items.Add(StringParser.Parse("${res:Dialog.NewProject.SearchReplace.SearchStrategy.Standard}"));
            Get <ComboBox>("use").Items.Add(StringParser.Parse("${res:Dialog.NewProject.SearchReplace.SearchStrategy.RegexSearch}"));
            Get <ComboBox>("use").Items.Add(StringParser.Parse("${res:Dialog.NewProject.SearchReplace.SearchStrategy.WildcardSearch}"));
            switch (SearchOptions.SearchMode)
            {
            case SearchMode.RegEx:
                Get <ComboBox>("use").SelectedIndex = 1;
                break;

            case SearchMode.Wildcard:
                Get <ComboBox>("use").SelectedIndex = 2;
                break;

            default:
                Get <ComboBox>("use").SelectedIndex = 0;
                break;
            }
        }
Ejemplo n.º 48
0
        private void gvResults_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            string    val = Convert.ToString(e.Value);
            DataTable dt  = this.gcResults.DataSource as DataTable;
            DataRow   dr  = this.gvResults.GetDataRow(e.RowHandle);

            if (dr == null)
            {
                return;
            }
            if (e.Column == this.gcolId)
            {
                if (dt != null && !string.IsNullOrEmpty(val))
                {
                    DataRow[] drs = dt.Select(string.Format("LABEL_ID='{0}'", val));
                    if (drs.Length > 0)
                    {
                        //MessageService.ShowMessage(string.Format("ID:{0} 已存在,请确认。", val), "提示");
                        MessageService.ShowMessage(string.Format(StringParser.Parse("${res:FanHai.Hemera.Addins.PrintLabelCtrl.msg.0005}"), val), StringParser.Parse("${res:Global.SystemInfo}"));
                        dr[e.Column.FieldName]       = string.Empty;
                        this.gvResults.FocusedColumn = e.Column;
                    }
                }
            }
            else if (e.Column == this.gcolIsValid)
            {
                if (val == "N")
                {
                    string           labelId = Convert.ToString(dr["LABEL_ID"]);
                    PrintLabelEntity entity  = new PrintLabelEntity();
                    if (!entity.IsAllowInvalid(labelId))
                    {
                        MessageService.ShowMessage(entity.ErrorMsg, StringParser.Parse("${res:Global.SystemInfo}"));
                        this.gvResults.FocusedColumn    = e.Column;
                        this.gvResults.FocusedRowHandle = e.RowHandle;
                        dr[e.Column.FieldName]          = "Y";
                    }
                }
            }
            if (dr.RowState == DataRowState.Modified)
            {
                bool rejectChanges = true;
                foreach (DataColumn col in dt.Columns)
                {
                    string original = Convert.ToString(dr[col, DataRowVersion.Original]);
                    string current  = Convert.ToString(dr[col, DataRowVersion.Default]);
                    if (current != original)
                    {
                        rejectChanges = false;
                        break;
                    }
                }
                if (rejectChanges)
                {
                    dr.RejectChanges();
                }
            }
        }
 private void FillKeyFileComboBox()
 {
     FindKeys(base.BaseDirectory);
     keyFile.Add(StringParser.Parse("<${res:Global.CreateButtonText}...>"));
     keyFile.Add(StringParser.Parse("<${res:Global.BrowseText}...>"));
 }
Ejemplo n.º 50
0
 private void gvResults_MasterRowGetRelationDisplayCaption(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetRelationNameEventArgs e)
 {
     //e.RelationName = "修改历史";
     e.RelationName = StringParser.Parse("${res:FanHai.Hemera.Addins.PrintLabelCtrl.msg.0006}");
 }
Ejemplo n.º 51
0
 public void ShowSourceFilesContainErrorsMessage()
 {
     ShowErrorMessage(StringParser.Parse("${res:ICSharpCode.WixBinding.PackageFilesView.AllWixFilesContainErrorsMessage}"));
 }
Ejemplo n.º 52
0
        private void tsbSave_Click(object sender, EventArgs e)
        {
            if (this.gvResults.State == GridState.Editing &&
                this.gvResults.IsEditorFocused &&
                this.gvResults.EditingValueModified)
            {
                this.gvResults.SetFocusedRowCellValue(this.gvResults.FocusedColumn, this.gvResults.EditingValue);
            }
            this.gvResults.UpdateCurrentRow();

            int       rowIndex  = this.gvResults.FocusedRowHandle;
            DataTable dt        = this.gcResults.DataSource as DataTable;
            DataTable dtChanges = dt.GetChanges();

            if (dtChanges == null || dtChanges.Rows.Count <= 0)
            {
                this.tsbSave.Enabled = false;
                return;
            }
            var items = dtChanges.AsEnumerable();

            var ids = from item in items
                      where string.IsNullOrEmpty(Convert.ToString(item["LABEL_ID"]))
                      select item;

            foreach (var item in ids)
            {
                //MessageService.ShowMessage("ID 不能为空", "提示");
                MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PrintLabelCtrl.msg.0001}"), StringParser.Parse("${res:Global.SystemInfo}"));
                this.gvResults.FocusedColumn    = this.gcolId;
                this.gvResults.FocusedRowHandle = this.gvResults.GetRowHandle(dt.Rows.IndexOf(item));
                this.gvResults.ShowEditor();
                return;
            }

            var names = from item in items
                        where string.IsNullOrEmpty(Convert.ToString(item["LABEL_NAME"]))
                        select item;

            foreach (var item in names)
            {
                //MessageService.ShowMessage("名称 不能为空" ,"提示");
                MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PrintLabelCtrl.msg.0002}"), StringParser.Parse("${res:Global.SystemInfo}"));
                this.gvResults.FocusedColumn    = this.gcolName;
                this.gvResults.FocusedRowHandle = this.gvResults.GetRowHandle(dt.Rows.IndexOf(item));
                this.gvResults.ShowEditor();
                return;
            }

            var dataTypes = from item in items
                            where string.IsNullOrEmpty(Convert.ToString(item["DATA_TYPE"]))
                            select item;

            foreach (var item in dataTypes)
            {
                //MessageService.ShowMessage(string.Format("类型 不能为空"), "提示");
                MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PrintLabelCtrl.msg.0003}"), StringParser.Parse("${res:Global.SystemInfo}"));
                this.gvResults.FocusedColumn    = this.gcolDataType;
                this.gvResults.FocusedRowHandle = this.gvResults.GetRowHandle(dt.Rows.IndexOf(item));
                this.gvResults.ShowEditor();
                return;
            }

            var printerTypes = from item in items
                               where string.IsNullOrEmpty(Convert.ToString(item["PRINTER_TYPE"]))
                               select item;

            foreach (var item in printerTypes)
            {
                //MessageService.ShowMessage(string.Format("打印机类型 不能为空"), "提示");
                MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PrintLabelCtrl.msg.0004}"), StringParser.Parse("${res:Global.SystemInfo}"));
                this.gvResults.FocusedColumn    = this.gcolPrinterType;
                this.gvResults.FocusedRowHandle = this.gvResults.GetRowHandle(dt.Rows.IndexOf(item));
                this.gvResults.ShowEditor();
                return;
            }

            DataSet   dsParams = new DataSet();
            DataTable dtParams = dtChanges;

            foreach (DataRow dr in items)
            {
                dr["CREATOR"] = PropertyService.Get(PROPERTY_FIELDS.USER_NAME);
                dr["EDITOR"]  = PropertyService.Get(PROPERTY_FIELDS.USER_NAME);
            }
            dsParams.Tables.Add(dtParams);
            PrintLabelEntity entity = new PrintLabelEntity();

            entity.SavePrintLabelData(dsParams);

            if (!string.IsNullOrEmpty(entity.ErrorMsg))
            {
                MessageService.ShowError(entity.ErrorMsg);
                return;
            }
            BindLabelData();
            this.gvResults.FocusedRowHandle = rowIndex;
        }
Ejemplo n.º 53
0
 public void ShowNoSourceFileFoundMessage(string projectName)
 {
     ShowErrorMessage(String.Format(StringParser.Parse("${res:ICSharpCode.WixBinding.PackageFilesView.NoWixFileFoundInProjectMessage}"), projectName));
 }
Ejemplo n.º 54
0
        public override bool ExecuteAction(ActionProgramRun ap)
        {
            string res;

            if (ap.Functions.ExpandString(UserData, out res) != BaseUtils.Functions.ExpandResult.Failed)
            {
                StringParser sp = new StringParser(res);

                string prefix  = "T_";
                string cmdname = sp.NextWord();

                if (cmdname != null && cmdname.Equals("PREFIX", StringComparison.InvariantCultureIgnoreCase))
                {
                    prefix = sp.NextWord();

                    if (prefix == null)
                    {
                        ap.ReportError("Missing name after Prefix in Target");
                        return(true);
                    }

                    cmdname = sp.NextWord();
                }

                EDDiscoveryForm discoveryform = (ap.ActionController as ActionController).DiscoveryForm;

                if (cmdname != null)
                {
                    if (cmdname.Equals("GET", StringComparison.InvariantCultureIgnoreCase))
                    {
                        bool tset = EliteDangerousCore.DB.TargetClass.IsTargetSet();
                        ap[prefix + "TargetSet"] = tset.ToStringIntValue();
                        if (tset)
                        {
                            EliteDangerousCore.DB.TargetClass.GetTargetPosition(out string name, out double x, out double y, out double z);
                            ap[prefix + "TargetType"]             = EliteDangerousCore.DB.TargetClass.GetTargetType().ToString();
                            ap[prefix + "TargetPositionFullName"] = name;
                            ap[prefix + "TargetPositionName"]     = EliteDangerousCore.DB.TargetClass.GetNameWithoutPrefix(name);

                            if (!double.IsNaN(x) && !double.IsNaN(y) && !double.IsNaN(z))
                            {
                                ap[prefix + "TargetPositionX"] = x.ToStringInvariant("0.##");
                                ap[prefix + "TargetPositionY"] = y.ToStringInvariant("0.##");
                                ap[prefix + "TargetPositionZ"] = z.ToStringInvariant("0.##");
                            }
                        }
                    }
                    else if (cmdname.Equals("CLEAR", StringComparison.InvariantCultureIgnoreCase))
                    {
                        bool tset = EliteDangerousCore.DB.TargetClass.IsTargetSet();
                        ap[prefix + "TargetClear"] = tset.ToStringIntValue();
                        if (tset)
                        {
                            TargetClass.ClearTarget();
                            discoveryform.NewTargetSet(this);
                        }
                    }
                    else
                    {
                        string name = sp.NextQuotedWord();

                        if (name != null)
                        {
                            if (cmdname.Equals("BOOKMARK", StringComparison.InvariantCultureIgnoreCase))
                            {
                                BookmarkClass bk = GlobalBookMarkList.Instance.FindBookmarkOnSystem(name);    // has it been bookmarked?

                                if (bk != null)
                                {
                                    TargetClass.SetTargetBookmark(name, bk.id, bk.x, bk.y, bk.z);
                                    discoveryform.NewTargetSet(this);
                                }
                                else
                                {
                                    ap.ReportError("Bookmark '" + name + "' not found");
                                }
                            }
                            else if (cmdname.Equals("GMO", StringComparison.InvariantCultureIgnoreCase))
                            {
                                EliteDangerousCore.EDSM.GalacticMapObject gmo = discoveryform.galacticMapping.Find(name, true, true);

                                if (gmo != null)
                                {
                                    TargetClass.SetTargetGMO("G:" + gmo.name, gmo.id, gmo.points[0].X, gmo.points[0].Y, gmo.points[0].Z);
                                    discoveryform.NewTargetSet(this);
                                }

                                else
                                {
                                    ap.ReportError("GMO '" + name + "' not found");
                                }
                            }
                            else if (cmdname.Equals("NOTE", StringComparison.InvariantCultureIgnoreCase))
                            {
                                SystemNoteClass nc = SystemNoteClass.GetNoteOnSystem(name);        // has it got a note?
                                ISystem         sc = discoveryform.history.FindSystem(name);

                                if (sc != null && sc.HasCoordinate && nc != null)
                                {
                                    TargetClass.SetTargetNotedSystem(name, nc.id, sc.X, sc.Y, sc.Z);
                                    discoveryform.NewTargetSet(this);
                                }
                                else
                                {
                                    ap.ReportError("No Note found on entries in system '" + name + "'");
                                }
                            }
                            else
                            {
                                ap.ReportError("Unknown TARGET command");
                            }
                        }
                        else
                        {
                            ap.ReportError("Missing name in command");
                        }
                    }
                }
                else
                {
                    ap.ReportError("Missing TARGET command");
                }
            }
            else
            {
                ap.ReportError(res);
            }

            return(true);
        }
Ejemplo n.º 55
0
 public TemplateItem(ProjectTemplate template) : base(StringParser.Parse(template.Name))
 {
     this.template = template;
     ImageIndex    = 0;
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Shows a status bar message indicating that the specified text
 /// was not found.
 /// </summary>
 void ShowTextNotFound(string find)
 {
     ShowMessage(String.Concat(find, StringParser.Parse(" ${res:ICSharpCode.SharpDevelop.DefaultEditor.IncrementalSearch.NotFoundStatusBarMessage}")), true);
 }
Ejemplo n.º 57
0
        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolbarSave_Click(object sender, EventArgs e)
        {
            if (MessageService.AskQuestion(StringParser.Parse("${res:FanHai.Hemera.Addins.Msg.SaveRemind}"), StringParser.Parse("${res:Global.SystemInfo}")))
            {//系统提示确定要保存吗
                //判断控件是否有空值
                if (string.IsNullOrEmpty(this.txtPartNumber.Text))
                {
                    //MessageService.ShowMessage("请填写产品料号。", "系统错误提示");
                    MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PartEditor.msg.0001}"), StringParser.Parse("${res:Global.SystemInfo}"));
                    this.txtPartNumber.Focus();
                    return;
                }

                if (string.IsNullOrEmpty(this.txtDescriptions.Text))
                {
                    //MessageService.ShowMessage("请填写产品描述。", "系统错误提示");
                    MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PartEditor.msg.0002}"), StringParser.Parse("${res:Global.SystemInfo}"));
                    this.txtDescriptions.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.cbeMoudle.Text))
                {
                    //MessageService.ShowMessage("请填写产品型号。", "系统错误提示");
                    MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PartEditor.msg.0003}"), StringParser.Parse("${res:Global.SystemInfo}"));
                    this.cbeMoudle.Focus();
                    this.cbeMoudle.SelectAll();
                    return;
                }
                if (this.cbeMoudle.Text == StringParser.Parse("${res:FanHai.Hemera.Addins.FMM.PartEditor.lbl.0001}"))//"-填完描述后回车,自动带出描述中出现第一个\" - \"符号前面部分的信息作为产品型号,请慎重填写描述-")
                {
                    //MessageService.ShowMessage("请合理填写描述,然后回车带出型号。", "系统错误提示");
                    MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PartEditor.msg.0004}"), StringParser.Parse("${res:Global.SystemInfo}"));
                    this.txtDescriptions.Focus();
                    this.txtDescriptions.SelectAll();
                    return;
                }
                if (string.IsNullOrEmpty(this.luePartYtpe.Text))
                {
                    //MessageService.ShowMessage("请选择产品类型。", "系统错误提示");
                    MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PartEditor.msg.0005}"), StringParser.Parse("${res:Global.SystemInfo}"));
                    this.luePartYtpe.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.txtPartClass.Text))
                {
                    //MessageService.ShowMessage("请选择产品分类。", "系统错误提示");
                    MessageService.ShowMessage(StringParser.Parse("${res:FanHai.Hemera.Addins.PartEditor.msg.0006}"), StringParser.Parse("${res:Global.SystemInfo}"));
                    this.txtPartClass.Focus();
                    return;
                }
                //判断控件是否有空值

                MapControlsToPart();                      //变量赋值

                if (ControlState.New == State)
                {//判断状态为new
                    _part.PartVersion = "1";
                    if (_part.Insert())
                    {//插入操作成功
                        MessageService.ShowMessage("${res:FanHai.Hemera.Addins.Msg.SaveSucceed}", "${res:Global.SystemInfo}");
                        WorkbenchSingleton.Workbench.ActiveViewContent.TitleName
                            = StringParser.Parse("${res:FanHai.Hemera.Addins.FMM.PartManagement.Name}") + "_"
                              + _part.PartName;

                        State = ControlState.Edit;
                    }
                }
                else if (ControlState.Edit == State)
                {
                    if (_part.Update())
                    {
                        MessageService.ShowMessage("${res:FanHai.Hemera.Addins.Msg.UpdateSucceed}", "${res:Global.SystemInfo}");
                        State = ControlState.Edit;
                    }
                }

                toolbarSearch_Click(sender, e);
            }
        }
Ejemplo n.º 58
0
        void FileRemoving(object sender, FileCancelEventArgs e)
        {
            if (e.Cancel)
            {
                return;
            }
            string fullName = Path.GetFullPath(e.FileName);

            if (!CanBeVersionControlledFile(fullName))
            {
                return;
            }

            if (e.IsDirectory)
            {
                // show "cannot delete directories" message even if
                // AutomaticallyDeleteFiles (see below) is off!
                using (SvnClientWrapper client = new SvnClientWrapper()) {
                    SvnMessageView.HandleNotifications(client);

                    Status status = client.SingleStatus(fullName);
                    switch (status.TextStatus)
                    {
                    case StatusKind.None:
                    case StatusKind.Unversioned:
                    case StatusKind.Ignored:
                        break;

                    default:
                        // must be done using the subversion client, even if
                        // AutomaticallyDeleteFiles is off, because we don't want to corrupt the
                        // working copy
                        e.OperationAlreadyDone = true;
                        try {
                            client.Delete(new string[] { fullName }, false);
                        } catch (SvnClientException ex) {
                            LoggingService.Warn("SVN Error" + ex);
                            LoggingService.Warn(ex);

                            if (ex.IsKnownError(KnownError.CannotDeleteFileWithLocalModifications) ||
                                ex.IsKnownError(KnownError.CannotDeleteFileNotUnderVersionControl))
                            {
                                if (MessageService.ShowCustomDialog("${res:AddIns.Subversion.DeleteDirectory}",
                                                                    StringParser.Parse("${res:AddIns.Subversion.ErrorDelete}:\n", new string[, ] {
                                    { "File", fullName }
                                }) +
                                                                    ex.Message, 0, 1,
                                                                    "${res:AddIns.Subversion.ForceDelete}", "${res:Global.CancelButtonText}")
                                    == 0)
                                {
                                    try {
                                        client.Delete(new string[] { fullName }, true);
                                    } catch (SvnClientException ex2) {
                                        e.Cancel = true;
                                        MessageService.ShowError(ex2.Message);
                                    }
                                }
                                else
                                {
                                    e.Cancel = true;
                                }
                            }
                            else
                            {
                                e.Cancel = true;
                                MessageService.ShowError(ex.Message);
                            }
                        }
                        break;
                    }
                }
                return;
            }
            // not a directory, but a file:

            if (!AddInOptions.AutomaticallyDeleteFiles)
            {
                return;
            }
            try {
                using (SvnClientWrapper client = new SvnClientWrapper()) {
                    SvnMessageView.HandleNotifications(client);

                    Status status = client.SingleStatus(fullName);
                    switch (status.TextStatus)
                    {
                    case StatusKind.None:
                    case StatusKind.Unversioned:
                    case StatusKind.Ignored:
                    case StatusKind.Deleted:
                        return;                                 // nothing to do

                    case StatusKind.Normal:
                        // remove without problem
                        break;

                    case StatusKind.Modified:
                    case StatusKind.Replaced:
                        if (MessageService.AskQuestion("${res:AddIns.Subversion.RevertLocalModifications}"))
                        {
                            // modified files cannot be deleted, so we need to revert the changes first
                            client.Revert(new string[] { fullName }, e.IsDirectory ? Recurse.Full : Recurse.None);
                        }
                        else
                        {
                            e.Cancel = true;
                            return;
                        }
                        break;

                    case StatusKind.Added:
                        if (status.Copied)
                        {
                            if (!MessageService.AskQuestion("${res:AddIns.Subversion.RemoveMovedFile}"))
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                        client.Revert(new string[] { fullName }, e.IsDirectory ? Recurse.Full : Recurse.None);
                        return;

                    default:
                        MessageService.ShowErrorFormatted("${res:AddIns.Subversion.CannotRemoveError}", status.TextStatus.ToString());
                        e.Cancel = true;
                        return;
                    }
                    e.OperationAlreadyDone = true;
                    client.Delete(new string [] { fullName }, true);
                }
            } catch (Exception ex) {
                MessageService.ShowError("File removed exception: " + ex);
            }
        }
 public TortoiseSvnNotFoundForm()
     : base(StringParser.Parse("${res:AddIns.Subversion.TortoiseSVNRequired}"), "http://tortoisesvn.net/", null)
 {
 }
Ejemplo n.º 60
0
 public IMSBuildChainedLoggerFilter CreateFilter(IMSBuildLoggerContext context, IMSBuildChainedLoggerFilter nextFilter)
 {
     context.OutputTextLine(StringParser.Parse("${res:ICSharpCode.CodeAnalysis.RunningFxCopOn} " + context.ProjectFileName.GetFileNameWithoutExtension()));
     return(new FxCopLoggerImpl(context, nextFilter));
 }