コード例 #1
0
        public async Task <IActionResult> BuildJar([FromBody] CompileRequest request)
        {
            try
            {
                var bytes = await _service.BuildJarFromGit(request.GitPath);

                bytes = await _obfuscation.Obfuscate(new ObfuscateRequest
                {
                    Bytes  = bytes,
                    Config = request.ObfuscateConfig
                });

                return(File(bytes, "application/java-archive", "result.jar"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                var split = e.Message.Split("@@");
                return(BadRequest(JsonConvert.SerializeObject(new
                {
                    Logs = split[0],
                    Errors = split.Length > 1 ? split[1] : string.Empty
                })));
            }
        }
コード例 #2
0
        public async Task <CompiledScript> Handle(CompileScriptCommand request, CancellationToken cancellationToken)
        {
            var config = await _mediator.Send(new GetFileQuery { Name = "script-obfuscate-config.xml" }, cancellationToken);

            var compileRequest = new CompileRequest
            {
                GitPath         = request.GitlabUrl,
                ObfuscateConfig = Encoding.Default.GetString(config),
                Game            = request.Game
            };

            var res = await _client.PostAsync("/api/git/buildJar", new StringContent(
                                                  JsonSerializer.Serialize(compileRequest), Encoding.Default, "application/json"),
                                              cancellationToken);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                var error = await res.Content.ReadAsStringAsync();

                var result = JsonSerializer.Deserialize <CompileResult>(error);
                throw new CompileException(result);
            }

            var bytes = await res.Content.ReadAsByteArrayAsync();

            if (bytes.Length == 0)
            {
                throw new Exception("Failed to compile script by url: " + request.GitlabUrl);
            }

            return(new CompiledScript
            {
                Content = bytes
            });
        }
コード例 #3
0
        /// <summary>
        /// Compiles the given TypeScript source into pure JavaScript.
        /// </summary>
        /// <param name="source">The typescript source code to be compiled.</param>
        /// <param name="fileName">The filename that represents this source code.</param>
        /// <param name="options">The options to use when compiling.</param>
        /// <returns>The results of the compilation.</returns>
        public virtual CompiledModule Compile(string source, string fileName, CompileOptions options)
        {
            //
            // Generate the compilation request.
            //
            var request = new CompileRequest
            {
                SourceCode = source,
                FileName   = fileName,
                Options    = options
            };

            //
            // Make sure the queue is running and submit the new request to the queue.
            //
            EnsureWorkerThreadRunning();
            _sharedQueue.Enqueue(request);
            _sharedQueueEvent.Set();

            //
            // Wait for up to 30 seconds for the compilation to complete.
            //
            if (!request.WaitHandle.WaitOne(30000))
            {
                return(new CompiledModule
                {
                    FileName = fileName,
                    Success = false,
                    Messages = new[] { "Timeout waiting for compilation to complete." }
                });
            }

            return(request.CompiledModule);
        }
コード例 #4
0
        public IHttpActionResult PostCompile(CompileRequest request)
        {
            var source            = new Source(request.Code, request.Dependencies);
            var compilationResult = _compilationService.Compile(source);

            // Return an error response if compile was unsuccessful, otherwise the response was successful.
            return(Content(compilationResult.Success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, compilationResult));
        }
コード例 #5
0
        /// <summary>
        ///     Compiles the specified code and returns errors.
        /// </summary>
        /// <param name="req">The request</param>
        public IEnumerable<FSharpErrorInfo> Post(CompileRequest req)
        {
            // short circuit bad requests
            if (string.IsNullOrEmpty(req.Source))
            {
                return new List<FSharpErrorInfo>();
            }

            var c = WebApiApplication.Compiler.TypeCheck(req.Source, "/home/test.fsx");
            return c.Check.Errors;
        }
コード例 #6
0
 public CompileResponse CompileCode(CompileRequest request)
 {
     try
     {
         return(CompileResponse.ForSuccess(Executor.ExecuteSnippet(request.Snippet)));
     }
     catch (DynamicCompilationException e)
     {
         return(CompileResponse.ForError(e));
     }
 }
コード例 #7
0
        public async Task <CompileResult> Compile(CompileRequest request)
        {
            const string uri      = "/compile";
            var          response = await _http.PostAsJsonAsync(uri, request);

            if (response.IsSuccessStatusCode == false)
            {
                throw new BadRequestException(uri, response.StatusCode, await response.Content.ReadAsStringAsync());
            }

            var result = await response.Content.ReadFromJsonAsync <CompileResult>();

            return(result !);
        }
コード例 #8
0
        private static Request Map(CompileRequest code)
        {
            if (SupportedLanguages.TryGetValue(code.Language, out var language))
            {
                return(new Request
                {
                    LanguageChoice = language,
                    Input = code.Input,
                    CompilerArgs = code.CompilerArgs,
                    Program = code.Code
                });
            }

            throw new NotSupportedException($"{code.Language} is not supported by {ApiUrl}");
        }
コード例 #9
0
        public CompileResponse Compile(CompileRequest request)
        {
            var configuration = request.ModuleCompileTimeServices.Configuration;
            var container = request.ModuleCompileTimeServices.Container;
            var compiler = container
                .RoslynCompiler()
                .WithCodeLogging(configuration.Compiler.Logging.IsEnableCode)
                .WithCodeAuditDirectory(configuration.Compiler.Logging.AuditDirectory)
                .WithSources(
                    request.Classes
                        .Select(_ => new RoslynCompiler.SourceBasic(_.ClassName, _.Code))
                        .ToList<RoslynCompiler.Source>());

            return new CompileResponse(
                request,
                compiler.Compile());
        }
コード例 #10
0
        public async Task <CompileResult> RunCode(CompileRequest code)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, ApiUrl)
            {
                Content = Serialize(Map(code))
            };

            using var response = await HttpClient.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"RepDesk API throw exception with code {response.StatusCode}: {response.ReasonPhrase}");
            }

            //to avoid too many requests
            await Task.Delay(1000);

            var deserializedResponse = await DeserializeAsync <Response>(response.Content);

            return(Map(deserializedResponse));
        }
コード例 #11
0
        public Task <CompileResult> RunCode(CompileRequest code)
        {
            // define source code, then parse it (to the type used for compilation)
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
                using System;

                namespace RoslynCompileSample
                {
                    public class Writer
                    {
                        public void Write(string message)
                        {
                            Console.WriteLine(message);
                        }
                    }
                }");

            // define other necessary objects for compilation
            string assemblyName = Path.GetRandomFileName();

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            // analyse and generate IL code from syntax tree
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                // write IL code into memory
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    // handle exceptions
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }
                }
                else
                {
                    // load this 'virtual' DLL so that we can use
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    // create instance of the desired class and call the desired function
                    Type   type = assembly.GetType("RoslynCompileSample.Writer");
                    object obj  = Activator.CreateInstance(type);
                    type.InvokeMember("Write",
                                      BindingFlags.Default | BindingFlags.InvokeMethod,
                                      null,
                                      obj,
                                      new object[] { "Hello World" });
                }
            }

            return(Task.FromResult(new CompileResult()));
        }