Exemple #1
0
      /// <summary>
      /// Takes optional args[] and root configuration. If configuration is null then
      ///  application is configured from a file co-located with entry-point assembly and
      ///   called the same name as assembly with '.config' extension, unless args are specified and "/config file"
      ///   switch is used in which case 'file' has to be locatable and readable.
      /// </summary>
      public BaseApplication(string[] args, ConfigSectionNode rootConfig)
      {
        lock(typeof(BaseApplication))
        {
          if (s_Instance != null) throw new WFormsException(StringConsts.APP_INSTANCE_ALREADY_CREATED_ERROR);

          try
          {  
            Configuration argsConfig;
            if (args != null)
              argsConfig = new CommandArgsConfiguration(args);
            else
              argsConfig = new MemoryConfiguration();

            m_CommandArgs = argsConfig.Root;

            m_ConfigRoot = rootConfig ?? GetConfiguration().Root;

            InitApplication();
        
            s_Instance = this;

          }
          catch
          {
              Destructor();
              throw;
          }

        }
      }
Exemple #2
0
        /// <summary>
        /// Initializes local installation, tries to read local manifest from rootPath or localManifestDir if it is !=null
        /// </summary>
        public LocalInstallation(string rootPath, string localManifestDir = null)
        {
            if (rootPath.IsNullOrWhiteSpace())
              throw new NFXIOException(StringConsts.ARGUMENT_ERROR + GetType().Name + ".ctor(rootPath==null|empty)");

            var parent = Directory.GetParent(rootPath);
            if (!parent.Exists)
              throw new NFXIOException(StringConsts.LOCAL_INSTALL_ROOT_PATH_NOT_FOUND_ERROR.Args(parent.FullName));

            m_RootPath = rootPath;

            var manifestDir = localManifestDir.IsNotNullOrWhiteSpace() ? localManifestDir : m_RootPath;

            if (Directory.Exists(manifestDir))
            {
              var fn = Path.Combine(manifestDir, ManifestUtils.MANIFEST_FILE_NAME);
              if (File.Exists(fn))
              try
              {
             m_Packages = new LaconicConfiguration(fn).Root;
              }
              catch(Exception error)
              {
            throw new NFXIOException(StringConsts.LOCAL_INSTALL_LOCAL_MANIFEST_READ_ERROR.Args(fn, error.ToMessageWithType()), error);
              }
            }

            if (m_Packages==null)
            {
              var cfg = new LaconicConfiguration();
              cfg.Create(ManifestUtils.CONFIG_PACKAGES_SECTION);
              m_Packages = cfg.Root;
            }
        }
Exemple #3
0
        /// <summary>
        /// Initializaes check list from assembly names separated by semicolons.
        /// Optional path will be prepended to every assembly name
        /// </summary>
        public CheckList(string path, string checkAssemblies, ConfigSectionNode config)
        {
          path = path ?? string.Empty;

          var anames = checkAssemblies.Split(';');
          
          var al = new List<Assembly>();
          foreach(var aname in anames)
            al.Add(Assembly.LoadFrom(Path.Combine(path, aname)));

          load(al, config);
        }
Exemple #4
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);
                }
        public TestApplication(ConfigSectionNode cfgRoot = null)
        {
            this.ConfigRoot = cfgRoot;

            Active = true;
            StartTime = DateTime.Now;
            Log = NOPLog.Instance;
            Instrumentation = NOPInstrumentation.Instance;
            Throttling = NOPThrottling.Instance;
            DataStore = NOPDataStore.Instance;
            ObjectStore = NOPObjectStore.Instance;
            Glue = NOPGlue.Instance;
            SecurityManager = NOPSecurityManager.Instance;
            TimeSource = NFX.Time.DefaultTimeSource.Instance;
            TimeLocation = new Time.TimeLocation();
            EventTimer = NFX.Time.NOPEventTimer.Instance;

            ApplicationModel.ExecutionContext.__SetApplicationLevelContext(this, null, null, NOPSession.Instance);
        }
Exemple #6
0
 private void doBLOCK(Stopwatch sw, ConfigSectionNode blockStatement, ConfigSectionNode target)
 {
     initStatement(blockStatement);
     doNode(sw, blockStatement, target);
 }
Exemple #7
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);
          }
      
      } 
Exemple #8
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;
        }
Exemple #9
0
 private void initStatement(ConfigSectionNode statement)
 {
     statement.m_Script_Statement = true;
 }
Exemple #10
0
        private void doCALL(Stopwatch sw, ConfigSectionNode callStatement, ConfigSectionNode target)
        {
            initStatement(callStatement);

                                var path = callStatement.Value;
                                var callTarget = callStatement.NavigateSection(path);
                                if (!callTarget.Exists)
                                    throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_CALL_TARGET_PATH_ERROR.Args(callStatement.RootPath, path) );

                                doNode(sw, callTarget, target);
        }
Exemple #11
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;
        }
Exemple #12
0
        private void processIncludes(ConfigSectionNode node, HashSet<string> alreadyIncluded)
        {
            foreach(var includeNode in node.Children.Where(cn=>cn.IsSameName(CONFIG_INCLUDE_SECTION)))
                {
                    var include = includeNode.Value;

                    if (!File.Exists(include))
                    {
                        foreach(var path in m_IncludePaths)
                        {
                            var fn = Path.Combine(path, include);
                            if (File.Exists(fn))
                            {
                                include = fn;
                                break;
                            }
                        }
                    }

                    if (!File.Exists(include))
                     throw new SchemaException(StringConsts.SCHEMA_INCLUDE_FILE_DOSNT_EXIST_ERROR + include);

                    if (alreadyIncluded.Contains(include))
                     throw new SchemaException(StringConsts.SCHEMA_INCLUDE_FILE_REFERENCED_MORE_THAN_ONCE_ERROR + include);

                    alreadyIncluded.Add( include );

                    var included = Configuration.ProviderLoadFromFile( include );
                    processIncludes(included.Root, alreadyIncluded);

                    includeNode.Configuration.Include(includeNode, included.Root);
                }
        }
            public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
            {
                var data = "score=110 description='Cars built in Japan' origin{_override=stop country=jap} z=1".AsLaconicConfig();

                dataRoot.MergeAttributes(data);
                dataRoot.MergeSections(data);
                return(dataRoot);
            }
            public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
            {
                var data = "score=40 description='Luxury item, but unreliable'  origin{country=XYZYZ/*this will never take effect*/}".AsLaconicConfig();

                dataRoot.MergeAttributes(data);
                dataRoot.MergeSections(data);
                return(dataRoot);
            }
            public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
            {
                var data = "score=90 description='Very usable and decent quality' a=-900".AsLaconicConfig();

                dataRoot.MergeAttributes(data);
                dataRoot.MergeSections(data);
                return(dataRoot);
            }
            public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
            {
                var data = "a=123 b=789 score=100 description='Generic car' origin{_override=all country=world} z=0".AsLaconicConfig();

                dataRoot.MergeAttributes(data);
                dataRoot.MergeSections(data);
                return(dataRoot);
            }
 private Amount Convert(ConfigSectionNode config, string rateTable, Amount amount, string currencyISO)
 {
     var market = new ConfigBasedCurrencyMarket(config);
     return market.ConvertCurrency(rateTable, amount, currencyISO);
 }
 private Amount Convert(ConfigSectionNode config, Amount amount, string currencyISO)
 {
     return Convert(config, NO_RATE_TABLE, amount, currencyISO);
 }
Exemple #19
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);
                    }
                }
            }
        }
Exemple #20
0
        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;
            }
        }
Exemple #21
0
        protected virtual void DoELSE(Stopwatch sw, ConfigSectionNode elseStatement, ConfigSectionNode priorStatement, ConfigSectionNode target)
        {
            if (priorStatement == null || !priorStatement.IsSameName(DEFAULT_KEYWORD_IF))
            {
                throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_ELSE_NOT_AFTER_IF_ERROR.Args(elseStatement.RootPath));
            }

            InitStatement(elseStatement);

            var condition = priorStatement.m_Script_Bool_Condition_Result;

            if (condition)
            {
                return;
            }

            DoNode(sw, elseStatement, target);
        }
            public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
            {
                var data = "description='Honda motors'".AsLaconicConfig();

                dataRoot.MergeAttributes(data);
                dataRoot.MergeSections(data);
                return(dataRoot);
            }
Exemple #23
0
 /// <summary>
 /// Takes optional application args[] and root configuration.
 /// The args are parsed into CommandArgsConfiguration. If configuration is null then
 /// application is configured from a file co-located with entry-point assembly and
 ///  called the same name as assembly with '.config' extension, unless args are specified and "/config file"
 ///   switch is used in which case 'file' has to be locatable and readable.
 /// </summary>
 public ServiceBaseApplication(string[] args, ConfigSectionNode rootConfig)
     : this(false, args, rootConfig)
 {
 }
Exemple #24
0
 private void load(IEnumerable<Assembly> assemblies, ConfigSectionNode config)
 {
   foreach(var assembly in assemblies)
     foreach(var type in assembly.GetExportedTypes().Where(t=>t.IsSubclassOf(typeof(BaseCheck))))
     {
       var check = Activator.CreateInstance(type) as BaseCheck;
      
       if (config!=null)
        check.Configure(config);
      
       m_Checks.Add(check);
     }
 }
Exemple #25
0
 private void cloneAttributes(ConfigSectionNode from, ConfigSectionNode to, bool evaluate = false)
 {
     if (evaluate)
                            foreach(var atr in from.Attributes) to.AddAttributeNode(atr.Name, atr.Value);
                         else
                            foreach(var atr in from.Attributes) to.AddAttributeNode(atr.Name, atr.VerbatimValue);
 }
 public void SetUp()
 {
     m_Config = LACONF.AsLaconicConfig(handling: ConvertErrorHandling.Throw);
     m_App    = new ServiceBaseApplication(null, m_Config);
 }
Exemple #27
0
 public SkyApplication(SystemApplicationType sysAppType, string[] args, ConfigSectionNode rootConfig)
     : this(sysAppType, false, args, rootConfig)
 {
 }
Exemple #28
0
 /// <summary>
 /// Initializaes check list from assemblies 
 /// </summary>
 public CheckList(IEnumerable<Assembly> checkAssemblies, ConfigSectionNode config)
 {
   load(checkAssemblies, config);
 }
Exemple #29
0
 public void SetUp()
 {
     m_RootCfg = initConf();
 }
        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);
        }
Exemple #31
0
 protected CommonApplicationLogic(bool allowNesting, Configuration cmdLineArgs, ConfigSectionNode rootConfig)
 {
     m_AllowNesting = allowNesting;
     m_CommandArgs  = (cmdLineArgs ?? new MemoryConfiguration()).Root;
     m_ConfigRoot   = rootConfig ?? GetConfiguration().Root;
 }
Exemple #32
0
 /// <summary>
 /// Initializaes check list from assemblies
 /// </summary>
 public CheckList(IEnumerable <Assembly> checkAssemblies, ConfigSectionNode config)
 {
     load(checkAssemblies, config);
 }
Exemple #33
0
        private void includeCommonConfig(ConfigSectionNode levelRoot)
        {
            var placeholder = levelRoot.AddChildNode(Guid.NewGuid().ToString());

            placeholder.Configuration.Include(placeholder, m_CommonLevelConfig);
        }
Exemple #34
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));

                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
                {
                    field(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);
        }
Exemple #35
0
 private void initStatement(ConfigSectionNode statement)
 {
     statement.m_Script_Statement = true;
 }
Exemple #36
0
        private void field(Schema.FieldDef def, IMetadataGenerator context, ConfigSectionNode data, TypedDoc doc)
        {
            var fname = def.GetBackendNameForTarget(context.DataTargetName, 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);

            if (def.Type == typeof(string))
            {
                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, context.DataTargetName, null);
                if (lookup != null)
                {
                    lookup.ForEach(item => nvlist.Value.AddAttributeNode(item.Key, item.Value));
                }
            }
        }
Exemple #37
0
 protected virtual void DoBLOCK(Stopwatch sw, ConfigSectionNode blockStatement, ConfigSectionNode target)
 {
     InitStatement(blockStatement);
     DoNode(sw, blockStatement, target);
 }
        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);
        }
Exemple #39
0
 protected virtual void InitStatement(ConfigSectionNode statement)
 {
     statement.m_Script_Statement = true;
 }
        public override ConfigSectionNode ProvideMetadata(MemberInfo member, object instance, IMetadataGenerator context, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules = null)
        {
            if (member is Type tController && instance is ApiDocGenerator.ControllerContext apictx)
            {
                var apiAttr = tController.GetCustomAttribute <ApiControllerDocAttribute>();
                if (apiAttr != null)
                {
                    return(describe(tController, instance, apictx, dataRoot, overrideRules));
                }
            }

            return(null);
        }
        // -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();
        }
        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);
        }
Exemple #43
0
        private void buildDocNode(XmlDocument doc, XmlNode xnode, ConfigSectionNode node)
        {
            XmlNode xnew = doc.CreateElement(node.Name);

              if (xnode != null)
            xnode.AppendChild(xnew);
              else
            doc.AppendChild(xnew);

              foreach (ConfigAttrNode anode in node.Attributes)
              {
            XmlNode xattr = doc.CreateNode(XmlNodeType.Attribute, anode.Name, string.Empty);
            xattr.Value = anode.Value;
            xnew.Attributes.SetNamedItem(xattr);
              }

              if (node.HasChildren)
              {
            foreach (ConfigSectionNode cnode in node.Children)
              buildDocNode(doc, xnew, cnode);
              }
              else
              {
            xnew.AppendChild(doc.CreateTextNode(node.Value));
              }
        }
Exemple #44
0
        private void doIF(Stopwatch sw, ConfigSectionNode ifStatement, ConfigSectionNode target)
        {
            initStatement(ifStatement);

                                var condition = evaluateBooleanConditionExpression(ifStatement);
                                if (!condition) return;

                                doNode(sw, ifStatement, target);
        }
Exemple #45
0
        public void Configure(IConfigSectionNode node)
        {
            var appRoot = node.NavigateSection("/" + ErlConsts.ERLANG_CONFIG_SECTION);

              if (appRoot == null)
            throw new ErlException(
              StringConsts.CONFIGURATION_NAVIGATION_SECTION_REQUIRED_ERROR,
              ErlConsts.ERLANG_CONFIG_SECTION);

              // Configure global node variables

              ErlAbstractNode.s_DefaultCookie = new ErlAtom(
            appRoot.AttrByName(ErlConsts.ERLANG_COOKIE_ATTR)
            .ValueAsString(ErlAbstractNode.s_DefaultCookie.Value));

              ErlAbstractNode.s_UseShortNames =
            appRoot.AttrByName(ErlConsts.ERLANG_SHORT_NAME_ATTR)
            .ValueAsBool(ErlAbstractNode.s_UseShortNames);

              ErlAbstractConnection.ConnectTimeout =
            appRoot.AttrByName(ErlConsts.ERLANG_CONN_TIMEOUT_ATTR)
            .ValueAsInt(ErlAbstractConnection.ConnectTimeout);

              // Configure local node and remote connections

              var cfg = new MemoryConfiguration();
              cfg.CreateFromNode(appRoot);

              var root  = cfg.Root;
              var nodes = root.Children
                      .Where(n => n.Name.EqualsIgnoreCase(ErlConsts.ERLANG_NODE_SECTION));

              var localNodes = nodes.Where(n => n.AttrByName(ErlConsts.CONFIG_IS_LOCAL_ATTR).ValueAsBool()).ToArray();
              if (localNodes.Length != 1)
            throw new ErlException(StringConsts.ERL_CONFIG_SINGLE_NODE_ERROR, localNodes.Length);

              var localNode = localNodes[0];

              // Create and configure local node

              s_Node = new ErlLocalNode(localNode.Value, localNode);

              // Configure connections to all remote nodes

              //m_AllNodes = nodes.Where(n => !n.AttrByName(ErlConsts.CONFIG_IS_LOCAL_ATTR).ValueAsBool());
              m_AllNodes = root;
        }
Exemple #46
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;
                }
        }
Exemple #47
0
 private void doBLOCK(Stopwatch sw, ConfigSectionNode blockStatement, ConfigSectionNode target)
 {
     initStatement(blockStatement);
                         doNode(sw, blockStatement, target);
 }
Exemple #48
0
 private string evaluateAnyExpression(ConfigSectionNode exprContainer, string expression)
 {
     try
                         {
                             var evl = new Evaluator( expression );
                             return evl.Evaluate();
                         }
                         catch(Exception error)
                         {
                             throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_EXPRESSION_EVAL_ERROR.Args( expression,
                                                                                                                     exprContainer.RootPath,
                                                                                                                     error.ToMessageWithType()),
                                                                                                                     error);
                         }
 }
Exemple #49
0
        private void doELSE(Stopwatch sw, ConfigSectionNode elseStatement, ConfigSectionNode priorStatement, ConfigSectionNode target)
        {
            if (priorStatement==null || !priorStatement.IsSameName(DEFAULT_KEYWORD_IF))
                                    throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_ELSE_NOT_AFTER_IF_ERROR.Args(elseStatement.RootPath));

                                initStatement(elseStatement);

                                var condition =  priorStatement.m_Script_Bool_Condition_Result;
                                if (condition) return;

                                doNode(sw, elseStatement, target);
        }
Exemple #50
0
 /// <summary>
 /// Takes optional application args[] and root configuration.
 /// The args are parsed into CommandArgsConfiguration. If configuration is null then
 /// application is configured from a file co-located with entry-point assembly and
 ///  called the same name as assembly with '.config' extension, unless args are specified and "/config file"
 ///   switch is used in which case 'file' has to be locatable and readable.
 /// Pass allowNesting=true to nest other app container instances
 /// </summary>
 public ServiceBaseApplication(bool allowNesting, string[] args, ConfigSectionNode rootConfig)
     : this(allowNesting, args == null ? null : new CommandArgsConfiguration(args), rootConfig)
 {
 }
Exemple #51
0
        private void doLOOP(Stopwatch sw, ConfigSectionNode loopStatement, ConfigSectionNode target)
        {
            initStatement(loopStatement);

                                while(true)
                                {
                                    var condition = evaluateBooleanConditionExpression(loopStatement);
                                    if (!condition) break;

                                    doNode(sw, loopStatement, target);
                                }
        }
Exemple #52
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);
        }
Exemple #53
0
        private void doSET(Stopwatch sw, ConfigSectionNode setStatement)
        {
            initStatement(setStatement);

                                var path = setStatement.AttrByName("path").Value ?? StringConsts.NULL_STRING;
                                var to =  setStatement.AttrByName("to").Value;

                                to = evaluateAnyExpression(setStatement, to);

                                var target = setStatement.Navigate(path);
                                if (!target.Exists)
                                    throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_SET_PATH_ERROR.Args(setStatement.RootPath, path) );

                                target.Value = to;
        }
Exemple #54
0
 /// <summary>
 /// Tries to convert object to laconic config content and parse it. This is a shortcut to ObjectValueConversion.AsLaconicConfig(object)
 /// </summary>
 public static ConfigSectionNode AsLaconicConfig(this string val,
                                                 ConfigSectionNode dflt = null,
                                                 string wrapRootName    = "azos",
                                                 Azos.Data.ConvertErrorHandling handling = Azos.Data.ConvertErrorHandling.ReturnDefault)
 => Azos.Data.ObjectValueConversion.AsLaconicConfig(val, dflt, wrapRootName, handling);
Exemple #55
0
        private bool evaluateBooleanConditionExpression(ConfigSectionNode exprContainer)
        {
            string expression = CoreConsts.UNKNOWN;
                                try
                                {
                                    expression = exprContainer.Value;
                                    var evl = new Evaluator( expression );
                                    var evlResult = evl.Evaluate();

                                    var condition = evlResult=="1" ||
                                                    evlResult.Equals("yes", StringComparison.InvariantCultureIgnoreCase) ||
                                                    evlResult.Equals("true", StringComparison.InvariantCultureIgnoreCase) ||
                                                    evlResult.Equals("t", StringComparison.InvariantCultureIgnoreCase);

                                    exprContainer.m_Script_Bool_Condition_Result = condition;
                                    return condition;
                                }
                                catch(Exception error)
                                {
                                    throw new ConfigException(StringConsts.CONFIGURATION_SCRIPT_EXPRESSION_EVAL_ERROR.Args( expression,
                                                                                                                            exprContainer.RootPath,
                                                                                                                            error.ToMessageWithType()),
                                                                                                                            error);
                                }
        }
Exemple #56
0
 /// <summary>
 /// Takes optional application args[] and root configuration.
 /// The args are parsed into CommandArgsConfiguration. If configuration is null then
 /// application is configured from a file co-located with entry-point assembly and
 ///  called the same name as assembly with '.config' extension, unless args are specified and "/config file"
 ///   switch is used in which case 'file' has to be locatable and readable.
 /// </summary>
 public AzosApplication(string[] cmdArgs, ConfigSectionNode rootConfig = null)
     : this(false, cmdArgs, rootConfig)
 {
 }
Exemple #57
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);
             }
               }
        }
Exemple #58
0
 /// <summary>
 /// Takes optional application args[] and root configuration.
 /// The args are parsed into CommandArgsConfiguration.
 /// </summary>
 public ServiceBaseApplication(string[] args, ConfigSectionNode rootConfig)
     : this(null, args == null ? null : new CommandArgsConfiguration(args), rootConfig)
 {
 }
Exemple #59
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);
      }
Exemple #60
0
 /// <summary>
 /// The base class does not implement this method. Override to persist row fields into config node
 /// </summary>
 public virtual void PersistConfiguration(ConfigSectionNode node)
 {
     throw new NotImplementedException();
 }