Example #1
0
 public static void Main()
 {
     XmlDoc dc=new XmlDoc();
     XmlElement nd=new XmlElement("dotgnu");
     XmlElement nd2=new XmlElement("pnet");
     nd2.AddChild(new XmlCData("Hey I work here &"));
     nd2.AddChild(new XmlComment("so does rhys !"));
     nd.AddChild(nd2);
     XmlElement nd3=new XmlElement("phpgw");
     nd3.AddChild(new XmlPI("php","echo \"phpgroupware\";"));
     nd.AddChild(nd3);
     dc.AddChild(nd);
     //dc.Compression = 3;
     //dc.SaveToFile("/tmp/xml.gz",1);
     Console.WriteLine(dc.DumpXml());
     //printRecursive(dc);
 }
Example #2
0
        /// <summary>
        /// Creates the content of the local style.
        /// </summary>
        private void CreateLocalStyleContent()
        {
            XElement nodeAutomaticStyles = XmlDoc.Elements(Ns.Office + "document-content")
                                           .Elements(Ns.Office + "automatic-styles").First();

            foreach (IStyle style in Styles.ToValueList())
            {
                bool exist = false;
                if (style.StyleName != null)
                {
                    string   styleName = style.StyleName;
                    XElement node      = nodeAutomaticStyles.Elements(Ns.Style + "style")
                                         .Where(e => string.Equals((string)e.Attribute(Ns.Style + "name"), styleName)).FirstOrDefault();
                    if (node != null)
                    {
                        exist = true;
                    }
                }
                if (!exist)
                {
                    nodeAutomaticStyles.Add(style.Node);
                }
            }
        }
        public override void Execute()
        {
            XmlNamespaceManager nsManager = new XmlNamespaceManager(this.XmlDoc.NameTable);

            nsManager.AddNamespace("cp1", "http://schemas.microsoft.com/pag/cab-profile");
            nsManager.AddNamespace("cp2", "http://schemas.microsoft.com/pag/cab-profile/2.0");
            XmlNode moduleList = this.XmlDoc.SelectSingleNode("//cp1:Modules", nsManager);
            XmlNode newModule  = null;

            if (moduleList == null && !string.IsNullOrEmpty(SectionName))
            {
                moduleList = this.XmlDoc.SelectSingleNode("//cp2:Section[@Name='" + SectionName + "']/cp2:Modules", nsManager);
                newModule  = XmlDoc.CreateElement("ModuleInfo", "http://schemas.microsoft.com/pag/cab-profile/2.0");
            }
            else
            {
                newModule = XmlDoc.CreateElement("ModuleInfo", "http://schemas.microsoft.com/pag/cab-profile");
            }
            XmlAttribute xmlAttrib = XmlDoc.CreateAttribute("AssemblyFile");

            xmlAttrib.Value = this.ModuleName + ".dll";
            newModule.Attributes.Append(xmlAttrib);
            moduleList.AppendChild(newModule);
        }
Example #4
0
        private static XmlDoc GetDoc(XmlReader reader)
        {
            var doc = new XmlDoc {
                Name = reader.GetAttribute("name")
            };

            do
            {
                reader.Read();
                if (reader.Name == "summary")
                {
                    doc.Summary = CleanString(reader.ReadInnerXml());
                }
                else if (reader.Name == "returns")
                {
                    doc.Returns = CleanString(reader.ReadInnerXml());
                }
                else if (reader.Name == "param")
                {
                    doc.Parameters.Add(reader.GetAttribute("name"), CleanString(reader.ReadInnerXml()));
                }
            } while (reader.Name != "member");
            return(doc);
        }
Example #5
0
        public static void SaveToDisk(IDataTypeDefinition item)
        {
            if (item != null)
            {
                var packagingService = ApplicationContext.Current.Services.PackagingService;
                try
                {
                    XElement node = packagingService.Export(item);
                    // node.AddMD5Hash(true); // md5 hash of file with preval ids blanked.
                    node = ReplaceCotentNodes(node);
                    // content node hunting goes here....

                    XmlDoc.SaveElement("DataTypeDefinition", XmlDoc.ScrubFile(item.Name), node);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <SyncDataType>(string.Format("DataType Failed {0}", item.Name), ex);
                }
            }
            else
            {
                LogHelper.Debug <SyncDataType>("Null DataType Save attempt - aborted");
            }
        }
Example #6
0
        private static ClassDeclarationSyntax GenerateClass(string ns, SourceFileContext ctx, IEnumerable <FileDescriptor> packageFileDescriptors)
        {
            var typ = Typ.Manual(ns, ClassName);
            var cls = Class(Internal | Static, typ)
                      .WithXmlDoc(XmlDoc.Summary("Static class to provide common access to package-wide API metadata."));

            var yieldStatements      = packageFileDescriptors.Select(GenerateYieldStatement).ToArray();
            var fileDescriptorMethod = Method(Private | Static, ctx.Type(Typ.Of <IEnumerable <FileDescriptor> >()), "GetFileDescriptors")()
                                       .WithBlockBody(yieldStatements);

            var apiMetadataType = ctx.Type <ApiMetadata>();
            var property        = AutoProperty(Internal | Static, apiMetadataType, PropertyName)
                                  .WithInitializer(New(apiMetadataType)(ns, IdentifierName(fileDescriptorMethod.Identifier)))
                                  .WithXmlDoc(XmlDoc.Summary("The ", apiMetadataType, " for services in this package."));

            return(cls.AddMembers(property, fileDescriptorMethod));

            YieldStatementSyntax GenerateYieldStatement(FileDescriptor descriptor)
            {
                var type = ctx.Type(ProtoTyp.OfReflectionClass(descriptor));

                return(YieldStatement(SyntaxKind.YieldReturnStatement, type.Access("Descriptor")));
            }
        }
Example #7
0
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        //var sm = ScriptManager.GetCurrent(this.Page);

        //sm.ScriptMode = ScriptMode.Release;

        if (this.Page.Request.FilePath.ToLower().Contains("index.aspx"))
        {
            _source.Visible = false;
            return;
        }

        var content = String.Empty;

        using (var fs = new FileStream(Server.MapPath(this.Page.Request.FilePath), FileMode.Open))
            using (var sr = new StreamReader(fs)) {
                content = sr.ReadToEnd();
            }

        var start = content.IndexOf("</h2>") + "<h2/>".Length;

        content = content.Substring(start);
        content = content.Replace("</asp:content>", String.Empty);
        content = "\t" + content.Trim();
        content = content.Replace("\t", "  ");         // tabs to spaces for pretty display on the web

        content = Server.HtmlEncode(content);

        source.Text = content;

        var desc = XmlDoc.GetDescription(Request.Path);

        _desc.Text = desc;
    }
        public async Task Bug17819()
        {
            await TestAsync(
                @"_ _()
{
}
///<param name='_
}",
                Identifier("_"),
                Method("_"),
                Punctuation.OpenParen,
                Punctuation.CloseParen,
                Punctuation.OpenCurly,
                Punctuation.CloseCurly,
                XmlDoc.Delimiter("///"),
                XmlDoc.Delimiter("<"),
                XmlDoc.Name("param"),
                XmlDoc.AttributeName(" "),
                XmlDoc.AttributeName("name"),
                XmlDoc.Delimiter("="),
                XmlDoc.AttributeQuotes("'"),
                Identifier("_"),
                Punctuation.CloseCurly);
        }
Example #9
0
        public ClassDeclarationSyntax GenerateClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, Typ, Parent is null ? new[] { ctx.Type <IDirectResponseSchema>() } : Array.Empty <TypeSyntax>());

            using (ctx.InClass(Typ))
            {
                if (_schema.Description is string description)
                {
                    cls = cls.WithXmlDoc(XmlDoc.Summary(description));
                }
                cls = cls.AddMembers(Properties.SelectMany(p => p.GeneratePropertyDeclarations(ctx)).ToArray());

                // Top-level data models automatically have an etag property if one isn't otherwise generated.
                if (Parent is null && !Properties.Any(p => p.Name == "etag"))
                {
                    var etag = AutoProperty(Modifier.Public | Modifier.Virtual, ctx.Type <string>(), "ETag", hasSetter: true)
                               .WithXmlDoc(XmlDoc.Summary("The ETag of the item."));
                    cls = cls.AddMembers(etag);
                }

                cls = cls.AddMembers(Properties.SelectMany(p => p.GenerateAnonymousModels(ctx)).ToArray());
            }
            return(cls);
        }
            private IEnumerable <MethodDeclarationSyntax> FormatMethods()
            {
                bool first = true;

                foreach (var pattern in PatternDetails)
                {
                    var xmlDoc = pattern.PathElements.Select(x => x.ParameterXmlDoc)
                                 .Prepend(XmlDoc.Summary("Formats the IDs into the string representation of this ", _ctx.Type(_def.ResourceNameTyp),
                                                         " with pattern ", XmlDoc.C(pattern.PatternString), "."))
                                 .Append(XmlDoc.Returns("The string representation of this ", _ctx.Type(_def.ResourceNameTyp), " with pattern ", XmlDoc.C(pattern.PatternString), "."))
                                 .ToArray();
                    var expandArgs = pattern.PathSegments.Where(x => x.Segment.ParameterCount > 0).Select(x =>
                    {
                        if (x.Segment.IsComplex)
                        {
                            var dollarItems = x.Elements.Zip(x.Segment.Separators.Select(x => x.ToString()).Append(""), (element, sep) => (FormattableString)
                                                             $"{Parens(_ctx.Type(typeof(GaxPreconditions)).Call(nameof(GaxPreconditions.CheckNotNullOrEmpty))(element.Parameter, Nameof(element.Parameter)))}{sep:raw}");
                            return((object)Dollar(dollarItems.ToArray()));
                        }
                        else
                        {
                            return(_ctx.Type(typeof(GaxPreconditions)).Call(nameof(GaxPreconditions.CheckNotNullOrEmpty))(x.Elements[0].Parameter, Nameof(x.Elements[0].Parameter)));
                        }
                    });
                    var method = Method(Public | Static, _ctx.Type <string>(), $"Format{pattern.UpperName}")(pattern.PathElements.Select(x => x.Parameter).ToArray())
                                 .WithBody(Return(pattern.PathTemplateField.Call(nameof(PathTemplate.Expand))(expandArgs)))
                                 .WithXmlDoc(xmlDoc);
                    if (first)
                    {
                        yield return(Method(Public | Static, _ctx.Type <string>(), "Format")(pattern.PathElements.Select(x => x.Parameter).ToArray())
                                     .WithBody(Return(This.Call(method)(pattern.PathElements.Select(x => x.Parameter))))
                                     .WithXmlDoc(xmlDoc));

                        first = false;
                    }
                    yield return(method);
                }
            }
 private IEnumerable <MethodDeclarationSyntax> FromMethods()
 {
     foreach (var pattern in PatternDetails)
     {
         var xmlDocSummary = XmlDoc.Summary($"Creates a ", _ctx.Type(_def.ResourceNameTyp), " with the pattern ", XmlDoc.C(pattern.PatternString), ".");
         var xmlDocReturns = XmlDoc.Returns("A new instance of ", _ctx.Type(_def.ResourceNameTyp), " constructed from the provided ids.");
         yield return(Method(Public | Static, _ctx.Type(_def.ResourceNameTyp), $"From{pattern.UpperName}")(pattern.PathElements.Select(x => x.Parameter).ToArray())
                      .WithBody(Return(New(_ctx.Type(_def.ResourceNameTyp))(
                                           pattern.PathElements.Select(x => (object)(x.Parameter.Identifier.ValueText, _ctx.Type(typeof(GaxPreconditions))
                                                                                     .Call(nameof(GaxPreconditions.CheckNotNullOrEmpty))(x.Parameter, Nameof(x.Parameter))))
                                           .Prepend(_ctx.Type(ResourceNameTypeTyp).Access(pattern.UpperName)).ToArray())))
                      .WithXmlDoc(pattern.PathElements.Select(x => x.ParameterXmlDoc).Prepend(xmlDocSummary).Append(xmlDocReturns).ToArray()));
     }
 }
            private EnumDeclarationSyntax ResourceTypeEnum()
            {
                var resources = PatternDetails.Select((x, i) => EnumMember(x.UpperName, value: i + 1).WithXmlDoc(
                                                          XmlDoc.Summary("A resource name with pattern ", XmlDoc.C(x.PatternString), ".")))
                                .Prepend(EnumMember("Unparsed", value: 0).WithXmlDoc(XmlDoc.Summary("An unparsed resource name.")));

                return(Enum(Public, ResourceNameTypeTyp)(resources.ToArray())
                       .WithXmlDoc(XmlDoc.Summary("The possible contents of ", _ctx.Type(_def.ResourceNameTyp), ".")));
            }
Example #13
0
 /// <summary>
 /// 通过节点名称读取节点列表
 /// </summary>
 /// <param name="nodeName"></param>
 /// <returns></returns>
 private XmlNodeList Read(string nodeName)
 {
     return(XmlDoc.GetElementsByTagName(nodeName));
 }
        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="filename">文件名称.xml</param>
        /// <param name="rootnode">根结点</param>
        /// <param name="node">rootnode的子节点</param>
        /// <param name="attributename">rootnode的子节点属性名称</param>
        /// <param name="attributevalue">rootnode的子节点属性值</param>
        /// <param name="subnode">node的子节点</param>
        /// <param name="subatt">node的子节点属性名称</param>
        /// <param name="subattvalue">node的子节点属性名称</param>
        private static string AddNode(string filename, string rootnode, string node, string attributename, string attributevalue, string subnode, string subatt, string subattvalue, object[] prams)
        {
            bool saveorno = false;

            System.Uri u = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);

            string xmlpath = System.IO.Path.GetDirectoryName(u.LocalPath) + "\\" + filename;

            if (prams != null && prams.Length > 0)
            {
                if (File.Exists(filename))
                {
                    xmlpath = filename;
                }
            }
            System.Xml.XmlDocument XmlDoc = GetDocument(xmlpath);

            if (XmlDoc == null)
            {
                XmlDoc   = new XmlDocument();
                saveorno = true;
            }
            if (XmlDoc.ChildNodes.Count == 0)
            {
                XmlDeclaration dec = XmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                XmlDoc.AppendChild(dec);
                saveorno = true;
            }

            XmlElement root = (XmlElement)XmlDoc.SelectSingleNode("/" + rootnode);

            if (root == null)
            {
                root = XmlDoc.CreateElement(rootnode);
                XmlDoc.AppendChild(root);
                saveorno = true;
            }
            XmlElement ele = XmlDoc.SelectSingleNode("/" + rootnode + "/" + node) as XmlElement;

            if (ele == null)
            {
                ele = XmlDoc.CreateElement(node);
                if (!string.IsNullOrEmpty(attributename))
                {
                    ele.SetAttribute(attributename, attributevalue);
                }
                if (!string.IsNullOrEmpty(subnode))
                {
                    XmlElement sub = XmlDoc.CreateElement(subnode);
                    if (!string.IsNullOrEmpty(subatt))
                    {
                        sub.SetAttribute(subatt, subattvalue);
                    }
                    ele.AppendChild(sub);
                }
                root.AppendChild(ele);
                saveorno = true;
            }
            else
            {
                XmlNodeList nodes     = XmlDoc.SelectNodes("/" + rootnode + "/" + node);
                XmlNode     existnode = null;
                if (!string.IsNullOrEmpty(attributename))
                {
                    foreach (XmlNode n1 in nodes)
                    {
                        if (n1.Attributes[attributename].Value.Equals(attributevalue))
                        {
                            existnode = n1;
                            break;
                        }
                    }
                    if (existnode == null)
                    {
                        XmlElement ele1 = XmlDoc.CreateElement(node);
                        ele1.SetAttribute(attributename, attributevalue);
                        if (!string.IsNullOrEmpty(subnode))
                        {
                            XmlElement sub = XmlDoc.CreateElement(subnode);
                            ele1.AppendChild(sub);
                        }
                        root.InsertBefore(ele1, ele);
                        saveorno = true;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(subnode))
                        {
                            XmlElement ele2 = (XmlElement)existnode.SelectSingleNode(subnode);
                            if (ele2 == null)
                            {
                                ele2 = XmlDoc.CreateElement(subnode);
                                existnode.AppendChild(ele2);
                                saveorno = true;
                            }
                        }
                    }
                }
                else
                {
                    if (nodes != null)
                    {
                        if (!string.IsNullOrEmpty(subnode))
                        {
                            existnode = nodes[0];
                            XmlElement ele2 = (XmlElement)existnode.SelectSingleNode(subnode);
                            if (ele2 == null)
                            {
                                ele2 = XmlDoc.CreateElement(subnode);
                                existnode.AppendChild(ele2);
                                saveorno = true;
                            }
                        }
                    }
                }
            }
            if (saveorno)
            {
                XmlDoc.Save(xmlpath);
            }
            return(xmlpath);
        }
Example #15
0
 public XPathNavigator Navigator()
 {
     return(XmlDoc.CreateNavigator());
 }
        public override List <string> ListPreprocess(IReadOnlyList <string> list)
        {
            _PreProcessResult = new Dictionary <string, XmlDoc>();
            List <string> errors = new List <string>();

            try
            {
                List <string> keys = KeyElements.Split(',').ToList();

                string firstKey = keys.FirstOrDefault();

                if (String.IsNullOrEmpty(firstKey))
                {
                    throw new Exception("KeyElements has no value.");
                }

                foreach (string d in list)
                {
                    XmlDoc doc = null;
                    try
                    {
                        lock (_Documents)
                        {
                            doc = _Documents.FirstOrDefault(i => i.Filename.Equals(d, StringComparison.InvariantCultureIgnoreCase));

                            if (doc != null)
                            {
                                System.Threading.Monitor.Enter(doc);

                                if (!File.Exists(doc.Filename) || doc.OriginalLastWriteTime == File.GetLastWriteTimeUtc(doc.Filename))
                                {
                                    foreach (string s in doc.Nodes.Keys)
                                    {
                                        _PreProcessResult[s] = doc;
                                    }

                                    continue;
                                }
                                else
                                {
                                    doc.OriginalLastWriteTime = File.GetLastWriteTimeUtc(d);
                                    doc.Document = XDocument.Parse(File.ReadAllText(d));
                                    doc.Nodes    = new Dictionary <string, XElement>();
                                }
                            }
                            else
                            {
                                doc          = new XmlDoc();
                                doc.Filename = d;
                                doc.OriginalLastWriteTime = File.GetLastWriteTimeUtc(d);
                                doc.Document = XDocument.Parse(File.ReadAllText(d));
                                doc.Nodes    = new Dictionary <string, XElement>();

                                System.Threading.Monitor.Enter(doc);

                                _Documents.Add(doc);
                            }
                        }

                        foreach (XElement e in doc.Document.Descendants().Where(i => i.Name.LocalName.Equals(firstKey)).Select(i => i.Parent))
                        {
                            string fullKey = "";
                            foreach (string key in keys)
                            {
                                string s = e.Descendants().Where(i => i.Name.LocalName.Equals(key)).Select(i => i.Value).FirstOrDefault();
                                if (s == null)
                                {
                                    fullKey = null;
                                    break;
                                }

                                if (fullKey != "")
                                {
                                    fullKey += " ";
                                }

                                fullKey += s;
                            }

                            if (fullKey == null)
                            {
                                continue;
                            }

                            doc.Nodes[fullKey]         = e;
                            _PreProcessResult[fullKey] = doc;
                        }
                    }
                    catch (Exception ex)
                    {
                        errors.Add("XmlConsumingController encountered an error processing " + d + ": " + ex.Message);
                        STEM.Sys.EventLog.WriteEntry("XmlConsumingController.ListPreprocess", d + ": " + ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
                    }
                    finally
                    {
                        if (doc != null)
                        {
                            System.Threading.Monitor.Exit(doc);
                        }
                    }
                }

                if (errors.Count == 0)
                {
                    PollError = "";
                }
                else
                {
                    throw new Exception(String.Join("\r\n", errors));
                }
            }
            catch (Exception ex)
            {
                PollError = "(" + STEM.Sys.IO.Net.MachineIP() + ") encountered errors: \r\n" + ex.Message;
                STEM.Sys.EventLog.WriteEntry("XmlConsumingController.ListPreprocess", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
            }

            List <string> returnList = _PreProcessResult.Keys.ToList();

            if (HonorPriorityFilters)
            {
                returnList = ApplyPriorityFilterOrdering(returnList);
            }

            return(returnList);
        }
Example #17
0
        public ClassDeclarationSyntax GenerateServiceClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, ServiceTyp, ctx.Type <BaseClientService>()).WithXmlDoc(XmlDoc.Summary($"The {ClassName} Service."));

            using (ctx.InClass(cls))
            {
                var discoveryVersionTyp = Typ.Manual("Google.Apis.Discovery", "DiscoveryVersion");
                var version             = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), "Version")
                                          .WithInitializer(ApiVersion)
                                          .WithXmlDoc(XmlDoc.Summary("The API version."));
                var discoveryVersion = Field(Modifier.Public | Modifier.Static, ctx.Type(discoveryVersionTyp), "DiscoveryVersionUsed")
                                       .WithInitializer(ctx.Type(discoveryVersionTyp).Access(nameof(DiscoveryVersion.Version_1_0)))
                                       .WithXmlDoc(XmlDoc.Summary("The discovery version used to generate this service."));

                var parameterlessCtor = Ctor(Modifier.Public, cls, ThisInitializer(New(ctx.Type <BaseClientService.Initializer>())()))()
                                        .WithBody()
                                        .WithXmlDoc(XmlDoc.Summary("Constructs a new service."));

                var initializerParam = Parameter(ctx.Type <BaseClientService.Initializer>(), "initializer");

                var featuresArrayInitializer = ApiFeatures.Any()
                    ? NewArray(ctx.ArrayType(Typ.Of <string[]>()))(ApiFeatures.ToArray())
                    : NewArray(ctx.ArrayType(Typ.Of <string[]>()), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
                var features = Property(Modifier.Public | Modifier.Override, ctx.Type <IList <string> >(), "Features")
                               .WithGetBody(featuresArrayInitializer)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service supported features."));

                var nameProperty = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "Name")
                                   .WithGetBody(ApiName)
                                   .WithXmlDoc(XmlDoc.Summary("Gets the service name."));

                // Note: the following 4 properties have special handling post-generation, in terms
                // of adding the #if directives in.
                var baseUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BaseUri")
                              .WithGetBody(IdentifierName("BaseUriOverride").NullCoalesce(BaseUri))
                              .WithXmlDoc(XmlDoc.Summary("Gets the service base URI."));

                var basePath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BasePath")
                               .WithGetBody(BasePath)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service base path."));

                var batchUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchUri")
                               .WithGetBody(BatchUri)
                               .WithXmlDoc(XmlDoc.Summary("Gets the batch base URI; ", XmlDoc.C("null"), " if unspecified."));
                var batchPath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchPath")
                                .WithGetBody(BatchPath)
                                .WithXmlDoc(XmlDoc.Summary("Gets the batch base path; ", XmlDoc.C("null"), " if unspecified."));

                var resourceProperties = Resources.Select(resource => resource.GenerateProperty(ctx)).ToArray();

                var parameterizedCtor = Ctor(Modifier.Public, cls, BaseInitializer(initializerParam))(initializerParam)
                                        .WithBlockBody(resourceProperties.Zip(Resources).Select(pair => pair.First.Assign(New(ctx.Type(pair.Second.Typ))(This))).ToArray())
                                        .WithXmlDoc(
                    XmlDoc.Summary("Constructs a new service."),
                    XmlDoc.Param(initializerParam, "The service initializer."));

                cls = cls.AddMembers(version, discoveryVersion, parameterlessCtor, parameterizedCtor, features, nameProperty, baseUri, basePath, batchUri, batchPath);

                if (AuthScopes.Any())
                {
                    var scopeClass = Class(Modifier.Public, Typ.Manual(PackageName, "Scope"))
                                     .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scopes for use with the {Title}."));
                    using (ctx.InClass(scopeClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Static, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeClass = scopeClass.AddMembers(field);
                        }
                    }

                    var scopeConstantsClass = Class(Modifier.Public | Modifier.Static, Typ.Manual(PackageName, "ScopeConstants"))
                                              .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scope constants for use with the {Title}."));
                    using (ctx.InClass(scopeConstantsClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeConstantsClass = scopeConstantsClass.AddMembers(field);
                        }
                    }

                    cls = cls.AddMembers(scopeClass, scopeConstantsClass);
                }

                // TODO: Find an example of this...
                foreach (var method in Methods)
                {
                    cls = cls.AddMembers(method.GenerateDeclarations(ctx).ToArray());
                }

                cls = cls.AddMembers(resourceProperties);
            }
            return(cls);
        }
Example #18
0
 /// <summary>
 /// Flushes this instance. This action is optional, for example if a DataContext should be flushed multiple times before committing or rolling back a transaction.
 /// </summary>
 /// <remarks></remarks>
 public override void Flush()
 {
     this.CheckThrowObjectDisposed(base.IsDisposed, "XmlStore...DataContext:Flush");
     XmlDoc.Save(_path); // The XmlStore transaction method is to backup at the start of a transaction, and rollback overwrites from the backup, so just save to normal path
 }
Example #19
0
 internal IEnumerable <XElement> FindElementsByExpression(string expression)
 {
     return(((IEnumerable)XmlDoc.XPathEvaluate(expression)).Cast <XElement>());
 }
Example #20
0
 public XmlNode GetNode(string xmlPathNode)
 {
     return(XmlDoc.SelectSingleNode(xmlPathNode));
 }
Example #21
0
 /// <summary>
 /// 保存文档
 /// </summary>
 /// <param name="fileName">要保存的路径</param>
 public void Save(string fileName)
 {
     XmlDoc.Save(fileName);
 }
Example #22
0
 public string GetNodeText(string xmlPathNode)
 {
     return(XmlDoc.SelectSingleNode(xmlPathNode).InnerText);
 }
Example #23
0
        private IEnumerable <Tuple <string, Response> > GetResponses(MethodInfo method,
                                                                     Dictionary <string, List <Attribute> > methodAttr, XmlDoc doc)
        {
            bool IsVoid(Type type) => type == null || type.FullName == "System.Void";

            var docDescription = doc?.Returns ?? string.Empty;

            var methodReturnType = method.ReturnType;

            if (methodReturnType == typeof(Task))
            {
                methodReturnType = typeof(void);
            }
            else if (methodReturnType.Name == "Task`1")
            {
                methodReturnType = methodReturnType.GenericTypeArguments[0];
            }
            else if (methodReturnType == typeof(HttpResponseMessage) || typeof(IActionResult).IsAssignableFrom(methodReturnType))
            {
                methodReturnType = typeof(object);
            }
            var methodStatusCode  = IsVoid(methodReturnType) ? "204" : "200";
            var methodDescription = IsVoid(methodReturnType) ? "No Content" : docDescription;

            const string responsetypeattribute = nameof(ResponseTypeAttribute);
            var          overriddenCodes       = new HashSet <string>();

            if (methodAttr.ContainsKey(responsetypeattribute))
            {
                var responseTypeAttributes = methodAttr[responsetypeattribute].Cast <ResponseTypeAttribute>();
                foreach (var responseTypeAttribute in responseTypeAttributes)
                {
                    var returnType = responseTypeAttribute.ResponseType;
                    var statusCode = responseTypeAttribute.HttpStatusCode ?? (IsVoid(returnType) ? "204" : "200");
                    overriddenCodes.Add(statusCode);
                    var schema      = _schemaGenerator.MapToSchema(_schemaGenerator.GetSchema(returnType));
                    var description = IsVoid(returnType) ? "No Content" : docDescription;
                    yield return(Tuple.Create(statusCode, new Response
                    {
                        Description = description,
                        Schema = schema
                    }));
                }
            }

            if (!overriddenCodes.Contains(methodStatusCode))
            {
                var response = new Response {
                    Description = methodDescription
                };
                if (!IsVoid(methodReturnType))
                {
                    response.Schema = _schemaGenerator.MapToSchema(_schemaGenerator.GetSchema(methodReturnType));
                }

                yield return(Tuple.Create(methodStatusCode, response));
            }

            yield return
                (Tuple.Create("default",
                              new Response
            {
                Description = "Unexected Error",
                Schema = new SchemaObject()
                {
                    Ref = "#/definitions/ErrorModel"
                }
            }));
        }
Example #24
0
        } // InitEmptyXMLDoc

        #endregion

        // *******************************************************************************
        // *******************************************************************************
        #region ***** WRITE METHODS

        /// <summary>
        /// Adds a concept element as child to the root element
        /// </summary>
        public void AddConcept()
        // Code History:
        // 2014-03-05 mws
        {
            AddNarPropertyToParent("/nar:" + RootElemName, NameSeqCiRoot, XmlDoc.CreateElement("concept", G2NsCs));
        } // AddConcept
Example #25
0
        public void JsonSerialise_Object_GetAsArrayReturnsNull()
        {
            var d1 = new XmlDoc
             {
            SV = "test"
             };

             string s = d1.ToJsonString();

             string[] array = s.AsJsonObject<string[]>();
             Assert.Null(array);
        }
Example #26
0
        /// <summary>
        /// 根据字段类型,显示此类型所需要配置的信息项
        /// </summary>
        public void Attribute()
        {
            if (!String.IsNullOrEmpty(Field))
            {
                xml             = new XmlDoc();
                xml.xmlfilePath = "../../App_Data/TableXml/" + TableName + ".xml";
                dt = xml.GetDataTable("Type='" + FieldType + "' and Name='" + Field + "'", "");
            }
            switch (FieldType)
            {
            case "SingleLine":
                SingleLineType();
                break;

            case "Password":
                PasswordType();
                break;

            case "MultiLine":
                MultiLineType();
                break;

            case "Editor":
                EditorType();
                break;

            case "Select":
                SelectType();
                break;

            case "Number":
                NumberType();
                break;

            case "DateTime":
                DateTimeType();
                break;

            case "Image":
                ImageType();
                break;

            case "File":
                FileType();
                break;

            case "BatchImage":
                BatchImageType();
                break;

            case "BatchFile":
                BatchFileType();
                break;

            case "OtherMenu":
                OtherMenuType();
                break;

            case "Provinces":
                ProvincesType();
                break;

            case "Increment":
                Increment();
                break;
            }
        }
Example #27
0
        public void JsonSerialise_Object_ValidString()
        {
            var d1 = new XmlDoc
             {
            SV = "test"
             };

             string s = d1.ToJsonString();
             Assert.NotNull(s);

             XmlDoc d2 = s.AsJsonObject<XmlDoc>();

             Assert.Equal(d1.SV, d2.SV);
        }
Example #28
0
 /// <summary>
 /// 保存文档
 /// </summary>
 public void Save()
 {
     XmlDoc.Save(XmlPath);
 }
Example #29
0
        public void XmlSerialiseDeserialise_Object_ValidString()
        {
            XmlDoc d1 = new XmlDoc
             {
            SV = "test"
             };

             string s = d1.XmlSerialise();
             XmlDoc d2 = s.XmlDeserialise<XmlDoc>();
             XmlDoc d3 = (XmlDoc)s.XmlDeserialise(typeof(XmlDoc));

             Assert.Equal("test", d2.SV);
             Assert.Equal("test", d3.SV);
        }
Example #30
0
        private static IEnumerable <MemberDeclarationSyntax> LroPartialClasses(SourceFileContext ctx, ServiceDetails svc)
        {
            if (svc.Methods.Any(m => m is MethodDetails.StandardLro))
            {
                // Emit partial class to give access to an LRO operations client.
                var grpcOuterCls = Class(Public | Static | Partial, svc.GrpcClientTyp.DeclaringTyp);
                using (ctx.InClass(grpcOuterCls))
                {
                    var grpcInnerClass = Class(Public | Partial, svc.GrpcClientTyp);
                    using (ctx.InClass(grpcInnerClass))
                    {
                        var callInvoker = Property(Private, ctx.TypeDontCare, "CallInvoker");
                        var opTyp       = ctx.Type <Operations.OperationsClient>();
                        var createOperationsClientMethod = Method(Public | Virtual, opTyp, "CreateOperationsClient")()
                                                           .WithBody(New(opTyp)(callInvoker))
                                                           .WithXmlDoc(
                            XmlDoc.Summary("Creates a new instance of ", opTyp, " using the same call invoker as this client."),
                            XmlDoc.Returns("A new Operations client for the same target as this client.")
                            );
                        grpcInnerClass = grpcInnerClass.AddMembers(createOperationsClientMethod);
                    }
                    grpcOuterCls = grpcOuterCls.AddMembers(grpcInnerClass);
                }
                yield return(grpcOuterCls);
            }

            // Generate partial classes to delegate to other services handling operations
            if (svc.Methods.Any(m => m is MethodDetails.NonStandardLro))
            {
                var operationServices = svc.Methods.OfType <MethodDetails.NonStandardLro>().Select(lro => lro.OperationService).Distinct().ToList();

                // Emit partial class to give access to an LRO operations client.
                var grpcOuterCls = Class(Public | Static | Partial, svc.GrpcClientTyp.DeclaringTyp);
                using (ctx.InClass(grpcOuterCls))
                {
                    var grpcInnerClass = Class(Public | Partial, svc.GrpcClientTyp);
                    using (ctx.InClass(grpcInnerClass))
                    {
                        var callInvoker = Property(Private, ctx.TypeDontCare, "CallInvoker");
                        var opTyp       = ctx.Type <Operations.OperationsClient>();

                        foreach (var operationService in operationServices)
                        {
                            var grpcClient = ctx.Type(Typ.Nested(Typ.Manual(ctx.Namespace, operationService), $"{operationService}Client"));
                            var createOperationsClientMethod = Method(Public | Virtual, opTyp, $"CreateOperationsClientFor{operationService}")()
                                                               .WithBody(grpcClient.Call("CreateOperationsClient")(callInvoker))
                                                               .WithXmlDoc(
                                XmlDoc.Summary("Creates a new instance of ", opTyp, $" using the same call invoker as this client, delegating to {operationService}."),
                                XmlDoc.Returns("A new Operations client for the same target as this client.")
                                );
                            grpcInnerClass = grpcInnerClass.AddMembers(createOperationsClientMethod);
                        }
                    }
                    grpcOuterCls = grpcOuterCls.AddMembers(grpcInnerClass);
                }
                yield return(grpcOuterCls);
            }

            // Generate partial classes for the operation-handling services
            if (svc.NonStandardLro is ServiceDetails.NonStandardLroDetails lroDetails)
            {
                // Emit partial class to give access to an LRO operations client.
                var grpcOuterCls = Class(Public | Static | Partial, svc.GrpcClientTyp.DeclaringTyp);
                using (ctx.InClass(grpcOuterCls))
                {
                    var grpcInnerClass = Class(Public | Partial, svc.GrpcClientTyp);
                    using (ctx.InClass(grpcInnerClass))
                    {
                        var callInvoker                  = Parameter(ctx.Type <CallInvoker>(), "callInvoker");
                        var request                      = Parameter(ctx.TypeDontCare, "request");
                        var response                     = Parameter(ctx.TypeDontCare, "response");
                        var opTyp                        = ctx.Type <Operations.OperationsClient>();
                        var forwardingCallInvoker        = Local(ctx.Type <CallInvoker>(), "forwardingCallInvoker");
                        var createOperationsClientMethod = Method(Internal | Static, opTyp, "CreateOperationsClient")(callInvoker)
                                                           .WithBody(
                            forwardingCallInvoker.WithInitializer(
                                // Note: can't use Typ.Of<ForwardingCallInvoker<GetOperationRequest>> as it's a static class.
                                ctx.Type(Typ.Generic(Typ.Of(typeof(ForwardingCallInvoker <>)), Typ.Of <GetOperationRequest>())).Call("Create")(
                                    callInvoker,
                                    "/google.longrunning.Operations/GetOperation",
                                    Property(Private, ctx.TypeDontCare, $"__Method_{lroDetails.PollingMethod.Name}"),
                                    ctx.Type(lroDetails.PollingRequestTyp).Access("ParseLroRequest"),     // Method group conversion
                                    Lambda(request, response)(response.Call("ToLroResponse")(request.Access("Name")))
                                    )),
                            Return(New(opTyp)(forwardingCallInvoker)))
                                                           .WithXmlDoc(
                            XmlDoc.Summary(
                                "Creates a new instance of ", opTyp, "using the specified call invoker, but ",
                                $"redirecting Google.LongRunning RPCs to {lroDetails.Service.Name} RPCs."),
                            XmlDoc.Returns("A new Operations client for the same target as this client.")
                            );
                        grpcInnerClass = grpcInnerClass.AddMembers(createOperationsClientMethod);
                    }
                    grpcOuterCls = grpcOuterCls.AddMembers(grpcInnerClass);
                }
                yield return(grpcOuterCls);
            }
        }
Example #31
0
        public void JsonSerialise_ObjectAsCompressed_SmallerString()
        {
            var odoc = new XmlDoc { SV = "value" };

             string fullString = odoc.ToJsonString();
             string compString = odoc.ToCompressedJsonString();

             Assert.True(fullString.Length > compString.Length);
        }
Example #32
0
        public DomConverter CompileAllIfNeed(string FileName, bool parse_only_interface = false)
        {
            this.FileName = FileName;
            this.Text     = comp.GetSourceFileText(FileName);
            string                 ext        = Path.GetExtension(FileName);
            List <Error>           ErrorsList = new List <Error>();
            List <CompilerWarning> Warnings   = new List <CompilerWarning>();
            compilation_unit       cu         = null;

            if (Text != null)
            {
                cu = ParsersController.GetCompilationUnit(FileName, Text, ErrorsList, Warnings);
            }
            Parser = ParsersController.selectParser(Path.GetExtension(FileName).ToLower());
            ErrorsList.Clear();
            Warnings.Clear();
            documentation_comment_list dt       = ParsersController.Compile(System.IO.Path.ChangeExtension(FileName, get_doctagsParserExtension(ext)), Text, ErrorsList, Warnings, ParseMode.Normal) as documentation_comment_list;
            DocumentationConstructor   docconst = new DocumentationConstructor();

            if (cu != null)
            {
                docs = docconst.Construct(cu, dt);
            }
            DomConverter dconv = new DomConverter(this);

            dconv.visitor.parse_only_interface = parse_only_interface;
            if (XmlDoc.LookupLocalizedXmlDocForUnitWithSources(FileName, CodeCompletionController.currentLanguageISO) != null)
            {
                dconv.visitor.add_doc_from_text = false;
            }
            if (cu != null)
            {
                dconv.ConvertToDom(cu);
            }
            else
            {
                ErrorsList.Clear();
                Warnings.Clear();
                //cu = ParsersControllerGetComilationUnit(FileName, Text, ErrorsList, true);
                if (comp_modules[FileName] == null)
                {
                    string tmp = ParsersHelper.GetModifiedProgramm(Text);
                    if (tmp != null)
                    {
                        cu = ParsersControllerGetCompilationUnitSpecial(FileName, tmp, ErrorsList, Warnings);
                        ErrorsList.Clear();
                    }
                    if (cu == null)
                    {
                        cu = get_fictive_unit(Text, FileName);
                    }
                }
                ErrorsList.Clear();
                Warnings.Clear();
                dt = ParsersController.Compile(System.IO.Path.ChangeExtension(FileName, get_doctagsParserExtension(ext)), Text, ErrorsList, Warnings, ParseMode.Normal) as documentation_comment_list;
                if (cu != null)
                {
                    docs = docconst.Construct(cu, dt);
                }
                if (XmlDoc.LookupLocalizedXmlDocForUnitWithSources(FileName, CodeCompletionController.currentLanguageISO) != null)
                {
                    dconv.visitor.add_doc_from_text = false;
                }
                if (cu != null)
                {
                    dconv.ConvertToDom(cu);
                }
            }
            if (dconv.is_compiled)
            {
                comp_modules[FileName] = dconv;
            }
            if (docs != null)
            {
                docs.Clear();
            }
            //comp_modules[FileName] = dconv;
            // GC.Collect();
            return(dconv);
        }
Example #33
0
        /// <summary>
        /// 设置XML输出信息
        /// </summary>
        /// <param name="To_JavaXml">XML文档</param>
        /// <param name="project">工程对象</param>
        /// <param name="sqlID">SQL查询标识</param>
        /// <param name="xmlInfo">节点XML</param>
        /// <param name="template">模板名称</param>
        /// <param name="where">查询条件</param>
        /// <returns>自定义字段集合</returns>
        public static List <T_Model> setXmlInfo(XmlDocument To_JavaXml, T_Projects project, string sqlID, XmlElement xmlInfo, string template, string where = "")
        {
            XmlDoc         doc        = new XmlDoc(Application.StartupPath + @"\Common\XMLTemplate\" + template + ".xml");
            XmlNodeList    nodeList   = doc.GetNodeList("root");
            XmlNodeList    columList  = null;
            XmlNodeList    sqlList    = null;
            List <T_Model> modelList  = new List <T_Model>();
            List <T_Model> resultList = new List <T_Model>();
            string         sql        = string.Empty;

            #region XML节点
            for (int i = 0; i < nodeList.Count; i++)
            {
                switch (nodeList[i].Name.ToLower())
                {
                case "columns":
                    columList = nodeList[i].ChildNodes;
                    break;

                case "selects":
                    sqlList = nodeList[i].ChildNodes;
                    break;
                }
            }
            #endregion

            #region 模板字段
            if (columList != null)
            {
                modelList.Clear();
                resultList.Clear();

                T_Model model = null;

                for (int i = 0; i < columList.Count; i++)
                {
                    XmlNode node = columList[i];
                    XmlAttributeCollection attrCollection = node.Attributes;

                    if (attrCollection == null)
                    {
                        continue;
                    }
                    model = new T_Model();

                    for (int j = 0; j < attrCollection.Count; j++)
                    {
                        switch (attrCollection[j].Name)
                        {
                        case "column":
                            model.Column = attrCollection[j].Value;
                            break;

                        case "mappColumn":
                            model.MappColumn = attrCollection[j].Value;
                            break;

                        case "display":
                            model.Display = attrCollection[j].Value;
                            break;

                        case "description":
                            model.Description = attrCollection[j].Value;
                            break;

                        case "type":
                            model.Type = attrCollection[j].Value;
                            break;

                        case "default":
                            model.Default = attrCollection[j].Value;
                            break;
                        }
                    }

                    if (model.Display == "1")
                    {
                        modelList.Add(model);
                    }

                    if (model.Type == "1")
                    {
                        resultList.Add(model);
                    }
                }
            }
            #endregion

            #region  射字段
            if (sqlList.Count > 0)
            {
                for (int j = 0; j < sqlList.Count; j++)
                {
                    XmlAttributeCollection attrColl = sqlList[j].Attributes;
                    if (attrColl["id"].Value.ToString() == sqlID)
                    {
                        sql = sqlList[j].InnerText.Trim();

                        #region 参数处理
                        //switch (attrColl["parameterClass"].Value.ToLower())
                        //{
                        //    case "string":
                        //        sql = sql.Replace("#value#", "'" + project.ProjectNO + "'");
                        //        break;
                        //    case "int":
                        //        sql = sql.Replace("#value#", project.ProjectNO);
                        //        break;
                        //    default:
                        //        dynamic d = attrColl["parameterClass"].Value;

                        //        sql = sql.Replace("#value#", project.ProjectNO);
                        //        break;
                        //}
                        #endregion

                        #region 输出XML
                        try
                        {
                            DataSet ds = ERM.DAL.MyBatis.QueueyForSql(sql + "  " + where);
                            if (ds.Tables.Count > 0)
                            {
                                for (int m = 0; m < ds.Tables[0].Rows.Count; m++)
                                {
                                    for (int k = 0; k < modelList.Count; k++)
                                    {
                                        for (int n = 0; n < ds.Tables[0].Columns.Count; n++)
                                        {
                                            if (modelList[k].Column.ToString().ToLower() == ds.Tables[0].Columns[n].ColumnName.ToString().ToLower())
                                            {
                                                XmlElement X_temp = To_JavaXml.CreateElement(modelList[k].MappColumn);
                                                if (!string.IsNullOrEmpty(ds.Tables[0].Rows[m][n].ToString()))
                                                {
                                                    X_temp.SetAttribute("value", ds.Tables[0].Rows[m][n].ToString());
                                                }
                                                else
                                                {
                                                    X_temp.SetAttribute("value", modelList[k].Default);
                                                }
                                                xmlInfo.AppendChild(X_temp);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            TX.Framework.WindowUI.Forms.TXMessageBoxExtensions.Info(ex.Message.ToString());
                        }
                        break;
                        #endregion
                    }
                }
            }
            return(resultList);

            #endregion
        }
Example #34
0
 /// <summary>
 /// 关闭
 /// </summary>
 public void Close()
 {
     XmlDoc.Save(xmlPath);
     XmlDoc  = null;
     xmlPath = null;
 }
Example #35
0
        private IEnumerable <Tuple <string, Response> > GetResponses(MethodInfo method, Dictionary <string, List <Attribute> > methodAttr, XmlDoc doc)
        {
            Func <Type, bool> isVoid = type => type == null || type.FullName == "System.Void";
            var returnType           = method.ReturnType;

            if (returnType == typeof(Task))
            {
                returnType = typeof(void);
            }
            else if (returnType.Name == "Task`1")
            {
                returnType = returnType.GenericTypeArguments[0];
            }
            else if (returnType == typeof(HttpResponseMessage) || returnType == typeof(ActionResult))
            {
                returnType = typeof(object);
            }

            var description = doc?.Returns ?? string.Empty;

            var          mayBeNull             = !SchemaGenerator.IsParameterRequired(method.ReturnParameter);
            const string responsetypeattribute = nameof(ResponseTypeAttribute);

            if (methodAttr.ContainsKey(responsetypeattribute))
            {
                var responseTypeAttributes = methodAttr[responsetypeattribute].Cast <ResponseTypeAttribute>();
                foreach (var responseTypeAttribute in responseTypeAttributes)
                {
                    returnType = responseTypeAttribute.ResponseType;
                    var httpStatusCode = responseTypeAttribute.HttpStatusCode ??
                                         (isVoid(returnType) ? "204" : "200");

                    yield return(Tuple.Create(httpStatusCode, new Response
                    {
                        Description = isVoid(returnType) ? "No Content" : description,
                        Schema = _schemaGenerator.MapToSchema(_schemaGenerator.GetSchema(returnType))
                    }));
                }
            }
            else
            {
                yield return(isVoid(returnType)
                    ? Tuple.Create("204", new Response()
                {
                    Description = "No Content."
                })
                    : Tuple.Create("200", new Response
                {
                    Description = description,
                    Schema = _schemaGenerator
                             .MapToSchema(_schemaGenerator.GetSchema(returnType))
                }));
            }
            yield return
                (Tuple.Create("default",
                              new Response()
            {
                Description = "Unexected Error",
                Schema = new SchemaObject()
                {
                    Ref = "#/definitions/ErrorModel"
                }
            }));
        }