public void EmptySwitchStatement() { var stmt = ParseStatement <JsSwitchStatement>("switch(a) {}"); Assert.That(OutputFormatter.Format(stmt.Expression), Is.EqualTo("a")); Assert.That(stmt.Sections.Count, Is.EqualTo(0)); }
public void DoWhileStatement() { var stmt = ParseStatement <JsDoWhileStatement>("do { y; } while (x);"); Assert.That(OutputFormatter.Format(stmt.Condition), Is.EqualTo("x")); Assert.That(OutputFormatter.Format(stmt.Body).Replace("\r\n", "\n"), Is.EqualTo("{\n\ty;\n}\n")); }
public void WithStatement() { var stmt = ParseStatement <JsWithStatement>("with (x) { y; }"); Assert.That(OutputFormatter.Format(stmt.Object), Is.EqualTo("x")); Assert.That(OutputFormatter.Format(stmt.Body).Replace("\r\n", "\n"), Is.EqualTo("{\n\ty;\n}\n")); }
public override void Execute() { if (!(DataProvider.GetCharacters() is IList <BaseCharacter> characters)) { throw new ArgumentNullException("Karakter listesi bulunamadı."); } Console.Out.WriteLine(OutputFormatter.CharactersToString(characters)); int choice; var loop = true; do { Console.Out.Write("Bir karakter seç: "); var choiceStr = Console.In.ReadLine(); if (!int.TryParse(choiceStr, out choice) || choice < 1 || choice > characters.Count) { Console.Out.WriteLine("Hatalı giriş yaptınız tekrar deneyin."); } else { loop = false; } } while (loop); var character = characters[choice - 1]; var nextState = GetNextState(character); _manager.SetData(nextState, character); _manager.State = nextState; }
public static Tuple <string, MockErrorReporter> Compile(string source, bool expectErrors = false) { var sourceFile = new MockSourceFile("file.cs", source); var er = new MockErrorReporter(!expectErrors); var n = new Namer(); var references = new[] { Files.Mscorlib }; var compilation = PreparedCompilation.CreateCompilation(new[] { sourceFile }, references, null);; var md = new MetadataImporter(er, compilation.Compilation, new CompilerOptions()); var rtl = new CoreLib.Plugin.RuntimeLibrary(md, er, compilation.Compilation, n); md.Prepare(compilation.Compilation.GetAllTypeDefinitions()); var compiler = new Saltarelle.Compiler.Compiler.Compiler(md, n, rtl, er); var compiledTypes = compiler.Compile(compilation); if (expectErrors) { Assert.That(er.AllMessages, Is.Not.Empty, "Compile should have generated errors"); return(Tuple.Create((string)null, er)); } Assert.That(er.AllMessages, Is.Empty, "Compile should not generate errors"); var js = new OOPEmulator(compilation.Compilation, md, rtl, n, er).Process(compiledTypes, null); js = new Linker(md, n, compilation.Compilation).Process(js); string script = string.Join("", js.Select(s => OutputFormatter.Format(s, allowIntermediates: false))); return(Tuple.Create(script, er)); }
private void OutputWriter_Clear() { OutputFormatter.Clear(); OutputText = string.Empty; _outputParagraph.Inlines.Clear(); HasOutput = false; }
protected void AssertCorrect(string csharp, string expected, IMetadataImporter metadataImporter = null, bool useFirstConstructor = false) { Compile(csharp, metadataImporter, useFirstConstructor: useFirstConstructor); string actual = OutputFormatter.Format(CompiledConstructor, allowIntermediates: true); Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n"))); }
internal Tuple <string, ICompilation, IMetadataImporter, MockErrorReporter> Compile(string source, bool includeLinq = false, bool expectErrors = false) { var sourceFile = new MockSourceFile("file.cs", source); var md = new MetadataImporter.ScriptSharpMetadataImporter(false); var n = new DefaultNamer(); var er = new MockErrorReporter(!expectErrors); PreparedCompilation compilation = null; var rtl = new ScriptSharpRuntimeLibrary(md, er, n.GetTypeParameterName, tr => new JsTypeReferenceExpression(tr.Resolve(compilation.Compilation).GetDefinition())); var compiler = new Compiler.Compiler(md, n, rtl, er, allowUserDefinedStructs: false); var references = includeLinq ? new[] { Common.Mscorlib, Common.Linq } : new[] { Common.Mscorlib }; compilation = compiler.CreateCompilation(new[] { sourceFile }, references, null); var compiledTypes = compiler.Compile(compilation); if (expectErrors) { Assert.That(er.AllMessages, Is.Not.Empty, "Compile should have generated errors"); return(Tuple.Create((string)null, compilation.Compilation, (IMetadataImporter)md, er)); } er.AllMessagesText.Should().BeEmpty("Compile should not generate errors"); var js = new OOPEmulator.ScriptSharpOOPEmulator(compilation.Compilation, md, rtl, n, er).Process(compiledTypes, compilation.Compilation, null); js = new DefaultLinker(md, n).Process(js, compilation.Compilation.MainAssembly); string script = string.Join("", js.Select(s => OutputFormatter.Format(s, allowIntermediates: false))); if (Output == OutputType.GeneratedScript) { Console.WriteLine(script); } return(Tuple.Create(script, compilation.Compilation, (IMetadataImporter)md, er)); }
protected void AssertCorrect(string orig, string expected, MethodType methodType = MethodType.Normal) { int tempIndex = 0, stateIndex = 0, loopLabelIndex = 0; var stmt = JsBlockStatement.MakeBlock(JavaScriptParser.Parser.ParseStatement(orig)); JsBlockStatement result; if (methodType == MethodType.Iterator) { int finallyHandlerIndex = 0; result = StateMachineRewriter.RewriteIteratorBlock(stmt, e => e.NodeType != ExpressionNodeType.Identifier, () => "$tmp" + (++tempIndex).ToString(CultureInfo.InvariantCulture), () => "$state" + (++stateIndex).ToString(CultureInfo.InvariantCulture), () => string.Format("$loop" + (++loopLabelIndex).ToString(CultureInfo.InvariantCulture)), () => string.Format("$finally" + (++finallyHandlerIndex).ToString(CultureInfo.InvariantCulture)), v => JsExpression.Invocation(JsExpression.Identifier("setCurrent"), v), sm => { var body = new List <JsStatement>(); if (sm.Variables.Count > 0) { body.Add(new JsVariableDeclarationStatement(sm.Variables)); } body.AddRange(sm.FinallyHandlers.Select(h => new JsExpressionStatement(JsExpression.Assign(JsExpression.Identifier(h.Item1), h.Item2)))); if (sm.Disposer != null) { body.Add(new JsExpressionStatement(JsExpression.Assign(JsExpression.Identifier("dispose"), new JsFunctionDefinitionExpression(new string[0], sm.Disposer)))); } body.Add(sm.MainBlock); return(new JsBlockStatement(body)); }); } else if (methodType == MethodType.AsyncTask || methodType == MethodType.AsyncVoid) { result = StateMachineRewriter.RewriteAsyncMethod(stmt, e => e.NodeType != ExpressionNodeType.Identifier, () => "$tmp" + (++tempIndex).ToString(CultureInfo.InvariantCulture), () => "$state" + (++stateIndex).ToString(CultureInfo.InvariantCulture), () => string.Format("$loop" + (++loopLabelIndex).ToString(CultureInfo.InvariantCulture)), "$sm", "$doFinally", methodType == MethodType.AsyncTask ? new JsVariableDeclaration("$tcs", JsExpression.New(JsExpression.Identifier("TaskCompletionSource"))) : null, expr => { if (methodType != MethodType.AsyncTask) { throw new InvalidOperationException("Should not set result in async void method"); } return(JsExpression.Invocation(JsExpression.Member(JsExpression.Identifier("$tcs"), "setResult"), expr ?? JsExpression.String("<<null>>"))); }, expr => { if (methodType != MethodType.AsyncTask) { throw new InvalidOperationException("Should not set exception in async void method"); } return(JsExpression.Invocation(JsExpression.Member(JsExpression.Identifier("$tcs"), "setException"), expr)); }, () => { if (methodType != MethodType.AsyncTask) { throw new InvalidOperationException("Should not get task async void method"); } return(JsExpression.Invocation(JsExpression.Member(JsExpression.Identifier("$tcs"), "getTask"))); }, (sm, ctx) => JsExpression.Invocation(JsExpression.Identifier("$Bind"), sm, ctx)); } else { result = StateMachineRewriter.RewriteNormalMethod(stmt, e => e.NodeType != ExpressionNodeType.Identifier, () => "$tmp" + (++tempIndex).ToString(CultureInfo.InvariantCulture), () => "$state" + (++stateIndex).ToString(CultureInfo.InvariantCulture), () => string.Format("$loop" + (++loopLabelIndex).ToString(CultureInfo.InvariantCulture))); } var actual = OutputFormatter.Format(result); Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")), "Expected:\n" + expected + "\n\nActual:\n" + actual); }
public FuncMetric(string keyName, TValue initialValue, Func <T, TValue, TValue> metricFunc, OutputFormatter formatter) { ColumnNames = new[] { keyName }; _value = initialValue; _initialValue = initialValue; _metricFunc = metricFunc; _outputFormatter = formatter; }
private string GenerateOutput() { var solution = DTETransformer.BuildDteSolution(this.Types.ToArray()); var generator = new CodeTraverser(solution, this.Settings); var data = generator.GetAllInterfaces().ToList(); return(OutputFormatter.GetOutput(data, this.Settings)); }
public void Program() { var stmts = JavaScriptParser.Parser.ParseProgram("x;y;"); Assert.That(stmts.Count, Is.EqualTo(2)); Assert.That(OutputFormatter.Format(stmts[0]).Replace("\r\n", "\n"), Is.EqualTo("x;\n")); Assert.That(OutputFormatter.Format(stmts[1]).Replace("\r\n", "\n"), Is.EqualTo("y;\n")); }
private void AssertCorrect(IList <JsType> types, string expected, IOOPEmulator emulator, IMethod entryPoint) { var invoker = new OOPEmulatorInvoker(emulator, new MockMetadataImporter(), new MockErrorReporter()); var result = invoker.Process(types, entryPoint); var actual = OutputFormatter.Format(result, allowIntermediates: true).Replace("\r\n", "\n"); Assert.That(actual, Is.EqualTo(expected.Replace("\r\n", "\n"))); }
public void TheTypesStaticInitStatementsAreReturnedAsTheStaticInitStatementsForNormalTypes() { var compilation = Compile(@"class C { static C() { int x = 0; int y = 1; } }"); var statements = compilation.Item2.GetStaticInitStatements((JsClass)compilation.Item3.Single()); var actual = OutputFormatter.Format(statements, allowIntermediates: true); Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo("(function() {\n\tvar x = 0;\n\tvar y = 1;\n})();\n")); }
public void Should_Return_Collection_of_Output_Lines() { var outputFormatter = new OutputFormatter(); var formattedOutput = outputFormatter.Format(_generatedPrimes); Assert.That(formattedOutput, Is.Not.Empty); }
public void Collection_of_Output_Lines_is_Returned() { var outputFormatter = new OutputFormatter(); IList <string> formattedOutput = outputFormatter.Format(_generatedPrimes); Assert.IsAssignableFrom(typeof(List <string>), formattedOutput); }
private void OutputWriter_OutputWritten(string text) { var formattedOutput = OutputFormatter.Format(text, _writer.ForegroundColor, OutputColorMappings); OutputText += formattedOutput.Text; _outputParagraph.Inlines.AddRange(formattedOutput.Inlines); HasOutput = true; }
/// <summary> /// SMHelp class constructor, populate commandsList /// </summary> public SMHelp(string UserId) { this.commandList = this.GetCommandsList(); this.character = new SlackMud().GetCharacter(UserId); this.outputFormatter = OutputFormatterFactory.Get(); }
public void SwitchStatementWithEmptyClause() { var stmt = ParseStatement <JsSwitchStatement>("switch(a) { case b: }"); Assert.That(OutputFormatter.Format(stmt.Expression), Is.EqualTo("a")); Assert.That(stmt.Sections.Count, Is.EqualTo(1)); Assert.That(stmt.Sections[0].Values.Select(v => OutputFormatter.Format(v)), Is.EqualTo(new[] { "b" })); Assert.That(stmt.Sections[0].Body.Statements.Count, Is.EqualTo(0)); }
public void ReturnStatement() { var stmt = ParseStatement <JsReturnStatement>("return;"); Assert.That(stmt.Value, Is.Null); stmt = ParseStatement <JsReturnStatement>("return x;"); Assert.That(OutputFormatter.Format(stmt.Value), Is.EqualTo("x")); }
public async Task FormatOutputText_ReturnsFormattedText(string path) { // arrange var service = new OutputFormatter(); var storageCollection = new List <Storage>() { new Storage() { Id = "testId1", Materials = new List <Material>() { new Material() { Id = "materialId1", Name = "materialName1", Quantity = 12 } } }, new Storage() { Id = "testId2", Materials = new List <Material>() { new Material() { Id = "materialId2", Name = "materialName1", Quantity = 5 } } }, new Storage() { Id = "testId3", Materials = new List <Material>() { new Material() { Id = "materialId3", Name = "materialName3", Quantity = 7 } } } }; var expected = await FileReadeHelper.ReadFromFileAsync(path); // act var actual = service.FormatOutputText(storageCollection); // assert Assert.IsNotNull(actual); Assert.AreEqual(expected, actual); }
/// <summary> /// Writes the event. /// </summary> /// <param name="properties">The properties.</param> /// <param name="metrics">The metrics.</param> /// <returns>Task.</returns> public override Task WriteEventAsync(Dictionary <string, string> properties, Dictionary <string, double> metrics = null) { if (_configuration.Handles(TelemetryTypes.CustomEvents)) { Debug.WriteLine(OutputFormatter.FormatEvent(properties, metrics)); } return(Task.Delay(0)); }
public void CreateOutputContentTest2() { var productIncrementalValue1 = CreateProductIncrementalValue("Comp", 1992, 1992, 110.0); var productIncrementalValue2 = CreateProductIncrementalValue("COMP", 1992, 1993, 170.0); var productIncrementalValue3 = CreateProductIncrementalValue("ComP", 1993, 1993, 200.0); var productIncrementalValue4 = CreateProductIncrementalValue("Non - Comp", 1990, 1990, 45.2); var productIncrementalValue5 = CreateProductIncrementalValue("NON - Comp", 1990, 1991, 64.8); var productIncrementalValue6 = CreateProductIncrementalValue("Non - Comp", 1990, 1993, 37.0); var productIncrementalValue7 = CreateProductIncrementalValue("Non - CoMp", 1991, 1991, 50.0); var productIncrementalValue8 = CreateProductIncrementalValue("Non - ComP", 1991, 1992, 75.0); var productIncrementalValue9 = CreateProductIncrementalValue("NoN - Comp", 1991, 1993, 25.0); var productIncrementalValue10 = CreateProductIncrementalValue("Non - COMp", 1992, 1992, 55.0); var productIncrementalValue11 = CreateProductIncrementalValue("Non - Comp", 1992, 1993, 85.0); var productIncrementalValue12 = CreateProductIncrementalValue("Non - Comp", 1993, 1993, 100.0); var productIncrementValues = new List <ProductIncrementalValue>() { productIncrementalValue1, productIncrementalValue2, productIncrementalValue3, productIncrementalValue4, productIncrementalValue5, productIncrementalValue6, productIncrementalValue7, productIncrementalValue8, productIncrementalValue9, productIncrementalValue10, productIncrementalValue11, productIncrementalValue12 }; var mockedCumulativeDataCalculator = new Mock <ICumulativeDataCalculator>(); mockedCumulativeDataCalculator.Setup(x => x.Calculate(It.Is <Product>(p => p.ProductName == "comp"))) .Returns(new List <double>() { 0, 0, 0, 0, 0, 0, 0, 110, 280, 200 }); mockedCumulativeDataCalculator.Setup(x => x.Calculate(It.Is <Product>(p => p.ProductName == "non - comp"))) .Returns(new List <double>() { 45.2, 110, 110, 147, 50, 125, 150, 55, 140, 100 }); IList <string> expectedOutputList = new List <string>(); expectedOutputList.Add("1990,4"); expectedOutputList.Add("comp,0,0,0,0,0,0,0,110,280,200"); expectedOutputList.Add("non - comp,45.2,110,110,147,50,125,150,55,140,100"); var outputFormatter = new OutputFormatter(mockedCumulativeDataCalculator.Object); CollectionAssert.AreEqual(expectedOutputList, outputFormatter.CreateOutputContent(productIncrementValues)); }
private string Process(IList <JsStatement> stmts, IAssembly mainAssembly, IMetadataImporter metadata = null, INamer namer = null) { var compilation = new Mock <ICompilation>(); compilation.SetupGet(_ => _.MainAssembly).Returns(mainAssembly); var obj = new Linker(metadata ?? new MockMetadataImporter(), namer ?? new MockNamer(), compilation.Object); var processed = obj.Process(stmts); return(string.Join("", processed.Select(s => OutputFormatter.Format(s, allowIntermediates: false)))); }
public void TestOutputSubClasses() { var settings = new Settings { UseNativeDates = "Date" }; string res = OutputFormatter.GetOutput(GetDataToRenderSubClasses(settings), settings); Console.WriteLine(res); Assert.AreEqual(ExpectedSubClassesResult, res); }
public void TestInheritedGeneric() { var settings = new Settings { UseNativeDates = "Date", ProcessDataContracts = true }; string res = OutputFormatter.GetOutput(GetInheritedGenericDataToRender(settings), settings); Console.WriteLine(res); Assert.AreEqual(ExpectedInheritedGenericResult, res); }
private void OutputWriter_Clear() { this.Dispatcher.Invoke(new Action(() => { OutputFormatter.Clear(); OutputText = string.Empty; _outputParagraph.Inlines.Clear(); HasOutput = false; })); }
private void OutputWriter_OutputWritten(string text) { this.Dispatcher.Invoke(new Action(() => { var formattedOutput = OutputFormatter.Format(text, _writer.ForegroundColor, OutputColorMappings); OutputText += formattedOutput.Text; _outputParagraph.Inlines.AddRange(formattedOutput.Inlines); HasOutput = true; })); }
/// <summary> /// write event as an asynchronous operation. /// </summary> /// <param name="eventProperties">The event properties.</param> /// <param name="eventMetrics">The event metrics.</param> /// <returns>Task.</returns> public override async Task WriteEventAsync(Dictionary <string, string> eventProperties, Dictionary <string, double> eventMetrics = null) { if (_configuration.Handles(TelemetryTypes.CustomEvents)) { await Task.Run(async() => { await AppendToBlob(OutputFormatter.FormatEvent(eventProperties, eventMetrics)); }); } }
public void Register(Version fromInclusive, Version toExclusive, OutputFormatter formatter) { var range = new VersionRange(fromInclusive, toExclusive); if (_formatters.Any(f => f.Item1.IsOverlapping(range)) == true) { throw new ArgumentException("Version ranges must not overlap."); } _formatters.Add(new Tuple <VersionRange, OutputFormatter>(range, formatter)); }
/// <summary> /// write event as an asynchronous operation. /// </summary> /// <param name="properties">The properties.</param> /// <param name="metrics">The metrics.</param> /// <returns>Task.</returns> public override async Task WriteEventAsync(Dictionary <string, string> properties, Dictionary <string, double> metrics = null) { if (_configuration.Handles(TelemetryTypes.CustomEvents)) { await Task.Run(() => { ThreadsafeWriteToFile(OutputFormatter.FormatEvent(properties, metrics)); }); } }
public void Should_Contains_Count_For_Every_Tenth_Line() { var generatedPrimes = new PrimeGenerator(new PrimeEvaluationEngine()).GeneratePrimesUpTo(2000); var outputFormatter = new OutputFormatter(); var formattedOutput = outputFormatter.Format(generatedPrimes); for (var i = 10; i < formattedOutput.Count; i += 11) { Assert.That(formattedOutput[i].Contains("Count:")); } }
public void Should_Have_No_More_Than_Five_Items_For_Each_Output_Line() { var outputFormatter = new OutputFormatter(); var formattedOutput = outputFormatter.Format(_generatedPrimes); string[] splitPrimes; foreach (var item in formattedOutput) { splitPrimes = item.Split(",".ToCharArray()); Assert.That(splitPrimes.Length, Is.LessThanOrEqualTo(5)); } }
public static void Run() { var ip = IPAddress.Any; int port = 5000; var thread = new UvThread(); var listener = new UvTcpListener(thread, new IPEndPoint(ip, port)); listener.OnConnection(async connection => { var httpParser = new HttpRequestParser(); while (true) { // Wait for data var result = await connection.Input.ReadAsync(); var input = result.Buffer; try { if (input.IsEmpty && result.IsCompleted) { // No more data break; } // Parse the input http request var parseResult = httpParser.ParseRequest(ref input); switch (parseResult) { case HttpRequestParser.ParseResult.Incomplete: if (result.IsCompleted) { // Didn't get the whole request and the connection ended throw new EndOfStreamException(); } // Need more data continue; case HttpRequestParser.ParseResult.Complete: break; case HttpRequestParser.ParseResult.BadRequest: throw new Exception(); default: break; } // Writing directly to pooled buffers var output = connection.Output.Alloc(); var formatter = new OutputFormatter<WritableBuffer>(output, EncodingData.InvariantUtf8); formatter.Append("HTTP/1.1 200 OK"); formatter.Append("\r\nContent-Length: 13"); formatter.Append("\r\nContent-Type: text/plain"); formatter.Append("\r\n\r\n"); formatter.Append("Hello, World!"); await output.FlushAsync(); httpParser.Reset(); } finally { // Consume the input connection.Input.Advance(input.Start, input.End); } } }); listener.StartAsync().GetAwaiter().GetResult(); Console.WriteLine($"Listening on {ip} on port {port}"); var wh = new ManualResetEventSlim(); Console.CancelKeyPress += (sender, e) => { wh.Set(); }; wh.Wait(); listener.Dispose(); thread.Dispose(); }