コード例 #1
0
    private static object CreateGenericDelegatesForFunction(InstanceGenerator instanceGenerator, MethodInfo methodInfo,
                                                            GenerationRequest request)
    {
        var fullSignatureTypes = ReturnTypeOf(methodInfo).Concat(ParameterTypes(methodInfo));

        return(CreateGenericDelegatesObjectForConcreteTypes(fullSignatureTypes, WithArgumentGeneratedBy(instanceGenerator, methodInfo, request)));
    }
コード例 #2
0
        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"));
            }
        }
コード例 #3
0
    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);
コード例 #4
0
    public object GenerateCustomizedInstance(InstanceGenerator instanceGenerator, GenerationRequest request, Type type)
    {
        var generateInstance = GenerateInstance(instanceGenerator, request, type);

        CustomizeCreatedValue(generateInstance, instanceGenerator, request, type);
        return(generateInstance);
    }
コード例 #5
0
        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());
        }
コード例 #6
0
    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);
    }
コード例 #7
0
 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)));
 }
コード例 #8
0
ファイル: BaseGenerator.cs プロジェクト: duaneking/Tychaia
        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));
    }
コード例 #10
0
 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.");
     }
 }
コード例 #11
0
        /// <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);
            }
        }
コード例 #12
0
 public AbstractClassInterceptor(
     CachedReturnValueGeneration cachedGeneration,
     Func <Type, GenerationRequest, object> instanceSource,
     GenerationRequest request)
 {
     _cachedGeneration = cachedGeneration;
     _instanceSource   = instanceSource;
     _request          = request;
 }
コード例 #13
0
    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);
    }
コード例 #14
0
        public void Generate(GenerationRequest request)
        {
            Creator.CreateDirectory(request.FolderOfResults);

            for (int i = 0; i < request.NumberOfFiles; i++)
            {
                CreateFile(GetPathToFile(request, i), request.NumberOfInts);
            }
        }
コード例 #15
0
    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);
    }
コード例 #16
0
 private T WithCustomizations <T>(
     InstanceGenerator gen,
     GenerationRequest request,
     Func <FixtureWrapper, T> creation)
 {
     using (_generator.Customize(request, gen))
     {
         return(creation.Invoke(_generator));
     }
 }
コード例 #17
0
        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));
        }
コード例 #18
0
    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);
    }
コード例 #19
0
    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);
    }
コード例 #20
0
    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));
    }
コード例 #21
0
 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!");
     }
 }
コード例 #22
0
    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);
    }
コード例 #23
0
    public byte GenerateInstance(InstanceGenerator instanceGenerator, GenerationRequest request)
    {
        byte digit = _digitGenerator.GenerateInstance(instanceGenerator, request);

        while (digit == 0)
        {
            digit = _digitGenerator.GenerateInstance(instanceGenerator, request);
        }

        return(digit);
    }
コード例 #24
0
        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);
        }
コード例 #25
0
        /// <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);
            }
        }
コード例 #26
0
    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);
    }
コード例 #27
0
ファイル: JsonGenerator.cs プロジェクト: duaneking/Tychaia
        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);
        }
コード例 #28
0
    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);
    }
コード例 #29
0
ファイル: JsonGenerator.cs プロジェクト: TreeSeed/Tychaia
        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;
        }
コード例 #30
0
 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;
     }
 }
コード例 #31
0
    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);
    }
コード例 #32
0
ファイル: ImageGenerator.cs プロジェクト: TreeSeed/Tychaia
 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();
     }
 }
コード例 #33
0
ファイル: BaseGenerator.cs プロジェクト: TreeSeed/Tychaia
        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);
        }
コード例 #34
0
ファイル: BaseGenerator.cs プロジェクト: TreeSeed/Tychaia
 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;
 }
コード例 #35
0
ファイル: BaseGenerator.cs プロジェクト: TreeSeed/Tychaia
 /// <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);
コード例 #36
0
ファイル: BaseGenerator.cs プロジェクト: TreeSeed/Tychaia
        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));
        }