public override void Import(DocumentNode node) { if (node is ChildCollection) { var col = (ChildCollection)node; if (col.Count > 0 && col[0] is Element && ((Element)col[0]).Name.ToLower() == "html") { var html = (Element)col[0]; if (html.Children.Count > 1 && html.Children[1] is Element && ((Element)html.Children[1]).Name.ToLower() == "body") { var body = (Element)html.Children[1]; var txt = body.Children.Text; // remove identation var builder = new StringBuilder(); var lines = txt.Split('\n').ToList(); lines.RemoveAt(0); var mint = lines.Select(l => l.TakeWhile(ch => ch == '\t').Count()).Min(); // compute minimal tab indentation if (mint > 0) { while (mint-- > 0) builder.Append('\t'); var indent = builder.ToString(); lines = lines.Select(l => l.Replace(indent, "")).ToList(); } builder.Clear(); builder.AppendLine(); foreach (var l in lines) { builder.Append(l); builder.Append('\n'); } col.Text = builder.ToString(); } } } }
public virtual void Export(DocumentNode node, out string html) { Export(node); var w = node.Writer; node.Writer = Writer; html = node.Text; node.Writer = w; }
public override void Visit(DocumentNode node) { StartVisit(node); var first = true; foreach(var child in node.Childs) { if ((!first) && (!(child is CodeBlockNode))) WriteText(System.Environment.NewLine); Visit(child); if ((!(child is MetaNode)) && (!(child is CodeBlockNode))) first = false; } EndVisit(node); }
internal DocumentNode Parse(InputReader reader) { var document = new DocumentNode(); _rules.Add(new MetaMarkupRule(document)); var parserReader = new ParserReader(_rules, reader); while(parserReader.Read()) { var node = parserReader.ParseNode(); if(node != null) document.Childs.Add(node); } return document; }
public virtual void Write(DocumentNode node) { if (node is Literal) { WriteLiteral((Literal)node); return; } if (node is Attribute) { WriteAttribute((Attribute)node); return; } if (node is Doctype) { WriteDoctype((Doctype)node); return; } if (node is ServerTag) { WriteServerTag((ServerTag)node); return; } if (node is Tag) { WriteTag((Tag)node); return; } if (node is XmlDocHeader) { WriteXmlDocHeader((XmlDocHeader)node); return; } if (node is Style) { WriteStyle((Style)node); return; } if (node is Script) { WriteScript((Script)node); return; } if (node is SpecialElement) { WriteSpecialElement((SpecialElement)node); return; } if (node is AttributeCollection) { WriteAttributes((AttributeCollection)node); return; } if (node is ChildCollection) { WriteChildren((ChildCollection)node); return; } if (node is Element) { WriteElement((Element)node); return; } if (node is Document) { WriteDocument((Document)node); return; } }
public virtual void Export(DocumentNode node) { if (node is Literal) { ExportLiteral((Literal)node); return; } if (node is Attribute) { ExportAttribute((Attribute)node); return; } if (node is Doctype) { ExportDoctype((Doctype)node); return; } if (node is ServerTag) { ExportServerTag((ServerTag)node); return; } if (node is Tag) { ExportTag((Tag)node); return; } if (node is XmlDocHeader) { ExportXmlDocHeader((XmlDocHeader)node); return; } if (node is Style) { ExportStyle((Style)node); return; } if (node is Script) { ExportScript((Script)node); return; } if (node is SpecialElement) { ExportSpecialElement((SpecialElement)node); return; } if (node is AttributeCollection) { ExportAttributes((AttributeCollection)node); return; } if (node is ChildCollection) { ExportChildren((ChildCollection)node); return; } if (node is Element) { ExportElement((Element)node); return; } if (node is Document) { ExportDocument((Document)node); return; } }
public static void Convert(DocumentNode document, Stream ostream) { if(null == document) throw Xception.Because.ArgumentNull(() => document); var references = new ReferenceCollection(document); using(var xmlWriter = XmlWriter.Create(ostream, new XmlWriterSettings { CloseOutput = false, Indent = true, IndentChars = "\t", NewLineChars = "\n", OmitXmlDeclaration = true })) { xmlWriter.WriteDocType("html", null, null, null); xmlWriter.WriteStartElement("html"); xmlWriter.WriteStartElement("body"); document.HandleWith(new XmlWritingNodeHandler(xmlWriter, references)); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); } }
private static void WriteDocumentInfo(DocumentNode dn) { Console.WriteLine(dn.Name + "\t" + dn.TaskCount.ToString() + "\t" + dn.RelativePath + "\t" + dn.ID); }
public virtual void Visit(DocumentNode node) { foreach(var chield in node.Childs) Visit(chield); }
protected void DoDrop(DragEventArgs eventArgs, int destinationIndex) { IDataObject data = eventArgs.Data; if (this.ResourceManager.IsFiltering) { return; } ResourceEntryItem resourceEntry = (ResourceEntryItem)null; if (!this.CanDrop(eventArgs, out resourceEntry) || resourceEntry == this) { return; } ResourceContainer dropTargetContainer = this.DragDropTargetContainer; if (resourceEntry.Container == dropTargetContainer) { if ((eventArgs.KeyStates & DragDropKeyStates.ControlKey) == DragDropKeyStates.ControlKey) { using (SceneEditTransaction editTransaction = resourceEntry.Container.ViewModel.CreateEditTransaction(StringTable.UndoUnitCopyResource)) { DocumentCompositeNode entryNode = resourceEntry.Resource.ResourceNode.Clone(dropTargetContainer.ViewModel.Document.DocumentContext) as DocumentCompositeNode; DocumentNode keyNode = Microsoft.Expression.DesignSurface.Utility.ResourceHelper.GenerateUniqueResourceKey(resourceEntry.Key.ToString(), dropTargetContainer.Node); ResourceNodeHelper.SetResourceEntryKey(entryNode, keyNode); Microsoft.Expression.DesignSurface.Utility.ResourceHelper.AddResource((DictionaryEntryNode)dropTargetContainer.ViewModel.GetSceneNode((DocumentNode)entryNode), dropTargetContainer.ResourceDictionaryNode, destinationIndex); editTransaction.Commit(); } } else { resourceEntry.Container.MoveItem(resourceEntry, destinationIndex); } } else { ObservableCollection <string> observableCollection = new ObservableCollection <string>(); observableCollection.Add(dropTargetContainer.DocumentContext.DocumentUrl); bool skipReferencedResourceCopy = this.IsContainerReachable((IEnumerable <string>)observableCollection, resourceEntry.Container); if ((eventArgs.KeyStates & DragDropKeyStates.ControlKey) == DragDropKeyStates.ControlKey) { this.CopyItem(resourceEntry, dropTargetContainer, destinationIndex, skipReferencedResourceCopy); } else { ReferencesFoundModel referencingResources = resourceEntry.InteractiveGetReferencingResources(ReferencesFoundModel.UseScenario.DeleteResource); if (referencingResources == null) { return; } bool doReferenceFixup = false; if (referencingResources.ReferenceNames.Count > 0 && !this.IsContainerReachable((IEnumerable <string>)referencingResources.ScenesWithReferences, dropTargetContainer)) { if (!new ReferencesFoundDialog(referencingResources).ShowDialog().GetValueOrDefault(false)) { return; } doReferenceFixup = referencingResources.SelectedUpdateMethod != ReferencesFoundModel.UpdateMethod.DontFix; } if (dropTargetContainer.ViewModel == resourceEntry.Container.ViewModel) { using (SceneEditTransaction editTransaction = dropTargetContainer.ViewModel.CreateEditTransaction(StringTable.UndoUnitMoveResource)) { if (this.MoveItem(resourceEntry, dropTargetContainer, destinationIndex, skipReferencedResourceCopy, referencingResources, doReferenceFixup)) { editTransaction.Commit(); } else { editTransaction.Cancel(); } } } else { this.MoveItem(resourceEntry, dropTargetContainer, destinationIndex, skipReferencedResourceCopy, referencingResources, doReferenceFixup); } } } }
// Token: 0x06003490 RID: 13456 RVA: 0x000E997C File Offset: 0x000E7B7C internal void PreCoalesceChildren(ConverterState converterState, int nStart, bool bChild) { DocumentNodeArray documentNodeArray = new DocumentNodeArray(); bool flag = false; DocumentNode documentNode = this.EntryAt(nStart); int num = documentNode.ChildCount; if (nStart + num >= this.Count) { num = this.Count - nStart - 1; } int num2 = nStart + num; if (bChild) { nStart++; } for (int i = nStart; i <= num2; i++) { DocumentNode documentNode2 = this.EntryAt(i); if (documentNode2.IsInline && documentNode2.RequiresXamlDir && documentNode2.ClosedParent != null) { int j; for (j = i + 1; j <= num2; j++) { DocumentNode documentNode3 = this.EntryAt(j); if (!documentNode3.IsInline || documentNode3.Type == DocumentNodeType.dnHyperlink || documentNode3.FormatState.DirChar != documentNode2.FormatState.DirChar || documentNode3.ClosedParent != documentNode2.ClosedParent) { break; } } int num3 = j - i; if (num3 > 1) { DocumentNode documentNode4 = new DocumentNode(DocumentNodeType.dnInline); documentNode4.FormatState = new FormatState(documentNode2.Parent.FormatState); documentNode4.FormatState.DirChar = documentNode2.FormatState.DirChar; this.InsertChildAt(documentNode2.ClosedParent, documentNode4, i, num3); num2++; } } else if (documentNode2.Type == DocumentNodeType.dnListItem) { this.PreCoalesceListItem(documentNode2); } else if (documentNode2.Type == DocumentNodeType.dnList) { this.PreCoalesceList(documentNode2); } else if (documentNode2.Type == DocumentNodeType.dnTable) { documentNodeArray.Add(documentNode2); num2 += this.PreCoalesceTable(documentNode2); } else if (documentNode2.Type == DocumentNodeType.dnRow) { this.PreCoalesceRow(documentNode2, ref flag); } } if (flag) { this.ProcessTableRowSpan(documentNodeArray); } }
public QueryValidationResult Validate( ISchema schema, DocumentNode queryDocument) { throw new NotImplementedException(); }
private DocumentNode MergeSchemaExtensions(DocumentNode schema) { if (_extensions.Count == 0) { return(schema); } var rewriter = new AddSchemaExtensionRewriter(new[] { new DirectiveDefinitionNode ( null, new NameNode(GeneratorDirectives.ClrType), null, false, new[] { new InputValueDefinitionNode( null, new NameNode(GeneratorDirectives.NameArgument), null, new NonNullTypeNode(new NamedTypeNode(ScalarNames.String)), null, Array.Empty <DirectiveNode>() ) }, new [] { new NameNode(HotChocolate.Language.DirectiveLocation.Scalar.ToString()) } ), new DirectiveDefinitionNode ( null, new NameNode(GeneratorDirectives.SerializationType), null, false, new[] { new InputValueDefinitionNode( null, new NameNode(GeneratorDirectives.NameArgument), null, new NonNullTypeNode(new NamedTypeNode(ScalarNames.String)), null, Array.Empty <DirectiveNode>() ) }, new [] { new NameNode(HotChocolate.Language.DirectiveLocation.Scalar.ToString()) } ), new DirectiveDefinitionNode ( null, new NameNode(GeneratorDirectives.Name), null, false, new[] { new InputValueDefinitionNode( null, new NameNode(GeneratorDirectives.NameArgument), null, new NonNullTypeNode(new NamedTypeNode(ScalarNames.String)), null, Array.Empty <DirectiveNode>() ) }, new [] { new NameNode(HotChocolate.Language.DirectiveLocation.Scalar.ToString()) } ) }); DocumentNode currentSchema = schema; foreach (DocumentNode extension in _extensions) { currentSchema = rewriter.AddExtensions( currentSchema, extension); } return(currentSchema); }
public async Task Handle_Subscription_DataReceived_And_Completed() { // arrange var connection = new SocketConnectionMock(); var services = new ServiceCollection(); services.AddInMemorySubscriptionProvider(); services.AddStarWarsRepositories(); IQueryExecutor executor = SchemaBuilder.New() .AddServices(services.BuildServiceProvider()) .AddStarWarsTypes() .Create() .MakeExecutable(); DocumentNode query = Utf8GraphQLParser.Parse( "subscription { onReview(episode: NEWHOPE) { stars } }"); var handler = new DataStartMessageHandler(executor, null); var message = new DataStartMessage( "123", new GraphQLRequest(query)); // act await handler.HandleAsync( connection, message, CancellationToken.None); // assert Assert.Empty(connection.SentMessages); Assert.NotEmpty(connection.Subscriptions); IResponseStream stream = (IResponseStream)await executor.ExecuteAsync( "subscription { onReview(episode: NEWHOPE) { stars } }"); await executor.ExecuteAsync(@" mutation { createReview(episode:NEWHOPE review: { commentary: ""foo"" stars: 5 }) { stars } }"); using var cts = new CancellationTokenSource(15000); IAsyncEnumerator <IReadOnlyQueryResult> enumerator = stream.GetAsyncEnumerator(cts.Token); Assert.True(await enumerator.MoveNextAsync()); await Task.Delay(2000); Assert.Collection(connection.SentMessages, t => { Assert.True(t.SequenceEqual( new DataResultMessage(message.Id, enumerator.Current).Serialize())); }); }
protected override void EndVisit(DocumentNode node) { PopString(); _runContent.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Child"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeStatement[] { new CodeThrowExceptionStatement( new CodeObjectCreateExpression( new CodeTypeReference(typeof(InvalidOperationException)), new CodeBinaryOperatorExpression( new CodeBinaryOperatorExpression( new CodePrimitiveExpression("Template Entry Point "), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression("name") ), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(" is missing") ) ) ) }, new CodeStatement[] {new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),"Child"), "RunContent"), new CodeArgumentReferenceExpression("textWriter"), new CodeArgumentReferenceExpression("name") ) ) } )); _containsContent.Statements.Add( new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Child"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null) ), new CodeStatement[] {new CodeMethodReturnStatement(new CodePrimitiveExpression(false))}, new CodeStatement[] {new CodeMethodReturnStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),"Child"), "ContainsContent"), new CodeArgumentReferenceExpression("name") ) ) } )); base.EndVisit(node); }
internal ResourceEvaluation(DictionaryEntryNode originalResource, DocumentNode evaluatedResource, ResourceEvaluationResult conflictType) { this.originalResource = originalResource; this.evaluatedResource = evaluatedResource; this.conflictType = conflictType; }
protected virtual ISyntaxVisitorAction Leave( DocumentNode node, ISyntaxVisitorContext context) => DefaultAction;
protected override object CreateTileBrush(BaseFrameworkElement element) { DocumentNode documentNode = (DocumentNode)element.ViewModel.Document.DocumentContext.CreateNode(PlatformTypes.ImageBrush); return(element.ViewModel.CreateInstance(new DocumentNodePath(documentNode, documentNode))); }
private bool AppliesToImpl(DocumentNode node) { return(this.referentialObjectType.IsAssignableFrom((ITypeId)node.Type)); }
private bool IsSampleDataTypeNode(DocumentNode compositeNode) { return(this.SampleData.IsTypeOwner(DataContextHelper.GetDataType(compositeNode))); }
private static bool GetPathFigureAsString(DocumentNode pathFigureNode, StringBuilder stringBuilder) { bool flag; bool flag1; StringBuilder stringBuilder1; DocumentCompositeNode documentCompositeNode = pathFigureNode as DocumentCompositeNode; if (documentCompositeNode == null) { return(false); } if (PathGeometrySerializationHelper.IsCompositeOrNonDefaultValue <bool>(documentCompositeNode, PathMetadata.PathFigureIsFilledProperty, true)) { return(false); } Point point = new Point(); if (PathGeometrySerializationHelper.GetPrimitiveValue <Point>(documentCompositeNode, PathMetadata.PathFigureStartPointProperty, ref point) == PathGeometrySerializationHelper.PropertyValueKind.Composite) { return(false); } stringBuilder.Append('M'); PointSerializationHelper.AppendPoint(stringBuilder, point); DocumentNode item = documentCompositeNode.Properties[PathMetadata.PathFigureSegmentsProperty]; if (item != null) { DocumentCompositeNode documentCompositeNode1 = item as DocumentCompositeNode; if (documentCompositeNode1 == null) { return(false); } using (IEnumerator <DocumentNode> enumerator = documentCompositeNode1.Children.GetEnumerator()) { while (enumerator.MoveNext()) { if (PathGeometrySerializationHelper.GetPathSegmentAsString(enumerator.Current, stringBuilder)) { continue; } flag1 = false; return(flag1); } flag = false; if (PathGeometrySerializationHelper.GetPrimitiveValue <bool>(documentCompositeNode, PathMetadata.PathFigureIsClosedProperty, ref flag) == PathGeometrySerializationHelper.PropertyValueKind.Composite) { return(false); } if (flag) { stringBuilder1 = stringBuilder.Append(" z"); } return(true); } return(flag1); } flag = false; if (PathGeometrySerializationHelper.GetPrimitiveValue <bool>(documentCompositeNode, PathMetadata.PathFigureIsClosedProperty, ref flag) == PathGeometrySerializationHelper.PropertyValueKind.Composite) { return(false); } if (flag) { stringBuilder1 = stringBuilder.Append(" z"); } return(true); }
private IEnumerable <MamlCommand> NodeModelToMamlModelV2(DocumentNode doc, string[] applicableTag = null) { return((new ModelTransformerVersion2(null, null, applicableTag)).NodeModelToMamlModel(doc)); }
public SelfSourceContextReference(DocumentNode documentNode) : base(documentNode) { }
public async Task ValidateMaxComplexityWithMiddlewareWithObjectsAndVar( int count, bool valid) { // arrange var schema = Schema.Create( @" type Query { foo(i: FooInput): String @cost(complexity: 5 multipliers: [""i.index""]) } input FooInput { index : Int } ", c => { c.BindResolver(() => "Hello") .To("Query", "foo"); }); var options = new Mock <IValidateQueryOptionsAccessor>(); options.SetupGet(t => t.MaxOperationComplexity).Returns(20); options.SetupGet(t => t.UseComplexityMultipliers).Returns(true); DocumentNode query = Parser.Default.Parse( "query f($i:Int) { foo(i: { index:$i }) }"); OperationDefinitionNode operationNode = query.Definitions .OfType <OperationDefinitionNode>() .FirstOrDefault(); var operation = new Operation ( query, operationNode, new VariableValueBuilder( schema, operationNode) .CreateValues(new Dictionary <string, object> { { "i", count } }), schema.QueryType, null ); IReadOnlyQueryRequest request = QueryRequestBuilder.New() .SetQuery("{ a }") .Create(); var services = new DictionaryServiceProvider( new KeyValuePair <Type, object>( typeof(IErrorHandler), ErrorHandler.Default)); var context = new QueryContext ( schema, services.CreateRequestServiceScope(), request, (f, s) => f.Middleware ) { Document = query, Operation = operation }; var middleware = new MaxComplexityMiddleware( c => Task.CompletedTask, options.Object, null); // act await middleware.InvokeAsync(context); // assert if (valid) { Assert.Null(context.Result); } else { context.Result.Snapshot( "ValidateMaxComplexityWithMiddlewareWithObjectsAndVar" + count); } }
private static bool SearchForAnimationsInTriggers(DocumentCompositeNode elementNode, IPropertyId triggersProperty, DocumentNode pathNameNode) { bool flag; IProperty property = elementNode.Context.TypeResolver.ResolveProperty(triggersProperty); if (property != null) { DocumentCompositeNode item = elementNode.Properties[property] as DocumentCompositeNode; if (item != null && item.Children != null) { using (IEnumerator <DocumentNode> enumerator = item.FindPointAnimationDescendantNodes().GetEnumerator()) { while (enumerator.MoveNext()) { if (!PathGeometrySerializationHelper.DoesAnimationTargetPath(pathNameNode, enumerator.Current)) { continue; } flag = true; return(flag); } return(false); } return(flag); } } return(false); }
public void TestInPlaceNPOIFSWrite() { NPOIFSFileSystem fs = null; DirectoryEntry root = null; DocumentNode sinfDoc = null; DocumentNode dinfDoc = null; SummaryInformation sinf = null; DocumentSummaryInformation dinf = null; // We need to work on a File for in-place changes, so create a temp one FileInfo copy = TempFile.CreateTempFile("Test-HPSF", "ole2"); //copy.DeleteOnExit(); // Copy a test file over to a temp location Stream inp = _samples.OpenResourceAsStream("TestShiftJIS.doc"); FileStream out1 = new FileStream(copy.FullName, FileMode.Create); IOUtils.Copy(inp, out1); inp.Close(); out1.Close(); // Open the copy in Read/write mode fs = new NPOIFSFileSystem(new FileStream(copy.FullName, FileMode.Open, FileAccess.ReadWrite), null, false, true); root = fs.Root; // Read the properties in there sinfDoc = (DocumentNode)root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); sinf = (SummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(sinfDoc)); Assert.AreEqual(131077, sinf.OSVersion); dinf = (DocumentSummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(dinfDoc)); Assert.AreEqual(131077, dinf.OSVersion); // Check they start as we expect Assert.AreEqual("Reiichiro Hori", sinf.Author); Assert.AreEqual("Microsoft Word 9.0", sinf.ApplicationName); Assert.AreEqual("\u7b2c1\u7ae0", sinf.Title); Assert.AreEqual("", dinf.Company); Assert.AreEqual(null, dinf.Manager); // Do an in-place replace via an InputStream new NPOIFSDocument(sinfDoc).ReplaceContents(sinf.ToInputStream()); new NPOIFSDocument(dinfDoc).ReplaceContents(dinf.ToInputStream()); // Check it didn't Get Changed sinfDoc = (DocumentNode)root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); sinf = (SummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(sinfDoc)); Assert.AreEqual(131077, sinf.OSVersion); dinf = (DocumentSummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(dinfDoc)); Assert.AreEqual(131077, dinf.OSVersion); // Start again! fs.Close(); inp = _samples.OpenResourceAsStream("TestShiftJIS.doc"); out1 = new FileStream(copy.FullName, FileMode.Open, FileAccess.ReadWrite); IOUtils.Copy(inp, out1); inp.Close(); out1.Close(); fs = new NPOIFSFileSystem(new FileStream(copy.FullName, FileMode.Open, FileAccess.ReadWrite), null, false, true); root = fs.Root; // Read the properties in once more sinfDoc = (DocumentNode)root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); sinf = (SummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(sinfDoc)); Assert.AreEqual(131077, sinf.OSVersion); dinf = (DocumentSummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(dinfDoc)); Assert.AreEqual(131077, dinf.OSVersion); // Have them write themselves in-place with no Changes sinf.Write(new NDocumentOutputStream(sinfDoc)); dinf.Write(new NDocumentOutputStream(dinfDoc)); // And also write to some bytes for Checking MemoryStream sinfBytes = new MemoryStream(); sinf.Write(sinfBytes); MemoryStream dinfBytes = new MemoryStream(); dinf.Write(dinfBytes); // Check that the filesystem can give us back the same bytes sinfDoc = (DocumentNode)root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME); dinfDoc = (DocumentNode)root.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); byte[] sinfData = IOUtils.ToByteArray(new NDocumentInputStream(sinfDoc)); byte[] dinfData = IOUtils.ToByteArray(new NDocumentInputStream(dinfDoc)); Assert.That(sinfBytes.ToArray(), new EqualConstraint(sinfData)); Assert.That(dinfBytes.ToArray(), new EqualConstraint(dinfData)); // Read back in as-is sinf = (SummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(sinfDoc)); Assert.AreEqual(131077, sinf.OSVersion); dinf = (DocumentSummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(dinfDoc)); Assert.AreEqual(131077, dinf.OSVersion); Assert.AreEqual("Reiichiro Hori", sinf.Author); Assert.AreEqual("Microsoft Word 9.0", sinf.ApplicationName); Assert.AreEqual("\u7b2c1\u7ae0", sinf.Title); Assert.AreEqual("", dinf.Company); Assert.AreEqual(null, dinf.Manager); // Now alter a few of them sinf.Author = (/*setter*/ "Changed Author"); sinf.Title = (/*setter*/ "Le titre \u00e9tait chang\u00e9"); dinf.Manager = (/*setter*/ "Changed Manager"); // Save this into the filesystem sinf.Write(new NDocumentOutputStream(sinfDoc)); dinf.Write(new NDocumentOutputStream(dinfDoc)); // Read them back in again sinfDoc = (DocumentNode)root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinf = (SummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(sinfDoc)); Assert.AreEqual(131077, sinf.OSVersion); dinfDoc = (DocumentNode)root.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinf = (DocumentSummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(dinfDoc)); Assert.AreEqual(131077, dinf.OSVersion); Assert.AreEqual("Changed Author", sinf.Author); Assert.AreEqual("Microsoft Word 9.0", sinf.ApplicationName); Assert.AreEqual("Le titre \u00e9tait chang\u00e9", sinf.Title); Assert.AreEqual("", dinf.Company); Assert.AreEqual("Changed Manager", dinf.Manager); // Close the whole filesystem, and open it once more fs.WriteFileSystem(); fs.Close(); fs = new NPOIFSFileSystem(new FileStream(copy.FullName, FileMode.Open)); root = fs.Root; // Re-check on load sinfDoc = (DocumentNode)root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME); sinf = (SummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(sinfDoc)); Assert.AreEqual(131077, sinf.OSVersion); dinfDoc = (DocumentNode)root.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); dinf = (DocumentSummaryInformation)PropertySetFactory.Create(new NDocumentInputStream(dinfDoc)); Assert.AreEqual(131077, dinf.OSVersion); Assert.AreEqual("Changed Author", sinf.Author); Assert.AreEqual("Microsoft Word 9.0", sinf.ApplicationName); Assert.AreEqual("Le titre \u00e9tait chang\u00e9", sinf.Title); Assert.AreEqual("", dinf.Company); Assert.AreEqual("Changed Manager", dinf.Manager); // Tidy up fs.Close(); copy.Delete(); }
public async Task BuildAsync() { if (_output is null) { throw new InvalidOperationException( "You have to specify a field output handler before you " + "can generate any client APIs."); } if (_schemas.Count == 0) { throw new InvalidOperationException( "You have to specify at least one schema file before you " + "can generate any client APIs."); } if (_queries.Count == 0) { throw new InvalidOperationException( "You have to specify at least one query file before you " + "can generate any client APIs."); } IDocumentHashProvider hashProvider = _hashProvider ?? new MD5DocumentHashProvider(); _namespace = _namespace ?? "StrawberryShake.Client"; // create schema DocumentNode mergedSchema = MergeSchema(); mergedSchema = MergeSchemaExtensions(mergedSchema); ISchema schema = CreateSchema(mergedSchema); InitializeScalarTypes(schema); // parse queries IReadOnlyList <HCError> errors = ValidateQueryDocuments(schema); if (errors.Count > 0) { throw new GeneratorException(errors); } IReadOnlyList <IQueryDescriptor> queries = await ParseQueriesAsync(hashProvider) .ConfigureAwait(false); // generate abstarct client models var usedNames = new HashSet <string>(); var descriptors = new List <ICodeDescriptor>(); var fieldTypes = new Dictionary <FieldNode, string>(); GenerateModels(schema, queries, usedNames, descriptors, fieldTypes); var typeLookup = new TypeLookup( _options.LanguageVersion, _leafTypes.Values, fieldTypes); // generate code from models foreach (ICodeGenerator generator in CreateGenerators(_options)) { foreach (ICodeDescriptor descriptor in descriptors) { if (generator.CanHandle(descriptor)) { _output.Register(descriptor, generator); } } } await _output.WriteAllAsync(typeLookup) .ConfigureAwait(false); }
public async Task <int> OnExecute() { var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(Url); if (Token != null) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( Scheme ?? "bearer", Token); } var stopwatch = Stopwatch.StartNew(); Console.WriteLine("Download schema started."); DocumentNode schema = await IntrospectionClient.LoadSchemaAsync(httpClient); schema = IntrospectionClient.RemoveBuiltInTypes(schema); Console.WriteLine( "Download schema completed in " + $"{stopwatch.ElapsedMilliseconds} ms."); stopwatch.Restart(); Console.WriteLine("Client configuration started."); if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } SchemaName = SchemaName ?? "schema"; string schemaFielName = SchemaName + ".graphql"; var configuration = new Configuration(); configuration.ClientName = SchemaName + "Client"; configuration.Schemas = new List <SchemaFile>(); configuration.Schemas.Add(new SchemaFile { Type = "http", Name = SchemaName, File = schemaFielName, Url = Url }); using (var stream = File.Create(IOPath.Combine(Path, "config.json"))) { await JsonSerializer.SerializeAsync(stream, configuration); } using (var stream = File.Create(IOPath.Combine(Path, schemaFielName))) { using (var sw = new StreamWriter(stream)) { SchemaSyntaxSerializer.Serialize(schema, sw, true); } } Console.WriteLine( "Client configuration completed in " + $"{stopwatch.ElapsedMilliseconds} ms for {Path}."); return(0); }
public override void Visit(DocumentNode node) { List<MetaNode> data; if (node.Metadata.TryGetValue("namespace",out data)) { foreach (MetaNode str in data) { WriteText("<%@ Import Namespace=\""+str.Value+"\" %>" + Environment.NewLine); } } if (node.Metadata.TryGetValue("assembly",out data)) { foreach (MetaNode str in data) { WriteText("<%@ Assembly Name=\"" + str.Value + "\" %>" + Environment.NewLine); } } MetaNode pagedefiniton = MetaDataFiller.FillAndGetPageDefinition(node.Metadata, Options); if (pagedefiniton.Attributes.Find(x => x.Name == "Inherits") == null) { if (pagedefiniton.Name == "page") pagedefiniton.Attributes.Add(new AttributeNode("Inherits") { Value = new TextNode(new TextChunk("System.Web.Mvc.ViewPage")) }); else if (pagedefiniton.Name == "control") pagedefiniton.Attributes.Add(new AttributeNode("Inherits") { Value = new TextNode(new TextChunk("System.Web.Mvc.ViewUserControl")) }); else pagedefiniton.Attributes.Add(new AttributeNode("Inherits") { Value = new TextNode(new TextChunk("System.Web.Mvc.ViewMasterPage")) }); } if (node.Metadata.TryGetValue("type", out data)) { var tc = pagedefiniton.Attributes.Find(x => x.Name == "Inherits"); tc.Value = new TextNode(new TextChunk(((tc.Value as TextNode).Chunks[0] as TextChunk).Text + "<" + data[0].Value + ">")); } if (pagedefiniton.Name == "page") { WriteText("<%@ Page "); } else if (pagedefiniton.Name == "control") { WriteText("<%@ Control "); } else { WriteText("<%@ Master "); } foreach (var attr in pagedefiniton.Attributes) { WriteText(attr.Name); WriteText("=\""); WriteText(((attr.Value as TextNode).Chunks[0] as TextChunk).Text); WriteText("\" "); } WriteText(" %>" + System.Environment.NewLine); bool hasContentMetaFlags = node.Metadata.ContainsKey("content") || pagedefiniton.Name != "page"; if (!hasContentMetaFlags) { WriteText("<asp:Content ID=\"Main\" runat=\"server\">"); WriteText(Environment.NewLine); Indent++; } foreach(var child in node.Childs) { WriteText(System.Environment.NewLine); Visit(child); } if (!hasContentMetaFlags) { WriteText(System.Environment.NewLine); Indent--; WriteIndent(); WriteText("</asp:Content>"); } }
public Task Send_Start_Stop() { return(TryTest(async() => { // arrange using TestServer testServer = CreateStarWarsServer(); WebSocketClient client = CreateWebSocketClient(testServer); WebSocket webSocket = await ConnectToServerAsync(client); DocumentNode document = Utf8GraphQLParser.Parse( "subscription { onReview(episode: NEW_HOPE) { stars } }"); var request = new GraphQLRequest(document); const string subscriptionId = "abc"; await webSocket.SendSubscriptionStartAsync(subscriptionId, request); await testServer.SendPostRequestAsync(new ClientQueryRequest { Query = @" mutation { createReview(episode:NEW_HOPE review: { commentary: ""foo"" stars: 5 }) { stars } }" }); await WaitForMessage( webSocket, MessageTypes.Subscription.Data, TimeSpan.FromSeconds(15)); // act await webSocket.SendSubscriptionStopAsync(subscriptionId); await testServer.SendPostRequestAsync(new ClientQueryRequest { Query = @" mutation { createReview(episode:NEW_HOPE review: { commentary: ""foo"" stars: 5 }) { stars } }" }); IReadOnlyDictionary <string, object> message = await WaitForMessage( webSocket, MessageTypes.Subscription.Data, TimeSpan.FromSeconds(5)); // assert Assert.Null(message); })); }
// Token: 0x0600348C RID: 13452 RVA: 0x000E98E4 File Offset: 0x000E7AE4 internal void Push(DocumentNode documentNode) { this.InsertNode(this.Count, documentNode); }
public async ValueTask <bool> MoveNextAsync() { if (_index >= _batch.Count) { Current = null; return(false); } try { IReadOnlyQueryRequest request = _batch[_index++]; DocumentNode document = request.Query is QueryDocument d ? d.Document : Utf8GraphQLParser.Parse(request.Query.ToSpan()); OperationDefinitionNode operation = document.GetOperation(request.OperationName); if (document != _previous) { _fragments = document.GetFragments(); _visitationMap.Initialize(_fragments); } operation.Accept( _visitor, _visitationMap, n => VisitorAction.Continue); _previous = document; document = RewriteDocument(operation); operation = (OperationDefinitionNode)document.Definitions[0]; IReadOnlyDictionary <string, object> variableValues = MergeVariables(request.VariableValues, operation); request = QueryRequestBuilder.From(request) .SetQuery(document) .SetVariableValues(variableValues) .AddExportedVariables(_exportedVariables) .SetQueryName(null) // TODO ... should we create a name here? .SetQueryHash(null) .Create(); Current = (IReadOnlyQueryResult)await _executor.ExecuteAsync( request, _cancellationToken) .ConfigureAwait(false); IsCompleted = false; } catch (QueryException ex) { IsCompleted = true; Current = QueryResultBuilder.CreateError(ex.Errors); } catch (Exception ex) { IsCompleted = true; Current = QueryResultBuilder.CreateError( _errorHandler.Handle( _errorHandler.CreateUnexpectedError(ex).Build())); } return(!IsCompleted); }
public MetaMarkupRule(DocumentNode node) { _node = node; }
public static DocumentNode EvaluateExpression(DocumentNode expression) { DocumentNodePath documentNodePath = new DocumentNodePath(expression.DocumentRoot.RootNode, expression); return((new ExpressionEvaluator(expression.Context)).EvaluateExpression(documentNodePath, expression)); }
private static void WriteUserDocumentAccessEntry(DocumentNode dn, DocumentAccessEntry dae) { Console.WriteLine(dn.Name + "\t" + dn.ID.ToString() + "\t" + dae.UserName + "\t" + dae.AccessMode.ToString()); }
public virtual void SetDocument(TemplateOptions options, DocumentNode node, string className) { if (options != null) { Visitor.Options = options; } _node = node; Visitor.Visit(node); ClassName = className; }
public virtual void Import(DocumentNode node, string html) { Parser.Reader = Reader; var p = node.Parser; node.Parser = Parser; node.Text = html; node.Parser = p; Import(node); }
protected virtual void StartVisit(DocumentNode node) { }
private DocumentNode EvaluateResourceAtSpecificSite(ResourceSite resourceSite, DocumentNode keyNode, ICollection <DocumentCompositeNode> resourcesHostNodePath, ICollection <IDocumentRoot> relatedRoots, int lastResourceToSearch, ICollection <string> warnings) { DocumentCompositeNode documentCompositeNode = resourceSite.FindResource(this.documentRootResolver, keyNode, resourcesHostNodePath, relatedRoots, lastResourceToSearch, warnings); if (documentCompositeNode == null) { return(null); } return(documentCompositeNode.Properties[KnownProperties.DictionaryEntryValueProperty]); }
public Modal(DocumentNode node) : base((JSObjectHandle)JSObjectHandle.Global.CallNew("Modal", node)) { }
protected virtual void EndVisit(DocumentNode node) { }
public DocumentNode EvaluateResource(DocumentNodePath nodePath, ResourceReferenceType referenceType, DocumentNode keyNode) { return(this.EvaluateResourceAndCollectionPath(nodePath, referenceType, keyNode, null, null, null)); }
private static bool SearchForAnimationsInVisualStateGroups(DocumentCompositeNode elementNode, DocumentNode pathNameNode) { bool flag; IPropertyId member = (IPropertyId)ProjectNeutralTypes.VisualStateManager.GetMember(MemberType.AttachedProperty, "VisualStateGroups", MemberAccessTypes.Public); IProperty property = elementNode.Context.TypeResolver.ResolveProperty(member); if (property != null) { DocumentCompositeNode item = elementNode.Properties[property] as DocumentCompositeNode; if (item != null && item.Children != null) { using (IEnumerator <DocumentNode> enumerator = item.FindPointAnimationDescendantNodes().GetEnumerator()) { while (enumerator.MoveNext()) { if (!PathGeometrySerializationHelper.DoesAnimationTargetPath(pathNameNode, enumerator.Current)) { continue; } flag = true; return(flag); } return(false); } return(flag); } } return(false); }
public DocumentNode EvaluateResourceAndCollectionPath(DocumentNodePath nodePath, ResourceReferenceType referenceType, DocumentNode keyNode, ICollection <DocumentCompositeNode> resourcesHostNodePath, ICollection <IDocumentRoot> relatedRoots, ICollection <string> warnings, out bool invalidForwardReference) { Uri uri; DocumentNode documentNode; IDocumentRoot applicationRoot; IDocumentRoot documentRoot = nodePath.RootNode.DocumentRoot; if (this.documentRootResolver != null) { applicationRoot = this.documentRootResolver.ApplicationRoot; } else { applicationRoot = null; } IDocumentRoot documentRoot1 = applicationRoot; bool flag = (documentRoot1 == null ? false : documentRoot1.RootNode != null); IDocumentRoot documentRoot2 = null; invalidForwardReference = false; if (referenceType != ResourceReferenceType.Static) { DocumentNode node = nodePath.Node; while (node != null) { if (flag && node.DocumentRoot != null && node == node.DocumentRoot.RootNode && PlatformTypes.ResourceDictionary.IsAssignableFrom(node.Type)) { string documentUrl = node.Context.DocumentUrl; DocumentCompositeNode rootNode = documentRoot1.RootNode as DocumentCompositeNode; if (rootNode != null && Uri.TryCreate(documentUrl, UriKind.Absolute, out uri) && ResourceNodeHelper.FindReferencedDictionaries(rootNode).Contains <Uri>(uri)) { documentRoot2 = node.DocumentRoot; break; } } DocumentNode documentNode1 = this.EvaluateResourceAtSpecificNode(node, keyNode, resourcesHostNodePath, relatedRoots, warnings); if (documentNode1 != null) { return(documentNode1); } node = node.Parent; if (node == null || nodePath == null) { continue; } DocumentNode containerNode = nodePath.ContainerNode; DocumentNode styleForSetter = ExpressionEvaluator.GetStyleForSetter(node); if (styleForSetter == null || styleForSetter != containerNode) { styleForSetter = ExpressionEvaluator.GetStyleForResourceEntry(node); if (styleForSetter == null) { if (node != containerNode) { continue; } nodePath = null; } else { if (styleForSetter == containerNode) { nodePath = null; } node = styleForSetter.Parent; } } else { nodePath = nodePath.GetContainerOwnerPath(); if (nodePath == null) { continue; } node = nodePath.Node; } } } else { DocumentNode documentNode2 = null; for (DocumentNode i = nodePath.Node; i != null; i = i.Parent) { ISupportsResources resourcesCollection = ResourceNodeHelper.GetResourcesCollection(i); if (resourcesCollection != null) { ResourceSite resourceSite = new ResourceSite(i.Context, resourcesCollection); DocumentNode documentNode3 = null; if (ResourceNodeHelper.IsResourceDictionary(resourcesCollection)) { int siteChildIndex = -1; if (documentNode2 != null) { siteChildIndex = documentNode2.SiteChildIndex; } documentNode3 = this.EvaluateResourceAtSpecificSite(resourceSite, keyNode, resourcesHostNodePath, relatedRoots, siteChildIndex, warnings); } else if (ResourceNodeHelper.IsResourceContainer(resourcesCollection, documentNode2)) { documentNode3 = this.EvaluateResourceAtSpecificSite(resourceSite, keyNode, resourcesHostNodePath, relatedRoots, -1, warnings); } if (documentNode3 != null) { if (keyNode != null && keyNode.Parent != null && keyNode.Parent.Parent == i) { ITextRange nodeSpan = DocumentNodeHelper.GetNodeSpan(keyNode.Parent); ITextRange textRange = DocumentNodeHelper.GetNodeSpan(documentNode3); if (!TextRange.IsNull(textRange) && !TextRange.IsNull(nodeSpan) && nodeSpan.Offset < textRange.Offset) { documentNode3 = null; invalidForwardReference = true; } } if (documentNode3 != null) { return(documentNode3); } } } documentNode2 = i; } } if (flag) { DocumentNode documentNode4 = this.EvaluateResourceAtSpecificNode(documentRoot1.RootNode, keyNode, resourcesHostNodePath, relatedRoots, warnings); if (documentNode4 != null) { if (relatedRoots != null && documentNode4.DocumentRoot != documentRoot2) { relatedRoots.Add(documentRoot1); } return(documentNode4); } } if (documentRoot != null) { using (IEnumerator <IDocumentRoot> enumerator = documentRoot.DesignTimeResources.GetEnumerator()) { while (enumerator.MoveNext()) { IDocumentRoot current = enumerator.Current; DocumentNode documentNode5 = this.EvaluateResourceAtSpecificNode(current.RootNode, keyNode, resourcesHostNodePath, relatedRoots, warnings); if (documentNode5 == null) { continue; } if (relatedRoots != null && documentNode5.DocumentRoot != documentRoot2) { relatedRoots.Add(current); } documentNode = documentNode5; return(documentNode); } return(null); } return(documentNode); } return(null); }
protected override void StartVisit(DocumentNode node) { if (node.Metadata.ContainsKey("content")) { _actualCode = CreateNewMethod("BaseContentHolderMethod"); } else { _actualCode = CreateNewMethod("Main"); } base.StartVisit(node); }
public ClientGenerator AddQueryDocument( string name, DocumentNode document) => AddQueryDocument(name, name, document);
public DocumentNode EvaluateResourceAndCollectionPath(DocumentNodePath nodePath, ResourceReferenceType referenceType, DocumentNode keyNode, ICollection <DocumentCompositeNode> resourcesHostNodePath, ICollection <IDocumentRoot> relatedRoots, ICollection <string> warnings) { bool flag; return(this.EvaluateResourceAndCollectionPath(nodePath, referenceType, keyNode, resourcesHostNodePath, relatedRoots, warnings, out flag)); }
public static InvalidOperationException BufferedRequest_OperationNotFound( DocumentNode document) => new InvalidOperationException(string.Format( ThrowHelper_BufferedRequest_OperationNotFound, document));