Exemplo n.º 1
0
 protected override void ProcessEmpty(GenerationResult result, HttpContext context)
 {
     var cache = this.GetCacheName(result.Request, context, "json");
     context.Response.ContentType = "application/json";
     using (var cacheWriter = new StreamWriter(cache))
     {
         using (var webWriter = new StreamWriter(context.Response.OutputStream))
         {
             cacheWriter.Write("{\"empty\":true}");
             webWriter.Write("{\"empty\":true}");
         }
     }
 }
Exemplo n.º 2
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            if (project != null)
            {
                ValidateSettings();

                try
                {
                    SolutionType solutionType = (SolutionType)cboSolutionType.SelectedIndex;
                    Generator    generator    = new Generator(project, solutionType);
                    string       destination  = txtDestination.Text;

                    GenerationResult result = generator.Generate(destination);
                    if (result == GenerationResult.Success)
                    {
                        MessageBox.Show(Strings.CodeGenerationCompleted,
                                        Strings.CodeGeneration, MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    else if (result == GenerationResult.Error)
                    {
                        MessageBox.Show(Strings.CodeGenerationFailed,
                                        Strings.Error, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                    else // Cancelled
                    {
                        this.DialogResult = DialogResult.None;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Strings.UnknownError,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemplo n.º 3
0
        public static void Run()
        {
            // ExStart:1
            // input and output preparation
            string testFolderPath = RunExamples.GetGenerationSourceDir();
            string outputPath     = RunExamples.GetResultDir();

            // initialize engine
            OmrEngine engine = new OmrEngine();

            GenerationResult res = engine.GenerateTemplate(Path.Combine(testFolderPath, "AsposeTestWithBarcode.txt"));

            // check in case of errors
            if (res.ErrorCode != 0)
            {
                Console.WriteLine("ERROR: " + res.ErrorCode + ": " + res.ErrorMessage);
            }

            // save generation result: image and .omr template
            res.Save(outputPath, "AsposeTestWithBarcode");
            // ExEnd:1

            Console.WriteLine("GenerateTemplateWithBarcode executed successfully.\n\r");
        }
Exemplo n.º 4
0
        private CodeTypeDeclaration GenerateClassFromOneOfAnyOfSchema(bool handleOneOf)
        {
            ISet <string> subSchemasSet = new HashSet <string>();
            int           index         = 0;
            var           schemaArray   = handleOneOf ? schema.OneOf : schema.AnyOf;

            foreach (JSONSchema subSchema in schemaArray)
            {
                if (context.ContainsKey(subSchema))
                {
                    subSchemasSet.Add(context[subSchema].TypeName);
                }
                else if (subSchema.Type?.GetUnderlyingType() == typeof(SimpleType) &&
                         (subSchema.Type.Value as SimpleType).Value != SimpleType.Object &&
                         (subSchema.Type.Value as SimpleType).Value != SimpleType.Array
                         )
                {
                    subSchemasSet.Add(ComputeType((SimpleType)subSchema.Type.GetValue()).Name);
                }
                else
                {
                    var nestedClassGenerator = new ClassGeneratorFromJsonSchema(subSchema, context, string.Concat(targetClass.Name, handleOneOf?"OneOf":"AnyOf", index));
                    context[subSchema] = new GenerationResult()
                    {
                        Type           = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name),
                        TypeName       = nestedClassGenerator.targetClass.Name,
                        ClassGenerator = nestedClassGenerator
                    };
                    nestedClassGenerator.GenerateClass();
                    subSchemasSet.Add(nestedClassGenerator.targetClass.Name);
                }
                index++;
            }


            targetClass = new CodeTypeDeclaration(targetClass.Name)
            {
                IsClass        = true,
                TypeAttributes = TypeAttributes.Public
            };

            var field = new CodeMemberField()
            {
                Attributes = MemberAttributes.Private | MemberAttributes.Final,
                Name       = "Value",
                Type       = new CodeTypeReference(typeof(object))
            };

            targetClass.Members.Add(field);

            CodeConstructor constructor = new CodeConstructor
            {
                Attributes = MemberAttributes.Private
            };

            constructor.Comments.Add(new CodeCommentStatement("Hiding visiblity of default constructor"));
            targetClass.Members.Add(constructor);

            CodeStatement[] codeStatements = new CodeStatement[subSchemasSet.Count + 1];
            index = 0;
            foreach (string subSchemaName in subSchemasSet)
            {
                codeStatements[index] = If(NewSnippet("value is " + subSchemaName), new CodeAssignStatement(new CodeVariableReferenceExpression("Value"), new CodeVariableReferenceExpression("value")));
                index++;
            }
            codeStatements[index] = Throw(typeof(ArgumentException), "Value's type is not correct");

            CodeConstructor publicConstructor = NewPublicConstructor(
                Array(NewParameter(typeof(object), "value")),
                codeStatements
                );

            targetClass.Members.Add(publicConstructor);

            foreach (string subSchemaName in subSchemasSet)
            {
                var implicitOperator = new CodeSnippetTypeMember(string.Format("\t\tpublic static implicit operator {0}({1} d) => ({0})d.Value;", subSchemaName, targetClass.Name));
                targetClass.Members.Add(implicitOperator);

                var explicitOperator = new CodeSnippetTypeMember(string.Format("\t\tpublic static explicit operator {0}({1} v) => new {0}(v);", targetClass.Name, subSchemaName));
                targetClass.Members.Add(explicitOperator);
            }

            return(targetClass);
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hsmm Error Sources Generation Application started");
            Console.WriteLine(
                "Please, specify Pseudo Random Generator mode as a number from the list:\r\n" +
                " 0 - Standart; \r\n" +
                " 1 - RC4; \r\n" +
                " 2 - Security");
            PseudoRandomGeneratorType prngMode = PromptParseUtils.ParsePseudoRandomGeneratorType(Console.ReadLine());

            Task.Factory.StartNew(() =>
            {
                bool ifExit = false;
                while (!ifExit)
                {
                    Console.WriteLine(
                        "Please, specify generation parameters");
                    string jsonModel = null;

                    while (jsonModel == null)
                    {
                        Console.WriteLine(
                            "Specify path to model file:");
                        string pathToFile = Console.ReadLine();
                        jsonModel         = ParseModelFile(pathToFile);
                    }

                    Console.WriteLine(
                        "Specify desired sequence length:");
                    int sequenceLength = Convert.ToInt32(Console.ReadLine());

                    string outputPath = null;

                    while (outputPath == null)
                    {
                        Console.WriteLine("Specify output file path:");
                        outputPath = ParseOutputPath(Console.ReadLine());
                    }

                    Console.WriteLine("Starting generation");
                    GenerationManager manager = new GenerationManager(prngMode);
                    GenerationResult result   = manager.Generate(jsonModel, sequenceLength);
                    if (result.HasErrors())
                    {
                        Console.WriteLine("Generation failed due to the following errors:" + String.Join(", ", result.Errors.ToArray()));
                    }
                    else
                    {
                        WriteOutputToFile(outputPath, result.Value);
                        Console.WriteLine("Generation has been successfully completed. See result in " + outputPath);
                    }

                    Console.WriteLine("Do you want to continue? (y/n)");
                    ifExit = !PromptParseUtils.ParseBoolean(Console.ReadLine());
                }
                Console.WriteLine("Press Ctrl+C to exit...");
            });

            Console.CancelKeyPress += new ConsoleCancelEventHandler(OnExit);
            Closing.WaitOne();
        }
        public void CanConstruct()
        {
            var instance = new GenerationResult(_fileContent);

            Assert.That(instance, Is.Not.Null);
        }
Exemplo n.º 7
0
 protected override void ProcessEmpty(GenerationResult result, HttpContext context)
 {
     var bitmap = new Bitmap(1, 1);
     this.SaveToCache(bitmap, result.Request, context);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Processes a request using the generated data and layer information.
 /// </summary>
 protected abstract void ProcessGeneration(GenerationResult result, HttpContext context);
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        protected async Task <AllGenerationsResult> Generate(
            GeneratorConfig config,
            BatchSettings batchSettings,
            CancellationToken ct = default)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (batchSettings == null)
            {
                throw new ArgumentNullException(nameof(batchSettings));
            }

            try
            {
                config.Validate();
                batchSettings.Validate();
            }
            catch (ValidationException ve)
            {
                _logger.Fatal(ve, "Cannot start generation, configuration is invalid");
                throw;
            }

            if (batchSettings.RestartIisBeforeBatch)
            {
                try
                {
                    using (StopwatchLoggerFactory.ForceLogDispose(_logger, LogLevel.Debug, "iisreset completed"))
                    {
                        IisManager.Instance.RestartIis();
                    }
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Cannot restart IIS. Perhaps application was batched without administrator rights");
                }
            }

            if (batchSettings.CollectGarbageBeforeBatch)
            {
                if (_logger.IsDebugEnabled)
                {
                    _logger.Debug("Memory before GC.Collect: {byte:N0}", GC.GetTotalMemory(false));
                    GC.Collect();
                    _logger.Debug("Memory after GC.Collect: {byte:N0}", GC.GetTotalMemory(true));
                }
                else
                {
                    GC.Collect();
                }
            }

            var generatationResults = new List <GenerationResult>();
            var batch = batchSettings.CompileBatch();

            bool stopProcessing = false;

            using (StopwatchLoggerFactory.ForceLogStartDispose(
                       _logger,
                       "Start generation all settings for batch, Settings count = {count}, Id = {id}",
                       "Generation all settings for batch completed, Settings count = {count}, Id = {id}",
                       Params.ToArray <object>(batch.AvailableCount, batchSettings.Id, batchSettings),
                       callback: time => LogHelper.ResultsLogger.Info("Batch, Time: {time} ({time-sec} sec)", time, time.TotalSeconds)))
            {
                foreach (var settings in batch)
                {
                    GenerationResult result;
                    try
                    {
                        ct.ThrowIfCancellationRequested();
                        if (settings is IBatchDependent bd)
                        {
                            bd.Inject(batch);
                        }

                        var runner = settings.GetGenerationRunner(config.ApiConnectionConfig);
                        config.SubscriptionManager?.SubscribeGenerationRunner(runner);
                        await runner.RunGeneration(ct).ConfigureAwait(false);

                        result = new GenerationResult(settings);
                    }
                    catch (OperationCanceledException oce)
                    {
                        _logger.Fatal(oce, "Operation was canceled");
                        throw;
                    }
                    catch (GenerationException ge)
                    {
                        _logger.Error(ge, "Generation failed");
                        result = new GenerationResult(settings, ge);
                        if (batchSettings.StopProcessingAtException)
                        {
                            stopProcessing = true;
                        }
                    }
                    catch (ValidationException ve)
                    {
                        _logger.Error(ve, "Generation not started because of invalid configuration");
                        result = new GenerationResult(settings, ve);
                    }
                    // this should not happen
                    catch (Exception e)
                    {
                        _logger.Fatal(e, "Generation failed with unexpected error");
                        result = new GenerationResult(settings, e);
                        if (batchSettings.StopProcessingAtException)
                        {
                            stopProcessing = true;
                        }
                    }
                    generatationResults.Add(result);
                    if (stopProcessing)
                    {
                        break;
                    }
                }
            }
            return(new AllGenerationsResult(generatationResults, stopProcessing));
        }
Exemplo n.º 11
0
        protected override void ProcessEmpty(GenerationResult result, HttpContext context)
        {
            var bitmap = new Bitmap(1, 1);

            this.SaveToCache(bitmap, result.Request, context);
        }
Exemplo n.º 12
0
    public void StartTest(RTLLog log = null)
    {
        File   testData = new File();
        string fileName = "test.csv";

        if (testData.FileExists(fileName))
        {
            testData.Open(fileName, File.ModeFlags.ReadWrite);
            testData.GetCsvLine();
            while (!testData.EofReached())
            {
                Int32.TryParse(testData.GetCsvLine()[0], out int tId);
                if (this.TestId <= tId)
                {
                    this.TestId++;
                }
            }
        }
        else
        {
            testData.Open(fileName, File.ModeFlags.Write);
            testData.StoreCsvLine(GenerationResult.GetHeaderStringArray());
        }
        if (log != null)
        {
            log.LogLine($"Initiating test id {this.TestId} with config: popSize {this.PopulationSize}, mutRate {MutationRate}, elitism {Elitism}, maxIterations {MaxIterations}.");
        }
        // First generation of this test batch
        // Start timer to track ellapsed time per generation
        var    watch    = System.Diagnostics.Stopwatch.StartNew();
        double duration = 0;
        // the code that you want to measure comes here
        int genNumber = 0;
        List <MapIndividual> population              = Generator.EvolveTestChunkOnRight();
        MapIndividual        bestIndividual          = population[population.Count - 1];
        GenerationResult     currentGenerationResult = new GenerationResult {
            TestId                    = this.TestId,
            BestFitness               = bestIndividual.Fitness,
            GenerationNumber          = genNumber,
            FivePercentBestFitnessAvg = getFivePercentAvg(population),
            IsBestPlayable            = bestIndividual.IsPlayable,
            FitnessAverage            = getFitnessAverage(population),
            FitnessMedian             = getFitnessMedian(population),
            PopulationSize            = this.PopulationSize,
            GenChunkSize              = this.GenChunkSize,
            MutationRate              = this.MutationRate,
            Elitism                   = this.Elitism,
        };

        watch.Stop();
        currentGenerationResult.ExecutionTimeMs = watch.ElapsedMilliseconds;
        testData.StoreCsvLine(currentGenerationResult.GetCsvStringArray());

        for (genNumber = genNumber + 1; genNumber <= MaxIterations; genNumber++)
        {
            watch                   = System.Diagnostics.Stopwatch.StartNew();
            population              = Generator.EvolveTestChunkOnRight(population);
            bestIndividual          = population[population.Count - 1];
            currentGenerationResult = new GenerationResult {
                TestId                    = this.TestId,
                BestFitness               = bestIndividual.Fitness,
                GenerationNumber          = genNumber,
                FivePercentBestFitnessAvg = getFivePercentAvg(population),
                IsBestPlayable            = bestIndividual.IsPlayable,
                FitnessAverage            = getFitnessAverage(population),
                FitnessMedian             = getFitnessMedian(population),
                PopulationSize            = this.PopulationSize,
                GenChunkSize              = this.GenChunkSize,
                MutationRate              = this.MutationRate,
                Elitism                   = this.Elitism,
            };
            watch.Stop();
            currentGenerationResult.ExecutionTimeMs = watch.ElapsedMilliseconds;
            duration += watch.ElapsedMilliseconds;
            testData.StoreCsvLine(currentGenerationResult.GetCsvStringArray());
        }
        // Close file at the end of this test
        testData.Close();
        TimeSpan t = TimeSpan.FromMilliseconds(duration);
        string   durationString = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
                                                t.Hours, t.Minutes, t.Seconds, t.Milliseconds);

        if (log != null)
        {
            log.LogLine($"Done with test {this.TestId} in {durationString}!");
        }
    }
Exemplo n.º 13
0
        protected override void ProcessGeneration(GenerationResult result, HttpContext context)
        {
            var bitmap = RenderPartial3D(result);

            this.SaveToCache(bitmap, result.Request, context);
        }
Exemplo n.º 14
0
        private static Bitmap RenderPartial3D(GenerationResult result)
        {
            var    width  = result.Request.Size;
            var    height = result.Request.Size;
            Bitmap bitmap;

            if (result.Request.AsSquare)
            {
                bitmap = new Bitmap(width, height - 1);
            }
            else
            {
                bitmap = new Bitmap(width * 2, height * 3);
            }
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
                var depth = result.Layer.Algorithm.Is2DOnly ? 1 : result.Request.Size;
                try
                {
                    var render      = GetCellRenderOrder(RenderToNE, width, height);
                    var ztop        = depth;
                    var zbottom     = 0;
                    var parentLayer = StorageAccess.FromRuntime(result.Layer.GetInputs()[0]);
                    for (int z = zbottom; z < ztop; z++)
                    {
                        int rcx = width / 2 - 1 + 32;
                        int rcy = height / 2 - 15 + 32;
                        int rw  = 2;
                        int rh  = 1;
                        for (int i = 0; i < render.Length; i++)
                        {
                            // Calculate the X / Y of the tile in the grid.
                            int x = render[i] % width;
                            int y = render[i] / width;

                            // Calculate the render position on screen.
                            int rx = rcx + (int)((x - y) / 2.0 * rw);
                            int ry = rcy + (x + y) * rh - (rh / 2 * (width + height)) - (z - zbottom) * 1;

                            // Adjust for square mode.
                            if (result.Request.AsSquare)
                            {
                                rx = (rx - rcx) + width / 2;
                                ry = (ry - rcy) - height / 2;
                                if (rx < -1 || ry < -1 ||
                                    rx > width + 1 || ry > height + 1)
                                {
                                    continue;
                                }
                            }

                            while (true)
                            {
                                try
                                {
                                    Color lc = result.Layer.Algorithm.GetColorForValue(
                                        parentLayer,
                                        result.Data[x + y * width + z * width * height]);
                                    var sb = new SolidBrush(Color.FromArgb(lc.A, lc.R, lc.G, lc.B));
                                    graphics.FillRectangle(sb, new Rectangle(rx, ry, rw, rh));
                                    break;
                                }
                                catch (InvalidOperationException)
                                {
                                    // Graphics can be in use elsewhere, but we don't care; just try again.
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
            return(bitmap);
        }
Exemplo n.º 15
0
        private static void AddAssembliesToGenerationResult(SemanticModel sourceModel, IFrameworkSet frameworkSet, GenerationResult generationResult)
        {
            var addedAssemblies = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var reference in frameworkSet.Context.EmittedTypes.Select(x => x.ContainingAssembly).Where(x => x != null))
            {
                if (addedAssemblies.Add(reference.Identity.ToString()))
                {
                    if (sourceModel.Compilation.GetMetadataReference(reference) is PortableExecutableReference location && !string.IsNullOrWhiteSpace(location.FilePath))
                    {
                        if (!generationResult.AssemblyReferences.Any(x => string.Equals(x.Name, reference.Identity.Name, StringComparison.OrdinalIgnoreCase)))
                        {
                            generationResult.AssemblyReferences.Add(new ReferencedAssembly(reference.Identity.Name, reference.Identity.Version, location.FilePath));
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
        private CodeTypeDeclaration GenerateClass()
        {
            if (!context.ContainsKey(schema))
            {
                context.Add(schema, new GenerationResult()
                {
                    TypeName       = targetClass.Name,
                    Type           = MyTypeBuilder.CreateType(targetClass.Name),
                    ClassGenerator = this
                });
            }

            if (schema.Enum?.Count > 0)
            {
                return(GenerateClassFromEnumSchema());
            }

            if (schema.Type?.Value is SimpleType && (schema.Type.Value as SimpleType).Value != SimpleType.Object)
            {
                var schemaType = schema.Type.Value as SimpleType;
                if (schemaType.Value == SimpleType.Integer)
                {
                    return(GenerateClassFromIntegerSchema());
                }

                if (schemaType.Value == SimpleType.Number)
                {
                    return(GenerateClassFromNumberSchema());
                }

                if (schemaType.Value == SimpleType.String)
                {
                    return(GenerateClassFromStringSchema());
                }

                if (schemaType.Value == SimpleType.Array)
                {
                    return(GenerateClassFromArraySchema());
                }
            }
            var definitions = schema.Definitions;

            if (definitions != null)
            {
                foreach (string definitionName in schema.Definitions.Keys)
                {
                    var definition = definitions[definitionName];
                    if (!context.ContainsKey(definition))
                    {
                        var nestedClassGenerator = new ClassGeneratorFromJsonSchema(definition, context);
                        context[definition] = new GenerationResult()
                        {
                            Type           = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name),
                            TypeName       = nestedClassGenerator.targetClass.Name,
                            ClassGenerator = nestedClassGenerator
                        };
                        nestedClassGenerator.GenerateClass();
                    }
                    //context.Add(definition, new GenerationResult() { TypeName = nestedClassGenerator.targetClass.Name });
                }
            }

            var properties           = schema.Properties;
            var additionalProperties = schema.AdditionalProperties;

            //Oneof/AnyOf/AllOf are only supported when there are no properties or additionalProperties and when the schema type is not a primitive type or array type
            if (properties == null && additionalProperties == null)
            {
                if (schema.OneOf != null && schema.OneOf.Count > 0)
                {
                    return(GenerateClassFromOneOfAnyOfSchema(true));
                }

                if (schema.AnyOf != null && schema.AnyOf.Count > 0)
                {
                    return(GenerateClassFromOneOfAnyOfSchema(false));
                }

                if (schema.AllOf != null && schema.AllOf.Count > 0)
                {
                    var mergedSchema         = JSONSchema.MergeSchemas(schema.AllOf);
                    var mergedClassGenerator = new ClassGeneratorFromJsonSchema(mergedSchema, this.targetClass.Name);
                    targetClass     = mergedClassGenerator.GenerateClass();
                    context[schema] = mergedClassGenerator.context[mergedSchema];
                    foreach (var jsonSchema in mergedClassGenerator.context.Keys)
                    {
                        if (jsonSchema != mergedSchema)
                        {
                            context[jsonSchema] = mergedClassGenerator.context[jsonSchema];
                        }
                    }
                    return(targetClass);
                }
            }

            if (properties != null)
            {
                foreach (string propertyName in properties.Keys)
                {
                    var cleanPropertyName = Clean(propertyName);
                    if (propertyNames.Contains(cleanPropertyName))
                    {
                        //to avoid property names that would collide
                        continue;
                    }
                    propertyNames.Add(cleanPropertyName);
                    var property = properties[propertyName];

                    if (context.ContainsKey(property))
                    {
                        targetClass.AddProperty(cleanPropertyName, context[property].TypeName);
                    }
                    else if (property.Type?.GetUnderlyingType() == typeof(SimpleType) &&
                             (property.Type.Value as SimpleType).Value != SimpleType.Object &&
                             (property.Type.Value as SimpleType).Value != SimpleType.Array &&
                             (property.Enum == null || property.Enum.Count < 1)
                             )
                    {
                        targetClass.AddProperty(cleanPropertyName, ComputeType((SimpleType)property.Type.GetValue()));
                    }
                    else
                    {
                        var nestedClassGenerator = new ClassGeneratorFromJsonSchema(property, context, cleanPropertyName);
                        context[property] = new GenerationResult()
                        {
                            Type           = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name),
                            TypeName       = nestedClassGenerator.targetClass.Name,
                            ClassGenerator = nestedClassGenerator
                        };
                        nestedClassGenerator.GenerateClass();
                        targetClass.AddProperty(cleanPropertyName, context[property].Type);
                    }
                }
            }


            if (additionalProperties != null)
            {
                if (additionalProperties.Value is bool)
                {
                    if ((bool)additionalProperties.Value == true)
                    {
                        targetClass.BaseTypes.Add(new CodeTypeReference(typeof(Dictionary <string, object>)));
                    }
                }
                else
                {
                    var additionalPropertiesSchema = additionalProperties.Value as JSONSchema;
                    if (!context.ContainsKey(additionalPropertiesSchema))
                    {
                        var nestedClassGenerator = new ClassGeneratorFromJsonSchema(additionalPropertiesSchema, context, context[schema].TypeName + "AdditionalProperties");
                        context[additionalPropertiesSchema] = new GenerationResult()
                        {
                            Type           = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name),
                            TypeName       = nestedClassGenerator.targetClass.Name,
                            ClassGenerator = nestedClassGenerator
                        };
                        nestedClassGenerator.GenerateClass();
                    }
                    targetClass.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference(typeof(string)), new CodeTypeReference(context[additionalPropertiesSchema].Type)));
                    context[schema].Imports.Add("System.Collections.Generic");
                }
            }



            return(targetClass);
        }
Exemplo n.º 17
0
        protected override void ProcessGeneration(GenerationResult result, HttpContext context)
        {
            var cache = this.GetCacheName(result.Request, context, "json");

            context.Response.ContentType = "application/json";
            using (var cacheWriter = new StreamWriter(cache))
            {
                using (var webWriter = new StreamWriter(context.Response.OutputStream))
                {
                    if (result.Request.Packed)
                    {
                        cacheWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":true,\"data\":[");
                        webWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":true,\"data\":[");
                        {
                            var continuousValue = 0;
                            var continuousCount = 1;
                            var first           = true;
                            var i = 0;
                            do
                            {
                                // Store the value into our continuity tracker.
                                if (i != result.Data.Length)
                                {
                                    continuousValue = result.Data[i];
                                }

                                // Increment to the next position.
                                i++;

                                if (i == result.Data.Length ||
                                    continuousValue != result.Data[i])
                                {
                                    // Output in the most efficient manner.
                                    if (("[" + continuousCount + "," + continuousValue + "]").Length >
                                        ((continuousValue.ToString().Length + 1) * continuousCount) - 1)
                                    {
                                        // Single value.
                                        for (var a = 0; a < continuousCount; a++)
                                        {
                                            if (!first)
                                            {
                                                cacheWriter.Write(",");
                                                webWriter.Write(",");
                                            }
                                            first = false;

                                            cacheWriter.Write(continuousValue);
                                            webWriter.Write(continuousValue);
                                        }
                                    }
                                    else
                                    {
                                        if (!first)
                                        {
                                            cacheWriter.Write(",");
                                            webWriter.Write(",");
                                        }
                                        first = false;

                                        // Multiple copies of the same
                                        // value in a row.
                                        cacheWriter.Write("[" + continuousCount + "," + continuousValue + "]");
                                        webWriter.Write("[" + continuousCount + "," + continuousValue + "]");
                                    }

                                    // Reset the continity count.
                                    continuousCount = 1;
                                }
                                else
                                {
                                    continuousCount++;
                                }
                            } while (i < result.Data.Length);
                        }
                    }
                    else
                    {
                        cacheWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":false,\"data\":[");
                        webWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":false,\"data\":[");
                        {
                            var first = true;
                            for (var i = 0; i < result.Data.Length; i++)
                            {
                                if (!first)
                                {
                                    cacheWriter.Write(",");
                                    webWriter.Write(",");
                                }
                                first = false;
                                cacheWriter.Write(result.Data[i]);
                                webWriter.Write(result.Data[i]);
                            }
                        }
                    }
                    cacheWriter.Write("],\"mappings\":{");
                    webWriter.Write("],\"mappings\":{");
                    var mappings    = new Dictionary <int, Color>();
                    var parentLayer = StorageAccess.FromRuntime(result.Layer.GetInputs()[0]);
                    for (var i = 0; i < result.Data.Length; i++)
                    {
                        if (!mappings.ContainsKey(result.Data[i]))
                        {
                            mappings.Add(result.Data[i],
                                         result.Layer.Algorithm.GetColorForValue(
                                             parentLayer,
                                             result.Data[i]));
                        }
                    }
                    {
                        var first = true;
                        foreach (var kv in mappings)
                        {
                            if (!first)
                            {
                                cacheWriter.Write(",");
                                webWriter.Write(",");
                            }
                            first = false;

                            var colorString =
                                "[" + kv.Value.A +
                                "," + kv.Value.R +
                                "," + kv.Value.G +
                                "," + kv.Value.B + "]";
                            cacheWriter.Write("\"" + kv.Key + "\":" + colorString);
                            webWriter.Write("\"" + kv.Key + "\":" + colorString);
                        }
                    }
                    cacheWriter.Write("}}");
                    webWriter.Write("}}");
                }
            }
        }
Exemplo n.º 18
0
        protected override void ProcessGeneration(GenerationResult result, HttpContext context)
        {
            var cache = this.GetCacheName(result.Request, context, "json");
            context.Response.ContentType = "application/json";
            using (var cacheWriter = new StreamWriter(cache))
            {
                using (var webWriter = new StreamWriter(context.Response.OutputStream))
                {
                    if (result.Request.Packed)
                    {
                        cacheWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":true,\"data\":[");
                        webWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":true,\"data\":[");
                        {
                            var continuousValue = 0;
                            var continuousCount = 1;
                            var first = true;
                            var i = 0;
                            do
                            {
                                // Store the value into our continuity tracker.
                                if (i != result.Data.Length)
                                    continuousValue = result.Data[i];

                                // Increment to the next position.
                                i++;

                                if (i == result.Data.Length ||
                                    continuousValue != result.Data[i])
                                {
                                    // Output in the most efficient manner.
                                    if (("[" + continuousCount + "," + continuousValue + "]").Length >
                                        ((continuousValue.ToString().Length + 1) * continuousCount) - 1)
                                    {
                                        // Single value.
                                        for (var a = 0; a < continuousCount; a++)
                                        {
                                            if (!first)
                                            {
                                                cacheWriter.Write(",");
                                                webWriter.Write(",");
                                            }

                                            first = false;

                                            cacheWriter.Write(continuousValue);
                                            webWriter.Write(continuousValue);
                                        }
                                    }
                                    else
                                    {
                                        if (!first)
                                        {
                                            cacheWriter.Write(",");
                                            webWriter.Write(",");
                                        }

                                        first = false;

                                        // Multiple copies of the same
                                        // value in a row.
                                        cacheWriter.Write("[" + continuousCount + "," + continuousValue + "]");
                                        webWriter.Write("[" + continuousCount + "," + continuousValue + "]");
                                    }

                                    // Reset the continity count.
                                    continuousCount = 1;
                                }
                                else
                                    continuousCount++;
                            }
                            while (i < result.Data.Length);
                        }
                    }
                    else
                    {
                        cacheWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":false,\"data\":[");
                        webWriter.Write("{\"empty\":false,\"time\":\"" + result.TotalTime + "\",\"packed\":false,\"data\":[");
                        {
                            var first = true;
                            for (var i = 0; i < result.Data.Length; i++)
                            {
                                if (!first)
                                {
                                    cacheWriter.Write(",");
                                    webWriter.Write(",");
                                }

                                first = false;
                                cacheWriter.Write(result.Data[i]);
                                webWriter.Write(result.Data[i]);
                            }
                        }
                    }

                    cacheWriter.Write("],\"mappings\":{");
                    webWriter.Write("],\"mappings\":{");
                    var mappings = new Dictionary<int, Color>();
                    var parentLayer = StorageAccess.FromRuntime(result.Layer.GetInputs()[0]);

                    for (var i = 0; i < result.Data.Length; i++)
                    {
                        if (!mappings.ContainsKey(result.Data[i]))
                            mappings.Add(
                                result.Data[i],
                                result.Layer.Algorithm.GetColorForValue(parentLayer, result.Data[i]));
                    }

                    {
                        var first = true;
                        foreach (var kv in mappings)
                        {
                            if (!first)
                            {
                                cacheWriter.Write(",");
                                webWriter.Write(",");
                            }

                            first = false;

                            var colorString =
                            "[" + kv.Value.A +
                                "," + kv.Value.R +
                                "," + kv.Value.G +
                                "," + kv.Value.B + "]";
                            cacheWriter.Write("\"" + kv.Key + "\":" + colorString);
                            webWriter.Write("\"" + kv.Key + "\":" + colorString);
                        }
                    }

                    cacheWriter.Write("}}");
                    webWriter.Write("}}");
                }
            }
        }
Exemplo n.º 19
0
 protected override void ProcessGeneration(GenerationResult result, HttpContext context)
 {
     var bitmap = this.RenderPartial3D(result);
     this.SaveToCache(bitmap, result.Request, context);
 }
Exemplo n.º 20
0
 public static string JoinTypesAndEnums(this GenerationResult result)
 {
     return(string.Join($"{Environment.NewLine}---{Environment.NewLine}", result.Types,
                        result.Enums));
 }
Exemplo n.º 21
0
        public async Task <Models.GenerationResult> Get(Models.GenerationRequest request)
        {
            bool   success   = false;
            string errors    = "";
            long   binlength = -1;
            string base64    = "";

            var name = request.Output.FileName;

            if (string.IsNullOrEmpty(name))
            {
                name = "Document.pdf";
            }


            MemoryStream content = null;

            try
            {
                content = await InvokeCreation(request);

                content.Flush();

                binlength        = content.Length;
                content.Position = 0;
                base64           = Convert.ToBase64String(content.ToArray());
                success          = true;
            }
            catch (Exception ex)
            {
                success = false;
                errors  = ex.Message;
            }
            finally
            {
                if (null != content)
                {
                    await content.DisposeAsync();
                }
            }

            GenerationResultData data = null;

            if (success)
            {
                data = new GenerationResultData()
                {
                    Base64 = base64, Length = base64.Length, DecodedLength = binlength
                };
            }

            GenerationResult result = new GenerationResult()
            {
                Data           = data,
                Success        = success,
                Errors         = errors,
                OriginalSource = request.Template.Url,
                FileName       = name
            };

            return(result);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Processes a request using the generated data and layer information.
 /// </summary>
 protected abstract void ProcessGeneration(GenerationResult result, HttpContext context);
Exemplo n.º 23
0
        static Assembly GenerateSerializers(GenerationBatch batch, CompilerParameters cp)
        {
            DateTime tim = DateTime.Now;

            XmlMapping[] maps = batch.Maps;

            if (cp == null)
            {
                cp = new CompilerParameters();
                cp.IncludeDebugInformation = false;
                cp.GenerateInMemory        = true;
                cp.TempFiles.KeepFiles     = !deleteTempFiles;
            }

            string       file = cp.TempFiles.AddExtension("cs");
            StreamWriter sw   = new StreamWriter(file);

            if (!deleteTempFiles)
            {
                Console.WriteLine("Generating " + file);
            }

            SerializationCodeGenerator gen = new SerializationCodeGenerator(maps);

            try
            {
                gen.GenerateSerializers(sw);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Serializer could not be generated");
                Console.WriteLine(ex);
                cp.TempFiles.Delete();
                return(null);
            }
            sw.Close();

            CSharpCodeProvider provider = new CSharpCodeProvider();
            ICodeCompiler      comp     = provider.CreateCompiler();

            cp.GenerateExecutable = false;

            foreach (Type rtype in gen.ReferencedTypes)
            {
                string path = new Uri(rtype.Assembly.CodeBase).LocalPath;
                if (!cp.ReferencedAssemblies.Contains(path))
                {
                    cp.ReferencedAssemblies.Add(path);
                }
            }

            if (!cp.ReferencedAssemblies.Contains("System.dll"))
            {
                cp.ReferencedAssemblies.Add("System.dll");
            }
            if (!cp.ReferencedAssemblies.Contains("Mono.System.Xml"))
            {
                cp.ReferencedAssemblies.Add("Mono.System.Xml");
            }
            if (!cp.ReferencedAssemblies.Contains("System.Data"))
            {
                cp.ReferencedAssemblies.Add("System.Data");
            }

            CompilerResults res = comp.CompileAssemblyFromFile(cp, file);

            if (res.Errors.HasErrors || res.CompiledAssembly == null)
            {
                Console.WriteLine("Error while compiling generated serializer");
                foreach (CompilerError error in res.Errors)
                {
                    Console.WriteLine(error);
                }

                cp.TempFiles.Delete();
                return(null);
            }

            GenerationResult[] results = gen.GenerationResults;
            for (int n = 0; n < results.Length; n++)
            {
                GenerationResult gres = results[n];
                SerializerData   sd   = batch.Datas [n];
                lock (sd)
                {
                    sd.WriterType   = res.CompiledAssembly.GetType(gres.Namespace + "." + gres.WriterClassName);
                    sd.ReaderType   = res.CompiledAssembly.GetType(gres.Namespace + "." + gres.ReaderClassName);
                    sd.WriterMethod = sd.WriterType.GetMethod(gres.WriteMethodName);
                    sd.ReaderMethod = sd.ReaderType.GetMethod(gres.ReadMethodName);
                    sd.Batch        = null;
                }
            }

            cp.TempFiles.Delete();

            if (!deleteTempFiles)
            {
                Console.WriteLine("Generation finished - " + (DateTime.Now - tim).TotalMilliseconds + " ms");
            }

            return(res.CompiledAssembly);
        }
Exemplo n.º 24
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            if (project != null)
            {
                ValidateSettings();

                // Initialize the dialog that will contain the progress bar
                ProgressDialog progressDialog = new ProgressDialog();

                // Set the dialog to operate in indeterminate mode
                progressDialog.SetIndeterminate(true);

                SolutionType solutionType = (SolutionType)cboSolutionType.SelectedIndex;
                string       destination  = txtDestination.Text;

                try
                {
                    Generator        generator = new Generator(project, solutionType);
                    GenerationResult result    = new GenerationResult();

                    Thread backgroundThread = new Thread(
                        new ThreadStart(() =>
                    {
                        result = generator.Generate(destination);

                        // Close the dialog if it hasn't been already
                        if (progressDialog.InvokeRequired)
                        {
                            progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
                        }
                    }));

                    result = CheckDestination(destination);

                    if (result == GenerationResult.Success)
                    {
                        // Start the background process thread
                        backgroundThread.Start();

                        // Open the dialog
                        progressDialog.ShowDialog();
                    }

                    if (result == GenerationResult.Success)
                    {
                        MessageBox.Show(Strings.CodeGenerationCompleted,
                                        Strings.CodeGeneration, MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    else if (result == GenerationResult.Error)
                    {
                        MessageBox.Show(Strings.CodeGenerationFailed,
                                        Strings.Error, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                    else // Cancelled
                    {
                        this.DialogResult = DialogResult.None;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Strings.UnknownError,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 public void SetUp()
 {
     _fileContent = "TestValue1767881884";
     _testClass   = new GenerationResult(_fileContent);
 }
Exemplo n.º 26
0
        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]))
                {
                    throw new HttpException(500, "The final component of the URL must be one of {" +
                                            permittedNames.Aggregate((a, b) => a + ", " + b) + "} for fast caching to work.");
                }
            }
            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 = 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);
        }
Exemplo n.º 27
0
        private Bitmap RenderPartial3D(GenerationResult result)
        {
            var width = result.Request.Size;
            var height = result.Request.Size;
            Bitmap bitmap;
            if (result.Request.AsSquare)
                bitmap = new Bitmap(width, height - 1);
            else
                bitmap = new Bitmap(width * 2, height * 3);
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
                var depth = result.Layer.Algorithm.Is2DOnly ? 1 : result.Request.Size;
                try
                {
                    var render = GetCellRenderOrder(RenderToNE, width, height);
                    var ztop = depth;
                    var zbottom = 0;
                    var parentLayer = this.StorageAccess.FromRuntime(result.Layer.GetInputs()[0]);
                    for (int z = zbottom; z < ztop; z++)
                    {
                        var rcx = (width / 2) - 1 + 32;
                        var rcy = (height / 2) - 15 + 32;
                        int rw = 2;
                        int rh = 1;
                        for (int i = 0; i < render.Length; i++)
                        {
                            // Calculate the X / Y of the tile in the grid.
                            int x = render[i] % width;
                            int y = render[i] / width;

                            // Calculate the render position on screen.
                            int rx = rcx + (int)((x - y) / 2.0 * rw);
                            var ry = rcy + ((x + y) * rh) - (rh / 2 * (width + height)) - ((z - zbottom) * 1);

                            // Adjust for square mode.
                            if (result.Request.AsSquare)
                            {
                                rx = (rx - rcx) + (width / 2);
                                ry = (ry - rcy) - (height / 2);
                                if (rx < -1 || ry < -1 ||
                                    rx > width + 1 || ry > height + 1)
                                    continue;
                            }

                            while (true)
                            {
                                try
                                {
                                    Color lc = result.Layer.Algorithm.GetColorForValue(
                                        parentLayer,
                                        result.Data[x + (y * width) + (z * width * height)]);
                                    var sb = new SolidBrush(Color.FromArgb(lc.A, lc.R, lc.G, lc.B));
                                    graphics.FillRectangle(sb, new Rectangle(rx, ry, rw, rh));
                                    break;
                                }
                                catch (InvalidOperationException)
                                {
                                    // Graphics can be in use elsewhere, but we don't care; just try again.
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            return bitmap;
        }