private static object CreateGenericDelegatesForFunction(InstanceGenerator instanceGenerator, MethodInfo methodInfo, GenerationRequest request) { var fullSignatureTypes = ReturnTypeOf(methodInfo).Concat(ParameterTypes(methodInfo)); return(CreateGenericDelegatesObjectForConcreteTypes(fullSignatureTypes, WithArgumentGeneratedBy(instanceGenerator, methodInfo, request))); }
public async Task <FileStreamResult> GetFromUrl(string outputfile, string template) { using (_logger.BeginScope("Generate Direct " + template)) { var data = new GenerationRequest() { Template = new GenerationTemplateData() { Url = template }, Output = new GenerationOutputData() { FileName = outputfile } }; _logger.LogInformation("Beginning Document Creation"); var result = await InvokeCreation(data); result.Flush(); result.Position = 0; _logger.LogInformation("Completed Document Creation"); return(new FileStreamResult(result, "application/pdf")); } }
public object?Dummy(GenerationRequest request, Type type) { var smartType = SmartType.For(type); if (type.IsPrimitive) { return(_unconstrainedChain.Resolve(this, request, type)); } if (type == typeof(string)) { return(_unconstrainedChain.Resolve(this, request, type)); } var emptyCollectionInstantiation = new EmptyCollectionInstantiation(); if (smartType.IsImplementationOfOpenGeneric(typeof(IEnumerable <>))) { return(emptyCollectionInstantiation.CreateCollectionPassedAsGenericType(type)); } if (smartType.IsOpenGeneric(typeof(IEnumerable <>))) { return(emptyCollectionInstantiation.EmptyEnumerableOf(type.GetCollectionItemType())); } if (type.IsAbstract) { return(default);
public object GenerateCustomizedInstance(InstanceGenerator instanceGenerator, GenerationRequest request, Type type) { var generateInstance = GenerateInstance(instanceGenerator, request, type); CustomizeCreatedValue(generateInstance, instanceGenerator, request, type); return(generateInstance); }
internal static string[] GetCommandLineArguments(GenerationRequest req, out string currentDirectory, out string tempDirectory, out string libDirectory) { currentDirectory = null; libDirectory = null; tempDirectory = null; List <string> commandLineArguments = new List <string>(); foreach (GenerationRequest.Argument arg in req.Arguments) { if (arg.ArgumentId == GenerationProtocolConstants.ArgumentId.CurrentDirectory) { currentDirectory = arg.Value; } else if (arg.ArgumentId == GenerationProtocolConstants.ArgumentId.TempDirectory) { tempDirectory = arg.Value; } else if (arg.ArgumentId == GenerationProtocolConstants.ArgumentId.CommandLineArgument) { int argIndex = arg.ArgumentIndex; while (argIndex >= commandLineArguments.Count) { commandLineArguments.Add(""); } commandLineArguments[argIndex] = arg.Value; } } return(commandLineArguments.ToArray()); }
public string GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { var preprocessedStrings = from str in _excludedSubstrings where !string.IsNullOrEmpty(str) select str; var result = _stringGenerator.GenerateInstance(instanceGenerator, request); var found = false; for (int i = 0; i < 100; ++i) { result = _stringGenerator.GenerateInstance(instanceGenerator, request); if (!preprocessedStrings.Any(result.Contains)) { found = true; break; } } if (!found) { foreach (var excludedSubstring in _excludedSubstrings.Where(s => s != string.Empty)) { result = result.Replace(excludedSubstring, ""); } } return(result); }
public object Instance(Type type, GenerationRequest request) { return(request.GenerationCustomizations.Where(c => c.AppliesTo(type)).FirstMaybe() .SelectOrElse( c => c.Generate(type, this, request), () => _inner.Instance(type, request, request.GenerationCustomizations))); }
protected string GetCacheName(GenerationRequest request, HttpContext context, string extension) { if (request.LayerName.Contains(".") || request.LayerName.Contains("/")) { throw new HttpException("Layer name is not valid."); } var cacheComponents = new string[] { "~", "App_Cache", "api-v1", request.LayerName, request.Seed.ToString(), request.X.ToString(), request.Y.ToString(), request.Z.ToString(), request.Size.ToString(), "get" + (request.AsSquare ? "_square" : "") + (request.Packed ? "_packed" : "") + "." + extension }; for (var i = 0; i < cacheComponents.Length - 1; i++) { var path = context.Server.MapPath(cacheComponents.Where((x, id) => id <= i).Aggregate((a, b) => a + "/" + b)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } return(context.Server.MapPath(cacheComponents.Aggregate((a, b) => a + "/" + b))); }
public object NewInstanceOf(Type type, InstanceGenerator instanceGenerator, GenerationRequest request) { var typeInfo = type.GetTypeInfo(); var type1 = typeInfo.GetGenericArguments()[0]; var type2 = typeInfo.GetGenericArguments()[1]; return(_factoryMethod.Invoke(type1, type2, instanceGenerator, request)); }
protected override void ValidateGenerationRequest(GenerationRequest request) { // Now that we've read data from the stream we can validate the identity. if (!ClientAndOurIdentitiesMatch(_pipeStream)) { throw new Exception("Client identity does not match server identity."); } }
/// <summary> /// Try to compile using the server. Returns a null-containing Task if a response /// from the server cannot be retrieved. /// </summary> private static async Task <GenerationResponse> TryGeneration(NamedPipeClientStream pipeStream, GenerationRequest request, CancellationToken cancellationToken) { GenerationResponse response; using (pipeStream) { // Write the request try { _log.Debug("Begin writing request"); await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false); _log.Debug("End writing request"); } catch (Exception e) { _log.Error($"Error writing build request. {e.Message}", e); return(new RejectedGenerationResponse()); } // Wait for the compilation and a monitor to detect if the server disconnects var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); _log.Debug("Begin reading response"); var responseTask = GenerationResponse.ReadAsync(pipeStream, serverCts.Token); var monitorTask = CreateMonitorDisconnectTask(pipeStream, "client", serverCts.Token); await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false); _log.Debug("End reading response"); if (responseTask.IsCompleted) { // await the task to log any exceptions try { response = await responseTask.ConfigureAwait(false); } catch (Exception e) { _log.Error("Error reading response", e); response = new RejectedGenerationResponse(); } } else { _log.Debug("Server disconnect"); response = new RejectedGenerationResponse(); } // Cancel whatever task is still around serverCts.Cancel(); Debug.Assert(response != null); return(response); } }
public AbstractClassInterceptor( CachedReturnValueGeneration cachedGeneration, Func <Type, GenerationRequest, object> instanceSource, GenerationRequest request) { _cachedGeneration = cachedGeneration; _instanceSource = instanceSource; _request = request; }
public object Apply(InstanceGenerator instanceGenerator, GenerationRequest request, Type type) { //todo think it through - should it need access to InlineGenerators? var elementType = type.GetElementType(); var array = InlineGenerators.GetByNameAndType(nameof(InlineGenerators.Array), elementType) .GenerateInstance(instanceGenerator, request); return(array); }
public void Generate(GenerationRequest request) { Creator.CreateDirectory(request.FolderOfResults); for (int i = 0; i < request.NumberOfFiles; i++) { CreateFile(GetPathToFile(request, i), request.NumberOfInts); } }
public static ICollection <T> AddTo <T>(ICollection <T> collection, int many, InstanceGenerator instanceGenerator, GenerationRequest request) { for (int i = 0; i < many; ++i) { collection.Add(instanceGenerator.Instance <T>(request)); } return(collection); }
private T WithCustomizations <T>( InstanceGenerator gen, GenerationRequest request, Func <FixtureWrapper, T> creation) { using (_generator.Customize(request, gen)) { return(creation.Invoke(_generator)); } }
internal static RunRequest GetRunRequest(GenerationRequest req) { string currentDirectory; string libDirectory; string tempDirectory; string[] arguments = GetCommandLineArguments(req, out currentDirectory, out tempDirectory, out libDirectory); return(new RunRequest(currentDirectory, tempDirectory, arguments)); }
public object Apply(InstanceGenerator instanceGenerator, GenerationRequest request, Type type) { var resultType = type.GenericTypeArguments.First(); var parameters = instanceGenerator.Instance(resultType, request); var result = new GenericMethodProxyCalls().ResultOfGenericVersionOfStaticMethod <Task>( type.GenericTypeArguments.First(), "FromResult", parameters); return(result); }
public IEnumerable <T> GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { var list = new List <T>(); list.Add(instanceGenerator.Instance <T>(request)); list.AddRange(_included); list.Add(instanceGenerator.Instance <T>(request)); return(list); }
public string GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { var result = string.Empty; while (result.Length < _length) { result += _stringGenerator.GenerateInstance(instanceGenerator, request); } return(result.Substring(0, _length)); }
public T GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { if (typeof(T).IsInterface) { return(ProxyGenerator.CreateInterfaceProxyWithoutTarget <T>(new ExplodingInterceptor())); } else { throw new Exception("Exploding instances can be created out of interfaces only!"); } }
public string GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { var result = string.Empty; for (var i = 0; i < _maxLength; ++i) { result += _charGenerator.GenerateInstance(instanceGenerator, request); } return(result); }
public byte GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { byte digit = _digitGenerator.GenerateInstance(instanceGenerator, request); while (digit == 0) { digit = _digitGenerator.GenerateInstance(instanceGenerator, request); } return(digit); }
public async Task Generate_ReturnsOk_IfRequestIsCorrect() { var request = new GenerationRequest { DinosaursCount = 1, SpeciesCount = 1, }; var result = await _api.Generate <string>(request); Assert.AreEqual(result.StatusCode, HttpStatusCode.OK); }
/// <summary> /// Shutting down the server is an inherently racy operation. The server can be started or stopped by /// external parties at any time. /// /// This function will return success if at any time in the function the server is determined to no longer /// be running. /// </summary> internal async Task <int> RunShutdownAsync(string pipeName, bool waitForProcess = true, TimeSpan?timeout = null, CancellationToken cancellationToken = default(CancellationToken)) { if (WasServerRunning(pipeName) == false) { // The server holds the mutex whenever it is running, if it's not open then the // server simply isn't running. return(CommonGenerator.Succeeded); } try { var realTimeout = timeout != null ? (int)timeout.Value.TotalMilliseconds : Timeout.Infinite; using (var client = await ConnectForShutdownAsync(pipeName, realTimeout).ConfigureAwait(false)) { var request = GenerationRequest.CreateShutdown(); await request.WriteAsync(client, cancellationToken).ConfigureAwait(false); var response = await GenerationResponse.ReadAsync(client, cancellationToken).ConfigureAwait(false); var shutdownResponse = (ShutdownGenerationResponse)response; if (waitForProcess) { try { var process = Process.GetProcessById(shutdownResponse.ServerProcessId); process.WaitForExit(); } catch (Exception) { // There is an inherent race here with the server process. If it has already shutdown // by the time we try to access it then the operation has succeed. } } } return(CommonGenerator.Succeeded); } catch (Exception) { if (WasServerRunning(pipeName) == false) { // If the server was in the process of shutting down when we connected then it's reasonable // for an exception to happen. If the mutex has shutdown at this point then the server // is shut down. return(CommonGenerator.Succeeded); } return(CommonGenerator.Failed); } }
public string GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request) { string result = _alphaChar.GenerateInstance(instanceGenerator, request).ToString(CultureInfo.InvariantCulture); for (var i = 0; i < 5; ++i) { result += _digitChar.GenerateInstance(instanceGenerator, request); result += _alphaChar.GenerateInstance(instanceGenerator, request); } return(result); }
protected override bool ProcessCache(GenerationRequest request, HttpContext context) { var cache = this.GetCacheName(request, context, "json"); if (File.Exists(cache)) { context.Response.ContentType = "application/json"; context.Response.TransmitFile(cache); return(true); } return(false); }
public object Apply(InstanceGenerator instanceGenerator, GenerationRequest request, Type type) { var result = _proxyGenerator.CreateClassProxy( type, _fallbackTypeGenerator.GenerateConstructorParameters(instanceGenerator.Instance, request, type).ToArray(), new AbstractClassInterceptor(_generation, instanceGenerator.Instance, request)); _fallbackTypeGenerator.CustomizeCreatedValue(result, instanceGenerator, request, type); return(result); }
protected override bool ProcessCache(GenerationRequest request, HttpContext context) { var cache = this.GetCacheName(request, context, "json"); if (File.Exists(cache)) { context.Response.ContentType = "application/json"; context.Response.TransmitFile(cache); return true; } return false; }
private void ApplyCustomizations(IFixture generator, InstanceGenerator gen, GenerationRequest request) { Monitor.Enter(_syncRoot); try { generator.Customizations.Insert(0, new CustomizationRelay(gen, request)); } catch { Monitor.Exit(_syncRoot); throw; } }
public object Resolve(InstanceGenerator instanceGenerator, GenerationRequest request, Type type) { foreach (var resolution in _resolutions) { if (resolution.AppliesTo(type)) { request.Trace.SelectedResolution(type, resolution); return(resolution.Apply(instanceGenerator, request, type)); } } throw new ChainFailedException(type); }
private void SaveToCache(Image bitmap, GenerationRequest request, HttpContext context) { try { context.Response.ContentType = "image/png"; bitmap.Save(context.Response.OutputStream, ImageFormat.Png); var cache = this.GetCacheName(request, context, "png"); if (cache != null) { try { using (var stream = new FileStream(cache, FileMode.CreateNew)) bitmap.Save(stream, ImageFormat.Png); } catch (Exception) { } } } finally { bitmap.Dispose(); } }
public override sealed void ProcessRequest(HttpContext context) { // Read in provided parameters, using either the fast or slow // API URLs. GenerationRequest request; if (context.Request.Url.AbsolutePath.StartsWith("/api-v1/", StringComparison.Ordinal)) { // The format of this URL allows Nginx to automatically // serve the resource if it already exists, which the // query string version does not. However it means that // we have to parse out the path components of the request // so that we have the information we want. var components = context.Request.Url.AbsolutePath.Substring("/api-v1/".Length).Split('/'); if (components.Length != 7) throw new HttpException(500, "Not enough URL components to determine request."); request = new GenerationRequest { X = Convert.ToInt64(components[2]), Y = Convert.ToInt64(components[3]), Z = Convert.ToInt64(components[4]), Size = Convert.ToInt32(components[5]), Seed = Convert.ToInt64(components[1]), LayerName = HttpUtility.UrlDecode(components[0]), Packed = components[6].Contains("_packed"), AsSquare = components[6].Contains("_square") }; if (request.LayerName.Contains(".") || request.LayerName.Contains("/")) throw new HttpException("Layer name is not valid."); var permittedNames = new[] { "get.png", "get_square.png", "get.json", "get_packed.json" }; if (!permittedNames.Contains(components[6])) { var message = "The final component of the URL must be one of {" + permittedNames.Aggregate((a, b) => a + ", " + b) + "} for fast caching to work."; throw new HttpException( 500, message); } } else { request = new GenerationRequest { X = Convert.ToInt64(context.Request.QueryString["x"]), Y = Convert.ToInt64(context.Request.QueryString["y"]), Z = Convert.ToInt64(context.Request.QueryString["z"]), Size = Convert.ToInt32(context.Request.QueryString["size"]), Seed = Convert.ToInt64(context.Request.QueryString["seed"]), LayerName = context.Request.QueryString["layer"], Packed = Convert.ToBoolean(context.Request.QueryString["packed"]), AsSquare = Convert.ToBoolean(context.Request.QueryString["as_square"]) }; } // Force the size to be 64x64x64. request.Size = Math.Max(0, request.Size); request.Size = Math.Min(request.Size, 128); // Load the configuration. var layer = this.CreateLayerFromConfig(context.Server.MapPath("~/bin/WorldConfig.xml"), request); if (layer == null) throw new HttpException(404, "The layer name was invalid"); // Handle with cache if possible. if (this.ProcessCache(request, context)) return; // Generate the requested data. int computations; layer.SetSeed(request.Seed); var start = DateTime.Now; var data = layer.GenerateData( request.X, request.Y, layer.Algorithm.Is2DOnly ? 0 : request.Z, request.Size, request.Size, layer.Algorithm.Is2DOnly ? 1 : request.Size, out computations); var end = DateTime.Now; // Store the result. var generation = new GenerationResult { Request = request, Layer = layer, Data = data, Computations = computations, TotalTime = end - start }; // 3D layers can be optimized to empty results. if (!layer.Algorithm.Is2DOnly && DataIsAllSame(data)) { this.ProcessEmpty(generation, context); return; } // Handle with generation processing. this.ProcessGeneration(generation, context); }
private RuntimeLayer CreateLayerFromConfig(string path, GenerationRequest request) { // Use StorageAccess to load reference to world generation. StorageLayer[] layers; using (var reader = new StreamReader(path)) layers = this.StorageAccess.LoadStorage(reader); foreach (var layer in layers) if ((layer.Algorithm is AlgorithmResult) && (layer.Algorithm as AlgorithmResult).Name == request.LayerName && ((layer.Algorithm as AlgorithmResult).ShowInMakeMeAWorld || (layer.Algorithm as AlgorithmResult).PermitInMakeMeAWorld)) return this.StorageAccess.ToRuntime(layer); return null; }
/// <summary> /// Processes a request by checking the cache and handling it if possible. Returns /// true if the request has been handled by the cache. /// </summary> protected abstract bool ProcessCache(GenerationRequest request, HttpContext context);
protected string GetCacheName(GenerationRequest request, HttpContext context, string extension) { if (request.LayerName.Contains(".") || request.LayerName.Contains("/")) throw new HttpException("Layer name is not valid."); var cacheComponents = new string[] { "~", "App_Cache", "api-v1", request.LayerName, request.Seed.ToString(), request.X.ToString(), request.Y.ToString(), request.Z.ToString(), request.Size.ToString(), "get" + (request.AsSquare ? "_square" : string.Empty) + (request.Packed ? "_packed" : string.Empty) + "." + extension }; for (var i = 0; i < cacheComponents.Length - 1; i++) { var path = context.Server.MapPath(cacheComponents.Where((x, id) => id <= i).Aggregate((a, b) => a + "/" + b)); if (!Directory.Exists(path)) Directory.CreateDirectory(path); } return context.Server.MapPath(cacheComponents.Aggregate((a, b) => a + "/" + b)); }