Пример #1
0
        private void populateSection(ConfigSectionNode section)
        {
            if (token.Type != LaconfigTokenType.tBraceOpen)
            {
                errorAndAbort(LaconfigMsgCode.eSectionOpenBraceExpected);
            }

            fetchPrimary();    //skip {  section started

            while (true)
            {
                if (token.Type == LaconfigTokenType.tBraceClose)
                {
                    fetchPrimaryOrEOF();  //skip }  section ended
                    return;
                }

                if (token.Type != LaconfigTokenType.tIdentifier && token.Type != LaconfigTokenType.tStringLiteral)
                {
                    errorAndAbort(LaconfigMsgCode.eSectionOrAttributeNameExpected);
                }

                var name = token.Text;
                fetchPrimary();

                if (token.Type == LaconfigTokenType.tBraceOpen)  //section w/o value
                {
                    var subsection = section.AddChildNode(name, null);
                    populateSection(subsection);
                }
                else if (token.Type == LaconfigTokenType.tEQ) //section with value or attribute
                {
                    fetchPrimary();                           //skip =

                    if (token.Type != LaconfigTokenType.tIdentifier &&
                        token.Type != LaconfigTokenType.tStringLiteral &&
                        token.Type != LaconfigTokenType.tNull)
                    {
                        errorAndAbort(LaconfigMsgCode.eSectionOrAttributeValueExpected);
                    }

                    var value = token.Type == LaconfigTokenType.tNull ? null : token.Text;
                    fetchPrimary();                                 //skip value

                    if (token.Type == LaconfigTokenType.tBraceOpen) //section with value
                    {
                        var subsection = section.AddChildNode(name, value);
                        populateSection(subsection);
                    }
                    else
                    {
                        section.AddAttributeNode(name, value);
                    }
                }
                else
                {
                    errorAndAbort(LaconfigMsgCode.eSyntaxError);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Describes type including generic arguments
        /// </summary>
        public static void WriteType(Type t, ConfigSectionNode node)
        {
            node.AddAttributeNode("name-in-code", tname(t));
            node.AddAttributeNode("name", t.Name);
            if (t == typeof(void))
            {
                node.AddAttributeNode("void", true);
                return;
            }
            node.AddAttributeNode("ns", t.Namespace);
            node.AddAttributeNode("asm-q-name", t.AssemblyQualifiedName);
            node.AddAttributeNode("asm-name", t.Assembly.FullName);
            node.AddAttributeNode("intf", t.IsInterface);
            node.AddAttributeNode("valuetype", t.IsValueType);

            if (t.IsEnum)
            {
                var enode = node.AddChildNode("enum");
                foreach (var name in Enum.GetNames(t))
                {
                    var inode = enode.AddChildNode("item");
                    inode.AddAttributeNode("key", name);
                    inode.AddAttributeNode("value", (int)Enum.Parse(t, name));
                }
            }

            if (t.IsGenericType)
            {
                var ganode = node.AddChildNode("generic-type-args");
                foreach (var garg in t.GetGenericArguments())
                {
                    WriteType(garg, ganode.AddChildNode("type-arg"));
                }
            }
        }
        private (Lazy <ConfigSectionNode> request, Lazy <ConfigSectionNode> response) writeCommon(
            string defTitle,
            string defDescription,
            MemberInfo info,
            ApiDocGenerator gen,
            ApiDocAttribute attr,
            ConfigSectionNode data)
        {
            MetadataUtils.AddMetadataTokenIdAttribute(data, info);

            var title = attr.Title.Default(defTitle);

            if (title.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("title", title);
            }

            var descr = attr.Description.Default(defDescription);

            if (descr.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("description", descr);
            }

            var drequest  = new Lazy <ConfigSectionNode>(() => data.AddChildNode("request"));
            var dresponse = new Lazy <ConfigSectionNode>(() => data.AddChildNode("response"));

            writeCollection(attr.RequestHeaders, "header", drequest, ':');
            writeCollection(attr.RequestQueryParameters, "param", drequest, '=');
            writeCollection(attr.ResponseHeaders, "header", dresponse, ':');

            if (attr.Connection.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("connection", attr.Connection);
            }

            if (attr.RequestBody.IsNotNullOrWhiteSpace())
            {
                drequest.Value.AddAttributeNode("body", attr.RequestBody);
            }

            if (attr.ResponseContent.IsNotNullOrWhiteSpace())
            {
                dresponse.Value.AddAttributeNode("content", attr.ResponseContent);
            }

            writeTypeCollection(attr.TypeSchemas, TYPE_REF, data, gen);

            return(drequest, dresponse);
        }
Пример #4
0
        public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
        {
            if (instance is ReleaseAttribute release)
            {
                var node = dataRoot.AddChildNode("release");
                node.AddAttributeNode("type", release.Type);
                node.AddAttributeNode("utc", release.ReleaseTimestampUtc);
                node.AddAttributeNode("title", release.Title);

                if (release.Tags.IsNotNullOrWhiteSpace())
                {
                    node.AddAttributeNode("tags", release.Tags);
                }

                if (release.Description.IsNotNullOrWhiteSpace())
                {
                    node.AddAttributeNode("descr", release.Description);
                }

                if (context.DetailLevel > MetadataDetailLevel.Public)
                {
                    if (release.Metadata.IsNotNullOrWhiteSpace())
                    {
                        node.AddAttributeNode("meta", release.Metadata);
                    }
                }
            }

            return(dataRoot);
        }
Пример #5
0
        /// <summary>
        /// Adds nodes for InventoryAttributes
        /// </summary>
        public static void WriteInventoryAttributes(IEnumerable <InventoryAttribute> attrs, ConfigSectionNode root)
        {
            foreach (var attr in attrs)
            {
                var node = root.AddChildNode("item");
                node.AddAttributeNode("tiers", attr.Tiers.ToString());
                node.AddAttributeNode("concerns", attr.Concerns.ToString());
                node.AddAttributeNode("schema", attr.Schema);
                node.AddAttributeNode("tech", attr.Technology);
                node.AddAttributeNode("tool", attr.Tool);

                if (attr.StartDate.HasValue)
                {
                    node.AddAttributeNode("sdate", attr.StartDate.Value);
                }

                if (attr.EndDate.HasValue)
                {
                    node.AddAttributeNode("edate", attr.EndDate.Value);
                }

                if (attr.Parameters != null)
                {
                    node.AddChildNode("params", attr.Parameters);
                }
            }
        }
Пример #6
0
        public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
        {
            var tdoc = member.NonNull(nameof(member)) as Type;

            if (tdoc == null || !typeof(Doc).IsAssignableFrom(tdoc))
            {
                return(null);
            }

            var typed = tdoc.IsSubclassOf(typeof(TypedDoc));

            var    ndoc = dataRoot.AddChildNode("data-doc");
            Schema schema;

            if (instance is Doc doc)
            {
                schema = doc.Schema;
            }
            else if (typed)
            {
                schema = Schema.GetForTypedDoc(tdoc);
            }
            else
            {
                schema = null;
            }

            MetadataUtils.AddMetadataTokenIdAttribute(ndoc, tdoc);
            ndoc.AddAttributeNode("kind", typed ? "typed" : "dynamic");

            CustomMetadataAttribute.Apply(typeof(Schema), schema, context, ndoc, overrideRules);

            return(ndoc);
        }
Пример #7
0
        public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
        {
            var tperm = member.NonNull(nameof(member)) as Type;

            if (tperm == null || !typeof(Permission).IsAssignableFrom(tperm))
            {
                return(null);
            }

            var node = dataRoot.AddChildNode("permission");

            MetadataUtils.AddMetadataTokenIdAttribute(node, tperm);
            if (instance is Permission perm)
            {
                node.AddAttributeNode("name", perm.Name);
                node.AddAttributeNode("path", perm.Path);
                node.AddAttributeNode("description", perm.Description);
                node.AddAttributeNode("level", perm.Level);
            }
            else
            {
                node.AddAttributeNode("name", tperm.Name.Replace("Permission", string.Empty));
                node.AddAttributeNode("ns", tperm.Namespace);
            }
            return(dataRoot);
        }
Пример #8
0
        // IConfigurationPersistent Members
        /// <summary>
        /// Persists column configuration to config node. [grid] subnode will be created under specified node pr reused if one already exists
        /// </summary>
        public void PersistConfiguration(ConfigSectionNode node)
        {
            if (node == null)
            {
                return;
            }

            ConfigSectionNode gnode = findSubNodeForThisGrid(node) as ConfigSectionNode; //see if node for this grid already exists

            if (gnode != null)                                                           //delete with all column defs that are different now
            {
                gnode.Delete();
            }


            gnode = node.AddChildNode(CONFIG_GRID_SECTION);

            if (!string.IsNullOrEmpty(m_ID))
            {
                gnode.AddAttributeNode(CONFIG_ID_ATTR, ID);
            }

            foreach (var col in m_Columns)
            {
                col.PersistConfiguration(gnode);
            }
        }
Пример #9
0
        private ConfigSectionNode buildSection(string name, JSONDataMap sectData, ConfigSectionNode parent)
        {
            var value = sectData[SECTION_VALUE_ATTR].AsString();
            ConfigSectionNode result = parent == null ? new ConfigSectionNode(this, null, name, value)
                                                  : parent.AddChildNode(name, value);

            foreach (var kvp in sectData)
            {
                if (kvp.Value is JSONDataMap)
                {
                    buildSection(kvp.Key, (JSONDataMap)kvp.Value, result);
                }
                else if (kvp.Value is JSONDataArray)
                {
                    var lst = (JSONDataArray)kvp.Value;
                    foreach (var lnode in lst)
                    {
                        var lmap = lnode as JSONDataMap;
                        if (lmap == null)
                        {
                            throw new ConfigException(StringConsts.CONFIG_JSON_STRUCTURE_ERROR, new ConfigException("Bad structure: " + sectData.ToJSON()));
                        }
                        buildSection(kvp.Key, lmap, result);
                    }
                }
                else
                {
                    result.AddAttributeNode(kvp.Key, kvp.Value);
                }
            }

            return(result);
        }
Пример #10
0
        /// <summary>
        /// Runs inventorization routine dumping result into config node
        /// </summary>
        public void Run(ConfigSectionNode root)
        {
            if (m_Startegies.Count == 0)
            {
                throw new InventorizationException(StringConsts.INVENTORIZATION_NEED_STRATEGY_ERROR);
            }

            foreach (var asm in m_Assemblies.Where(a => filter(a)))
            {
                var asmnode = root.AddChildNode("assembly");
                asmnode.AddAttributeNode("name", asm.FullName);
                WriteInventoryAttributes(asm.GetCustomAttributes(typeof(InventoryAttribute), false).Cast <InventoryAttribute>(),
                                         asmnode.AddChildNode(ATTRIBUTES_NODE));


                var types = asm.GetTypes();
                foreach (var type in types.Where(t => filter(t)).OrderBy(t => t.FullName))
                {
                    var tnode = asmnode.AddChildNode("type");
                    tnode.AddAttributeNode("ns", type.Namespace);
                    tnode.AddAttributeNode("name", type.Name);

                    foreach (var strategy in m_Startegies)
                    {
                        strategy.Inventorize(type, tnode);
                    }
                }
            }
        }
Пример #11
0
        public VolumeMetadataBuilder SetCompressionSection(Action <ConfigSectionNode> compressionBuilder)
        {
            if (compressionBuilder == null)
            {
                return(this);
            }

            var compression = SectionSystem[VolumeMetadata.CONFIG_COMPRESSION_SECTION];

            if (!compression.Exists)
            {
                compression = SectionSystem.AddChildNode(VolumeMetadata.CONFIG_COMPRESSION_SECTION);
            }

            compressionBuilder(compression);
            return(this);
        }
Пример #12
0
        public void AddAddressee(Addressee addressee)
        {
            var aSection = m_Config.AddChildNode(CONFIG_A_SECT);

            aSection.AddAttributeNode(ATTR_NAME, addressee.Name);
            aSection.AddAttributeNode(ATTR_CHANNEL_NAME, addressee.ChannelName);
            aSection.AddAttributeNode(ATTR_CHANNEL_ADDRESS, addressee.ChannelAddress);
        }
Пример #13
0
        /// <summary>
        /// Unconditionally installs a package - copies a set of files contained in the FileSystemDirectory assigning it some mnemonic name
        /// </summary>
        public void InstallPackage(PackageInfo package)
        {
            if (!m_InstallationStarted)
            {
                throw new AzosIOException(StringConsts.LOCAL_INSTALL_NOT_STARTED_INSTALL_PACKAGE_ERROR);
            }

            var path = m_RootPath;

            if (package.RelativePath.IsNotNullOrWhiteSpace())
            {
                path = Path.Combine(path, package.RelativePath);
                IOUtils.EnsureAccessibleDirectory(path);
            }

            var packageName = package.Name;
            var source      = package.Source;
            var manifest    = package.Manifest;

            using (var lfs = new Local.LocalFileSystem(App))
                using (var fss = lfs.StartSession(null))
                {
                    var targetDir = fss[path] as FileSystemDirectory;
                    if (targetDir == null)
                    {
                        throw new AzosIOException(StringConsts.LOCAL_INSTALL_ROOT_PATH_NOT_FOUND_ERROR.Args(path));
                    }

                    source.DeepCopyTo(targetDir, FileSystemDirectory.DirCopyFlags.FilesAndDirsOnly,
                                      filter: (item) =>
                    {
                        var file = item as FileSystemFile;
                        if (file == null)
                        {
                            return(true);
                        }

                        if (file.ParentPath == source.Path && file.Name == ManifestUtils.MANIFEST_FILE_NAME)
                        {
                            return(false);
                        }

                        return(true);
                    }

                                      );
                }

            var existing = this[packageName];

            if (existing != null)
            {
                ((ConfigSectionNode)existing).Delete();
            }
            m_Packages.AddChildNode(manifest);

            m_Modified = true;
        }
Пример #14
0
        public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
        {
            var schema = instance as Schema;//is a sealed class by design

            if (schema == null)
            {
                return(null);
            }

            var ndoc = dataRoot.AddChildNode("schema");

            if (context.DetailLevel > MetadataDetailLevel.Public)
            {
                ndoc.AddAttributeNode("name", schema.Name);
            }
            else
            {
                ndoc.AddAttributeNode("name", schema.TypedDocType?.Name ?? schema.Name);
            }

            ndoc.AddAttributeNode("read-only", schema.ReadOnly);

            TypedDoc doc = null;

            if (schema.TypedDocType != null)
            {
                ndoc.AddAttributeNode("typed-doc-type", context.AddTypeToDescribe(schema.TypedDocType));

                if (!schema.TypedDocType.IsAbstract)
                {
                    try
                    { //this may fail because there may be constructor incompatibility, then we just can get instance-specific metadata
                        doc = Activator.CreateInstance(schema.TypedDocType, true) as TypedDoc;
                        context.App.InjectInto(doc);
                    }
                    catch { }
                }
            }

            foreach (var def in schema)
            {
                var nfld = ndoc.AddChildNode("field");
                try
                {
                    var targetName = context.GetSchemaDataTargetName(schema, doc);
                    field(targetName, def, context, nfld, doc);
                }
                catch (Exception error)
                {
                    var err = new CustomMetadataException(StringConsts.METADATA_GENERATION_SCHEMA_FIELD_ERROR.Args(schema.Name, def.Name, error.ToMessageWithType()), error);
                    nfld.AddAttributeNode("--ERROR--", StringConsts.METADATA_GENERATION_SCHEMA_FIELD_ERROR.Args(schema.Name, def.Name, "<logged>"));
                    context.ReportError(Log.MessageType.CriticalAlert, err);
                }
            }

            return(ndoc);
        }
Пример #15
0
        // -arg1 -arg2 -arg3 opt1 opt2 -arg4 optA=v1 optB=v2
        private void parseArgs()
        {
            m_Root = new ConfigSectionNode(this, null, ROOT_NODE_NAME, string.Empty);

            var uargcnt = 1; //unknown arg length

            for (int i = 0; i < m_Args.Length;)
            {
                var argument = m_Args[i];

                if (argument.Length > 1 && ((!m_InhibitSlashArg && argument.StartsWith(ARG_PREFIX_SLASH)) || argument.StartsWith(ARG_PREFIX_DASH)))
                {
                    argument = argument.Remove(0, 1);//get rid of prefix
                    var argNode = m_Root.AddChildNode(argument, null);

                    var uopcnt = 1;               //unknown option length
                    for (i++; i < m_Args.Length;) //read args's options
                    {
                        var option = m_Args[i];
                        if ((!m_InhibitSlashArg && option.StartsWith(ARG_PREFIX_SLASH)) || option.StartsWith(ARG_PREFIX_DASH))
                        {
                            break;
                        }
                        i++;

                        var j = option.IndexOf(OPTION_EQ);

                        if (j < 0)
                        {
                            argNode.AddAttributeNode(string.Format("?{0}", uopcnt), option);
                            uopcnt++;
                        }
                        else
                        {
                            var name = option.Substring(0, j);
                            var val  = (j < option.Length - 1) ? option.Substring(j + 1) : string.Empty;

                            if (string.IsNullOrEmpty(name))
                            {
                                name = string.Format("?{0}", uopcnt);
                                uopcnt++;
                            }
                            argNode.AddAttributeNode(name, val);
                        }
                    }
                }
                else
                {
                    m_Root.AddAttributeNode(string.Format("?{0}", uargcnt), argument);
                    uargcnt++;
                    i++;
                }
            }

            m_Root.ResetModified();
        }
Пример #16
0
        private static void buildDirLevel(ConfigSectionNode pNode, FileSystemDirectory directory)
        {
            const int BUFF_SIZE = 64 * 1024;

            foreach (var sdn in directory.SubDirectoryNames)
            {
                using (var sdir = directory.GetSubDirectory(sdn))
                {
                    var dnode = pNode.AddChildNode(CONFIG_DIR_SECTION);
                    dnode.AddAttributeNode(CONFIG_NAME_ATTR, sdir.Name);
                    buildDirLevel(dnode, sdir);
                }
            }

            foreach (var fn in directory.FileNames.Where(fn => !MANIFEST_FILE_NAME.EqualsIgnoreCase(fn)))
            {
                using (var file = directory.GetFile(fn))
                {
                    var fnode = pNode.AddChildNode(CONFIG_FILE_SECTION);
                    fnode.AddAttributeNode(CONFIG_NAME_ATTR, file.Name);

                    long size = 0;
                    var  csum = new Adler32();
                    var  buff = new byte[BUFF_SIZE];
                    using (var fs = file.FileStream)
                        while (true)
                        {
                            var read = fs.Read(buff, 0, BUFF_SIZE);
                            if (read <= 0)
                            {
                                break;
                            }
                            size += read;
                            csum.Add(buff, 0, read);
                        }

                    fnode.AddAttributeNode(CONFIG_SIZE_ATTR, size);
                    fnode.AddAttributeNode(CONFIG_CSUM_ATTR, csum.Value);
                }
            }
        }
Пример #17
0
        // IConfigurationPersistent Members
        public void PersistConfiguration(ConfigSectionNode node)
        {
            var cn = node.AddChildNode(Grid.CONFIG_COLUMN_SECTION);

            cn.AddAttributeNode(Grid.CONFIG_ID_ATTR, m_ID);
            cn.AddAttributeNode(CONFIG_WIDTH_ATTR, m_Width);

            if (SortingAllowed)
            {
                cn.AddAttributeNode(CONFIG_SORT_ATTR, m_SortDirection);
            }
        }
Пример #18
0
        public void AddAddressee(Addressee addressee)
        {
            var aSection = m_Config.AddChildNode(CONFIG_A_SECT);

            aSection.AddAttributeNode(ATTR_NAME, addressee.Name);
            aSection.AddAttributeNode(ATTR_CHANNEL_NAME, addressee.ChannelName);
            aSection.AddAttributeNode(ATTR_CHANNEL_ADDRESS, addressee.ChannelAddress);

            if (MessageBuilderChange != null)
            {
                MessageBuilderChange(this);
            }
        }
Пример #19
0
                private void reportCheck(ConfigSectionNode parent, BaseCheck check)
                {
                  var node = parent.AddChildNode("check", null);
                  node.AddAttributeNode("name", check.Name);
                  node.AddAttributeNode("description", check.Description);
                  node.AddAttributeNode("skipped", check.Result.Skipped);
                  node.AddAttributeNode("successful", check.Result.Successful);
                  node.AddAttributeNode("error", check.Result.Exception!=null? check.Result.Exception.ToString() : string.Empty);
                  var keys = node.AddChildNode("results", null);

                  foreach(var kv in check.Result)
                    keys.AddChildNode(kv.Key, kv.Value);
                }
Пример #20
0
 private void buildNode(ConfigSectionNode node, JsonDataMap map)
 {
     foreach (var kvp in map)
     {
         var cmap = kvp.Value as JsonDataMap;
         if (cmap != null)
         {
             buildNode(node.AddChildNode(kvp.Key), cmap);
         }
         else
         {
             node.AddAttributeNode(kvp.Key, kvp.Value);
         }
     }
 }
Пример #21
0
        private void outError(ConfigSectionNode node, Exception error)
        {
            var nesting = 0;

            while (error != null)
            {
                node = node.AddChildNode("error", error.GetType().Name);
                node.AddAttributeNode("type", error.GetType().AssemblyQualifiedName);
                node.AddAttributeNode("nesting", nesting);
                node.AddAttributeNode("msg", error.Message);
                node.AddAttributeNode("stack", error.StackTrace);

                error = error.InnerException;
                nesting++;
            }
        }
Пример #22
0
        private void reportCheck(ConfigSectionNode parent, BaseCheck check)
        {
            var node = parent.AddChildNode("check", null);

            node.AddAttributeNode("name", check.Name);
            node.AddAttributeNode("description", check.Description);
            node.AddAttributeNode("skipped", check.Result.Skipped);
            node.AddAttributeNode("successful", check.Result.Successful);
            node.AddAttributeNode("error", check.Result.Exception != null? check.Result.Exception.ToString() : string.Empty);
            var keys = node.AddChildNode("results", null);

            foreach (var kv in check.Result)
            {
                keys.AddChildNode(kv.Key, kv.Value);
            }
        }
Пример #23
0
        public VolumeMetadataBuilder SetApplicationSection(Action <ConfigSectionNode> applicationBuilder)
        {
            if (applicationBuilder == null)
            {
                return(this);
            }

            var application = Root[VolumeMetadata.CONFIG_APP_SECTION];

            if (!application.Exists)
            {
                application = Root.AddChildNode(VolumeMetadata.CONFIG_APP_SECTION);
            }

            applicationBuilder(application);
            return(this);
        }
Пример #24
0
        public void AddAddressee(Addressee addressee)
        {
            if (m_All == null)
            {
                m_All = new Addressee[] { addressee }
            }
            ;
            else
            {
                m_All = m_All.Concat(new Addressee[] { addressee });
            }

            var aSection = m_Config.AddChildNode(CONFIG_A_SECT);

            aSection.AddAttributeNode(ATTR_NAME, addressee.Name);
            aSection.AddAttributeNode(ATTR_CHANNEL_NAME, addressee.ChannelName);
            aSection.AddAttributeNode(ATTR_CHANNEL_ADDRESS, addressee.ChannelAddress);
        }
Пример #25
0
        private ConfigSectionNode buildNode(XmlNode xnode, ConfigSectionNode parent)
        {
            ConfigSectionNode result;

            if (xnode.NodeType == XmlNodeType.Text && parent != null)
            {
                parent.Value = xnode.Value;
                return(null);
            }

            if (parent != null)
            {
                result = parent.AddChildNode(xnode.Name, string.Empty);
            }
            else
            {
                result = new ConfigSectionNode(this, null, xnode.Name, string.Empty);
            }

            if (xnode.Attributes != null)
            {
                foreach (XmlAttribute xattr in xnode.Attributes)
                {
                    result.AddAttributeNode(xattr.Name, xattr.Value);
                }
            }


            foreach (XmlNode xn in xnode)
            {
                if (xn.NodeType != XmlNodeType.Comment)
                {
                    buildNode(xn, result);
                }
            }

            return(result);
        }
Пример #26
0
        public void Inventorize(Type t, ConfigSectionNode root)
        {
            InventorizationManager.WriteInventoryAttributes(
                 t.GetCustomAttributes(typeof(InventoryAttribute), false).Cast<InventoryAttribute>(),
                 root.AddChildNode(InventorizationManager.ATTRIBUTES_NODE));

               if (t.BaseType!=null)
            root.AddAttributeNode("base", t.BaseType.FullName);

               root.AddAttributeNode("abstract",  t.IsAbstract);
               root.AddAttributeNode("class",  t.IsClass);
               root.AddAttributeNode("enum",  t.IsEnum);
               root.AddAttributeNode("intf",  t.IsInterface);
               root.AddAttributeNode("nested",  t.IsNested);
               root.AddAttributeNode("public",  t.IsPublic);
               root.AddAttributeNode("sealed",  t.IsSealed);
               root.AddAttributeNode("serializable",  t.IsSerializable);
               root.AddAttributeNode("valuetype",  t.IsValueType);
               root.AddAttributeNode("visible",  t.IsVisible);

               var members = t.GetMembers().Where(m=>m.GetCustomAttributes(typeof(InventoryAttribute), false).Count()>0);
               foreach(var mem in members)
               {
             var mnode = root.AddChildNode("member");
             mnode.AddAttributeNode("name", mem.Name);
             mnode.AddAttributeNode("kind", mem.MemberType.ToString());

             InventorizationManager.WriteInventoryAttributes(
                 mem.GetCustomAttributes(typeof(InventoryAttribute), false).Cast<InventoryAttribute>(),
                 mnode.AddChildNode(InventorizationManager.ATTRIBUTES_NODE));

             if (mem is PropertyInfo)
             {
               var pinf = (PropertyInfo)mem;
               mnode.AddAttributeNode("can-get", pinf.CanRead);
               mnode.AddAttributeNode("can-set", pinf.CanWrite);
               mnode.AddAttributeNode("type", pinf.PropertyType.FullName);
             }
             else
             if (mem is FieldInfo)
             {
               var finf = (FieldInfo)mem;
               mnode.AddAttributeNode("not-serialized", finf.IsNotSerialized);
               mnode.AddAttributeNode("public", finf.IsPublic);
               mnode.AddAttributeNode("private", finf.IsPrivate);
               mnode.AddAttributeNode("static", finf.IsStatic);
               mnode.AddAttributeNode("type", finf.FieldType.FullName);
             }
             else
             if (mem is MethodInfo)
             {
               var minf = (MethodInfo)mem;
               mnode.AddAttributeNode("virtual", minf.IsVirtual);
               mnode.AddAttributeNode("public", minf.IsPublic);
               mnode.AddAttributeNode("private", minf.IsPrivate);
               mnode.AddAttributeNode("static", minf.IsStatic);
               if (minf.ReturnType!=null)
                mnode.AddAttributeNode("return-type", minf.ReturnType.FullName);
             }
               }
        }
Пример #27
0
        /// <summary>
        /// Executes the source configuration script against the target (StopWatch is passed along to track timout adherence)
        /// </summary>
        protected virtual void DoNode(Stopwatch sw, ConfigSectionNode source, ConfigSectionNode target)
        {
            if (source == null || !source.Exists)
            {
                return;
            }
            if (target == null || !target.Exists)
            {
                return;
            }

            if (m_TimeoutMs > 0 && sw.ElapsedMilliseconds > m_TimeoutMs)
            {
                throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_TIMEOUT_ERROR.Args(m_TimeoutMs, source.RootPath));
            }


            ConfigSectionNode priorStatement = null;

            foreach (var subSource in source.Children)
            {
                if (subSource.IsSameName(KeywordBLOCK))
                {
                    DoBLOCK(sw, subSource, target);
                }
                else if (subSource.IsSameName(KeywordIF))
                {
                    DoIF(sw, subSource, target);
                }
                else if (subSource.IsSameName(KeywordELSE))
                {
                    DoELSE(sw, subSource, priorStatement, target);
                }
                else if (subSource.IsSameName(KeywordLOOP))
                {
                    DoLOOP(sw, subSource, target);
                }
                else if (subSource.IsSameName(KeywordSET))
                {
                    DoSET(sw, subSource);
                }
                else if (subSource.IsSameName(KeywordCALL))
                {
                    DoCALL(sw, subSource, target);
                }
                else
                {
                    var scriptOnly     = false;
                    var scriptOnlyAttr = subSource.AttrByName(AttributeScriptOnly);
                    if (scriptOnlyAttr.Exists)
                    {
                        scriptOnly = scriptOnlyAttr.ValueAsBool(false);
                    }

                    if (!scriptOnly)
                    {
                        var underStatement = false;
                        var p = subSource;
                        while (p != null && p.Exists)
                        {
                            if (p.m_Script_Statement)
                            {
                                underStatement = true;
                                break;
                            }
                            p = p.Parent;
                        }
                        var newTarget = target.AddChildNode(subSource.EvaluateValueVariables(subSource.Name), underStatement ? subSource.Value : subSource.VerbatimValue);
                        CloneAttributes(subSource, newTarget, underStatement);

                        DoNode(sw, subSource, newTarget);
                    }

                    priorStatement = null;
                    continue;
                }
                priorStatement = subSource;
            }
        }
Пример #28
0
        public void Inventorize(Type t, ConfigSectionNode root)
        {
            InventorizationManager.WriteInventoryAttributes(
                t.GetCustomAttributes(typeof(InventoryAttribute), false).Cast <InventoryAttribute>(),
                root.AddChildNode(InventorizationManager.ATTRIBUTES_NODE));

            if (t.BaseType != null)
            {
                root.AddAttributeNode("base", t.BaseType.FullName);
            }

            root.AddAttributeNode("abstract", t.IsAbstract);
            root.AddAttributeNode("class", t.IsClass);
            root.AddAttributeNode("enum", t.IsEnum);
            root.AddAttributeNode("intf", t.IsInterface);
            root.AddAttributeNode("nested", t.IsNested);
            root.AddAttributeNode("public", t.IsPublic);
            root.AddAttributeNode("sealed", t.IsSealed);
            root.AddAttributeNode("serializable", t.IsSerializable);
            root.AddAttributeNode("valuetype", t.IsValueType);
            root.AddAttributeNode("visible", t.IsVisible);

            var members = t.GetMembers().Where(m => m.GetCustomAttributes(typeof(InventoryAttribute), false).Count() > 0);

            foreach (var mem in members)
            {
                var mnode = root.AddChildNode("member");
                mnode.AddAttributeNode("name", mem.Name);
                mnode.AddAttributeNode("kind", mem.MemberType.ToString());

                InventorizationManager.WriteInventoryAttributes(
                    mem.GetCustomAttributes(typeof(InventoryAttribute), false).Cast <InventoryAttribute>(),
                    mnode.AddChildNode(InventorizationManager.ATTRIBUTES_NODE));

                if (mem is PropertyInfo)
                {
                    var pinf = (PropertyInfo)mem;
                    mnode.AddAttributeNode("can-get", pinf.CanRead);
                    mnode.AddAttributeNode("can-set", pinf.CanWrite);
                    mnode.AddAttributeNode("type", pinf.PropertyType.FullName);
                }
                else
                if (mem is FieldInfo)
                {
                    var finf = (FieldInfo)mem;
                    mnode.AddAttributeNode("not-serialized", finf.IsNotSerialized);
                    mnode.AddAttributeNode("public", finf.IsPublic);
                    mnode.AddAttributeNode("private", finf.IsPrivate);
                    mnode.AddAttributeNode("static", finf.IsStatic);
                    mnode.AddAttributeNode("type", finf.FieldType.FullName);
                }
                else
                if (mem is MethodInfo)
                {
                    var minf = (MethodInfo)mem;
                    mnode.AddAttributeNode("virtual", minf.IsVirtual);
                    mnode.AddAttributeNode("public", minf.IsPublic);
                    mnode.AddAttributeNode("private", minf.IsPrivate);
                    mnode.AddAttributeNode("static", minf.IsStatic);
                    if (minf.ReturnType != null)
                    {
                        mnode.AddAttributeNode("return-type", minf.ReturnType.FullName);
                    }
                }
            }
        }
Пример #29
0
        private void doNode(Stopwatch sw, ConfigSectionNode source, ConfigSectionNode target)
        {
            if (source==null || !source.Exists) return;
                if (target==null || !target.Exists) return;

                if (m_TimeoutMs>0 && sw.ElapsedMilliseconds > m_TimeoutMs)
                    throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_TIMEOUT_ERROR.Args(m_TimeoutMs, source.RootPath));

                ConfigSectionNode priorStatement = null;
                foreach(var subSource in source.Children)
                {
                    if      (subSource.IsSameName(KeywordBLOCK)) doBLOCK(sw, subSource, target);
                    else if (subSource.IsSameName(KeywordIF))    doIF  (sw, subSource, target);
                    else if (subSource.IsSameName(KeywordELSE))  doELSE(sw, subSource, priorStatement, target);
                    else if (subSource.IsSameName(KeywordLOOP))  doLOOP(sw, subSource, target);
                    else if (subSource.IsSameName(KeywordSET))   doSET (sw, subSource);
                    else if (subSource.IsSameName(KeywordCALL))  doCALL(sw, subSource, target);
                    else
                    {
                        var scriptOnly = false;
                        var scriptOnlyAttr = subSource.AttrByName(AttributeScriptOnly);
                        if (scriptOnlyAttr.Exists)
                         scriptOnly = scriptOnlyAttr.ValueAsBool(false);

                        if (!scriptOnly)
                        {
                            var underStatement = false;
                            var p = subSource;
                            while(p!=null && p.Exists)
                            {
                                if (p.m_Script_Statement)
                                {
                                    underStatement = true;
                                    break;
                                }
                                p = p.Parent;
                            }
                            var newTarget = target.AddChildNode( subSource.EvaluateValueVariables( subSource.Name ), underStatement ? subSource.Value : subSource.VerbatimValue);
                            cloneAttributes(subSource, newTarget, underStatement);

                            doNode(sw, subSource, newTarget);
                        }

                        priorStatement = null;
                        continue;
                    }
                    priorStatement = subSource;
                }
        }
        private ConfigSectionNode describe(Type tController, object instance, ApiDocGenerator.ControllerContext apictx, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules)
        {
            var cdata          = dataRoot.AddChildNode("scope");
            var cattr          = apictx.ApiDocAttr;
            var docContent     = tController.GetText(cattr.DocFile ?? "{0}.md".Args(tController.Name));
            var ctlTitle       = MarkdownUtils.GetTitle(docContent);
            var ctlDescription = MarkdownUtils.GetTitleDescription(docContent);

            (var drequest, var dresponse) = writeCommon(ctlTitle, ctlDescription, tController, apictx.Generator, cattr, cdata);
            cdata.AddAttributeNode("uri-base", cattr.BaseUri);
            cdata.AddAttributeNode("auth", cattr.Authentication);

            cdata.AddAttributeNode("doc-content", docContent);

            var allMethodContexts = apictx.Generator.GetApiMethods(tController, apictx.ApiDocAttr);

            foreach (var mctx in allMethodContexts)
            {
                var edata = cdata.AddChildNode("endpoint");
                (var mrequest, var mresponse) = writeCommon(null, null, mctx.Method, apictx.Generator, mctx.ApiEndpointDocAttr, edata);

                var epuri = mctx.ApiEndpointDocAttr.Uri.AsString().Trim();
                if (epuri.IsNullOrWhiteSpace())
                {
                    // infer from action attribute
                    var action = mctx.Method.GetCustomAttributes <ActionBaseAttribute>().FirstOrDefault();
                    if (action != null)
                    {
                        epuri = action.Name;
                    }
                    if (epuri.IsNullOrWhiteSpace())
                    {
                        epuri = mctx.Method.Name;
                    }
                }


                if (!epuri.StartsWith("/"))
                {
                    var bu = cattr.BaseUri.Trim();
                    if (!bu.EndsWith("/"))
                    {
                        bu += "/";
                    }
                    epuri = bu + epuri;
                }

                edata.AddAttributeNode("uri", epuri);
                writeCollection(mctx.ApiEndpointDocAttr.Methods, "method", mrequest, ':');

                //docAnchor
                var docAnchor = mctx.ApiEndpointDocAttr.DocAnchor.Default("### " + epuri);
                edata.AddAttributeNode("doc-content", MarkdownUtils.GetSectionContent(docContent, docAnchor));

                //Get all method attributes except ApiDoc
                var epattrs = mctx.Method
                              .GetCustomAttributes(true)
                              .Where(a => !(a is ApiDocAttribute) && !(a is ActionBaseAttribute));

                writeInstanceCollection(epattrs.Where(a => !(a is IInstanceCustomMetadataProvider) ||
                                                      (a is IInstanceCustomMetadataProvider cip &&
                                                       cip.ShouldProvideInstanceMetadata(apictx.Generator, edata))).ToArray(), TYPE_REF, edata, apictx.Generator);

                writeTypeCollection(epattrs.Select(a => a.GetType())
                                    .Where(t => !apictx.Generator.IsWellKnownType(t))
                                    .Distinct()
                                    .ToArray(),
                                    TYPE_REF, edata, apictx.Generator);//distinct attr types

                //todo Get app parameters look for Docs and register them and also permissions
                var epargs = mctx.Method.GetParameters()
                             .Where(pi => !pi.IsOut && !pi.ParameterType.IsByRef && !apictx.Generator.IsWellKnownType(pi.ParameterType))
                             .Select(pi => pi.ParameterType).ToArray();
                writeTypeCollection(epargs, TYPE_REF, edata, apictx.Generator);
            }

            return(cdata);
        }
        private ConfigSectionNode describe(Type tController, object instance, ApiDocGenerator.ControllerContext apictx, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules)
        {
            var cdata          = dataRoot.AddChildNode("scope");
            var cattr          = apictx.ApiDocAttr;
            var docContent     = tController.GetText(cattr.DocFile ?? "{0}.md".Args(tController.Name));
            var ctlTitle       = MarkdownUtils.GetTitle(docContent);
            var ctlDescription = MarkdownUtils.GetTitleDescription(docContent);

            (var drequest, var dresponse) = writeCommon(ctlTitle, ctlDescription, tController, apictx.Generator, cattr, cdata);
            cdata.AddAttributeNode("uri-base", cattr.BaseUri);
            cdata.AddAttributeNode("auth", cattr.Authentication);

            cdata.AddAttributeNode("doc-content-tpl", docContent);

            var allMethodContexts = apictx.Generator.GetApiMethods(tController, apictx.ApiDocAttr);

            foreach (var mctx in allMethodContexts)
            {
                var edata = cdata.AddChildNode("endpoint");
                (var mrequest, var mresponse) = writeCommon(null, null, mctx.Method, apictx.Generator, mctx.ApiEndpointDocAttr, edata);

                var epuri = mctx.ApiEndpointDocAttr.Uri.AsString().Trim();
                if (epuri.IsNullOrWhiteSpace())
                {
                    // infer from action attribute
                    var action = mctx.Method.GetCustomAttributes <ActionBaseAttribute>().FirstOrDefault();
                    if (action != null)
                    {
                        epuri = action.Name;
                    }
                    if (epuri.IsNullOrWhiteSpace())
                    {
                        epuri = mctx.Method.Name;
                    }
                }


                if (!epuri.StartsWith("/"))
                {
                    var bu = cattr.BaseUri.Trim();
                    if (!bu.EndsWith("/"))
                    {
                        bu += "/";
                    }
                    epuri = bu + epuri;
                }

                edata.AddAttributeNode("uri", epuri);
                writeCollection(mctx.ApiEndpointDocAttr.Methods, "method", mrequest, ':');

                //Get all method attributes except ApiDoc
                var epattrs = mctx.Method
                              .GetCustomAttributes(true)
                              .Where(a => !(a is ApiDocAttribute) &&
                                     !(a is ActionBaseAttribute) &&
                                     !apictx.Generator.IgnoreTypePatterns.Any(ignore => a.GetType().FullName.MatchPattern(ignore))
                                     );

                writeInstanceCollection(epattrs.Where(a => !(a is IInstanceCustomMetadataProvider) ||
                                                      (a is IInstanceCustomMetadataProvider cip &&
                                                       cip.ShouldProvideInstanceMetadata(apictx.Generator, edata))).ToArray(), TYPE_REF, edata, apictx.Generator);

                writeTypeCollection(epattrs.Select(a => a.GetType())
                                    .Where(t => !apictx.Generator.IsWellKnownType(t))
                                    .Distinct()
                                    .ToArray(),
                                    TYPE_REF, edata, apictx.Generator);//distinct attr types

                //get method parameters
                var epargs = mctx.Method.GetParameters()
                             .Where(pi => !pi.IsOut &&
                                    !pi.ParameterType.IsByRef &&
                                    !apictx.Generator.IsWellKnownType(pi.ParameterType) &&
                                    !apictx.Generator.IgnoreTypePatterns.Any(ignore => pi.ParameterType.FullName.MatchPattern(ignore))
                                    )
                             .Select(pi => pi.ParameterType).ToArray();
                writeTypeCollection(epargs, TYPE_REF, edata, apictx.Generator);

                //docAnchor
                var docAnchor    = mctx.ApiEndpointDocAttr.DocAnchor.Default("### " + epuri);
                var epDocContent = MarkdownUtils.GetSectionContent(docContent, docAnchor);

                edata.AddAttributeNode("doc-content-tpl", epDocContent);

                //finally regenerate doc content expanding all variables
                epDocContent = MarkdownUtils.EvaluateVariables(epDocContent, (v) =>
                {
                    if (v.IsNullOrWhiteSpace())
                    {
                        return(v);
                    }
                    //Escape: ``{{a}}`` -> `{a}`
                    if (v.StartsWith("{") && v.EndsWith("}"))
                    {
                        return(v.Substring(1, v.Length - 2));
                    }
                    if (v.StartsWith("@"))
                    {
                        return($"`{{{v}}}`");        //do not expand TYPE spec here
                    }
                    //else navigate config path
                    return(edata.Navigate(v).Value);
                });

                edata.AddAttributeNode("doc-content", epDocContent);
            }//all endpoints

            //finally regenerate doc content expanding all variables for the controller
            docContent = MarkdownUtils.EvaluateVariables(docContent, (v) =>
            {
                if (v.IsNullOrWhiteSpace())
                {
                    return(v);
                }
                //Escape: ``{{a}}`` -> `{a}`
                if (v.StartsWith("{") && v.EndsWith("}"))
                {
                    return(v.Substring(1, v.Length - 2));
                }
                if (v.StartsWith("@"))
                {
                    return($"`{{{v}}}`");          //do not expand TYPE spec here
                }
                //else navigate config path
                return(cdata.Navigate(v).Value);
            });

            cdata.AddAttributeNode("doc-content", docContent);

            return(cdata);
        }
Пример #32
0
      private static void buildDirLevel(ConfigSectionNode pNode, FileSystemDirectory directory)
      {
        const int BUFF_SIZE = 64 * 1024;

        foreach(var sdn in directory.SubDirectoryNames)
          using(var sdir = directory.GetSubDirectory(sdn))
          {
            var dnode = pNode.AddChildNode(CONFIG_DIR_SECTION);
            dnode.AddAttributeNode(CONFIG_NAME_ATTR, sdir.Name);
            buildDirLevel(dnode, sdir);
          }

        foreach(var fn in directory.FileNames.Where(fn => !string.Equals(fn, MANIFEST_FILE_NAME, StringComparison.InvariantCultureIgnoreCase)))
          using(var file = directory.GetFile(fn))
          {
            var fnode = pNode.AddChildNode(CONFIG_FILE_SECTION);
            fnode.AddAttributeNode(CONFIG_NAME_ATTR, file.Name);
          
            long size = 0;
            var csum = new Adler32();
            var buff = new byte[BUFF_SIZE];
            using(var fs = file.FileStream)
              while(true)
              {
                var read = fs.Read(buff, 0, BUFF_SIZE);
                if (read<=0) break;
                size += read;
                csum.Add(buff, 0, read); 
              }

            fnode.AddAttributeNode(CONFIG_SIZE_ATTR, size);
            fnode.AddAttributeNode(CONFIG_CSUM_ATTR, csum.Value);
          }
      
      } 
Пример #33
0
        private void field(string targetName, Schema.FieldDef def, IMetadataGenerator context, ConfigSectionNode data, TypedDoc doc)
        {
            var fname = def.GetBackendNameForTarget(targetName, out var fatr);

            if (fatr == null)
            {
                return;
            }

            if (context.DetailLevel > MetadataDetailLevel.Public)
            {
                data.AddAttributeNode("prop-name", def.Name);
                data.AddAttributeNode("prop-type", def.Type.AssemblyQualifiedName);
                data.AddAttributeNode("non-ui", fatr.NonUI);
                data.AddAttributeNode("is-arow", fatr.IsArow);
                data.AddAttributeNode("store-flag", fatr.StoreFlag);
                data.AddAttributeNode("backend-type", fatr.BackendType);

                //try to disclose ALL metadata (as we are above PUBLIC)
                if (fatr.Metadata != null && fatr.Metadata.Exists)
                {
                    var metad = data.AddChildNode("meta");
                    metad.MergeSections(fatr.Metadata);
                    metad.MergeAttributes(fatr.Metadata);
                }
            }
            else //try to disclose pub-only metadata
            {
                var pubSection = context.PublicMetadataSection;
                if (fatr.Metadata != null && pubSection.IsNotNullOrWhiteSpace())
                {
                    var metasrc = fatr.Metadata[pubSection];//<-- pub metadata only
                    if (metasrc.Exists)
                    {
                        var metad = data.AddChildNode("meta");
                        metad.MergeSections(metasrc);
                        metad.MergeAttributes(metasrc);
                    }
                }
            }

            data.AddAttributeNode("name", fname);
            data.AddAttributeNode("type", context.AddTypeToDescribe(def.Type));
            data.AddAttributeNode("order", def.Order);

            if (fatr.Description.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("description", fatr.Description);
            }
            data.AddAttributeNode("key", fatr.Key);

            data.AddAttributeNode("kind", fatr.Kind);

            data.AddAttributeNode("required", fatr.Required);
            data.AddAttributeNode("visible", fatr.Required);
            data.AddAttributeNode("case", fatr.CharCase);
            if (fatr.Default != null)
            {
                data.AddAttributeNode("default", fatr.Default);
            }
            if (fatr.DisplayFormat.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("display-format", fatr.DisplayFormat);
            }
            if (fatr.FormatRegExp.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("format-reg-exp", fatr.FormatRegExp);
            }
            if (fatr.FormatDescription.IsNotNullOrWhiteSpace())
            {
                data.AddAttributeNode("format-description", fatr.FormatDescription);
            }
            if (fatr.Max != null)
            {
                data.AddAttributeNode("max", fatr.Max);
            }
            if (fatr.Min != null)
            {
                data.AddAttributeNode("min", fatr.Min);
            }
            if (fatr.MinLength > 0 || fatr.MaxLength > 0)
            {
                data.AddAttributeNode("min-len", fatr.MinLength);
            }
            if (fatr.MinLength > 0 || fatr.MaxLength > 0)
            {
                data.AddAttributeNode("max-len", fatr.MaxLength);
            }

            //add values from field attribute .ValueList property
            var nvlist = new Lazy <ConfigSectionNode>(() => data.AddChildNode("value-list"));

            if (fatr.HasValueList)
            {
                fatr.ParseValueList().ForEach(item => nvlist.Value.AddAttributeNode(item.Key, item.Value));
            }

            //if doc!=null call doc.GetClientFieldValueList on the instance to get values from Database lookups etc...
            if (doc != null)
            {
                var lookup = doc.GetDynamicFieldValueList(def, targetName, null);
                if (lookup != null)//non-null blank lookup is treated as blank lookup overshadowing the hard-coded choices from .ValueList
                {
                    if (nvlist.IsValueCreated)
                    {
                        nvlist.Value.DeleteAllAttributes();
                    }

                    lookup.ForEach(item => nvlist.Value.AddAttributeNode(item.Key, item.Value));
                }
            }
        }
Пример #34
0
        // -arg1 -arg2 -arg3 opt1 opt2 -arg4 optA=v1 optB=v2
        private void parseArgs()
        {
            m_Root = new ConfigSectionNode(this, null, ROOT_NODE_NAME, string.Empty);

              var uargcnt = 1; //unknown arg length
              for (int i = 0; i < m_Args.Length; )
              {
            var argument = m_Args[i];

            if (argument.Length > 1 && (argument.StartsWith(ARG_PREFIX1) || argument.StartsWith(ARG_PREFIX2)))
            {
              argument = argument.Remove(0, 1);//get rid of prefix
              var argNode = m_Root.AddChildNode(argument, null);

              var uopcnt = 1;//unknown option length
              for (i++; i < m_Args.Length; )//read args's options
              {
            var option = m_Args[i];
            if (option.StartsWith(ARG_PREFIX1) || option.StartsWith(ARG_PREFIX2)) break;
            i++;

            var j = option.IndexOf(OPTION_EQ);

            if (j < 0)
            {
              argNode.AddAttributeNode(string.Format("?{0}", uopcnt), option);
              uopcnt++;
            }
            else
            {
              var name = option.Substring(0, j);
              var val = (j < option.Length - 1) ? option.Substring(j + 1) : string.Empty;

              if (string.IsNullOrEmpty(name))
              {
                name = string.Format("?{0}", uopcnt);
                uopcnt++;
              }
              argNode.AddAttributeNode(name, val);
            }
              }
            }
            else
            {
              m_Root.AddAttributeNode(string.Format("?{0}", uargcnt), argument);
              uargcnt++;
              i++;
            }
              }

              m_Root.ResetModified();
        }
Пример #35
0
        private void includeCommonConfig(ConfigSectionNode levelRoot)
        {
            var placeholder = levelRoot.AddChildNode(Guid.NewGuid().ToString());

            placeholder.Configuration.Include(placeholder, m_CommonLevelConfig);
        }
Пример #36
0
        private ConfigSectionNode buildNode(XmlNode xnode, ConfigSectionNode parent)
        {
            ConfigSectionNode result;

              if (xnode.NodeType == XmlNodeType.Text && parent != null)
              {
            parent.Value = xnode.Value;
            return null;
              }

              if (parent != null)
            result = parent.AddChildNode(xnode.Name, string.Empty);
              else
            result = new ConfigSectionNode(this, null, xnode.Name, string.Empty);

              if (xnode.Attributes != null)
            foreach (XmlAttribute xattr in xnode.Attributes)
              result.AddAttributeNode(xattr.Name, xattr.Value);

              foreach (XmlNode xn in xnode)
               if (xn.NodeType != XmlNodeType.Comment)
             buildNode(xn, result);

              return result;
        }
Пример #37
0
Файл: Grid.cs Проект: kinpro/nfx
      // IConfigurationPersistent Members
      /// <summary>
      /// Persists column configuration to config node. [grid] subnode will be created under specified node pr reused if one already exists
      /// </summary>
      public void PersistConfiguration(ConfigSectionNode node)
      {
         if (node==null) return;
         
         ConfigSectionNode gnode = findSubNodeForThisGrid(node) as ConfigSectionNode; //see if node for this grid already exists

         if (gnode!=null)//delete with all column defs that are different now
           gnode.Delete();
         
         
         gnode = node.AddChildNode(CONFIG_GRID_SECTION);
         
         if (!string.IsNullOrEmpty(m_ID))
           gnode.AddAttributeNode(CONFIG_ID_ATTR, ID);
         
         foreach(var col in m_Columns)
           col.PersistConfiguration(gnode);
      }
Пример #38
0
        private ConfigSectionNode buildSection(string name, JSONDataMap sectData, ConfigSectionNode parent)
        {
            var value = sectData[SECTION_VALUE_ATTR].AsString();
              ConfigSectionNode result = parent==null ? new ConfigSectionNode(this, null, name, value)
                                                  : parent.AddChildNode(name, value);

              foreach(var kvp in sectData)
              {
            if (kvp.Value is JSONDataMap)
              buildSection(kvp.Key, (JSONDataMap)kvp.Value, result);
            else if (kvp.Value is JSONDataArray)
            {
              var lst = (JSONDataArray)kvp.Value;
              foreach(var lnode in lst)
              {
                var lmap = lnode as JSONDataMap;
                if (lmap==null)
                  throw new ConfigException(StringConsts.CONFIG_JSON_STRUCTURE_ERROR, new ConfigException("Bad structure: "+sectData.ToJSON()));
                buildSection(kvp.Key, lmap, result);
              }
            }
            else
             result.AddAttributeNode(kvp.Key, kvp.Value);
              }

              return result;
        }