예제 #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldUseLastKnownOnlineClusterMemberAndSetTimeoutForCatchup() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldUseLastKnownOnlineClusterMemberAndSetTimeoutForCatchup()
        {
            // Given
            LearnerState   state    = LearnerState.Learner;
            LearnerContext ctx      = mock(typeof(LearnerContext));
            MessageHolder  outgoing = mock(typeof(MessageHolder));

            Org.Neo4j.cluster.InstanceId upToDateClusterMember = new Org.Neo4j.cluster.InstanceId(1);

            // What we know
            when(ctx.LastLearnedInstanceId).thenReturn(0L);
            when(ctx.GetPaxosInstance(new Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId(1L))).thenReturn(new PaxosInstance(null, new Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId(1L)));
            when(ctx.LastKnownAliveUpToDateInstance).thenReturn(upToDateClusterMember);
            when(ctx.GetUriForId(upToDateClusterMember)).thenReturn(new URI("c:/1"));

            // What we know the cluster knows
            when(ctx.LastKnownLearnedInstanceInCluster).thenReturn(1L);

            // When
            Message <LearnerMessage> message = Message.to(LearnerMessage.CatchUp, new URI("c:/2"), 2L).setHeader(Message.HEADER_FROM, "c:/2").setHeader(Message.HEADER_INSTANCE_ID, "2");
            State newState = state.handle(ctx, message, outgoing);

            // Then

            assertThat(newState, equalTo(LearnerState.Learner));
            verify(outgoing).offer(Message.to(LearnerMessage.LearnRequest, new URI("c:/1"), new LearnerMessage.LearnRequestState()).setHeader(Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId.INSTANCE, Convert.ToString(1L)));
            verify(ctx).setTimeout("learn", Message.timeout(LearnerMessage.LearnTimedout, message));
        }
예제 #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void delayedVoteFromPreviousElectionMustNotCauseCurrentElectionToComplete() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DelayedVoteFromPreviousElectionMustNotCauseCurrentElectionToComplete()
        {
            // Given
            ElectionContext context = mock(typeof(ElectionContext));
            MessageHolder   holder  = mock(typeof(MessageHolder));

            when(context.GetLog(Mockito.any())).thenReturn(NullLog.Instance);

            const string role = "master";
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.cluster.InstanceId voter = new org.neo4j.cluster.InstanceId(2);
            InstanceId voter = new InstanceId(2);

            ElectionCredentials       voteCredentialComparable = mock(typeof(ElectionCredentials));
            Message <ElectionMessage> vote = Message.@internal(voted, new ElectionMessage.VersionedVotedData(role, voter, voteCredentialComparable, 4));

            when(context.Voted(role, voter, voteCredentialComparable, 4)).thenReturn(false);

            // When
            election.handle(context, vote, holder);

            verify(context).getLog(ArgumentMatchers.any());
            verify(context).voted(role, voter, voteCredentialComparable, 4);

            // Then
            verifyNoMoreInteractions(context, holder);
        }
예제 #3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void something() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void Something()
        {
            object acceptorValue = new object();
            object bookedValue   = new object();

            Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId instanceId = new Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId(42);

            PaxosInstanceStore paxosInstanceStore = new PaxosInstanceStore();

            ProposerContext context = Mockito.mock(typeof(ProposerContext));

            when(context.GetPaxosInstance(instanceId)).thenReturn(paxosInstanceStore.GetPaxosInstance(instanceId));
            when(context.GetMinimumQuorumSize(Mockito.anyList())).thenReturn(2);

            // The instance is closed
            PaxosInstance paxosInstance = new PaxosInstance(paxosInstanceStore, instanceId);                 // the instance

            paxosInstance.Propose(2001, Iterables.asList(Iterables.iterable(create("http://something1"), create("http://something2"), create("http://something3"))));

            Message message = Message.to(ProposerMessage.Promise, create("http://something1"), new ProposerMessage.PromiseState(2001, acceptorValue));

            message.setHeader(Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId.INSTANCE, instanceId.ToString());

            MessageHolder mockHolder = mock(typeof(MessageHolder));

            ProposerState.Proposer.handle(context, message, mockHolder);
        }
예제 #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat()
        public virtual void ShouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.neo4j.cluster.com.message.Message> sentOut = new java.util.LinkedList<>();
            IList <Message> sentOut = new LinkedList <Message>();

            // Given
            MessageHolder holder = mock(typeof(MessageHolder));

            // The sender, which adds messages outgoing to the list above.
            doAnswer(invocation =>
            {
                sentOut.Add(invocation.getArgument(0));
                return(null);
            }).when(holder).offer(ArgumentMatchers.any <Message <MessageType> >());

            ClusterContext       mockContext       = mock(typeof(ClusterContext));
            ClusterConfiguration mockConfiguration = mock(typeof(ClusterConfiguration));

            when(mockConfiguration.Members).thenReturn(new HashMapAnonymousInnerClass5(this));
            when(mockContext.Configuration).thenReturn(mockConfiguration);

            HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor(holder, mockContext);

            Message incoming = Message.to(mock(typeof(MessageType)), URI.create("ha://someAwesomeInstanceInJapan")).setHeader(Message.HEADER_INSTANCE_ID, "2").setHeader(Message.HEADER_FROM, "ha://2");

            // WHEN
            processor.Process(incoming);

            // THEN
            assertEquals(1, sentOut.Count);
            assertEquals(HeartbeatMessage.IAmAlive, sentOut[0].MessageType);
            assertEquals(new InstanceId(2), ((HeartbeatMessage.IAmAliveState)sentOut[0].Payload).Server);
        }
예제 #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void voteResponseShouldHaveSameVersionAsVoteRequest() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void VoteResponseShouldHaveSameVersionAsVoteRequest()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.neo4j.cluster.com.message.Message<?>> messages = new java.util.ArrayList<>(1);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
            IList <Message <object> > messages = new List <Message <object> >(1);
            MessageHolder             holder   = messages.add;

            ElectionContext context = mock(typeof(ElectionContext));

            const int version = 14;
            Message <ElectionMessage> voteRequest = Message.to(ElectionMessage.Vote, URI.create("some://instance"), new ElectionContext_VoteRequest("coordinator", version)
                                                               );

            voteRequest.SetHeader(Message.HEADER_FROM, "some://other");

            election.handle(context, voteRequest, holder);

            assertEquals(1, messages.Count);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: org.neo4j.cluster.com.message.Message<?> response = messages.get(0);
            Message <object> response = messages[0];

            assertEquals(ElectionMessage.Voted, response.MessageType);
            ElectionMessage.VersionedVotedData payload = response.Payload;
            assertEquals(version, payload.Version);
        }
예제 #6
0
        private void TestLes(string input, string expectOutput, int expectMessages = 0, Severity expectSev = 0)
        {
            using (G.PushTLV(Token.ToStringStrategyTLV, TokenExt.ToString))
            {
                MessageHolder errorList;
                var           input2 = StripInitialNewline(input);
                var           lexer  = new LesLexer(input2, errorList = new MessageHolder());
                var           wrapr  = new LesIndentTokenGenerator(lexer);
                var           output = new DList <Token>();
                for (var t = wrapr.NextToken(); t.HasValue; t = wrapr.NextToken())
                {
                    output.Add(t.Value);
                }
                var expectTokens = new LesLexer(expectOutput, MessageSink.Console).Buffered().Select(t =>
                                                                                                     t.Type() == TokenType.LBrack ? t.WithType((int)TokenType.Indent) :
                                                                                                     t.Type() == TokenType.RBrack ? t.WithType((int)TokenType.Dedent) : t).ToList();

                AreEqual(expectMessages, errorList.List.Count);
                if (expectMessages > 0)
                {
                    AreEqual(expectSev, errorList.List.Max(m => m.Severity));
                }
                ExpectList(output, expectTokens, false);
            }
        }
예제 #7
0
        public IResult ReceiveMoney(ITransaction earning)
        {
            IResult result = new Result();

            if (this.Balance.Currency.Name.Equals(CurrencyType.USD))
            {
                earning.Amount.ConvertToUSD();
            }
            else if (this.Balance.Currency.Name.Equals(CurrencyType.EUR
                                                       .ToString()))
            {
                earning.Amount.ConvertToEUR();
            }
            else if (this.Balance.Currency.Name.Equals(CurrencyType.UAH))
            {
                earning.Amount.ConvertToUAH();
            }

            this.Balance.Count += earning.Amount.Count;
            this.Transactions.Add(earning);
            result.Success = true;
            result.Message = string.Format(MessageHolder.GetMessage(MessageType
                                                                    .EarnMoney), this.Name,
                                           earning.Amount.GetStrValue(), earning.Name);

            return(result);
        }
예제 #8
0
        public HttpResponseMessage GetSign(HttpRequestMessage request, [FromUri] MessageHolder messageHolder)
        {
            IEnumerable <string> headerValues;
            var apiKey = string.Empty;

            if (request.Headers.TryGetValues("ApiKey", out headerValues))
            {
                apiKey = headerValues.FirstOrDefault();
            }
            Guid gApiKey = new Guid(apiKey);

            Models.User user = Models.UserDatabaseAccess.CheckUser(gApiKey);
            Models.UserDatabaseAccess.NewLog("Get Signed Message", user);
            bool userExists = Models.UserDatabaseAccess.CheckUser(gApiKey, user.UserName);

            if (userExists == true)
            {
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSA.FromXmlString(WebApiConfig.privateKey);
                    RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
                    RSAFormatter.SetHashAlgorithm("SHA1");
                    SHA1Managed SHhash          = new SHA1Managed();
                    byte[]      SignedHashValue = RSAFormatter.CreateSignature(SHhash.ComputeHash(new UnicodeEncoding().GetBytes(messageHolder.Message)));
                    string      sign            = BitConverter.ToString(SignedHashValue);
                    return(Request.CreateResponse(HttpStatusCode.Accepted, sign));
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
예제 #9
0
        public IDataResult <string> GetValue(IExcelWorksheetEntity excelWorksheet)
        {
            IDataResult <string> dataResult =
                new DataResult <string>()
            {
                Success = false
            };

            int rowNo  = excelWorksheet.RowNo;
            int cellNo = excelWorksheet.CellNo;

            if (excelWorksheet.ExcelWorksheet.Cells[rowNo, cellNo].Value != null)
            {
                string result = excelWorksheet.ExcelWorksheet
                                .Cells[rowNo, cellNo].Value.ToString();
                dataResult.Success = true;
                dataResult.Data    = result;

                return(dataResult);
            }

            dataResult.Message = "(" + AlphabetHolder.GetSmbol(cellNo) + ") " +
                                 MessageHolder.GetErrorMessage
                                     (MessageType.IsNullOrEmpty);
            //  MessageHolder.GetErrorMessage(MessageType.FrontBracket) +
            //"("+rowNo+")" +;
            //MessageHolder.GetErrorMessage(MessageType.BackBracket);

            return(dataResult);
        }
예제 #10
0
        public IResult ValidataExcelPath(string path)
        {
            IResult result = new Result()
            {
                Success = false
            };

            if (string.IsNullOrEmpty(path))
            {
                result.Message = MessageHolder.
                                 GetErrorMessage(MessageType.FileIsempty);

                return(result);
            }

            if (Path.GetExtension(path) != ".xlsx")
            {
                result.Message = MessageHolder.
                                 GetErrorMessage(MessageType.NotFormat);

                return(result);
            }

            result.Success = true;

            return(result);
        }
예제 #11
0
        public virtual void Handle(Message <MESSAGETYPE> message, MessageHolder outgoing)
        {
            lock (this)
            {
                try
                {
                    // Let the old state handle the incoming message and tell us what the new state should be
                    State <CONTEXT, MESSAGETYPE> oldState = _state;
                    State <CONTEXT, MESSAGETYPE> newState = oldState.Handle(_context, message, outgoing);
                    _state = newState;

                    // Notify any listeners of the new state
                    StateTransition transition = new StateTransition(oldState, message, newState);
                    foreach (StateTransitionListener listener in _listeners)
                    {
                        try
                        {
                            listener.StateTransition(transition);
                        }
                        catch (Exception e)
                        {
                            // Ignore
                            _logProvider.getLog(listener.GetType()).warn("Listener threw exception", e);
                        }
                    }
                }
                catch (Exception throwable)
                {
                    _logProvider.getLog(this.GetType()).warn("Exception in message handling", throwable);
                }
            }
        }
예제 #12
0
        /// <summary>
        /// 向服务器发送初始化消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="messages"></param>
        /// <param name="messageQueues"></param>
        /// <returns>若成功发送则返回真</returns>
        public static Boolean RequestForIniMsg(String url, Queue <Message> messages, MessageHolder messageQueues)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method      = "GET";
            webRequest.ContentType = "application/json; charset=utf-8";

            string msgJson = JsonHelper.SerializeMsgQueue(messages);

            try
            {
                using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    streamWriter.Write(msgJson);
                }

                WebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                String      result;

                using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }

                messageQueues.GetNewMessagesToHandle(result);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #13
0
        protected override MessageHolder Test(Mode mode, int errorsExpected, LNodePrinterOptions printerOptions, string text, params LNode[] expected)
        {
            var messages = new MessageHolder();
            var les3     = Les3LanguageService.Value;
            var results  = les3.Parse(text, messages, mode == Mode.Expr ? ParsingMode.Expressions : ParsingMode.Statements, true).ToList();

            if (messages.List.Count != System.Math.Max(errorsExpected, 0))
            {
                messages.WriteListTo(ConsoleMessageSink.Value);
                int errorCount = messages.List.Count(msg => msg.Severity >= Severity.Error);
                AreEqual(errorsExpected, errorCount,
                         "Error count was {0} for «{1}»", errorCount, text);                // fail
            }
            for (int i = 0; i < expected.Length; i++)
            {
                LNode expect = expected[i], actual = results.TryGet(i, null);
                if (!expect.Equals(actual, LNode.CompareMode.TypeMarkers))
                {
                    var options = new Les3PrinterOptions {
                        PrintTriviaExplicitly = true, IndentString = "  "
                    };
                    AreEqual(les3.Print(expect, null, null, options), les3.Print(actual, null, null, options));
                    AreEqual(expect, actual);
                    Fail("{0} has a different type marker than {1}", expect, actual);
                }
            }
            AreEqual(expected.Length, results.Count, "Got more result nodes than expected");
            return(messages);
        }
        private void Confirm_SIREmail_Button_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateSIREmail())
            {
                string currentID = id.Text; // Gets id from textbox.
                if (currentID.Length < 9)
                {
                    // Forces message ID to be 9 characters.
                    string zeros = String.Concat(Enumerable.Repeat("0", 9 - currentID.Length));
                    currentID = zeros + currentID;
                }

                currentID = "E" + currentID; // Makes sure E is added to the message ID for email type.

                // Collects incident type from drop down menu.
                ComboBoxItem cmb         = (ComboBoxItem)incidentTypeCombo.SelectedItem;
                string       subject     = "SIR " + System.DateTime.Now.ToString("dd/MM/yy");
                string       messageBody = "Cent Code: " + centerCode1.Text + "-" + centerCode2.Text + "-" + centerCode3.Text + " " + "Nature of Incident: " + cmb.Content + " " + messageTextbox.Text;

                subject += String.Concat(Enumerable.Repeat(" ", 20 - subject.Length));

                // Creates SIR email objects to be used later.
                SIR sir = new SIR(currentID + " " + emailTextbox.Text + " " + subject + messageBody);
                MessageHolder.currentEmailID++;
                MessageHolder.AddMessage(currentID, sir);

                // Confirmation message for user.
                MessageBox.Show("SIR Email Added!\n" + "Message ID: " + currentID + "\nEmail: " + emailTextbox.Text + "\nSubject: " + subject + "\nIncident: " + cmb.Content + "\nMessage: " + messageTextbox.Text);
            }
        }
예제 #15
0
        protected override MessageHolder Test(Mode mode, int parseErrors, string expected, params LNode[] inputs)
        {
            var messages = new MessageHolder();
            var options  = new Les2PrinterOptions {
                IndentString = "  "
            };

            if (parseErrors == 0)
            {
                if (mode == Mode.Exact)
                {
                    var result = Les2LanguageService.Value.Print(inputs, messages, ParsingMode.Statements, options);
                    Assert.AreEqual(expected, result);
                }
                else
                {
                    // Start by parsing. If parsing fails, just stop; such errors are
                    // already reported by LesParserTests so we need not report them here.
                    var _ = Les2LanguageService.Value.Parse(expected, msgs: messages);
                    if (messages.List.All(msg => msg.Severity < Severity.Error))
                    {
                        foreach (LNode input in inputs)
                        {
                            DoPrinterTest(input);
                        }
                    }
                }
            }
            return(messages);
        }
예제 #16
0
파일: UG.cs 프로젝트: sizzles/ecsharp
        public void TestProcessCommandLineArguments2()
        {
            // Generate two options files, where the first refers to the second
            string       atFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
            string       file1    = "test ProcessCmdLine 1.txt";
            string       file2    = "test ProcessCmdLine 2.txt";
            StreamWriter w        = new StreamWriter(Path.Combine(atFolder, file1));

            w.WriteLine("\"@" + file2 + "\" fox--jumps\n--over");
            w.Close();
            w = new StreamWriter(Path.Combine(atFolder, file2));
            w.WriteLine("these arguments are ignored (arg limit exceeded)");
            w.Close();

            // Expand command line and ensure that the arg limit is enforced
            List <string> args    = G.SplitCommandLineArguments("\"@" + file1 + "\" \"lazy dog\"");
            var           options = new DList <KeyValuePair <string, string> >();
            var           msgs    = new MessageHolder();

            using (MessageSink.SetDefault(msgs))
                UG.ProcessCommandLineArguments(args, options, atFolder, null, null, 5);

            ExpectList(args.AsListSource(), "@" + file1, "@" + file2, "fox--jumps", "lazy dog");
            ExpectList(options, P("over", null));
            ExpectList(msgs.List.Select(msg => msg.ToString()).AsListSource(),
                       "@test ProcessCmdLine 2.txt: Warning: Limit of 5 commands exceeded");
        }
예제 #17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void ifProposingWithClosedInstanceThenRetryWithNextInstance() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void IfProposingWithClosedInstanceThenRetryWithNextInstance()
        {
            ProposerContext context = Mockito.mock(typeof(ProposerContext));

            when(context.GetLog(any(typeof(Type)))).thenReturn(NullLog.Instance);

            Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId instanceId = new Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId(42);
            PaxosInstanceStore paxosInstanceStore = new PaxosInstanceStore();

            // The instance is closed
            PaxosInstance paxosInstance = new PaxosInstance(paxosInstanceStore, instanceId); // the instance

            paxosInstance.Closed(instanceId, "1/15#");                                       // is closed for that conversation, not really important
            when(context.UnbookInstance(instanceId)).thenReturn(Message.@internal(ProposerMessage.Accepted, "the closed payload"));

            when(context.GetPaxosInstance(instanceId)).thenReturn(paxosInstance);                     // required for

            // But in the meantime it was reused and has now (of course) timed out
            string  theTimedoutPayload = "the timed out payload";
            Message message            = Message.@internal(ProposerMessage.Phase1Timeout, theTimedoutPayload);

            message.setHeader(Org.Neo4j.cluster.protocol.atomicbroadcast.multipaxos.InstanceId.INSTANCE, instanceId.ToString());

            // Handle it
            MessageHolder mockHolder = mock(typeof(MessageHolder));

            ProposerState.Proposer.handle(context, message, mockHolder);

            // Verify it was resent as a propose with the same value
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(mockHolder, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher().onMessageType(ProposerMessage.propose).withPayload(theTimedoutPayload)));
            verify(mockHolder, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >((new MessageArgumentMatcher()).onMessageType(ProposerMessage.Propose).withPayload(theTimedoutPayload)));
            verify(context, times(1)).unbookInstance(instanceId);
        }
예제 #18
0
        private void Test(string input, string expectOutput, int expectMessages = 0, Severity expectSev = 0)
        {
            // Install token-to-string stategy to aid debugging
            using (G.PushTLV(Token.ToStringStrategyTLV, t => (t.Value ?? ((CalcTokenType)t.TypeInt).ToString()).ToString())) {
                MessageHolder errorList;
                var           input2 = StripInitialNewline(input);
                var           lexer  = new CalculatorLexer(input2)
                {
                    ErrorSink = errorList = new MessageHolder()
                };
                var wrapr = new IndentTokenGenerator(lexer, allIndTrig, new Token((int)CalcTokenType.Semicolon, 0, 0, null))
                {
                    EolIndentTriggers = eolIndTrig,
                    IndentToken       = new Token((int)CalcTokenType.LBrace, 0, 0, null),
                    DedentToken       = new Token((int)CalcTokenType.RBrace, 0, 0, null),
                };
                var output = new DList <Token>();
                for (var t = wrapr.NextToken(); t.HasValue; t = wrapr.NextToken())
                {
                    output.Add(t.Value);
                }
                var expectTokens = new CalculatorLexer(expectOutput).Buffered().ToList();

                AreEqual(expectMessages, errorList.List.Count);
                if (expectMessages > 0)
                {
                    AreEqual(expectSev, errorList.List.Max(m => m.Severity));
                }
                ExpectList(output, expectTokens, false);
            }
        }
예제 #19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void learnerServingOldInstanceShouldNotLogErrorIfItDoesNotHaveIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LearnerServingOldInstanceShouldNotLogErrorIfItDoesNotHaveIt()
        {
            // Given
            LearnerState   state    = LearnerState.Learner;
            LearnerContext ctx      = mock(typeof(LearnerContext));
            MessageHolder  outgoing = mock(typeof(MessageHolder));
            // The instance will be asked for paxos instance 4...
            InstanceId paxosInstanceIdIDontHave          = new InstanceId(4);
            Message <LearnerMessage> messageRequestingId = Message.to(LearnerMessage.LearnRequest, URI.create("c:/1")).setHeader(Message.HEADER_FROM, "c:/2").setHeader(InstanceId.INSTANCE, "4");

            // ...but it does not have it yet
            when(ctx.GetPaxosInstance(paxosInstanceIdIDontHave)).thenReturn(new PaxosInstance(mock(typeof(PaxosInstanceStore)), paxosInstanceIdIDontHave));

            // When
            state.handle(ctx, messageRequestingId, outgoing);

            // Then
            // verify there is no logging of the failure
            verify(ctx, never()).notifyLearnMiss(paxosInstanceIdIDontHave);
            // but the learn failed went out anyway
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(outgoing, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher()
            verify(outgoing, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >(new MessageArgumentMatcher()
                                                                                               .onMessageType(LearnerMessage.LearnFailed).to(URI.create("c:/2"))));
        }
예제 #20
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void discoveredInstancesShouldBeOnlyOnesWeHaveContactedDirectly() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DiscoveredInstancesShouldBeOnlyOnesWeHaveContactedDirectly()
        {
            // GIVEN
            ClusterContext context = mock(typeof(ClusterContext));

            when(context.GetLog(any(typeof(Type)))).thenReturn(NullLog.Instance);
            when(context.GetUriForId(Id(2))).thenReturn(Uri(2));

            IList <ConfigurationRequestState> discoveredInstances = new LinkedList <ConfigurationRequestState>();

            when(context.DiscoveredInstances).thenReturn(discoveredInstances);
            when(context.ShouldFilterContactingInstances()).thenReturn(true);

            MessageHolder             outgoing = mock(typeof(MessageHolder));
            ConfigurationRequestState configurationRequestFromTwo = Configuration(2);
            Message <ClusterMessage>  message = to(configurationRequest, Uri(1), configurationRequestFromTwo).setHeader(Message.HEADER_FROM, Uri(2).ToString());

            // WHEN
            // We receive a configuration request from an instance which we haven't contacted
            ClusterState.Discovery.handle(context, message, outgoing);

            // THEN
            // It shouldn't be added to the discovered instances
            assertTrue(discoveredInstances.Count == 0);

            // WHEN
            // It subsequently contacts us
            when(context.HaveWeContactedInstance(configurationRequestFromTwo)).thenReturn(true);
            ClusterState.Discovery.handle(context, message, outgoing);

            // Then
            assertTrue(discoveredInstances.Contains(configurationRequestFromTwo));
        }
예제 #21
0
		protected override MessageHolder Test(Mode mode, int parseErrors, string str, params LNode[] nodes)
		{
			var messages = new MessageHolder();
			if (parseErrors == 0) {
				if (mode == Mode.Exact) {
					var sb = new StringBuilder();
					var printer = LesNodePrinter.New(sb, "  ", "\n", messages);
					var sep = "";
					foreach (LNode node in nodes) {
						sb.Append(sep);
						sep = "\n";
						printer.Print(node);
					}
					Assert.AreEqual(str, sb.ToString());
				} else {
					// Start by parsing. If parsing fails, just stop; such errors are 
					// already reported by LesParserTests so we need not report them here.
					var results = LesLanguageService.Value.Parse(str, messages);
					if (messages.List.Count == 0)
					{
						var sb = new StringBuilder();
						foreach (LNode node in nodes)
							DoPrinterTest(node, sb);
					}
				}
			}
			return messages;
		}
예제 #22
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="UserID"></param>
 /// <param name="url"></param>
 public SynchronousController(string userID, string url)
 {
     TextDoc       = new TextDoc();
     this.Url      = url;
     MessageQueues = new MessageHolder();
     Watcher       = new MessageWatcher(MessageQueues, url);
     UserID        = userID;
 }
예제 #23
0
        public IResult ConvertToEUR(IBalance balance)
        {
            IResult result = _stateResult.Clone();

            result.Success = false;
            result.Message = MessageHolder.GetMessage(MessageType.AlreadyIn)
                             + this.Name;
            return(result);
        }
예제 #24
0
        public static Result GetDefaultResult()
        {
            Result result = new Result
            {
                Message = MessageHolder.GetMessage(MessageType.Default),
                Success = false
            };

            return(result);
        }
예제 #25
0
        private List <LogMessage> RunLeMPAndCaptureErrors(UString inputText)
        {
            MessageHolder       messages  = new MessageHolder();
            MacroProcessor      lemp      = NewLemp(0xFFFF, EcsLanguageService.Value).With(mp => mp.Sink = messages);
            IListSource <LNode> inputCode = EcsLanguageService.Value.Parse(inputText, MessageSink.Default);

            lemp.ProcessSynchronously(LNode.List(inputCode));

            return(messages.List.Where(m => m.Severity == Severity.Error).ToList());
        }
예제 #26
0
 public string GetSHA256([FromUri] MessageHolder messageHolder)
 {
     using (SHA256Managed sha1 = new SHA256Managed())
     {
         var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(messageHolder.Message));
         var sb   = new StringBuilder(hash.Length * 2);
         foreach (byte b in hash)
         {
             sb.Append(b.ToString("X2"));
         }
         return(sb.ToString());
     }
 }
예제 #27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void learnerShouldAskAllAliveInstancesAndTheseOnlyForMissingValue() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LearnerShouldAskAllAliveInstancesAndTheseOnlyForMissingValue()
        {
            // Given

            IList <URI> allMembers = new List <URI>(3);
            URI         instance1  = URI.create("c:/1");        // this one is failed
            URI         instance2  = URI.create("c:/2");        // this one is ok and will respond
            URI         instance3  = URI.create("c:/3");        // this one is the requesting instance
            URI         instance4  = URI.create("c:/4");        // and this one is ok and will respond too

            allMembers.Add(instance1);
            allMembers.Add(instance2);
            allMembers.Add(instance3);
            allMembers.Add(instance4);

            ISet <Org.Neo4j.cluster.InstanceId> aliveInstanceIds = new HashSet <Org.Neo4j.cluster.InstanceId>();

            Org.Neo4j.cluster.InstanceId id2 = new Org.Neo4j.cluster.InstanceId(2);
            Org.Neo4j.cluster.InstanceId id4 = new Org.Neo4j.cluster.InstanceId(4);
            aliveInstanceIds.Add(id2);
            aliveInstanceIds.Add(id4);

            LearnerState   state    = LearnerState.Learner;
            LearnerContext ctx      = mock(typeof(LearnerContext));
            MessageHolder  outgoing = mock(typeof(MessageHolder));
            InstanceId     paxosInstanceIdIAskedFor = new InstanceId(4);

            when(ctx.LastDeliveredInstanceId).thenReturn(3L);
            when(ctx.LastKnownLearnedInstanceInCluster).thenReturn(5L);
            when(ctx.MemberURIs).thenReturn(allMembers);
            when(ctx.Alive).thenReturn(aliveInstanceIds);
            when(ctx.GetUriForId(id2)).thenReturn(instance2);
            when(ctx.GetUriForId(id4)).thenReturn(instance4);
            when(ctx.GetPaxosInstance(paxosInstanceIdIAskedFor)).thenReturn(new PaxosInstance(mock(typeof(PaxosInstanceStore)), paxosInstanceIdIAskedFor));

            Message <LearnerMessage> theCause = Message.to(LearnerMessage.CatchUp, instance2);                // could be anything, really

            // When
            state.handle(ctx, Message.timeout(LearnerMessage.LearnTimedout, theCause), outgoing);

            // Then
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(outgoing, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher()
            verify(outgoing, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >(new MessageArgumentMatcher()
                                                                                               .onMessageType(LearnerMessage.LearnRequest).to(instance2)));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: verify(outgoing, times(1)).offer(org.mockito.ArgumentMatchers.argThat<org.neo4j.cluster.com.message.Message<? extends org.neo4j.cluster.com.message.MessageType>>(new org.neo4j.cluster.protocol.MessageArgumentMatcher()
            verify(outgoing, times(1)).offer(ArgumentMatchers.argThat <Message <MessageType> >(new MessageArgumentMatcher()
                                                                                               .onMessageType(LearnerMessage.LearnRequest).to(instance4)));
            verifyNoMoreInteractions(outgoing);
        }
예제 #28
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAlwaysAddItsInstanceIdToOutgoingMessages()
        public virtual void ShouldAlwaysAddItsInstanceIdToOutgoingMessages()
        {
            InstanceId me = new InstanceId(42);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.neo4j.cluster.com.message.Message> sentOut = new java.util.LinkedList<>();
            IList <Message> sentOut = new LinkedList <Message>();

            /*
             * Lots of setup required. Must have a sender that keeps messages so we can see what the machine sent out.
             * We must have the StateMachines actually delegate the incoming message and retrieve the generated outgoing.
             * That means we need an actual StateMachine with a registered MessageType. And most of those are void
             * methods, which means lots of Answer objects.
             */
            // Given
            MessageSender sender = mock(typeof(MessageSender));

            // The sender, which adds messages outgoing to the list above.
            doAnswer(invocation =>
            {
                ((IList <Org.Neo4j.cluster.com.message.Message>)sentOut).AddRange(invocation.getArgument(0));
                return(null);
            }).when(sender).process(ArgumentMatchers.any <IList <Message <? extends MessageType> > >());

            StateMachines stateMachines = new StateMachines(NullLogProvider.Instance, mock(typeof(StateMachines.Monitor)), mock(typeof(MessageSource)), sender, mock(typeof(Timeouts)), mock(typeof(DelayedDirectExecutor)), ThreadStart.run, me);

            // The state machine, which has a TestMessage message type and simply adds a HEADER_TO header to the messages it
            // is handed to handle.
            StateMachine machine = mock(typeof(StateMachine));

            when(machine.MessageType).then((Answer <object>)invocation => typeof(TestMessage));
            doAnswer(invocation =>
            {
                Message message      = invocation.getArgument(0);
                MessageHolder holder = invocation.getArgument(1);
                message.setHeader(Message.HEADER_TO, "to://neverland");
                holder.offer(message);
                return(null);
            }).when(machine).handle(any(typeof(Message)), any(typeof(MessageHolder)));
            stateMachines.AddStateMachine(machine);

            // When
            stateMachines.Process(Message.@internal(TestMessage.Message1));

            // Then
            assertEquals("StateMachines should not make up messages from thin air", 1, sentOut.Count);
            Message sent = sentOut[0];

            assertTrue("StateMachines should add the instance-id header", sent.hasHeader(Message.HEADER_INSTANCE_ID));
            assertEquals("StateMachines should add instance-id header that has the correct value", me.ToString(), sent.getHeader(Message.HEADER_INSTANCE_ID));
        }
예제 #29
0
        public void TestDefineEverything()
        {
            var holder = new MessageHolder();

            using (MessageSink.SetDefault(holder))             // suppress errors
            {
                TestEcs(@"define ($anything) { $anything + 1; }
					X();"                    ,
                        @"define ($anything) { $anything + 1; }
					X();"                    );
                Assert.AreEqual(1, holder.List.Count(msg =>
                                                     msg.Format.EndsWith("Defining a macro that could match everything is not allowed.")));
            }
        }
예제 #30
0
 protected void ExpectMessageContains(MessageHolder messages, params string[] substrings)
 {
     foreach (var msg in messages.List)
     {
         for (int i = 0; i < substrings.Length; i++)
         {
             if (msg.Formatted.IndexOf(substrings[i], StringComparison.InvariantCultureIgnoreCase) > -1)
             {
                 substrings[i] = null;
             }
         }
     }
     Assert.AreEqual(null, substrings.WhereNotNull().FirstOrDefault());
 }
예제 #31
0
        public IDataResult <ExcelConfiguration> GeneratExcelConfig(ExcelWorksheet excelWorksheet)
        {
            IDataResult <ExcelConfiguration> dataResult =
                new DataResult <ExcelConfiguration>();
            ExcelConfiguration excelConfiguration = new ExcelConfiguration();

            excelConfiguration.DataColumn = new DataColumn();
            IExcelWorksheetEntity tmpEntity = new ExcelWorksheetEntity();

            tmpEntity.ExcelWorksheet = excelWorksheet;
            tmpEntity.RowNo          = _excelConfiguration.DataRowIndex.Title;

            List <IDataResult <Data> > dataResults = new List <IDataResult <Data> >();

            int endColumn = excelWorksheet.Dimension.End.Column;

            StringBuilder messegeBuilder = new StringBuilder();

            foreach (var data in _excelConfiguration.DataColumn.Datas)
            {
                IDataResult <Data> tmResultHelper = HelperGenerat(data, tmpEntity, endColumn);

                if (!tmResultHelper.Success)
                {
                    messegeBuilder.Append(data.Name + MessageHolder.GetErrorMessage(MessageType.Space));
                }
                dataResults.Add(tmResultHelper);
            }
            excelConfiguration.DataColumn.Datas = dataResults.Select(p => p.Data).ToList();

            if (dataResults.Any(p => p.Success == false))
            {
                dataResult.Success = false;
                dataResult.Message = MessageHolder.
                                     GetErrorMessage(MessageType.NotIsTitle) +
                                     MessageHolder.GetErrorMessage(MessageType.Space)
                                     + messegeBuilder +
                                     MessageHolder.GetErrorMessage(MessageType.BackBracket);

                return(dataResult);
            }

            excelConfiguration.DataRowIndex      = _excelConfiguration.DataRowIndex;
            excelConfiguration.NameColumnSection = _excelConfiguration.NameColumnSection;
            dataResult.Data    = excelConfiguration;
            dataResult.Success = true;

            return(dataResult);
        }
예제 #32
0
		protected override void Test(bool exprMode, int parseErrors, string str, params LNode[] nodes)
		{
			if (parseErrors >= 0)
				return;
			// Start by parsing. If parsing fails, just stop; such errors are 
			// already reported by LesParserTests so we need not report them here.
			var messages = new MessageHolder();
			var results = LesLanguageService.Value.Parse(str, messages);
			if (messages.List.Count != 0)
				return;

			var sb = new StringBuilder();
			foreach (LNode node in nodes)
				DoPrinterTest(node, sb);
		}
예제 #33
0
		protected override MessageHolder Test(Mode mode, int errorsExpected, string text, params LNode[] expected)
		{
			var messages = new MessageHolder();
			var results = Les3LanguageService.Value.Parse(text, messages, mode == Mode.Expr ? ParsingMode.Expressions : ParsingMode.Statements, true).ToList();
			if (messages.List.Count != System.Math.Max(errorsExpected, 0))
			{
				messages.WriteListTo(ConsoleMessageSink.Value);
				AreEqual(errorsExpected, messages.List.Count, 
					"Error count was {0} for «{1}»", messages.List.Count, text); // fail
			}
			for (int i = 0; i < expected.Length; i++)
				AreEqual(expected[i], results.TryGet(i, null));
			AreEqual(expected.Length, results.Count, "Got more result nodes than expected");
			return messages;
		}
예제 #34
0
		protected override void Test(bool exprMode, int errorsExpected, string str, params LNode[] expected)
		{
			var messages = new MessageHolder();
			var results = LesLanguageService.Value.Parse(str, messages, exprMode ? ParsingService.Exprs : ParsingService.Stmts);
			for (int i = 0; i < expected.Length; i++)
			{
				var result = results[i]; // this is when parsing actually occurs
				AreEqual(expected[i], result);
			}
			AreEqual(expected.Length, results.Count);
			if (messages.List.Count != System.Math.Max(errorsExpected, 0))
			{
				messages.WriteListTo(MessageSink.Console);
				AreEqual(errorsExpected, messages.List.Count); // fail
			}
		}
예제 #35
0
		private void LexWithSCSAndCompare(List<Lexing.Token> originalTokens, string lesCode)
		{
			var msgs = new MessageHolder();
			var stream = new MemoryStream(Encoding.UTF8.GetBytes(lesCode));
			var source = new StreamCharSource(stream, Encoding.UTF8.GetDecoder(), _bufSize);
			var lexer = Les2LanguageService.Value.Tokenize(source, "StreamCharSource.les", msgs);
			var tokens = lexer.ToList().Where(tok => !tok.IsWhitespace).ToList();
			Assert.AreEqual(0, msgs.List.Count);
			ExpectList(tokens, originalTokens);

			// Now reset the lexer and read the same StreamCharSource again 
			// (different code paths are used the second time)
			lexer.Reset();
			tokens = lexer.ToList().Where(tok => !tok.IsWhitespace).ToList();
			Assert.AreEqual(0, msgs.List.Count);
			ExpectList(tokens, originalTokens);
		}
예제 #36
0
		protected override MessageHolder Test(Mode mode, int parseErrors, string expected, params LNode[] inputs)
		{
			var messages = new MessageHolder();
			var options = new Les2PrinterOptions { IndentString = "  " };
			if (parseErrors == 0) {
				if (mode == Mode.Exact) {
					var result = Les2LanguageService.Value.Print(inputs, messages, ParsingMode.Statements, options);
					Assert.AreEqual(expected, result);
				} else {
					// Start by parsing. If parsing fails, just stop; such errors are 
					// already reported by LesParserTests so we need not report them here.
					var _ = Les2LanguageService.Value.Parse(expected, msgs: messages);
					if (messages.List.All(msg => msg.Severity < Severity.Error))
						foreach (LNode input in inputs)
							DoPrinterTest(input);
				}
			}
			return messages;
		}
예제 #37
0
		public void TestWithLes()
		{
			// The idea: write some simple, correct LES code, then randomize it by
			// inserting comments in a bunch of places. Lex it both ways and verify 
			// that the non-whitespace tokens are the same either way.
			string lesCode = @"import System;
				import Loyc;
				namespace TestCode {
					class TestClass {
						public answer::float = 42.0e0f;
						public ComputeAnswer()::object {
							你好();
							// slack off while pretending to work
							Thread.Sleep(1042.0 * 1000 -> int);
							return answer;
						};
					};
				};";
			MessageHolder msgs = new MessageHolder();
			var lexer = Les2LanguageService.Value.Tokenize(lesCode, msgs);
			var tokens = lexer.ToList().Where(tok => !tok.IsWhitespace).ToList();
			Debug.Assert(msgs.List.Count == 0);

			LexWithSCSAndCompare(tokens, lesCode);

			var r = new Random();
			var lesCode2 = new StringBuilder(lesCode);
			for (int i = lesCode2.Length - 1; i >= 0; i--)
				if (lesCode2[i > 0 ? i - 1 : i] == ' ')
					if (r.Next(4) == 0)
					{
						if (r.Next(2) == 0)
							lesCode2.Insert(i, "/*你好 你好*/");
						else
							lesCode2.Insert(i, "/*2345678901234567 lárgér cómmént 45678901234567*/"); // 50
					}

			LexWithSCSAndCompare(tokens, lesCode2.ToString());
		}
예제 #38
0
		private void DoPrinterTest(LNode input)
		{
			var messages = new MessageHolder();
			var printed = Les2LanguageService.Value.Print(input, messages, null);
			Assert.AreEqual(0, messages.List.Count);
			var reparsed = Les2LanguageService.Value.Parse(printed, msgs: messages);
			if (messages.List.Count != 0)
				Assert.Fail("Printed node «{0}» causes error on parsing: {1}", printed, messages.List[0].Formatted);
			Assert.AreEqual(1, reparsed.Count);
			Assert.AreEqual(input, reparsed[0],
				"Printed node «{0}» is different from original node.\n  Old: «{1}»\n  New: «{2}»", printed, input, reparsed[0]);
		}
예제 #39
0
		protected void ExpectMessageContains(MessageHolder messages, params string[] substrings)
		{
			foreach (var msg in messages.List)
				for (int i = 0; i < substrings.Length; i++)
					if (msg.Formatted.IndexOf(substrings[i], StringComparison.InvariantCultureIgnoreCase) > -1)
						substrings[i] = null;
			Assert.AreEqual(null, substrings.WhereNotNull().FirstOrDefault());
		}
예제 #40
0
		protected override byte[] Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progressCallback)
		{
			string oldCurDir = Environment.CurrentDirectory;
			try {
				string inputFolder = Path.GetDirectoryName(inputFilePath);
 				Environment.CurrentDirectory = inputFolder; // --macros should be relative to file being processed

				// Originally I wrote a conversion from IVsGeneratorProgress to
 				// IMessageSink so that errors could be reported immediately and
				// directly to Visual Studio. This broke in a bizarre way when I
				// added processing on a separate thread (in order to be able to
				// abort the thread if it runs too long); I got the following
				// InvalidCastException: "Unable to cast COM object of type 'System.__ComObject' 
				// to interface type 'Microsoft.VisualStudio.Shell.Interop.IVsGeneratorProgress'.
				// This operation failed because the QueryInterface call on the COM component for 
				// the interface with IID '{BED89B98-6EC9-43CB-B0A8-41D6E2D6669D}' failed due to 
				// the following error: No such interface supported (Exception from HRESULT: 
				// 0x80004002 (E_NOINTERFACE))."
				// 
				// A simple solution is to store the messages rather than reporting
				// them immediately. I'll report the errors at the very end.
				MessageHolder sink = new MessageHolder();
				
				var sourceFile = new InputOutput((UString)inputFileContents, inputFilePath);

				Compiler.KnownOptions["no-out-header"] = Pair.Create("", "Remove explanatory comment from output file");
				Compiler.KnownOptions.Remove("parallel");   // not applicable to single file
				Compiler.KnownOptions.Remove("noparallel"); // not applicable to single file

				var c = new Compiler(sink, sourceFile) { 
					AbortTimeout = TimeSpan.FromSeconds(10),
					Parallel = false // only one file, parallel doesn't help
				};

				var argList = G.SplitCommandLineArguments(defaultNamespace);
				var options = c.ProcessArguments(argList, true, false);
				// Note: if default namespace is left blank, VS uses the namespace 
				// from project settings. Don't show an error in that case.
				if (argList.Count > 1 || (argList.Count == 1 && options.Count > 0))
					sink.Write(Severity.Error, "Command line", "'{0}': expected options only (try --help).", argList[0]);

				string _;
				if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
				{
					var ms = new MemoryStream();
					LeMP.Compiler.ShowHelp(LeMP.Compiler.KnownOptions, new StreamWriter(ms), false);
					return ms.GetBuffer();
				}

				LeMP.Compiler.WarnAboutUnknownOptions(options, sink, LeMP.Compiler.KnownOptions);
				
				if (options.ContainsKey("no-out-header"))
					c.NoOutHeader = true;
				
				if (c.InLang == LesLanguageService.Value || inputFilePath.EndsWith(".les", StringComparison.OrdinalIgnoreCase))
					c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude.Les"));
						
				Configure(c);
				_requestedExtension = c.OutExt;
				c.Run();

				// Report errors
				foreach (var msg in sink.List)
					ReportErrorToVS(progressCallback, msg.Severity, msg.Context, msg.Format, msg.Args);

				return Encoding.UTF8.GetBytes(c.Output.ToString());
			} finally {
				Environment.CurrentDirectory = oldCurDir;
			}
		}
예제 #41
0
		public void SetUp() {
			MessageSink.Current = new SeverityMessageFilter(MessageSink.Console, Severity.Debug);
			_msgHolder = new MessageHolder();
		}
        public void Enqueue(byte[] body, LinkMessageProperties properties, LinkRecieveMessageProperties recieveProperties, LinkMessageOnAckAsyncDelegate onAck,
            LinkMessageOnNackAsyncDelegate onNack)
        {
            if (_disposedCancellation.IsCancellationRequested)
                throw new ObjectDisposedException(GetType().Name);

            var cancellation = _messageCancellation;

            try
            {
                var message = new LinkMessage<byte[]>(body, properties, recieveProperties, onAck, onNack, cancellation);
                var holder = new MessageHolder(message, cancellation);
                _messageQueue.Enqueue(holder, cancellation);
            }
            catch (InvalidOperationException)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
        }
예제 #43
0
		public void SetUp() {
			// Block verbose messages
			MessageSink.SetDefault(new SeverityMessageFilter(ConsoleMessageSink.Value, Severity.DebugDetail));
			_msgHolder = new MessageHolder();
		}
예제 #44
0
		protected override MessageHolder Test(Mode mode, int errorsExpected, string str, params LNode[] expected)
		{
			var messages = new MessageHolder();
			var results = LesLanguageService.Value.Parse(str, messages, mode == Mode.Expr ? ParsingService.Exprs : ParsingService.Stmts).ToList();
			for (int i = 0; i < expected.Length; i++)
				AreEqual(expected[i], results[i]);
			AreEqual(expected.Length, results.Count);
			if (messages.List.Count != System.Math.Max(errorsExpected, 0))
			{
				messages.WriteListTo(MessageSink.Console);
				AreEqual(errorsExpected, messages.List.Count); // fail
			}
			return messages;
		}
예제 #45
0
파일: UG.cs 프로젝트: qwertie/ecsharp
		public void TestProcessCommandLineArguments2()
		{
			// Generate two options files, where the first refers to the second
			string atFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
			string file1 = "test ProcessCmdLine 1.txt";
			string file2 = "test ProcessCmdLine 2.txt";
			StreamWriter w = new StreamWriter(Path.Combine(atFolder, file1));
			w.WriteLine("\"@"+file2+"\" fox--jumps\n--over");
			w.Close();
			w = new StreamWriter(Path.Combine(atFolder, file2));
			w.WriteLine("these arguments are ignored (arg limit exceeded)");
			w.Close();

			// Expand command line and ensure that the arg limit is enforced
			List<string> args = G.SplitCommandLineArguments("\"@"+file1+"\" \"lazy dog\"");
			var options = new DList<KeyValuePair<string, string>>();
			var msgs = new MessageHolder();
			using (MessageSink.SetDefault(msgs))
				UG.ProcessCommandLineArguments(args, options, atFolder, null, null, 5);

			ExpectList(args.AsListSource(), "@"+file1, "@"+file2, "fox--jumps", "lazy dog");
			ExpectList(options, P("over", null));
			ExpectList(msgs.List.Select(msg => msg.ToString()).AsListSource(),
				"@test ProcessCmdLine 2.txt: Warning: Limit of 5 commands exceeded");
		}
예제 #46
0
		private void Test(string input, string expectOutput, int expectMessages = 0, Severity expectSev = 0)
		{
			// Install token-to-string stategy to aid debugging
			using (G.PushTLV(Token.ToStringStrategyTLV, t => (t.Value ?? ((CalcTokenType)t.TypeInt).ToString()).ToString())) {
				MessageHolder errorList;
				var input2 = StripInitialNewline(input);
				var lexer = new CalculatorLexer(input2) { ErrorSink = errorList = new MessageHolder() };
				var wrapr = new IndentTokenGenerator(lexer, allIndTrig, new Token((int)CalcTokenType.Semicolon, 0, 0, null)) {
					EolIndentTriggers = eolIndTrig, 
					IndentToken = new Token((int)CalcTokenType.LBrace, 0, 0, null),
					DedentToken = new Token((int)CalcTokenType.RBrace, 0, 0, null),
				};
				var output = new DList<Token>();
				for (var t = wrapr.NextToken(); t.HasValue; t = wrapr.NextToken())
					output.Add(t.Value);
				var expectTokens = new CalculatorLexer(expectOutput).Buffered().ToList();
				
				AreEqual(expectMessages, errorList.List.Count);
				if (expectMessages > 0)
					AreEqual(expectSev, errorList.List.Max(m => m.Severity));
				ExpectList(output, expectTokens, false);
			}
		}
예제 #47
0
		protected override byte[] Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progressCallback)
		{
			string oldCurDir = Environment.CurrentDirectory;
			try {
				string inputFolder = Path.GetDirectoryName(inputFilePath);
 				Environment.CurrentDirectory = inputFolder; // --macros should be relative to file being processed

				var options = new BMultiMap<string, string>();
				var argList = G.SplitCommandLineArguments(defaultNamespace);
				UG.ProcessCommandLineArguments(argList, options, "", LeMP.Compiler.ShortOptions, LeMP.Compiler.TwoArgOptions);

				string _;
				var KnownOptions = LeMP.Compiler.KnownOptions;
				if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
					LeMP.Compiler.ShowHelp(KnownOptions);
				
				// Originally I wrote a conversion from IVsGeneratorProgress to
 				// IMessageSink so that errors could be reported immediately and
				// directly to Visual Studio. This broke in a bizarre way when I
				// added processing on a separate thread (in order to be able to
				// abort the thread if it runs too long); I got the following
				// InvalidCastException: "Unable to cast COM object of type 'System.__ComObject' 
				// to interface type 'Microsoft.VisualStudio.Shell.Interop.IVsGeneratorProgress'.
				// This operation failed because the QueryInterface call on the COM component for 
				// the interface with IID '{BED89B98-6EC9-43CB-B0A8-41D6E2D6669D}' failed due to 
				// the following error: No such interface supported (Exception from HRESULT: 
				// 0x80004002 (E_NOINTERFACE))."
				// 
				// A simple solution is to store the messages rather than reporting
				// them immediately. I'll report the errors at the very end.
				MessageHolder sink = new MessageHolder();
				
				var sourceFile = new InputOutput((UString)inputFileContents, Path.GetFileName(inputFilePath));

				var c = new Compiler(sink, sourceFile) { 
					AbortTimeout = TimeSpan.FromSeconds(10),
					Parallel = false // only one file, parallel doesn't help
				};

				if (LeMP.Compiler.ProcessArguments(c, options))
				{
					if (options.ContainsKey("no-out-header"))
					{
						options.Remove("no-out-header", 1);
						c.NoOutHeader = true;
					}
					LeMP.Compiler.WarnAboutUnknownOptions(options, sink, KnownOptions);
					if (c != null)
					{
						if (inputFilePath.EndsWith(".les", StringComparison.OrdinalIgnoreCase))
							c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude.Les"));
						Configure(c);
						c.Run();

						// Report errors
						foreach (var msg in sink.List)
							ReportErrorToVS(progressCallback, msg.Severity, msg.Context, msg.Format, msg.Args);

						return Encoding.UTF8.GetBytes(c.Output.ToString());
					}
				}
				return null;
			} finally {
				Environment.CurrentDirectory = oldCurDir;
			}
		}
예제 #48
0
		private void TestLes(string input, string expectOutput, int expectMessages = 0, Severity expectSev = 0)
		{
			using (G.PushTLV(Token.ToStringStrategyTLV, TokenExt.ToString))
			{
				MessageHolder errorList;
				var input2 = StripInitialNewline(input);
				var lexer = new LesLexer(input2, errorList = new MessageHolder());
				var wrapr = new LesIndentTokenGenerator(lexer);
				var output = new DList<Token>();
				for (var t = wrapr.NextToken(); t.HasValue; t = wrapr.NextToken())
					output.Add(t.Value);
				var expectTokens = new LesLexer(expectOutput, MessageSink.Console).Buffered().Select(t =>
					t.Type() == TokenType.LBrack ? t.WithType((int)TokenType.Indent) :
					t.Type() == TokenType.RBrack ? t.WithType((int)TokenType.Dedent) : t).ToList();

				AreEqual(expectMessages, errorList.List.Count);
				if (expectMessages > 0)
					AreEqual(expectSev, errorList.List.Max(m => m.Severity));
				ExpectList(output, expectTokens, false);
			}
		}