Ejemplo n.º 1
0
        public static void SaveStreamAsPdf( object sender, Leadtools.Printer.EmfEventArgs e )
        {
            try
             {
            ConsoleMethods.Info( "EMF Event: SaveStreamAsPdf" );
            // Write the EMF as file to disk.
            const string format = "pdf";
            string path = Path.Combine(
               GetOutputRootPath(),
               format + @"\",
               GetRandomFileName( format ) );
            Directory.CreateDirectory( Path.GetDirectoryName( path ) );

            // Create an instance of the LEADTOOLS DocumentWriter
            var docWriter = new DocumentWriter();
            docWriter.BeginDocument( path, DocumentFormat.Pdf );

            var page = new DocumentEmfPage() {
               EmfHandle = new Metafile( new MemoryStream( e.Stream.ToArray() ) )
                  .GetHenhmetafile()
            };
            docWriter.AddPage( page );
            docWriter.EndDocument();
            ConsoleMethods.Success( "SaveStreamAsPdf: Complete" );
            ConsoleMethods.Verbose( path );
             }
             catch ( Exception ex )
             {
            ConsoleMethods.Error( ex.Message, 4000 );
             }
        }
 public GraphQlExecuter(MessageLogger logger)
 {
     this.logger = logger;
     executer = new DocumentExecuter();
     writer = new DocumentWriter();
 }
Ejemplo n.º 3
0
 public BufferingDocumentWriter(Action <JsonSerializerSettings> action)
 {
     documentWriter = new DocumentWriter(action);
 }
Ejemplo n.º 4
0
        public void Can_read()
        {
            var docs = new List <Document>
            {
                new Document(0, new List <Field>
                {
                    new Field(0, "title", "rambo"),
                    new Field(0, "_id", "0")
                }),
                new Document(1, new List <Field>
                {
                    new Field(1, "title", "rocky"),
                    new Field(1, "_id", "1")
                }),
                new Document(2, new List <Field>
                {
                    new Field(2, "title", "rocky 2"),
                    new Field(2, "_id", "2")
                })
            };

            var fileName = Path.Combine(Dir, "DocumentReaderTests.Can_read");
            var blocks   = new Dictionary <int, BlockInfo>();

            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                using (var writer = new DocumentWriter(fs, Compression.GZip))
                {
                    foreach (var doc in docs)
                    {
                        blocks.Add(doc.Id, writer.Write(doc));
                    }
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip))
                {
                    var doc = reader.Get(new[] { blocks[2] });

                    Assert.AreEqual(2, doc.First().Id);
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip))
                {
                    var doc = reader.Get(new[] { blocks[1] });

                    Assert.AreEqual(1, doc.First().Id);
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip))
                {
                    var doc = reader.Get(new[] { blocks[0] });

                    Assert.AreEqual(0, doc.First().Id);
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip))
                {
                    var ds = reader.Get(blocks.Values.OrderBy(b => b.Position).ToList()).ToList();

                    Assert.AreEqual(3, docs.Count);

                    Assert.IsTrue(ds.Any(d => d.Id == 0));
                    Assert.IsTrue(ds.Any(d => d.Id == 1));
                    Assert.IsTrue(ds.Any(d => d.Id == 2));
                }
        }
Ejemplo n.º 5
0
 public WriteSession(
     DocumentWriter streamWriter)
 {
     _streamWriter = streamWriter;
 }
Ejemplo n.º 6
0
            public override void Draw(DocumentWriter writer)
            {
                const int shadingPatternType = 2;           // tiling pattern = 1

                void WriteNumberHighPrecision(float v)
                {
                    // WriteNumber isn't high precision enough, only supports 2 decimal places :(

                    var bytes = Encoding.ASCII.GetBytes($"{v} ");

                    writer.Write(bytes);
                }

                writer.WriteBeginObject();
                writer.WriteDictionaryOpen();
                {
                    writer.WriteName(NamePatternTypeBytes);
                    writer.WriteNumber(shadingPatternType);

                    writer.WriteName(NameMatrixBytes);
                    writer.WriteArrayOpen();
                    {
                        _shadingColor.DrawMatrix(WriteNumberHighPrecision);
                    }
                    writer.WriteArrayClose();

                    writer.WriteName(NameShadingBytes);
                    writer.WriteDictionaryOpen();
                    {
                        writer.WriteName(NameShadingTypeBytes);
                        writer.WriteNumber((int)_shadingColor.ShadingType);

                        writer.WriteName(NameColorSpaceBytes);
                        _shadingColor.Stops[0].Color.ColorSpace.DrawColorSpace(writer);

                        writer.WriteName(NameCoordsBytes);
                        writer.WriteArrayOpen();
                        {
                            _shadingColor.DrawCoordinates(WriteNumberHighPrecision);
                        }
                        writer.WriteArrayClose();

                        writer.WriteName(NameExtendBytes);
                        writer.WriteArrayOpen();
                        {
                            writer.WriteBoolean(true);
                            writer.WriteBoolean(true);
                        }
                        writer.WriteArrayClose();

                        writer.WriteName(NameFunctionBytes);

                        if (_shadingColor.Stops.Count > 2)
                        {
                            WriteStitchingFunction(writer);
                        }
                        else if (_shadingColor.Stops.Count == 2)
                        {
                            var stop1 = _shadingColor.Stops[0];
                            var stop2 = _shadingColor.Stops[1];
                            WriteLinearColorInterpolationFunction(writer, stop1.Color, stop2.Color);
                        }
                        else
                        {
                            throw new InvalidOperationException($"Expected two or more color stops");
                        }
                    }
                    writer.WriteDictionaryClose();
                }
                writer.WriteDictionaryClose();
                writer.WriteEndObject();
            }
Ejemplo n.º 7
0
        private void _okButton_Click(object sender, EventArgs e)
        {
            DocumentWriter      docWriter          = _ocrDocument.Engine.DocumentWriterInstance;
            IOcrDocumentManager ocrDocumentManager = _ocrDocument.Engine.DocumentManager;

            // Save the options
            MyFormat mf = _formatComboBox.SelectedItem as MyFormat;

            DocumentOptions documentOptions;

            if (mf.Format != DocumentFormat.User)
            {
                documentOptions = docWriter.GetOptions(mf.Format);
            }
            else
            {
                documentOptions = null;
            }

            switch (mf.Format)
            {
            case DocumentFormat.User:
                // Update the User (Engine) options
            {
                MyEngineFormat mef = _userFormatNameComboBox.SelectedItem as MyEngineFormat;
                ocrDocumentManager.EngineFormat = mef.Format;
            }
            break;

            case DocumentFormat.Pdf:
                // Update the PDF options
            {
                PdfDocumentOptions pdfOptions = documentOptions as PdfDocumentOptions;

                pdfOptions.DocumentType    = (PdfDocumentType)_pdfDocumentTypeComboBox.SelectedItem;
                pdfOptions.ImageOverText   = _pdfImageOverTextCheckBox.Checked;
                pdfOptions.Linearized      = _pdfLinearizedCheckBox.Checked;
                pdfOptions.PageRestriction = DocumentPageRestriction.Relaxed;

                // Description options
                pdfOptions.Title    = _pdfOptions.Title;
                pdfOptions.Subject  = _pdfOptions.Subject;
                pdfOptions.Keywords = _pdfOptions.Keywords;
                pdfOptions.Author   = _pdfOptions.Author;
                pdfOptions.Creator  = _pdfOptions.Creator;
                pdfOptions.Producer = _pdfOptions.Producer;

                // Fonts options
                pdfOptions.FontEmbedMode = _pdfOptions.FontEmbedMode;

                // Security options
                pdfOptions.Protected = _pdfOptions.Protected;
                if (pdfOptions.Protected)
                {
                    pdfOptions.UserPassword            = _pdfOptions.UserPassword;
                    pdfOptions.OwnerPassword           = _pdfOptions.OwnerPassword;
                    pdfOptions.EncryptionMode          = _pdfOptions.EncryptionMode;
                    pdfOptions.PrintEnabled            = _pdfOptions.PrintEnabled;
                    pdfOptions.HighQualityPrintEnabled = _pdfOptions.HighQualityPrintEnabled;
                    pdfOptions.CopyEnabled             = _pdfOptions.CopyEnabled;
                    pdfOptions.EditEnabled             = _pdfOptions.EditEnabled;
                    pdfOptions.AnnotationsEnabled      = _pdfOptions.AnnotationsEnabled;
                    pdfOptions.AssemblyEnabled         = _pdfOptions.AssemblyEnabled;
                }

                // Compression options
                pdfOptions.OneBitImageCompression  = _pdfOptions.OneBitImageCompression;
                pdfOptions.ColoredImageCompression = _pdfOptions.ColoredImageCompression;
                pdfOptions.QualityFactor           = _pdfOptions.QualityFactor;
                pdfOptions.ImageOverTextSize       = _pdfOptions.ImageOverTextSize;
                pdfOptions.ImageOverTextMode       = _pdfOptions.ImageOverTextMode;

                // Initial View Options
                pdfOptions.PageModeType      = _pdfOptions.PageModeType;
                pdfOptions.PageLayoutType    = _pdfOptions.PageLayoutType;
                pdfOptions.PageFitType       = _pdfOptions.PageFitType;
                pdfOptions.ZoomPercent       = _pdfOptions.ZoomPercent;
                pdfOptions.InitialPageNumber = _pdfOptions.InitialPageNumber;
                pdfOptions.FitWindow         = _pdfOptions.FitWindow;
                pdfOptions.CenterWindow      = _pdfOptions.CenterWindow;
                pdfOptions.DisplayDocTitle   = _pdfOptions.DisplayDocTitle;
                pdfOptions.HideMenubar       = _pdfOptions.HideMenubar;
                pdfOptions.HideToolbar       = _pdfOptions.HideToolbar;
                pdfOptions.HideWindowUI      = _pdfOptions.HideWindowUI;
            }
            break;

            case DocumentFormat.Doc:
                // Update the DOC options
            {
                DocDocumentOptions docOptions = documentOptions as DocDocumentOptions;
                docOptions.TextMode = (_cbFramedDoc.Checked) ? DocumentTextMode.Framed : DocumentTextMode.NonFramed;
            }
            break;

            case DocumentFormat.Docx:
                // Update the DOC options
            {
                DocxDocumentOptions docxOptions = documentOptions as DocxDocumentOptions;
                docxOptions.TextMode = (_cbFramedDocX.Checked) ? DocumentTextMode.Framed : DocumentTextMode.NonFramed;
            }
            break;

            case DocumentFormat.Rtf:
                // Update the RTF options
            {
                RtfDocumentOptions rtfOptions = documentOptions as RtfDocumentOptions;
                rtfOptions.TextMode = (_cbFramedRtf.Checked) ? DocumentTextMode.Framed : DocumentTextMode.NonFramed;
            }
            break;

            case DocumentFormat.Html:
                // Update the HTML options
            {
                HtmlDocumentOptions htmlOptions = documentOptions as HtmlDocumentOptions;
                htmlOptions.FontEmbedMode      = (DocumentFontEmbedMode)_htmlEmbedFontModeComboBox.SelectedItem;
                htmlOptions.UseBackgroundColor = _htmlUseBackgroundColorCheckBox.Checked;
                htmlOptions.BackgroundColor    = MainForm.ConvertColor(_htmlBackgroundColorValueLabel.BackColor);
            }
            break;

            case DocumentFormat.Text:
                // Update the TEXT options
            {
                TextDocumentOptions textOptions = documentOptions as TextDocumentOptions;
                textOptions.DocumentType  = (TextDocumentType)_textDocumentTypeComboBox.SelectedItem;
                textOptions.AddPageNumber = _textAddPageNumberCheckBox.Checked;
                textOptions.AddPageBreak  = _textAddPageBreakCheckBox.Checked;
                textOptions.Formatted     = _textFormattedCheckBox.Checked;
            }
            break;

            case DocumentFormat.AltoXml:
                // Update the ALTOXML options
            {
                AltoXmlDocumentOptions altoXmlOptions = documentOptions as AltoXmlDocumentOptions;
                altoXmlOptions.FileName               = _altoXmlFileNameTextBox.Text;
                altoXmlOptions.SoftwareCreator        = _altoXmlSoftwareCreatorTextBox.Text;
                altoXmlOptions.SoftwareName           = _altoXmlSoftwareNameTextBox.Text;
                altoXmlOptions.ApplicationDescription = _altoXmlApplicationDescriptionTextBox.Text;
                altoXmlOptions.Formatted              = _altoXmlFormattedCheckBox.Checked;
                altoXmlOptions.Indentation            = (altoXmlOptions.Formatted) ? _altoXmlIndentationTextBox.Text : "";
                altoXmlOptions.Sort              = _altoXmlSort.Checked;
                altoXmlOptions.PlainText         = _altoXmlPlainText.Checked;
                altoXmlOptions.ShowGlyphInfo     = _altoXmlShowGlyphInfo.Checked;
                altoXmlOptions.ShowGlyphVariants = _altoXmlShowGlyphVariants.Checked;
                altoXmlOptions.MeasurementUnit   = (AltoXmlMeasurementUnit)_altoXmlMeasurementUnit.SelectedItem;
            }
            break;

            case DocumentFormat.Ltd:
            case DocumentFormat.Emf:
            case DocumentFormat.Xls:
            case DocumentFormat.Pub:
            case DocumentFormat.Mob:
            case DocumentFormat.Svg:
            default:
                // These formats have no options
                break;
            }

            if (documentOptions != null)
            {
                docWriter.SetOptions(mf.Format, documentOptions);
            }

            // Get the save paramters
            _selectedFileName     = _fileNameTextBox.Text;
            _selectedFormat       = mf.Format;
            _selectedViewDocument = _viewDocumentCheckBox.Checked;

            if (_isCustomFileName)
            {
                _outputDir = Path.GetDirectoryName(SelectedFileName);
            }
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/cvgraph"))
            {
                using (StreamReader reader = new StreamReader(context.Request.Body))
                {
                    var query = await reader.ReadToEndAsync();

                    if (string.IsNullOrEmpty(query))
                    {
                        await context.Response.WriteAsync("query are not valid");
                    }
                    else
                    {
                        try
                        {
                            var request = JsonConvert.DeserializeObject <GraphQLRequest>(query);

                            var result = await new DocumentExecuter().ExecuteAsync(options =>
                            {
                                options.Schema        = _schema;
                                options.Query         = request.Query;
                                options.OperationName = request.OperationName;
                                options.Inputs        = request.Variables.ToInputs();
                            }).ConfigureAwait(false);
                            var json = new DocumentWriter(indent: true).Write(result);
                            await context.Response.WriteAsync(json);
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
                    }
                }
            }
            else if (context.Request.Path.StartsWithSegments("/cvgraph-schema"))
            {
                string schema = @"
                                {
                                  person(firstName:"",lastName:"") {
                                    id
                                    firstName
                                    lastName
                                    age
                                    companies{
                                        id
                                        name
                                        positions {
                                            id,
                                            title
                                            duration{
                                                    start
                                                    end
                                            }
                                            description
                                        }
                                    }
                                    educations{
                                        id
                                        title
                                        institutionName
                                        specialization
                                        start
                                        end
                                    }
                                    personSkills{
                                        skill{
                                            name
                                        }
                                        level
                                    }
                                    projects{
                                        id
                                        name
                                    }
                                 }
                              } ";

                await context.Response.WriteAsync(schema);
            }
            else if (context.Request.Path.StartsWithSegments("/"))
            {
                await context.Response.WriteAsync("Curriculum Vitae Backend Service");
            }
            else
            {
                await this._next(context);
            }
        }
Ejemplo n.º 9
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context.WebSockets.IsWebSocketRequest || !context.Request.Path.StartsWithSegments(_path))
            {
                await next(context);

                return;
            }

            // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/
            var httpRequest    = context.Request;
            var gqlRequest     = new GraphQLRequest();
            var documentWriter = new DocumentWriter(Formatting.Indented, _schema.GetJsonSerializerSettings());

            if (HttpMethods.IsGet(httpRequest.Method) || (HttpMethods.IsPost(httpRequest.Method) && httpRequest.Query.ContainsKey(GraphQLRequest.QueryKey)))
            {
                ExtractGraphQLRequestFromQueryString(httpRequest.Query, gqlRequest);
            }
            else if (HttpMethods.IsPost(httpRequest.Method))
            {
                if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader))
                {
                    await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed.");

                    return;
                }

                switch (mediaTypeHeader.MediaType)
                {
                case JsonContentType:
                    gqlRequest = Deserialize <GraphQLRequest>(httpRequest.Body);
                    break;

                case GraphQLContentType:
                    gqlRequest.Query = await ReadAsStringAsync(httpRequest.Body);

                    break;

                case FormUrlEncodedContentType:
                    var formCollection = await httpRequest.ReadFormAsync();

                    ExtractGraphQLRequestFromPostBody(formCollection, gqlRequest);
                    break;

                default:
                    await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: non-supported media type. Must be of '{JsonContentType}', '{GraphQLContentType}', or '{FormUrlEncodedContentType}'. See: http://graphql.org/learn/serving-over-http/.");

                    return;
                }
            }

            var executer = new DocumentExecuter();
            var result   = await executer.ExecuteAsync(x =>
            {
                x.Schema                  = _schema;
                x.OperationName           = gqlRequest.OperationName;
                x.Query                   = gqlRequest.Query;
                x.Inputs                  = gqlRequest.GetInputs();
                x.UserContext             = _userContextBuilder.BuildContext();
                x.ValidationRules         = new[] { new AuthenticationValidationRule() }.Concat(DocumentValidator.CoreRules);
                x.CancellationToken       = context.RequestAborted;
                x.ComplexityConfiguration = _complexityConfigurationFactory.GetComplexityConfiguration();
            });

            if (result.Errors != null)
            {
                _logger.LogError("GraphQL execution error(s): {Errors}", result.Errors);
            }

            await WriteResponseAsync(context, documentWriter, result);
        }
Ejemplo n.º 10
0
        public IHttpActionResult Post([FromBody] ExecutionResult result)
        {
            var json = new DocumentWriter(indent: true).Write(result);

            return(this.Ok(JObject.Parse(json)));
        }
Ejemplo n.º 11
0
 public override void Write(DocumentWriter dw)
 {
     dw.WriteLine($"{Name}");
     dw.WriteLine($"{BumperPosition.X}, {BumperPosition.Y}, {BumperPosition.Z}", "bumper position");
     dw.WriteLine($"{CockpitPosition.X}, {CockpitPosition.Y}, {CockpitPosition.Z}", "cockpit position");
 }
Ejemplo n.º 12
0
 public abstract void Write(DocumentWriter dw);
Ejemplo n.º 13
0
        public void Save(string path)
        {
            using (DocumentWriter dw = new DocumentWriter(path))
            {
                dw.WriteLine($"VERSION {Version}");
                dw.WriteLine("//	Version 1 :		New crush data");
                if (Version > 1)
                {
                    dw.WriteLine("//		2 :		New windscreen spec");
                }
                dw.WriteLine($"{(FemaleDriver ? "GIRL" : "")}");
                dw.WriteLine($"{Name}", "Name of car");

                dw.WriteLine();

                dw.WriteLine($"{SoftnessFactor}", "softness_factor");

                dw.WriteLine();

                dw.WriteLine("START OF DRIVABLE STUFF");
                dw.WriteLine();
                dw.WriteLine($"{DriversHeadOffset.X},{DriversHeadOffset.Y},{DriversHeadOffset.Z}", "Offset of driver's head in 3D space");
                dw.WriteLine($"{DriversHeadTurnAngles.X},{DriversHeadTurnAngles.Y}", "Angles to turn to make head go left and right");
                dw.WriteLine($"{MirrorCamera.X},{MirrorCamera.Y},{MirrorCamera.Z},{MirrorCamera.W}", "Offset of 'mirror camera' in 3D space, viewing angle of mirror");
                dw.WriteLine($"{string.Join(",", PratcamBorders)}", "Pratcam border names (left, top, right, bottom)");
                dw.WriteLine();
                dw.WriteLine("END OF DRIVABLE STUFF");

                dw.WriteLine();

                dw.WriteLine($"{string.Join(",",EngineNoises)}", "Engine noise (normal, enclosed space, underwater)");

                dw.WriteLine();

                dw.WriteLine($"{(Stealworthy ? "stealworthy" : "")}", "Can be stolen");

                dw.WriteLine();

                foreach (ImpactSpec impactSpec in new List <ImpactSpec> {
                    ImpactTop, ImpactBottom, ImpactLeft, ImpactRight, ImpactFront, ImpactBack
                })
                {
                    dw.WriteLine($"// Damage info for {impactSpec.Description} impacts");
                    dw.WriteLine($"{impactSpec.Clauses.Count}", "Number of clauses");
                    dw.IncreaseIndent();
                    foreach (ImpactSpecClause clause in impactSpec.Clauses)
                    {
                        dw.WriteLine($"{clause.Clause}", "Condition");
                        dw.WriteLine($"{clause.Systems.Count}", "Systems count");

                        dw.IncreaseIndent();
                        foreach (ImpactSpecClauseSystem system in clause.Systems)
                        {
                            dw.WriteLine($"{system.Part},{system.Damage:F1}", "Damage");
                        }
                        dw.DecreaseIndent();
                    }
                    dw.DecreaseIndent();
                }

                dw.WriteLine();

                dw.WriteLine($"{string.Join(",", GridImages)}", "Grid image (opponent, frank, annie)");

                dw.WriteLine();

                dw.WriteLine($"{ExtraLevelsOfDetail.Count}", "Number of extra levels of detail");
                foreach (int extraLevelOfDetail in ExtraLevelsOfDetail)
                {
                    dw.WriteLine($"{extraLevelOfDetail}", "min_dist_squared");
                }

                dw.WriteLine();

                dw.WriteLine($"{WAM}", "crush data file (will be incorporated into this file)");

                dw.WriteLine();

                dw.WriteLine($"{ReflectiveScreenMaterial}", "Name of reflective screen material (or none if non-reflective)");
                dw.WriteLine($"{TransparencyOfWindscreen}", "Percentage transparency of windscreen");

                dw.WriteLine();

                dw.WriteLine($"{SteerableWheels.Count}", "Number of steerable wheels");
                foreach (int steerableWheel in SteerableWheels)
                {
                    dw.WriteLine($"{steerableWheel}", "GroovyFunkRef of nth steerable wheel");
                }

                dw.WriteLine();

                dw.WriteLine($"{string.Join(",", LeftFrontSuspension)}", "Left-front suspension parts GroovyFunkRef");
                dw.WriteLine($"{string.Join(",", RightFrontSuspension)}", "Right-front suspension parts GroovyFunkRef");
                dw.WriteLine($"{string.Join(",", LeftRearSuspension)}", "Left-rear suspension parts GroovyFunkRef");
                dw.WriteLine($"{string.Join(",", RightRearSuspension)}", "Right-rear suspension parts GroovyFunkRef");

                dw.WriteLine();

                dw.WriteLine($"{string.Join(",", DrivenWheels)}", "Driven wheels GroovyFunkRefs (for spinning) - MUST BE 4 ITEMS");
                dw.WriteLine($"{string.Join(",", NonDrivenWheels)}", "Non-driven wheels GroovyFunkRefs (for spinning) - MUST BE 4 ITEMS");

                dw.WriteLine();

                dw.WriteLine($"{DrivenWheelDiameter}", "Driven wheels diameter");
                dw.WriteLine($"{NonDrivenWheelDiameter}", "Non-driven wheels diameter");

                dw.WriteLine();
                dw.WriteLine("START OF FUNK");
                dw.WriteLine();

                for (int i = 0; i < Funks.Count; i++)
                {
                    Funk funk = Funks[i];

                    dw.WriteLine($"{funk.Material}");
                    dw.WriteLine($"{funk.Mode}");
                    dw.WriteLine($"{funk.MatrixModType}");
                    if (funk.MatrixModType != FunkMatrixMode.None)
                    {
                        dw.WriteLine($"{funk.MatrixModMode}");
                    }

                    switch (funk.MatrixModType)
                    {
                    case FunkMatrixMode.roll:
                        dw.WriteLine($"{funk.RollPeriods.X},{funk.RollPeriods.Y}");
                        break;

                    case FunkMatrixMode.slither:
                        dw.WriteLine($"{funk.SlitherSpeed.X},{funk.SlitherSpeed.Y}");
                        dw.WriteLine($"{funk.SlitherAmount.X},{funk.SlitherAmount.Y}");
                        break;

                    case FunkMatrixMode.spin:
                        dw.WriteLine($"{funk.SpinPeriod}");
                        break;
                    }

                    dw.WriteLine($"{funk.LightingMode}");
                    dw.WriteLine($"{funk.AnimationType}");

                    switch (funk.AnimationType)
                    {
                    case FunkAnimationType.frames:
                        dw.WriteLine($"{funk.Framerate}");
                        dw.WriteLine($"{funk.FrameMode}");

                        switch (funk.FrameMode)
                        {
                        case FrameType.texturebits:
                            dw.WriteLine($"{funk.TextureBitMode}");
                            break;

                        case FrameType.continuous:
                            dw.WriteLine($"{funk.FrameSpeed}");
                            break;
                        }

                        dw.WriteLine($"{funk.Frames.Count}");
                        foreach (string frame in funk.Frames)
                        {
                            dw.WriteLine($"{frame}");
                        }
                        break;
                    }

                    if (i + 1 != Funks.Count)
                    {
                        dw.WriteLine();
                        dw.WriteLine("NEXT FUNK");
                        dw.WriteLine();
                    }
                }

                dw.WriteLine();
                dw.WriteLine("END OF FUNK");
                dw.WriteLine();

                dw.WriteLine();
                dw.WriteLine("START OF GROOVE");
                dw.WriteLine();

                for (int i = 0; i < Grooves.Count; i++)
                {
                    Groove groove = Grooves[i];

                    dw.WriteLine($"{groove.Part}");
                    dw.WriteLine($"{groove.LollipopMode}");
                    dw.WriteLine($"{groove.Mode}");
                    dw.WriteLine($"{groove.PathType}");
                    if (groove.PathType != GroovePathNames.None)
                    {
                        dw.WriteLine($"{groove.PathMode}");
                    }

                    switch (groove.PathType)
                    {
                    case GroovePathNames.straight:
                        dw.WriteLine($"{groove.PathCentre.X},{groove.PathCentre.Y},{groove.PathCentre.Z}");
                        dw.WriteLine($"{groove.PathPeriod}");
                        dw.WriteLine($"{groove.PathDelta.X},{groove.PathDelta.Y},{groove.PathDelta.Z}");
                        break;
                    }

                    dw.WriteLine($"{groove.AnimationType}");
                    if (groove.AnimationType != GrooveAnimation.None)
                    {
                        dw.WriteLine($"{groove.AnimationMode}");
                    }

                    switch (groove.AnimationType)
                    {
                    case GrooveAnimation.rock:
                        dw.WriteLine($"{groove.AnimationPeriod}");
                        dw.WriteLine($"{groove.AnimationCentre.X},{groove.AnimationCentre.Y},{groove.AnimationCentre.Z}");
                        dw.WriteLine($"{groove.AnimationAxis}");
                        dw.WriteLine($"{groove.RockMaxAngle}");
                        break;

                    case GrooveAnimation.shear:
                        dw.WriteLine($"{groove.ShearPeriod.X},{groove.ShearPeriod.Y},{groove.ShearPeriod.Z}");
                        dw.WriteLine($"{groove.AnimationCentre.X},{groove.AnimationCentre.Y},{groove.AnimationCentre.Z}");
                        dw.WriteLine($"{groove.ShearMagnitude.X},{groove.ShearMagnitude.Y},{groove.ShearMagnitude.Z}");
                        break;

                    case GrooveAnimation.spin:
                        dw.WriteLine($"{groove.AnimationPeriod}");
                        dw.WriteLine($"{groove.AnimationCentre.X},{groove.AnimationCentre.Y},{groove.AnimationCentre.Z}");
                        dw.WriteLine($"{groove.AnimationAxis}");
                        break;
                    }

                    if (i + 1 != Grooves.Count)
                    {
                        dw.WriteLine();
                        dw.WriteLine("NEXT GROOVE");
                        dw.WriteLine();
                    }
                }

                dw.WriteLine();
                dw.WriteLine("END OF GROOVE");
                dw.WriteLine();

                dw.WriteLine("// END OF CRUSH DATA");

                dw.WriteLine();
                dw.WriteLine("START OF MECHANICS STUFF version 1");
                dw.WriteLine();

                dw.WriteLine($"{MinimumTurningCircle:F6}", "Minimum turning circle.");
                dw.WriteLine($"{BrakeMultiplier:F6}", "Brake multiplier.");
                dw.WriteLine($"{BrakingStrengthMultiplier:F6}", "Braking strength multiplier.");
                dw.WriteLine($"{NumberOfGears}", "Number of gears.");
                dw.WriteLine($"{TopGearRedlineSpeed:F4}", "Speed at red line in highest gear.");
                dw.WriteLine($"{TopGearAcceleration:F6}", "Acceleration in highest gear (m/s^2) i.e. engine strength.");

                dw.WriteLine();

                dw.WriteLine("// Sub member: Root part");
                dw.WriteLine($"{RootPartType}", "Type");
                dw.WriteLine($"{RootPartIdentifier}", "Identifier");
                dw.WriteLine($"{RootPartActor}", "Actor");
                dw.WriteLine("// Sub member: Joint data");
                dw.WriteLine($"{SubPartType}", "Type");
                dw.WriteLine($"{CentreOfMass.X:F6},{CentreOfMass.Y:F6},{CentreOfMass.Z:F6}", "Centre of mass");
                dw.WriteLine($"{Mass}", "Mass");
                dw.WriteLine($"{AngularMomentumProportions.X:F6},{AngularMomentumProportions.Y:F6},{AngularMomentumProportions.Z:F6}", "Angular momentum proportions");
                dw.WriteLine($"{DownforceToWeightBalanceSpeed:F6}", "Downforce-to-weight balance speed");
                dw.WriteLine($"{Wheels.Count}", "Number of 'Wheels' entries.");

                for (int i = 0; i < Wheels.Count; i++)
                {
                    Wheel wheel = Wheels[i];

                    dw.WriteLine($"// Wheels entry #{i + 1}");
                    dw.WriteLine($"{(int)wheel.Type}", "Type");
                    dw.WriteLine($"{wheel.Identifier}", "Identifier");
                    dw.WriteLine($"{wheel.Actor}", "Actor");
                    dw.WriteLine($"{wheel.Position.X},{wheel.Position.Y},{wheel.Position.Z}", "Position");
                    dw.WriteLine($"{wheel.SteerableFlags}", "Steerable flags");
                    dw.WriteLine($"{wheel.DrivenFlags}", "Driven flags");
                    dw.WriteLine($"{wheel.SuspensionGive:F6}", "Suspension give");
                    dw.WriteLine($"{wheel.DampingFactor:F6}", "Damping factor");
                    dw.WriteLine($"{wheel.SlipFrictionReductionFraction:F6}", "Fractional reduction in friction when slipping");
                    dw.WriteLine($"{wheel.FrictionAngles.X:F6},{wheel.FrictionAngles.Y:F6}", "Friction angles");
                    dw.WriteLine($"{wheel.TractionFractionalMultiplier:F6}", "Traction fractional multiplier");
                    dw.WriteLine($"{wheel.RollingResistance:F6}", "Rolling resistance");
                }

                dw.WriteLine();

                dw.WriteLine($"{BoundingShapes.Count}", "Number of 'Bounding shapes' entries.");

                for (int i = 0; i < BoundingShapes.Count; i++)
                {
                    BoundingShape shape = BoundingShapes[i];

                    dw.WriteLine($"// Bounding shapes entry #{i + 1}");
                    dw.WriteLine($"{shape.Type}", "Type");
                    dw.WriteLine($"{shape.Points.Count}");
                    foreach (Vector3 point in shape.Points)
                    {
                        dw.WriteLine($"{point.X:F2},{point.Y:F2},{point.Z:F2}");
                    }
                }

                dw.WriteLine();
                dw.WriteLine($"{SubParts.Count}", "Number of sub-parts.");
                dw.WriteLine();

                dw.WriteLine();
                dw.WriteLine("END OF MECHANICS STUFF");
                dw.WriteLine();

                dw.WriteLine("// Materials for shrapnel");
                dw.WriteLine($"{Shrapnel.Count}", "number of materials");
                foreach (string shrapnel in Shrapnel)
                {
                    dw.WriteLine($"{shrapnel}");
                }

                dw.WriteLine();

                dw.WriteLine("//damage vertices fire points");
                foreach (int point in FirePoints)
                {
                    dw.WriteLine($"{point}");
                }

                dw.WriteLine();

                dw.WriteLine("// start of keyword stuff");
                foreach (Keyword keyword in Keywords)
                {
                    keyword.Write(dw);
                }

                dw.WriteLine("// End of keyword stuff");
                dw.WriteLine("END");
            }
        }
Ejemplo n.º 14
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                await next(context);

                return;
            }

            // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/
            var httpRequest    = context.Request;
            var gqlRequest     = new GraphQLRequest();
            var documentWriter = new DocumentWriter(_schema.GetJsonSerializerSettings());

            if (HttpMethods.IsGet(httpRequest.Method) || (HttpMethods.IsPost(httpRequest.Method) && httpRequest.Query.ContainsKey(GraphQLRequest.QueryKey)))
            {
                ExtractGraphQLRequestFromQueryString(httpRequest.Query, gqlRequest);
            }
            else if (HttpMethods.IsPost(httpRequest.Method))
            {
                if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader))
                {
                    await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed.");

                    return;
                }

                switch (mediaTypeHeader.MediaType)
                {
                case JsonContentType:
                    gqlRequest = Deserialize <GraphQLRequest>(httpRequest.Body);
                    break;

                case GraphQLContentType:
                    gqlRequest.Query = await ReadAsStringAsync(httpRequest.Body);

                    break;

                case FormUrlEncodedContentType:
                    var formCollection = await httpRequest.ReadFormAsync();

                    ExtractGraphQLRequestFromPostBody(formCollection, gqlRequest);
                    break;

                default:
                    await WriteBadRequestResponseAsync(context, documentWriter, $"Invalid 'Content-Type' header: non-supported media type. Must be of '{JsonContentType}', '{GraphQLContentType}', or '{FormUrlEncodedContentType}'. See: http://graphql.org/learn/serving-over-http/.");

                    return;
                }
            }

            IEnumerable <IValidationRule> validationRules;

            try
            {
                validationRules = _container.GetAllInstances <IValidationRule>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                validationRules = new IValidationRule[0];
            }

            var executer = new DocumentExecuter();
            var result   = await executer.ExecuteAsync(x =>
            {
                x.Schema                  = _schema;
                x.OperationName           = gqlRequest.OperationName;
                x.Query                   = gqlRequest.Query;
                x.Inputs                  = gqlRequest.GetInputs();
                x.UserContext             = _userContextBuilder.BuildContext();
                x.ValidationRules         = validationRules.Concat(DocumentValidator.CoreRules);
                x.CancellationToken       = context.RequestAborted;
                x.ComplexityConfiguration = _complexityConfigurationFactory.GetComplexityConfiguration();
            });

            if (result.Errors?.Any(x => x.Code == "auth-required") == true && context.Response.Headers.ContainsKey("Token-Expired"))
            {
                await WriteUnauthorizedResponseAsync(context, documentWriter, result);
            }
            else
            {
                await WriteResponseAsync(context, documentWriter, result);
            }
        }
Ejemplo n.º 15
0
        private DialogResult SavePrintedJobsDocument()
        {
            System.Windows.Forms.DialogResult result = DialogResult.Cancel;

            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                string         strFilter;
#if LTV16_CONFIG
                strFilter = "(*.PDF Files)|*.pdf|(*.PDFA Files)|*.pdf|(*.Doc Files)|*.doc|(*.RTF Files)|*.rtf|(*.Text Files)|*.txt|(*.HTML Files)|*.html|(*.DOCX Files)|*.docx|(*.XPS Files)|*.xps";
#endif
#if LEADTOOLS_V17_OR_LATER
                strFilter = "(*.PDF Files)|*.pdf|(*.PDFA Files)|*.pdf|(*.Doc Files)|*.doc|(*.RTF Files)|*.rtf|(*.Text Files)|*.txt|(*.HTML Files)|*.html|(*.DOCX Files)|*.docx|(*.XPS Files)|*.xps|(*.XLS Files)|*.xls";
#endif
                saveFileDialog.Filter = strFilter;
                result = saveFileDialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    Application.DoEvents();
                    Cursor = Cursors.WaitCursor;
                    DocumentFormat     documentFormat     = DocumentFormat.User;
                    DocumentOptions    documentOptions    = null;
                    PdfDocumentOptions PdfdocumentOptions = new PdfDocumentOptions();
                    string             fileName           = saveFileDialog.FileName;

                    switch (saveFileDialog.FilterIndex)
                    {
                    case 1:
                        documentFormat  = DocumentFormat.Pdf;
                        documentOptions = new PdfDocumentOptions();
                        (documentOptions as PdfDocumentOptions).DocumentType  = PdfDocumentType.Pdf;
                        (documentOptions as PdfDocumentOptions).FontEmbedMode = DocumentFontEmbedMode.Auto;
                        break;

                    case 2:
                        documentFormat  = DocumentFormat.Pdf;
                        documentOptions = new PdfDocumentOptions();
                        (documentOptions as PdfDocumentOptions).DocumentType  = PdfDocumentType.PdfA;
                        (documentOptions as PdfDocumentOptions).FontEmbedMode = DocumentFontEmbedMode.Auto;
                        (documentOptions as PdfDocumentOptions).ImageOverText = true;
                        break;

                    case 3:
                        documentFormat  = DocumentFormat.Doc;
                        documentOptions = new DocDocumentOptions();
                        (documentOptions as DocDocumentOptions).TextMode = DocumentTextMode.Framed;
                        break;

                    case 4:
                        documentFormat  = DocumentFormat.Rtf;
                        documentOptions = new RtfDocumentOptions();
                        (documentOptions as RtfDocumentOptions).TextMode = DocumentTextMode.Framed;
                        break;

                    case 5:
                        documentFormat  = DocumentFormat.Text;
                        documentOptions = new TextDocumentOptions();
                        (documentOptions as TextDocumentOptions).DocumentType = TextDocumentType.Unicode;
                        (documentOptions as TextDocumentOptions).Formatted    = true;
                        break;

                    case 6:
                        documentFormat  = DocumentFormat.Html;
                        documentOptions = new HtmlDocumentOptions();
                        (documentOptions as HtmlDocumentOptions).FontEmbedMode = DocumentFontEmbedMode.Auto;
                        break;

                    case 7:
                        documentFormat  = DocumentFormat.Docx;
                        documentOptions = new DocxDocumentOptions();
                        (documentOptions as DocxDocumentOptions).MaintainAspectRatio = true;
                        (documentOptions as DocxDocumentOptions).PageRestriction     = DocumentPageRestriction.Default;
                        (documentOptions as DocxDocumentOptions).TextMode            = DocumentTextMode.Framed;
                        break;

                    case 8:
                        documentFormat  = DocumentFormat.Xps;
                        documentOptions = new XpsDocumentOptions();
                        break;

#if LTV16_CONFIG
                    case 9:
                        SaveAsEmf(fileName);
                        return(result);
#endif
#if LEADTOOLS_V17_OR_LATER
                    case 9:
                        documentFormat  = DocumentFormat.Xls;
                        documentOptions = new XlsDocumentOptions();
                        (documentOptions as XlsDocumentOptions).PageRestriction = DocumentPageRestriction.Relaxed;
                        break;

                    case 10:
                        SaveAsEmf(fileName);
                        return(result);
#endif
                    }

                    DocumentWriter documentWriter = new DocumentWriter();
                    documentWriter.SetOptions(documentFormat, documentOptions);
                    documentWriter.BeginDocument(fileName, documentFormat);

                    foreach (IntPtr metaFile in _lstMetaFiles)
                    {
#if LEADTOOLS_V20_OR_LATER
                        DocumentWriterEmfPage documentPage = new DocumentWriterEmfPage();
#elif LEADTOOLS_V19_OR_LATER
                        DocumentEmfPage documentPage = new DocumentEmfPage();
#else
                        DocumentPage documentPage = DocumentPage.Empty;
#endif // #if LEADTOOLS_V19_OR_LATER

                        int index = _lstMetaFiles.IndexOf(metaFile);

                        documentPage.EmfHandle = metaFile;

                        if (saveFileDialog.FilterIndex == 2)
                        {
                            documentPage.Image = _codec.Load(_tempFiles[index]);
                        }

                        documentWriter.AddPage(documentPage);
                    }
                    documentWriter.EndDocument();

                    if (ViewOutputFile)
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "LEADTOOLS Printer Demo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            return(result);
        }
Ejemplo n.º 16
0
        public void Can_read()
        {
            var docs = new List <Document>
            {
                new Document(0, new List <Field>
                {
                    new Field("title", "rambo"),
                    new Field("_id", "0")
                }),
                new Document(1, new List <Field>
                {
                    new Field("title", "rocky"),
                    new Field("_id", "1")
                }),
                new Document(2, new List <Field>
                {
                    new Field("title", "rocky 2"),
                    new Field("_id", "2")
                })
            };

            var fileName    = Path.Combine(CreateDir(), "DocumentReaderTests.Can_read");
            var blocks      = new Dictionary <int, BlockInfo>();
            var keyIndex    = docs[0].ToKeyIndex();
            var revKeyIndex = keyIndex.ToDictionary(x => x.Value, y => y.Key);

            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                using (var writer = new DocumentWriter(fs, Compression.GZip))
                {
                    foreach (var doc in docs)
                    {
                        blocks.Add(doc.Id, writer.Write(doc.ToTableRow(keyIndex)));
                    }
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex))
                {
                    var doc = reader.Read(new[] { blocks[2] });

                    Assert.AreEqual("rocky 2", doc.First().Fields["title"].Value);
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex))
                {
                    var doc = reader.Read(new[] { blocks[1] });

                    Assert.AreEqual("rocky", doc.First().Fields["title"].Value);
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex))
                {
                    var doc = reader.Read(new[] { blocks[0] });

                    Assert.AreEqual("rambo", doc.First().Fields["title"].Value);
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex))
                {
                    var ds = reader.Read(blocks.Values.OrderBy(b => b.Position).ToList()).ToList();

                    Assert.AreEqual(3, docs.Count);

                    Assert.IsTrue(ds.Any(d => d.Fields["title"].Value == "rambo"));
                    Assert.IsTrue(ds.Any(d => d.Fields["title"].Value == "rocky"));
                    Assert.IsTrue(ds.Any(d => d.Fields["title"].Value == "rocky 2"));
                }
        }
Ejemplo n.º 17
0
        public void SetDocumentWriter(DocumentWriter docWriter, bool showLtdFormat)
        {
            _documentWriter = docWriter;

            // This is the order of importance, show these first then the rest as they come along
            DocumentFormat[] importantFormats =
            {
                DocumentFormat.Pdf,
                DocumentFormat.Docx,
                DocumentFormat.Rtf,
                DocumentFormat.Text,
                DocumentFormat.Doc,
                DocumentFormat.Xls,
                DocumentFormat.Html
            };

            List <DocumentFormat> formatsToAdd = new List <DocumentFormat>();

            Array a = Enum.GetValues(typeof(DocumentFormat));
            List <DocumentFormat> allFormats = new List <DocumentFormat>();

            foreach (DocumentFormat format in a)
            {
                allFormats.Add(format);
            }

            // Add important once first:
            foreach (DocumentFormat format in importantFormats)
            {
                formatsToAdd.Add(format);
                allFormats.Remove(format);
            }

            // Add rest
            formatsToAdd.AddRange(allFormats);

            // Add rest
            foreach (DocumentFormat format in formatsToAdd)
            {
                bool addItem = true;

                if (format == DocumentFormat.User)
                {
                    addItem = false;
                }
                else if (format == DocumentFormat.Ltd && !showLtdFormat)
                {
                    addItem = false;
                }

                if (addItem)
                {
                    string             name = string.Format("{0} ({1})", DocumentWriter.GetFormatFriendlyName(format), DocumentWriter.GetFormatFileExtension(format).ToUpperInvariant());
                    DocumentFormatItem item = new DocumentFormatItem(format, name);
                    _formatComboBox.Items.Add(item);

                    if (format == DocumentFormat.Pdf)
                    {
                        _formatComboBox.SelectedItem = item;
                    }
                }
            }

            if (_formatComboBox.SelectedIndex == -1 && _formatComboBox.Items.Count > 0)
            {
                _formatComboBox.SelectedIndex = 0;
            }

            PdfDocumentOptions pdfOptions = _documentWriter.GetOptions(DocumentFormat.Pdf) as PdfDocumentOptions;

            if (string.IsNullOrEmpty(pdfOptions.Creator))
            {
                pdfOptions.Creator = "LEADTOOLS PDFWriter";
            }
            if (string.IsNullOrEmpty(pdfOptions.Producer))
            {
                pdfOptions.Producer = "LEAD Technologies, Inc.";
            }
            _documentWriter.SetOptions(DocumentFormat.Pdf, pdfOptions);
        }
Ejemplo n.º 18
0
        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                var schema = _applicationContext.ApplicationCache.RuntimeCache.GetCacheItem <UmbracoSchema>(
                    "Our.Umbraco.GraphQL::Schema",
                    () =>

                    new UmbracoSchema(
                        _applicationContext.Services.ContentTypeService,
                        _applicationContext.Services.MemberTypeService,
                        _options
                        )
                    );

                if (false == context.Request.Path.HasValue)
                {
                    var request = context.Get <GraphQLRequest>("Our.Umbraco.GraphQL::Request");
                    switch (context.Request.Method)
                    {
                    case "POST":
                        if (request == null)
                        {
                            context.Response.StatusCode = 400;
                            await context.Response.WriteAsync("POST body missing.");

                            return;
                        }
                        break;

                    default:
                        context.Response.StatusCode = 405;
                        await context.Response.WriteAsync("Server supports only POST requests.");

                        return;
                    }

                    IEnumerable <Task <ExecutionResult> > requests = request.Select(requestParams =>
                    {
                        try
                        {
                            string query         = requestParams.Query;
                            string operationName = requestParams.OperationName;
                            Inputs variables     = requestParams.Variables;

                            return(new DocumentExecuter()
                                   .ExecuteAsync(x =>
                            {
                                x.CancellationToken = context.Request.CallCancelled;
                                //x.ComplexityConfiguration = new ComplexityConfiguration();
                                x.ExposeExceptions = _options.Debug;
                                //x.FieldMiddleware.Use<InstrumentFieldsMiddleware>();
                                x.FieldNameConverter = new DefaultFieldNameConverter();
                                x.Inputs = variables;
                                x.OperationName = operationName;
                                x.Query = query;
                                //x.Root =
                                x.Schema = schema;
                                x.UserContext = new UmbracoGraphQLContext(
                                    context.Request.Uri,
                                    _applicationContext,
                                    UmbracoContext.Current,
                                    _options
                                    );
                            }));
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    });

                    var responses = await Task.WhenAll(requests);

                    context.Response.ContentType = "application/json";

                    var writer = new DocumentWriter();
                    if (false == request.IsBatched)
                    {
                        var response = writer.Write(responses[0]);
                        await context.Response.WriteAsync(response);
                    }
                    else
                    {
                        var response = writer.Write(responses);
                        await context.Response.WriteAsync(response);
                    }
                }
                else if (context.Request.Path.ToString() == "/schema")
                {
                    using (var schemaPrinter = new SchemaPrinter(schema))
                    {
                        context.Response.ContentType = "text/plain";
                        await context.Response.WriteAsync(schemaPrinter.Print());
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.StatusCode  = 500;

                if (_options.Debug)
                {
                    await context.Response.WriteAsync(ex.ToString());
                }
                else
                {
                    await context.Response.WriteAsync("Internal server error");
                }
            }
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var logger = httpContext.RequestServices.GetService <ILogger <GraphQlMiddleware> >();

            HttpRequest  request  = httpContext.Request;
            HttpResponse response = httpContext.Response;

            // GraphQL HTTP only supports GET and POST methods.
            if (request.Method != "GET" && request.Method != "POST")
            {
                response.Headers.Add("Allow", "GET, POST");
                response.StatusCode = 405;

                return;
            }

            // Check authorization
            if (_options.AuthorizationPolicy != null)
            {
                var authorizationService = httpContext.RequestServices.GetRequiredService <IAuthorizationService>();
                var authzResult          = await authorizationService.AuthorizeAsync(httpContext.User, _options.AuthorizationPolicy);

                if (!authzResult.Succeeded)
                {
                    await httpContext.ForbidAsync();

                    return;
                }
            }

            GraphQlParameters parameters = await GetParametersAsync(request);

            ISchema schema = _schemaProvider.Create(httpContext.RequestServices);

            var executer = new DocumentExecuter();

            var result = await executer.ExecuteAsync(options =>
            {
                options.Schema                  = schema;
                options.Query                   = parameters.Query;
                options.OperationName           = parameters.OperationName;
                options.Inputs                  = parameters.GetInputs();
                options.CancellationToken       = httpContext.RequestAborted;
                options.ComplexityConfiguration = _options.ComplexityConfiguration;
                options.UserContext             = httpContext;
                options.ExposeExceptions        = _options.ExposeExceptions;
            });

            if (result.Errors?.Count > 0)
            {
                logger.LogError("GraphQL Result {Errors}", result.Errors);
            }

            var writer = new DocumentWriter(indent: _options.FormatOutput);
            var json   = writer.Write(result);

            response.StatusCode  = 200;
            response.ContentType = "application/json; charset=utf-8";

            await response.WriteAsync(json);
        }
Ejemplo n.º 20
0
 public override void Save(DocumentWriter writer)
 {
     base.Save(writer);
     writer.Write(Points);
 }
Ejemplo n.º 21
0
        public SaveDocumentDialog(IOcrDocument ocrDocument, DocumentFormat initialFormat, string initialFileName, bool isCustomFileName, string outputDir, bool viewDocument)
        {
            InitializeComponent();

            _ocrDocument = ocrDocument;
            _outputDir   = outputDir;


            // Get the formats
            // This is the order of importance, show these first then the rest as they come along
            DocumentFormat[] importantFormats =
            {
                DocumentFormat.Ltd,
                DocumentFormat.Pdf,
                DocumentFormat.Docx,
                DocumentFormat.Rtf,
                DocumentFormat.Text,
                DocumentFormat.Doc,
                DocumentFormat.Xls,
                DocumentFormat.Html
            };

            List <DocumentFormat> formatsToAdd = new List <DocumentFormat>();

            Array temp = Enum.GetValues(typeof(DocumentFormat));
            List <DocumentFormat> allFormats = new List <DocumentFormat>();

            foreach (DocumentFormat format in temp)
            {
                allFormats.Add(format);
            }

            // Add important once first:
            foreach (DocumentFormat format in importantFormats)
            {
                formatsToAdd.Add(format);
                allFormats.Remove(format);
            }

            // Add rest
            formatsToAdd.AddRange(allFormats);

            MyFormat pdfFormat = null;

            DocumentWriter      docWriter          = _ocrDocument.Engine.DocumentWriterInstance;
            IOcrDocumentManager ocrDocumentManager = _ocrDocument.Engine.DocumentManager;

            string[] engineSupportedFormatNames = ocrDocumentManager.GetSupportedEngineFormats();

            foreach (DocumentFormat format in formatsToAdd)
            {
                bool addFormat = true;

                // If this is the "User" or Engines format, only add it if the OCR engine supports them
                if (format == DocumentFormat.User && engineSupportedFormatNames.Length == 0)
                {
                    addFormat = false;
                }

                if (addFormat)
                {
                    string friendlyName;
                    if (format == DocumentFormat.User)
                    {
                        friendlyName = "Engine native";
                    }
                    else
                    {
                        friendlyName = DocumentWriter.GetFormatFriendlyName(format);
                    }

                    MyFormat mf = new MyFormat(format, friendlyName);

                    _formatComboBox.Items.Add(mf);

                    if (mf.Format == initialFormat)
                    {
                        _formatComboBox.SelectedItem = mf;
                    }
                    else if (mf.Format == DocumentFormat.Pdf)
                    {
                        pdfFormat = mf;
                    }
                }

                switch (format)
                {
                case DocumentFormat.User:
                    // Update the User (Engine) options page
                {
                    foreach (string engineFormatName in engineSupportedFormatNames)
                    {
                        MyEngineFormat mef = new MyEngineFormat(
                            engineFormatName,
                            ocrDocumentManager.GetEngineFormatFriendlyName(engineFormatName));
                        _userFormatNameComboBox.Items.Add(mef);

                        if (mef.Format == ocrDocumentManager.EngineFormat)
                        {
                            _userFormatNameComboBox.SelectedItem = mef;
                        }
                    }

                    if (_userFormatNameComboBox.SelectedItem == null && _userFormatNameComboBox.Items.Count > 0)
                    {
                        _userFormatNameComboBox.SelectedIndex = 0;
                    }
                }
                break;

                case DocumentFormat.Pdf:
                    // Update the PDF options page
                {
                    PdfDocumentOptions pdfOptions = docWriter.GetOptions(DocumentFormat.Pdf) as PdfDocumentOptions;

                    // Clone it in case we change it in the Advance PDF options dialog
                    _pdfOptions = pdfOptions.Clone() as PdfDocumentOptions;

                    Array a = Enum.GetValues(typeof(PdfDocumentType));
                    foreach (PdfDocumentType i in a)
                    {
                        // PDFA does NOT support Arabic characters so we are not adding it in case of Arabic OCR engine.
                        if (i == PdfDocumentType.PdfA && _ocrDocument.Engine.EngineType == OcrEngineType.OmniPageArabic)
                        {
                            continue;
                        }

                        _pdfDocumentTypeComboBox.Items.Add(i);
                    }
                    _pdfDocumentTypeComboBox.SelectedItem = _pdfOptions.DocumentType;

                    _pdfImageOverTextCheckBox.Checked = _pdfOptions.ImageOverText;
                    _pdfLinearizedCheckBox.Checked    = _pdfOptions.Linearized;

                    if (string.IsNullOrEmpty(_pdfOptions.Creator))
                    {
                        _pdfOptions.Creator = "LEADTOOLS PDFWriter";
                    }
                    if (string.IsNullOrEmpty(_pdfOptions.Producer))
                    {
                        _pdfOptions.Producer = "LEAD Technologies, Inc.";
                    }
                }
                break;

                case DocumentFormat.Doc:
                    // Update the DOC options page
                {
                    DocDocumentOptions docOptions = docWriter.GetOptions(DocumentFormat.Doc) as DocDocumentOptions;
                    _cbFramedDoc.Checked = (docOptions.TextMode == DocumentTextMode.Framed) ? true : false;
                }
                break;

                case DocumentFormat.Docx:
                    // Update the DOCX options page
                {
                    DocxDocumentOptions docxOptions = docWriter.GetOptions(DocumentFormat.Docx) as DocxDocumentOptions;
                    _cbFramedDocX.Checked = (docxOptions.TextMode == DocumentTextMode.Framed) ? true : false;
                }
                break;

                case DocumentFormat.Rtf:
                    // Update the RTF options page
                {
                    RtfDocumentOptions rtfOptions = docWriter.GetOptions(DocumentFormat.Rtf) as RtfDocumentOptions;
                    _cbFramedRtf.Checked = (rtfOptions.TextMode == DocumentTextMode.Framed) ? true : false;
                }
                break;

                case DocumentFormat.Html:
                    // Update the HTML options page
                {
                    HtmlDocumentOptions htmlOptions = docWriter.GetOptions(DocumentFormat.Html) as HtmlDocumentOptions;

                    Array a = Enum.GetValues(typeof(DocumentFontEmbedMode));
                    foreach (DocumentFontEmbedMode i in a)
                    {
                        _htmlEmbedFontModeComboBox.Items.Add(i);
                    }
                    _htmlEmbedFontModeComboBox.SelectedItem = htmlOptions.FontEmbedMode;

                    _htmlUseBackgroundColorCheckBox.Checked = htmlOptions.UseBackgroundColor;

                    _htmlBackgroundColorValueLabel.BackColor = MainForm.ConvertColor(htmlOptions.BackgroundColor);

                    _htmlBackgroundColorLabel.Enabled      = _htmlUseBackgroundColorCheckBox.Checked;
                    _htmlBackgroundColorValueLabel.Enabled = _htmlUseBackgroundColorCheckBox.Checked;
                    _htmlBackgroundColorButton.Enabled     = _htmlUseBackgroundColorCheckBox.Checked;
                }
                break;

                case DocumentFormat.Text:
                    // Update the TEXT options page
                {
                    TextDocumentOptions textOptions = docWriter.GetOptions(DocumentFormat.Text) as TextDocumentOptions;

                    Array a = Enum.GetValues(typeof(TextDocumentType));
                    foreach (TextDocumentType i in a)
                    {
                        if (i == TextDocumentType.Ansi)
                        {
                            if (textOptions.DocumentType == TextDocumentType.Ansi)
                            {
                                textOptions.DocumentType = TextDocumentType.Unicode;
                            }
                            if (_ocrDocument.Engine.EngineType == OcrEngineType.OmniPageArabic)
                            {
                                continue;
                            }
                        }
                        _textDocumentTypeComboBox.Items.Add(i);
                    }
                    _textDocumentTypeComboBox.SelectedItem = textOptions.DocumentType;

                    _textAddPageNumberCheckBox.Checked = textOptions.AddPageNumber;
                    _textAddPageBreakCheckBox.Checked  = textOptions.AddPageBreak;
                    _textFormattedCheckBox.Checked     = textOptions.Formatted;
                }
                break;

                case DocumentFormat.AltoXml:
                    // Update the ALTOXML options page
                {
                    AltoXmlDocumentOptions altoXmlOptions = docWriter.GetOptions(DocumentFormat.AltoXml) as AltoXmlDocumentOptions;
                    _altoXmlFileNameTextBox.Text               = altoXmlOptions.FileName;
                    _altoXmlSoftwareCreatorTextBox.Text        = altoXmlOptions.SoftwareCreator;
                    _altoXmlSoftwareNameTextBox.Text           = altoXmlOptions.SoftwareName;
                    _altoXmlApplicationDescriptionTextBox.Text = altoXmlOptions.ApplicationDescription;
                    _altoXmlFormattedCheckBox.Checked          = altoXmlOptions.Formatted;
                    _altoXmlIndentationTextBox.Text            = altoXmlOptions.Indentation;
                    _altoXmlSort.Checked              = altoXmlOptions.Sort;
                    _altoXmlPlainText.Checked         = altoXmlOptions.PlainText;
                    _altoXmlShowGlyphInfo.Checked     = altoXmlOptions.ShowGlyphInfo;
                    _altoXmlShowGlyphVariants.Checked = altoXmlOptions.ShowGlyphVariants;

                    Array a = Enum.GetValues(typeof(AltoXmlMeasurementUnit));
                    foreach (AltoXmlMeasurementUnit i in a)
                    {
                        _altoXmlMeasurementUnit.Items.Add(i);
                    }
                    _altoXmlMeasurementUnit.SelectedItem = altoXmlOptions.MeasurementUnit;
                }
                break;

                case DocumentFormat.Ltd:
                case DocumentFormat.Emf:
                case DocumentFormat.Xls:
                case DocumentFormat.Pub:
                case DocumentFormat.Mob:
                case DocumentFormat.Svg:
                default:
                    // These formats have no options
                    break;
                }
            }

            // Remove all the tab pages
            _optionsTabControl.TabPages.Clear();

            // If no format is selected, default to PDF
            if (_formatComboBox.SelectedIndex == -1)
            {
                if (pdfFormat != null)
                {
                    _formatComboBox.SelectedItem = pdfFormat;
                }
                else
                {
                    _formatComboBox.SelectedIndex = -1;
                }
            }

            _viewDocumentCheckBox.Checked = viewDocument;
            _initialFileName  = initialFileName;
            _isCustomFileName = isCustomFileName;

            if (!string.IsNullOrEmpty(_outputDir))
            {
                MyFormat mf = _formatComboBox.SelectedItem as MyFormat;

                char[] trimChars = { '\\' };
                _fileNameTextBox.Text = _outputDir.TrimEnd(trimChars) + "\\" + Path.GetFileName(initialFileName);
                if (!_isCustomFileName)
                {
                    _fileNameTextBox.Text += "." + GetFileExtension(mf.Format);
                }
            }
            else
            {
                _fileNameTextBox.Text = initialFileName;
            }

            _formatComboBox_SelectedIndexChanged(this, EventArgs.Empty);
            UpdateUIState();
        }
        public DocumentFormatOptionsDialog(OcrEngineType ocrEngineType, DocumentWriter docWriter, DocumentFormat format, int totalPages)
        {
            InitializeComponent();

            _ocrEngineType  = ocrEngineType;
            _documentWriter = docWriter;
            _format         = format;
            _totalPages     = totalPages;

            _optionsTabControl.TabPages.Clear();

            switch (_format)
            {
            case DocumentFormat.Pdf:
                // Update the PDF options page
            {
                _optionsTabControl.TabPages.Add(_pdfOptionsTabPage);

                PdfDocumentOptions pdfOptions = _documentWriter.GetOptions(DocumentFormat.Pdf) as PdfDocumentOptions;

                // Clone it in case we change it in the Advance PDF options dialog
                _pdfOptions = pdfOptions.Clone() as PdfDocumentOptions;

                Array a = Enum.GetValues(typeof(PdfDocumentType));
                foreach (PdfDocumentType i in a)
                {
                    // PDFA does NOT support Arabic characters so we are not adding it in case of Arabic OCR engine.
                    if (ocrEngineType == OcrEngineType.OmniPageArabic && i == PdfDocumentType.PdfA)
                    {
                        continue;
                    }

                    _pdfDocumentTypeComboBox.Items.Add(i);
                }
                _pdfDocumentTypeComboBox.SelectedItem = pdfOptions.DocumentType;

                _pdfImageOverTextCheckBox.Checked = pdfOptions.ImageOverText;
                _pdfLinearizedCheckBox.Checked    = pdfOptions.Linearized;
            }
            break;

            case DocumentFormat.Doc:
                // Update the DOC options page
            {
                _optionsTabControl.TabPages.Add(_docOptionsTabPage);
                DocDocumentOptions docOptions = _documentWriter.GetOptions(DocumentFormat.Doc) as DocDocumentOptions;
                _docFramedCheckBox.Checked = (docOptions.TextMode == DocumentTextMode.Framed) ? true : false;
            }
            break;

            case DocumentFormat.Docx:
                // Update the DOCX options page
            {
                _optionsTabControl.TabPages.Add(_docxOptionsTabPage);
                DocxDocumentOptions docxOptions = _documentWriter.GetOptions(DocumentFormat.Docx) as DocxDocumentOptions;
                _docxFramedCheckBox.Checked = (docxOptions.TextMode == DocumentTextMode.Framed) ? true : false;
            }
            break;

            case DocumentFormat.Rtf:
                // Update the RTF options page
            {
                _optionsTabControl.TabPages.Add(_rtfOptionsTabPage);
                RtfDocumentOptions rtfOptions = _documentWriter.GetOptions(DocumentFormat.Rtf) as RtfDocumentOptions;
                _rtfFramedCheckBox.Checked = (rtfOptions.TextMode == DocumentTextMode.Framed) ? true : false;
            }
            break;

            case DocumentFormat.Html:
                // Update the HTML options page
            {
                _optionsTabControl.TabPages.Add(_htmlOptionsTabPage);

                HtmlDocumentOptions htmlOptions = _documentWriter.GetOptions(DocumentFormat.Html) as HtmlDocumentOptions;

                Array a = Enum.GetValues(typeof(DocumentFontEmbedMode));
                foreach (DocumentFontEmbedMode i in a)
                {
                    _htmlEmbedFontModeComboBox.Items.Add(i);
                }
                _htmlEmbedFontModeComboBox.SelectedItem = htmlOptions.FontEmbedMode;

                _htmlUseBackgroundColorCheckBox.Checked = htmlOptions.UseBackgroundColor;

                _htmlBackgroundColorValueLabel.BackColor = Leadtools.Demos.Converters.ToGdiPlusColor(htmlOptions.BackgroundColor);

                _htmlBackgroundColorLabel.Enabled      = _htmlUseBackgroundColorCheckBox.Checked;
                _htmlBackgroundColorValueLabel.Enabled = _htmlUseBackgroundColorCheckBox.Checked;
                _htmlBackgroundColorButton.Enabled     = _htmlUseBackgroundColorCheckBox.Checked;
            }
            break;

            case DocumentFormat.Text:
                // Update the TEXT options page
            {
                _optionsTabControl.TabPages.Add(_textOptionsTabPage);

                TextDocumentOptions textOptions = _documentWriter.GetOptions(DocumentFormat.Text) as TextDocumentOptions;

                Array a = Enum.GetValues(typeof(TextDocumentType));
                foreach (TextDocumentType i in a)
                {
                    if (i == TextDocumentType.Ansi && ocrEngineType == OcrEngineType.OmniPageArabic)
                    {
                        continue;
                    }

                    _textDocumentTypeComboBox.Items.Add(i);
                }
                _textDocumentTypeComboBox.SelectedItem = textOptions.DocumentType;

                _textAddPageNumberCheckBox.Checked = textOptions.AddPageNumber;
                _textAddPageBreakCheckBox.Checked  = textOptions.AddPageBreak;
                _textFormattedCheckBox.Checked     = textOptions.Formatted;
            }
            break;

            case DocumentFormat.AltoXml:
                // Update the ALTOXML options page
            {
                _optionsTabControl.TabPages.Add(_altoXmlOptionsTabPage);
                AltoXmlDocumentOptions altoXmlOptions = _documentWriter.GetOptions(DocumentFormat.AltoXml) as AltoXmlDocumentOptions;

                Array a = Enum.GetValues(typeof(AltoXmlMeasurementUnit));
                foreach (AltoXmlMeasurementUnit i in a)
                {
                    _altoXmlMeasurementUnitComboBox.Items.Add(i);
                }
                _altoXmlMeasurementUnitComboBox.SelectedItem = altoXmlOptions.MeasurementUnit;

                _altoXmlFileNameTextBox.Text               = altoXmlOptions.FileName;
                _altoXmlSoftwareCreatorTextBox.Text        = altoXmlOptions.SoftwareCreator;
                _altoXmlSoftwareNameTextBox.Text           = altoXmlOptions.SoftwareName;
                _altoXmlApplicationDescriptionTextBox.Text = altoXmlOptions.ApplicationDescription;
                _altoXmlFormattedCheckBox.Checked          = altoXmlOptions.Formatted;
                _altoXmlIndentationTextBox.Text            = altoXmlOptions.Indentation;
                _altoXmlSortCheckBox.Checked               = altoXmlOptions.Sort;
                _altoXmlPlainTextCheckBox.Checked          = altoXmlOptions.PlainText;
                _altoXmlShowGlyphInfoCheckBox.Checked      = altoXmlOptions.ShowGlyphInfo;
                _altoXmlShowGlyphVariantsCheckBox.Checked  = altoXmlOptions.ShowGlyphVariants;
            }
            break;

            case DocumentFormat.Ltd:
            {
                _optionsTabControl.TabPages.Add(_ldOptionsTabPage);
            }
            break;

            case DocumentFormat.Emf:
            {
                _optionsTabControl.TabPages.Add(_emfOptionsTabPage);
            }
            break;

            default:
            {
                _optionsTabControl.TabPages.Add(_emptyOptionsTabPage);
                _emptyOptionsTabPage.Text = string.Format("{0} Options", DocumentWriter.GetFormatFileExtension(_format).ToUpperInvariant());
            }
            break;
            }

            Text = DocumentWriter.GetFormatFriendlyName(_format) + " " + DemosGlobalization.GetResxString(GetType(), "Resx_Options");

            UpdateUIState();
        }
Ejemplo n.º 23
0
        private static void RunQuery()
        {
            var query = @" {
                droids {
                    droidId
                    name
                    primaryFunction
                    appearsIn
                    friends {
                        name
                        ... on Human {
                            humanId
                            appearsIn
                        }
                    }
                }
            }";

            var    executer = new DocumentExecuter();
            var    writer = new DocumentWriter(true);
            string output1, output2;

            // Example 1 - QueryRoot.
            using (var root = new QueryRoot())
                using (var schema = new Schema <QueryRoot>())
                {
                    var result = executer.ExecuteAsync(schema, root, query, null).Result;
                    output1 = writer.Write(result);
                    Console.WriteLine("Example 1 output (QueryRoot):");
                    Console.WriteLine("-----------------------------");
                    Console.WriteLine(output1);
                    Console.WriteLine();
                }

            // Example 2 - DbContext.
            // I get the feeling there are reasons why wouldn't
            // want to do this but for simple scenarios it seems to suffice.
            using (var db = new StarWarsContext())
                using (var schema = new Schema <StarWarsContext>())
                {
                    var result = executer.ExecuteAsync(schema, db, query, null).Result;
                    output2 = writer.Write(result);
                    Console.WriteLine("Example 2 output (StarWarsContext):");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine(output2);
                    Console.WriteLine();
                }

            // Confirm we got the same result, just 'cause...
            var defaultColor = Console.ForegroundColor;

            if (output1 == output2)
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("✓ Outputs are the same");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("× Outputs are different");
            }
            Console.ForegroundColor = defaultColor;
        }
        public async Task NonEmptyApiTest()
        {
            var viewerType = new ApiObjectType(
                "viewer",
                new[] { ApiField.Scalar("id", EnScalarType.Integer), ApiField.Scalar("name", EnScalarType.String) });

            var api = new ApiDescription(
                "TestApi1",
                "0.0.0.1",
                new[] { viewerType },
                new[] { viewerType.CreateField("viewer") });

            var provider = new MoqProvider
            {
                Description = api,
                Data        = "{\"viewer\": {\"__id\": 1, \"name\": \"test name\"}}"
            };

            var schema = SchemaGenerator.Generate(new List <ApiProvider> {
                provider
            });

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine("-------- Schema -----------");
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.NotNull(schema.Query);
            Assert.Equal(3, schema.Query.Fields.Count());
            Assert.True(schema.Query.HasField("api"));

            var result = await new DocumentExecuter().ExecuteAsync(
                r =>
            {
                r.Schema = schema;
                r.Query  = @"
                                query {
                                    api {
                                        viewer {
                                            __id,
                                            name
                                        }
                                    }
                                }            
                                ";
            }).ConfigureAwait(true);

            this.output.WriteLine("-------- Response -----------");
            var response = new DocumentWriter(true).Write(result);

            this.output.WriteLine(response);
            var expectedResponse = @"{
                                      ""data"": {
                                        ""api"": {
                                          ""viewer"": {
                                            ""__id"": 1,
                                            ""name"": ""test name""
                                          }
                                        }
                                      }
                                    }";

            Assert.Equal(CleanResponse(expectedResponse), CleanResponse(response));
        }
Ejemplo n.º 25
0
        internal static void ObjectTemplate(HtmlHelper html, IXcstPackage package, ISequenceWriter <object> seqOutput, TemplateHelpers.TemplateHelperDelegate templateHelper)
        {
            ViewDataDictionary viewData      = html.ViewData;
            ModelMetadata      modelMetadata = viewData.ModelMetadata;

            if (modelMetadata.Model is null ||
                viewData.TemplateInfo.TemplateDepth > 1)
            {
                MetadataInstructions.DisplayTextHelper(html, seqOutput, modelMetadata);
                return;
            }

            var filteredProperties = DisplayInstructions.DisplayProperties(html);
            var groupedProperties  = filteredProperties.GroupBy(p => p.GroupName());

            bool createFieldset = groupedProperties.Any(g => g.Key != null);

            foreach (var group in groupedProperties)
            {
                XcstWriter?fieldsetWriter = null;

                if (createFieldset)
                {
                    fieldsetWriter = DocumentWriter.CastElement(package, seqOutput);

                    fieldsetWriter.WriteStartElement("fieldset");
                    fieldsetWriter.WriteStartElement("legend");
                    fieldsetWriter.WriteString(group.Key);
                    fieldsetWriter.WriteEndElement();
                }

                foreach (ModelMetadata propertyMeta in group)
                {
                    XcstWriter?fieldWriter = null;

                    if (!propertyMeta.HideSurroundingHtml)
                    {
                        XcstDelegate <object>?memberTemplate =
                            DisplayInstructions.MemberTemplate(html, propertyMeta);

                        if (memberTemplate != null)
                        {
                            memberTemplate(null !/* argument is not used */, fieldsetWriter ?? seqOutput);
                            continue;
                        }

                        XcstWriter labelWriter = fieldsetWriter
                                                 ?? DocumentWriter.CastElement(package, seqOutput);

                        labelWriter.WriteStartElement("div");
                        labelWriter.WriteAttributeString("class", "display-label");
                        labelWriter.WriteString(propertyMeta.GetDisplayName() ?? String.Empty);
                        labelWriter.WriteEndElement();

                        fieldWriter = fieldsetWriter
                                      ?? DocumentWriter.CastElement(package, seqOutput);

                        fieldWriter.WriteStartElement("div");
                        fieldWriter.WriteAttributeString("class", "display-field");
                    }

                    templateHelper(
                        html,
                        package,
                        fieldWriter ?? fieldsetWriter ?? seqOutput,
                        propertyMeta,
                        htmlFieldName: propertyMeta.PropertyName,
                        templateName: null,
                        membersNames: null,
                        DataBoundControlMode.ReadOnly,
                        additionalViewData: null
                        );

                    if (!propertyMeta.HideSurroundingHtml)
                    {
                        fieldWriter !.WriteEndElement(); // </div>
                    }
                }

                if (createFieldset)
                {
                    fieldsetWriter !.WriteEndElement(); // </fieldset>
                }
            }
        }
        public async Task SchemaDescriptionTest()
        {
            var checkAttributeArguments = new[]
            {
                ApiField.Scalar(
                    "attribute",
                    EnScalarType.String,
                    description: "attribute to check")
            };

            var objectFields = new[]
            {
                ApiField.Scalar(
                    "uid",
                    EnScalarType.Guid,
                    description: "The object unique identifier"),
                ApiField.Scalar("name", EnScalarType.String, description: "The object name"),
                ApiField.Scalar(
                    "attributes",
                    EnScalarType.String,
                    EnFieldFlags.IsArray,
                    description: "The object attributes"),
                ApiField.Scalar(
                    "checkAttribute",
                    EnScalarType.Boolean,
                    arguments: checkAttributeArguments,
                    description: "checks the attribute")
            };

            var objectType = new ApiObjectType("object", objectFields)
            {
                Description = "Some abstract object"
            };
            var apiField = objectType.CreateField(
                "new",
                description: "The new object data");

            var mutations = new[]
            {
                ApiMutation.CreateFromField(
                    ApiField.Object(
                        "objects_create",
                        "object",
                        arguments: new[] { apiField },
                        description: "creates a new object"),
                    ApiMutation.EnType.ConnectionCreate,
                    new List <ApiRequest>())
            };

            var api = new ApiDescription(
                "TestApi",
                "0.0.0.1",
                new[] { objectType },
                new[] { objectType.CreateField("objects", EnFieldFlags.IsConnection, "The objects dataset") },
                mutations)
            {
                Description = "The test api"
            };

            var provider = new MoqProvider {
                Description = api
            };
            var schema = SchemaGenerator.Generate(new List <ApiProvider> {
                provider
            });

            var errors = SchemaGenerator.CheckSchema(schema).Select(e => $"Schema type error: {e}")
                         .Union(SchemaGenerator.CheckSchemaIntrospection(schema))
                         .Select(e => $"Schema introspection error: {e}");

            var hasErrors = false;

            foreach (var error in errors)
            {
                hasErrors = true;
                this.output.WriteLine(error);
            }

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine("-------- Schema -----------");
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.False(hasErrors);
            var query = BaseInstaller.ReadTextResource(
                this.GetType().GetTypeInfo().Assembly,
                "KlusterKite.Web.Tests.GraphQL.Resources.IntrospectionQuery.txt");

            var result = await new DocumentExecuter().ExecuteAsync(
                r =>
            {
                r.Schema = schema;

                r.Query = query;
            }).ConfigureAwait(true);
            var response = new DocumentWriter(true).Write(result);

            this.output.WriteLine(response);

            var expectedResponse = BaseInstaller.ReadTextResource(
                this.GetType().GetTypeInfo().Assembly,
                "KlusterKite.Web.Tests.GraphQL.Resources.SchemaDescriptionTestSnapshot.txt");

            Assert.Equal(CleanResponse(expectedResponse), CleanResponse(response));
        }
Ejemplo n.º 27
0
        private void _documentFormatSelector_SelectedFormatChanged(object sender, EventArgs e)
        {
            // Change the Document Image file extension when the document format is changed.
            DocumentFormat format    = _documentFormatSelector.SelectedFormat;
            string         extension = DocumentWriter.GetFormatFileExtension(format);

            _documentFileNameTextBox.Text = Path.ChangeExtension(_documentFileNameTextBox.Text, extension);

            DocumentOptions options = JobData.OcrEngine.DocumentWriterInstance.GetOptions(_documentFormatSelector.SelectedFormat);

            _documentFormatSelector.TotalPages = JobData.LastPageNumber - JobData.FirstPageNumber;
            switch (_documentFormatSelector.SelectedFormat)
            {
            case DocumentFormat.Xps:
                _documentFormatSelector.FormatHasOptions = false;
                break;

            case DocumentFormat.Doc:
                _documentFormatSelector.FormatHasOptions = true;
                break;

            case DocumentFormat.Docx:
                _documentFormatSelector.FormatHasOptions = true;
                break;

            case DocumentFormat.Rtf:
                _documentFormatSelector.FormatHasOptions = true;
                break;

#if LEADTOOLS_V17_OR_LATER
            case DocumentFormat.Xls:
                _documentFormatSelector.FormatHasOptions = false;
                break;
#endif

#if LEADTOOLS_V19_OR_LATER
            case DocumentFormat.AltoXml:
                _documentFormatSelector.FormatHasOptions = true;
                break;

            case DocumentFormat.Pub:
                _documentFormatSelector.FormatHasOptions = false;
                break;

            case DocumentFormat.Mob:
                _documentFormatSelector.FormatHasOptions = false;
                break;

            case DocumentFormat.Svg:
                _documentFormatSelector.FormatHasOptions = false;
                break;
#endif // #if LEADTOOLS_V19_OR_LATER

            default:
                _documentFormatSelector.FormatHasOptions = true;
                break;
            }

            if (options != null)
            {
                JobData.OcrEngine.DocumentWriterInstance.SetOptions(_documentFormatSelector.SelectedFormat, options);
            }
        }
        public async Task ArraysApiTest()
        {
            var viewerFields = new[]
            {
                ApiField.Scalar("id", EnScalarType.Guid, EnFieldFlags.Queryable | EnFieldFlags.IsKey),
                ApiField.Scalar("name", EnScalarType.String),
                ApiField.Scalar("numbers", EnScalarType.Integer, EnFieldFlags.IsArray | EnFieldFlags.Queryable)
            };
            var viewerType = new ApiObjectType("viewer", viewerFields);

            var objectFields = new[]
            {
                ApiField.Scalar("id", EnScalarType.Integer, EnFieldFlags.IsKey | EnFieldFlags.Queryable),
                ApiField.Scalar("name", EnScalarType.String)
            };

            var objectType = new ApiObjectType("object", objectFields);

            var api = new ApiDescription(
                "TestApi1",
                "0.0.0.1",
                new[] { viewerType, objectType },
                new[] { viewerType.CreateField("viewer"), objectType.CreateField("object", EnFieldFlags.IsConnection | EnFieldFlags.Queryable) });

            var provider = new MoqProvider
            {
                Description = api,
                Data        = @"{
	                    ""viewer"": {
		                    ""__id"": ""FD73BAFB-3698-4FA1-81F5-27C8C83BB4F0"", 
		                    ""name"": ""test name"",
		                    ""numbers"": [1, 2, 3]
	                    }, 
	                    ""object"": {
		                    ""count"": 2, 
		                    ""edges"": [
			                    {""__id"": 10, ""node___id"": 10}, 
			                    {""__id"": 20, ""node___id"": 20}
		                    ]
	                    }
                    }"
            };

            var schema = SchemaGenerator.Generate(new List <ApiProvider> {
                provider
            });

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine("-------- Schema -----------");
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.NotNull(schema.Query);
            Assert.Equal(3, schema.Query.Fields.Count());
            Assert.True(schema.Query.HasField("api"));

            var result = await new DocumentExecuter().ExecuteAsync(
                r =>
            {
                r.Schema = schema;
                r.Query  = @"
                                query {
                                    api {
                                        viewer {
                                            __id,
                                            name,
                                            numbers
                                        },
                                        object {
                                            count,
                                            edges {
                                                cursor,                                                
                                                node {
                                                    __id
                                                }
                                            }
                                        }
                                    }
                                }            
                                ";
            }).ConfigureAwait(true);

            this.output.WriteLine("-------- Response -----------");
            var response = new DocumentWriter(true).Write(result);

            this.output.WriteLine(response);

            var expectedResponse = @"{
                                      ""data"": {
                                        ""api"": {
                                          ""viewer"": {
                                            ""__id"": ""fd73bafb-3698-4fa1-81f5-27c8c83bb4f0"",
                                            ""name"": ""test name"",
		                                    ""numbers"": [1, 2, 3]
                                          },
                                          ""object"": {
                                            ""count"": 2,
                                            ""edges"": [
                                              {
                                                ""cursor"": 10,
                                                ""node"": {
                                                  ""__id"": 10
                                                }
                                              },
                                              {
                                                ""cursor"": 20,
                                                ""node"": {
                                                  ""__id"": 20
                                                }
                                              }
                                            ]
                                          }
                                        }
                                      }
                                    }";

            Assert.Equal(CleanResponse(expectedResponse), CleanResponse(response));
        }
Ejemplo n.º 29
0
        public void Can_read()
        {
            var docs = new List <Document>
            {
                new Document(new Dictionary <string, string>
                {
                    { "title", "rambo" },
                    { "_id", "0" }
                }),
                new Document(new Dictionary <string, string>
                {
                    { "title", "rocky" },
                    { "_id", "1" }
                }),
                new Document(new Dictionary <string, string>
                {
                    { "title", "rocky 2" },
                    { "_id", "2" }
                })
            };

            var fileName = Path.Combine(Setup.Dir, "DocumentReaderTests.Can_read");
            var blocks   = new Dictionary <int, BlockInfo>();

            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                using (var writer = new DocumentWriter(fs))
                {
                    var index = 0;
                    foreach (var doc in docs)
                    {
                        doc.Id = index++;
                        blocks.Add(doc.Id, writer.Write(doc));
                    }
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs))
                {
                    var doc = reader.Get(new[] { blocks[2] });

                    Assert.That(doc.First().Id, Is.EqualTo(2));
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs))
                {
                    var doc = reader.Get(new[] { blocks[1] });

                    Assert.That(doc.First().Id, Is.EqualTo(1));
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs))
                {
                    var doc = reader.Get(new[] { blocks[0] });

                    Assert.That(doc.First().Id, Is.EqualTo(0));
                }

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                using (var reader = new DocumentReader(fs))
                {
                    var ds = reader.Get(blocks.Values.OrderBy(b => b.Position)).ToList();

                    Assert.That(docs.Count, Is.EqualTo(3));

                    Assert.IsTrue(ds.Any(d => d.Id == 0));
                    Assert.IsTrue(ds.Any(d => d.Id == 1));
                    Assert.IsTrue(ds.Any(d => d.Id == 2));
                }
        }
Ejemplo n.º 30
0
        private void _documentFormatSelector_SelectedFormatChanged(object sender, EventArgs e)
        {
            // Update the file name of the document with the correct extension
            string documentFileName = _tbFinalDocumentFileName.Text.Trim();

            if (!string.IsNullOrEmpty(documentFileName))
            {
                DocumentFormat format    = _documentFormatSelector.SelectedFormat;
                string         extension = DocumentWriter.GetFormatFileExtension(format);
                documentFileName = Path.ChangeExtension(documentFileName, extension);
                _tbFinalDocumentFileName.Text = documentFileName;
            }

            DocumentOptions options = _ocrEngine.DocumentWriterInstance.GetOptions(_documentFormatSelector.SelectedFormat);

            _documentFormatSelector.TotalPages = 1;

            switch (_documentFormatSelector.SelectedFormat)
            {
            case DocumentFormat.Xps:
                _documentFormatSelector.FormatHasOptions = false;
                break;

            case DocumentFormat.Doc:
                _documentFormatSelector.FormatHasOptions = true;
                break;

            case DocumentFormat.Docx:
                _documentFormatSelector.FormatHasOptions = true;
                break;

            case DocumentFormat.Rtf:
                _documentFormatSelector.FormatHasOptions = true;
                break;

#if LEADTOOLS_V17_OR_LATER
            case DocumentFormat.Xls:
                _documentFormatSelector.FormatHasOptions = false;
                break;
#endif // #if LEADTOOLS_V17_OR_LATER

#if LEADTOOLS_V19_OR_LATER
            case DocumentFormat.AltoXml:
                _documentFormatSelector.FormatHasOptions = true;
                break;

            case DocumentFormat.Pub:
                _documentFormatSelector.FormatHasOptions = false;
                break;

            case DocumentFormat.Mob:
                _documentFormatSelector.FormatHasOptions = false;
                break;

            case DocumentFormat.Svg:
                _documentFormatSelector.FormatHasOptions = false;
                break;
#endif // #if LEADTOOLS_V19_OR_LATER

            default:
                _documentFormatSelector.FormatHasOptions = true;
                break;
            }

            if (options != null)
            {
                _ocrEngine.DocumentWriterInstance.SetOptions(_documentFormatSelector.SelectedFormat, options);
            }
        }
Ejemplo n.º 31
0
        public void Save()
        {
            try
            {
                _saving = true;
                if (_tempFiles.Count == 0)
                {
                    MessageBox.Show("No pages where printed.", FrmMain._strTittle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                Application.DoEvents();
                string             strName            = _savename;
                DocumentFormat     documentFormat     = DocumentFormat.User;
                DocumentOptions    documentOptions    = null;
                PdfDocumentOptions PdfdocumentOptions = new PdfDocumentOptions();

                InstallFonts();

                string strExt = "";

                if (_format.ToLower() == "pdf")
                {
                    documentFormat  = DocumentFormat.Pdf;
                    documentOptions = new PdfDocumentOptions();
                    (documentOptions as PdfDocumentOptions).DocumentType  = PdfDocumentType.Pdf;
                    (documentOptions as PdfDocumentOptions).FontEmbedMode = DocumentFontEmbedMode.Auto;
                    strExt = "pdf";
                }

                if (_format.ToLower() == "doc")
                {
                    documentFormat  = DocumentFormat.Doc;
                    documentOptions = new DocDocumentOptions();
                    (documentOptions as DocDocumentOptions).TextMode = DocumentTextMode.Framed;
                    strExt = "doc";
                }

                if (_format.ToLower() == "xps")
                {
                    documentFormat  = DocumentFormat.Xps;
                    documentOptions = new XpsDocumentOptions();
                    strExt          = "xps";
                }

                if (_format.ToLower() == "text")
                {
                    documentFormat  = DocumentFormat.Text;
                    documentOptions = new TextDocumentOptions();
                    strExt          = "txt";
                }

                if (!strName.Contains("." + strExt.ToLower()))
                {
                    strName += "." + strExt.ToLower();
                }

                if (_jobData != null)
                {
                    strName = Path.GetDirectoryName(strName) + "\\(" + _jobData.IPAddress + ") " + Path.GetFileName(strName);
                }

                _fileSaved = strName;

                DocumentWriter documentWriter = new DocumentWriter();
                documentWriter.SetOptions(documentFormat, documentOptions);
                documentWriter.BeginDocument(strName, documentFormat);

                foreach (string strFile in _tempFiles)
                {
#if LEADTOOLS_V20_OR_LATER
                    DocumentWriterEmfPage documentPage = new DocumentWriterEmfPage();
#elif LEADTOOLS_V19_OR_LATER
                    DocumentEmfPage documentPage = new DocumentEmfPage();
#else
                    DocumentPage documentPage = DocumentPage.Empty;
#endif // #if LEADTOOLS_V19_OR_LATER
                    Metafile metaFile = new Metafile(strFile);

                    documentPage.EmfHandle = metaFile.GetHenhmetafile();

                    documentWriter.AddPage(documentPage);

                    (new Metafile(documentPage.EmfHandle, true)).Dispose();
                    metaFile.Dispose();
                }
                documentWriter.EndDocument();

                _saved  = true;
                _saving = false;
            }
            catch (Exception Ex)
            {
                _saving = false;
                MessageBox.Show(Ex.Message, FrmMain._strTittle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Check the schema against introspection query
        /// </summary>
        /// <param name="schema">The schema</param>
        /// <returns>List of errors</returns>
        public static IEnumerable <string> CheckSchemaIntrospection(Schema schema)
        {
            var result = new DocumentExecuter().ExecuteAsync(
                r =>
            {
                r.Schema      = schema;
                r.Query       = Queries.IntrospectionQuery;
                r.UserContext = new RequestContext();
            }).Result;
            var response = new DocumentWriter(true).Write(result);
            var json     = JObject.Parse(response);
            var types    =
                (json.SelectToken("data.__schema.types") as JArray)?.ToDictionary(
                    p => ((JObject)p).Property("name")?.Value,
                    p => (JObject)p);

            if (types == null)
            {
                yield return("Could not get types list via introspection");

                yield break;
            }

            var inputTypesChecked = new List <string>();

            foreach (var type in types.Values.Where(t => !t.Property("name").Value.ToObject <string>().StartsWith("__")))
            {
                var typeName = type.Property("name").Value.ToObject <string>();
                var fields   = type.Property("fields")?.Value as JArray;
                if (fields != null)
                {
                    foreach (var field in fields)
                    {
                        var fieldType = field.SelectToken("type.kind")?.ToObject <string>() == "LIST"
                                            ? field.SelectToken("type.ofType.name")?.ToObject <string>()
                                            : field.SelectToken("type.name")?.ToObject <string>();
                        var fieldName = field.SelectToken("name")?.ToObject <string>();
                        if (!types.ContainsKey(fieldType ?? string.Empty))
                        {
                            yield return($"{typeName} property {fieldName} has unknown type {fieldType}");
                        }

                        var arguments = field.SelectToken("args") as JArray;
                        if (arguments == null || arguments.Count == 0)
                        {
                            continue;
                        }

                        foreach (var argument in arguments)
                        {
                            var argumentType = argument.SelectToken("type.kind")?.ToObject <string>() == "LIST"
                                                   ? argument.SelectToken("type.ofType.name")?.ToObject <string>()
                                                   : argument.SelectToken("type.name")?.ToObject <string>();
                            var argumentName = argument.SelectToken("name")?.ToObject <string>();

                            JObject argumentTypeJson;
                            if (!types.TryGetValue(argumentType ?? string.Empty, out argumentTypeJson))
                            {
                                yield return
                                    ($"{typeName} property {fieldName} "
                                     + $"has argument {argumentName} of unknown type {argumentType}");
                            }
                            else
                            {
                                var argumentTypeKind = argumentTypeJson.SelectToken("kind").ToObject <string>();
                                if (argumentTypeKind != "SCALAR" && argumentTypeKind != "ENUM" &&
                                    argumentTypeKind != "INPUT_OBJECT")
                                {
                                    yield return
                                        ($"{typeName} property {fieldName} "
                                         + $"has argument {argumentName} of type {argumentType} "
                                         + $"of unsupported kind {argumentTypeKind}");
                                }
                                else if (argumentTypeKind == "INPUT_OBJECT")
                                {
                                    foreach (
                                        var error in
                                        CheckIntrospectionInputType(argumentTypeJson, types, inputTypesChecked))
                                    {
                                        yield return(error);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }