コード例 #1
0
        /// <summary>
        /// Generate treescheme json for a given type.
        /// </summary>
        /// <param name="rootAliasTypeName">Fullname of the type to use as the root of the tree</param>
        /// <param name="fieldSource">Enum to indicator how to find fields on types</param>
        /// <param name="typeIgnorePattern">Optional regex pattern to ignore types</param>
        /// <param name="nodeCommentProvider">Optional provider of node-comments</param>
        /// <param name="logger">Optional logger for diagnostic output</param>
        /// <returns>Json string representing the scheme</returns>
        public static string GenerateScheme(
            string rootAliasTypeName,
            FieldSource fieldSource,
            Regex typeIgnorePattern = null,
            INodeCommentProvider nodeCommentProvider = null,
            Core.ILogger logger = null)
        {
            try
            {
                // Gather all the types.
                var typeCollection = TypeCollection.Create(AppDomain.CurrentDomain.GetAssemblies(), logger);

                // Create mapping context.
                var context = Context.Create(
                    typeCollection,
                    fieldSource,
                    typeIgnorePattern,
                    nodeCommentProvider,
                    logger);

                // Map the tree.
                var tree = TreeMapper.MapTree(context, rootAliasTypeName);

                // Serialize the scheme.
                return(JsonSerializer.ToJson(tree, JsonSerializer.Mode.Pretty));
            }
            catch (Exception e)
            {
                logger?.LogCritical($"Failed to generate scheme: {e.Message.ToDistinctLines()}");
                return(null);
            }
        }
コード例 #2
0
        /// <summary>
        /// Generate treescheme json file for a given type.
        /// </summary>
        /// <param name="rootAliasTypeName">Fullname of the type to use as the root of the tree</param>
        /// <param name="fieldSource">Enum to indicator how to find fields on types</param>
        /// <param name="outputPath">Path to save the output file relative to the Assets directory</param>
        /// <param name="typeIgnorePattern">Optional regex pattern to ignore types</param>
        /// <param name="nodeCommentProvider">Optional provider of node-comments</param>
        /// <param name="logger">Optional logger for diagnostic output</param>
        public static void GenerateSchemeToFile(
            string rootAliasTypeName,
            FieldSource fieldSource,
            string outputPath,
            Regex typeIgnorePattern = null,
            INodeCommentProvider nodeCommentProvider = null,
            Core.ILogger logger = null)
        {
            // Generate the json.
            var json = GenerateScheme(
                rootAliasTypeName, fieldSource, typeIgnorePattern, nodeCommentProvider, logger);

            if (json != null)
            {
                // Write the file.
                try
                {
                    var fullPath  = Path.Combine(UnityEngine.Application.dataPath, outputPath);
                    var outputDir = Path.GetDirectoryName(fullPath);
                    if (!Directory.Exists(outputDir))
                    {
                        logger?.LogDebug($"Creating output directory: '{outputDir}'");
                        Directory.CreateDirectory(outputDir);
                    }

                    File.WriteAllText(fullPath, json);
                    logger?.LogInformation($"Saved scheme: '{outputPath}'");
                }
                catch (Exception e)
                {
                    logger?.LogCritical($"Failed to save file: {e.Message.ToDistinctLines()}");
                }
            }
        }
コード例 #3
0
        public void FieldSourceWithNoStringsHasNoTokens()
        {
            IEnumerable <string> values = null;                             // TODO: Initialize to an appropriate value
            FieldSource <string> target = new FieldSource <string>(values); // TODO: Initialize to an appropriate value

            var result = target.Tokens;

            Verify.That(result).IsNotNull()
            .IsACollectionThat()
            .IsAnInstanceOfType(typeof(IEnumerable <Token>))
            .Count().IsEqualTo(0);
        }
コード例 #4
0
        public void FieldSourceWithSingleStringHasOneToken()
        {
            string value = "Test";             // TODO: Initialize to an appropriate value
            FieldSource <string> target = new FieldSource <string>(value);

            var tokens = target.Tokens.ToList();

            Verify.That(tokens).IsACollectionThat().Count().IsEqualTo(1);

            Token token = tokens.First();

            Verify.That(token.Value).IsAStringThat().IsEqualTo(value);
            Verify.That(token.Offset).IsEqualTo(0);
        }
コード例 #5
0
 internal PipelineFieldAction(PipelineFieldAction template, String name, Regex regex)
     : base(template, name, regex)
 {
     this.toField        = optReplace(regex, name, template.toField);
     this.toVar          = optReplace(regex, name, template.toVar);
     this.fromVar        = optReplace(regex, name, template.fromVar);
     this.fromField      = optReplace(regex, name, template.fromField);
     this.fromValue      = optReplace(regex, name, template.fromValue);
     this.toFieldFromVar = optReplace(regex, name, template.toFieldFromVar);
     this.sep            = template.sep;
     this.fieldFlags     = template.fieldFlags;
     this.fieldSource    = template.fieldSource;
     toFieldReal         = toField == "*" ? null : toField;
 }
コード例 #6
0
        /// <summary>
        /// Create a mapping context.
        /// </summary>
        /// <param name="types">Set of types</param>
        /// <param name="fieldSource">Where to look for fields on a node</param>
        /// <param name="typeIgnorePattern">Optional regex pattern for types to ignore</param>
        /// <param name="nodeCommentProvider">Optional provider for node comments</param>
        /// <param name="logger">Optional logger</param>
        /// <returns>Newly created context</returns>
        public static Context Create(
            ITypeCollection types,
            FieldSource fieldSource,
            Regex typeIgnorePattern = null,
            INodeCommentProvider nodeCommentProvider = null,
            ILogger logger = null)
        {
            if (types == null)
            {
                throw new ArgumentNullException(nameof(types));
            }

            return(new Context(types, fieldSource, typeIgnorePattern, nodeCommentProvider, logger));
        }
コード例 #7
0
        public static Func <ParameterExpression, KeyValuePair <string, object>, Expression> GetFieldFunc(
            FieldSource fieldSource)
        {
            switch (fieldSource)
            {
            case FieldSource.Propety:
                return(GetPropertyExpression);

            case FieldSource.Column:
                return(GetColumnExpression);

            default:
                throw new ArgumentOutOfRangeException(nameof(fieldSource), fieldSource, null);
            }
        }
コード例 #8
0
        public void FieldSourceWithThreeStringsHasThreeTokens()
        {
            string[]             values = new string[] { "One", "Two", "Three" }; // TODO: Initialize to an appropriate value
            FieldSource <string> target = new FieldSource <string>(values);

            var tokens = target.Tokens.ToList();

            Verify.That(tokens).IsACollectionThat().Count().IsEqualTo(3);

            int i = 0;

            foreach (var token in tokens)
            {
                Verify.That(token.Value).IsAStringThat().IsEqualTo(values[i]);
                Verify.That(token.Offset).IsEqualTo(0);
                i++;
            }
        }
コード例 #9
0
        internal Context(
            ITypeCollection types,
            FieldSource fieldSource,
            Regex typeIgnorePattern = null,
            INodeCommentProvider nodeCommentProvider = null,
            ILogger logger = null)
        {
            if (types == null)
            {
                throw new ArgumentNullException(nameof(types));
            }

            this.Types               = types;
            this.FieldSource         = fieldSource;
            this.TypeIgnorePattern   = typeIgnorePattern;
            this.NodeCommentProvider = nodeCommentProvider;
            this.Logger              = logger;
        }
コード例 #10
0
        public override void LoadXML(XmlNode element, FileVersion version)
        {
            try {
                base.LoadXML(element, version);

                LandSign  = ReadElement(element, "LandID");
                LayerSign = ReadElement(element, "LayerID");
                Source    = (FieldSource)Enum.Parse(typeof(FieldSource), ReadElement(element, "Source"));

                if (Source == FieldSource.fsTemplate)
                {
                    LoadTemplate();
                }
            } catch (Exception ex) {
                Logger.Write("FieldEntry.loadXML(): " + ex.Message);
                throw ex;
            }
        }
コード例 #11
0
        public PipelineFieldAction(Pipeline pipeline, XmlNode node)
            : base(pipeline, node)
        {
            fieldSource = FieldSource.Event;
            toVar       = node.ReadStr("@tovar", null);
            fromVar     = node.ReadStr("@fromvar", null);
            fromField   = node.ReadStr("@fromfield", null);
            fromValue   = node.ReadStr("@fromvalue", null);

            int cnt = 0;

            if (fromVar != null)
            {
                cnt++;
                fieldSource = FieldSource.Variable;
            }
            if (fromField != null)
            {
                cnt++;
                fieldSource = FieldSource.Field;
            }
            if (fromValue != null)
            {
                cnt++;
                fieldSource = FieldSource.Value;
            }
            if (cnt > 1)
            {
                throw new BMNodeException(node, "Cannot specify fromvar, fromfield or fromvalue together.");
            }

            toField        = node.ReadStr("@field", null);
            toFieldFromVar = node.ReadStr("@fieldfromvar", null);
            sep            = node.ReadStr("@sep", null);
            fieldFlags     = node.ReadEnum("@flags", sep == null ? FieldFlags.OverWrite : FieldFlags.Append);

            if (toField == null && toVar == null && base.scriptName == null && toFieldFromVar == null)
            {
                throw new BMNodeException(node, "At least one of 'field', 'toFieldFromVar', 'tovar', 'script'-attributes is mandatory.");
            }

            toFieldReal = toField == "*" ? null : toField;
        }
コード例 #12
0
 /// <summary>
 /// Initializes _destination with the field destination
 /// </summary>
 /// <param name="Destination">Field destination of type FieldDestination</param>
 public FieldsCollection(FieldSource Source)
 {
     _Source = Source;
 }
コード例 #13
0
 /// <summary>
 /// Defines when an event is raised.
 /// </summary>
 /// <param name="Source"></param>
 /// <param name="ID"></param>
 private void RaiseAfterAddedEvent(FieldSource Source, string ID)
 {
     if (this.AfterAdded != null)
     {
         this.AfterAdded(Source, ID);
     }
 }
コード例 #14
0
 public static IUpdatable <T> SetValues <T>(this IUpdatable <T> source,
                                            IEnumerable <KeyValuePair <string, object> > values,
                                            FieldSource fieldSource = FieldSource.Propety)
 {
     return(SetValues(source, values, GetFieldFunc(fieldSource)));
 }
コード例 #15
0
 public QuickEntryPopupDialog2(IHtmlInput inputData, string formTitle, InputFormInfo formInfo, int sizeWidth, int sizeHeight, FieldSource fieldSource, string helpTag, Sessions.Session session)
     : this(inputData, formTitle, formInfo, sizeWidth, sizeHeight, fieldSource, helpTag, session, (object)null)
 {
 }
コード例 #16
0
 public static IUpdatable <T> SetValues <T>(this IQueryable <T> source,
                                            IEnumerable <KeyValuePair <string, object> > values,
                                            FieldSource fieldSource = FieldSource.Propety)
 {
     return(source.AsUpdatable().SetValues(values, fieldSource));
 }
コード例 #17
0
ファイル: Fields.cs プロジェクト: SDRC-India/sdrcdevinfo
        /// <summary>
        /// Handles event when item is added to rows and delete this item from column or available
        /// </summary>
        /// <param name="Source">Field source</param>
        /// <param name="ID">Field Id</param>
        void _Rows_AfterAdded(FieldSource Source, string ID)
        {
            Field Field;

            Field = Columns[ID];

            if (Field != null)
            {
                // Remove metadata, if parent column is removed from the collection (Indicator, Area, Source)
                if (Field.FieldID == Indicator.IndicatorName || Field.FieldID == Area.AreaID || Field.FieldID == Area.AreaName || Field.FieldID == IndicatorClassifications.ICName)
                {
                    this.RemoveMetadata(this.Columns, Field);
                }
                this._Columns.Remove(Field);
                this.RaiseUpdateColumnAggangementEvent();
            }
            Field = null;
            Field = Available[ID];
            if (Field != null)
            {
                this._Available.Remove(Field);
            }
            this.RaiseChangeSortEvent();
            this.RaiseChangeAggregateFieldEvent(ID, true);
        }
コード例 #18
0
ファイル: Fields.cs プロジェクト: SDRC-India/sdrcdevinfo
        /// <summary>
        /// Handles event when item is added to column and delete this item from rows or available
        /// </summary>
        /// <param name="Source">Field source</param>
        /// <param name="ID">Field Id</param>
        void _Columns_AfterAdded(FieldSource Source, string ID)
        {
            this.RaiseUpdateColumnAggangementEvent();
            Field Field;
            Field = Rows[ID];
            if (Field != null)
            {
                this.RaiseChangeAggregateFieldEvent(ID, false);
                // Remove metadata, if parent column is removed from the collection (Indicator, Area, Source)
                if (Field.FieldID == Indicator.IndicatorName || Field.FieldID == Area.AreaID || Field.FieldID == Area.AreaName || Field.FieldID == IndicatorClassifications.ICName)
                {
                    this.RemoveMetadata(this.Rows, Field);
                }
                this._Rows.Remove(Field);
            }

            // -- Remove the field from the sort collection
            Field = this.Sort[ID];
            if (Field != null)
            {
                this._Sort.Remove(Field);
            }

            // -- Update the UI in step 4
            this.RaiseChangeSortEvent();

            Field = null;
            Field = Available[ID];
            if (Field != null)
            {
                this._Available.Remove(Field);
            }
        }
コード例 #19
0
		/// --------------------------------------------------------------------------------
		/// <summary>
		/// Add a field to the MetaDataCache.
		/// </summary>
		/// <param name="className">Name of the class.</param>
		/// <param name="flid">The flid.</param>
		/// <param name="fieldName">Name of the field.</param>
		/// <param name="fieldLabel">The field label.</param>
		/// <param name="fieldHelp">The field help.</param>
		/// <param name="fieldXml">The field XML.</param>
		/// <param name="fieldSignature">The field signature.</param>
		/// <param name="type">The type.</param>
		/// <param name="fsSource">The fs source.</param>
		/// <param name="fieldListRoot">The field list root.</param>
		/// <param name="fieldWs">The field ws.</param>
		/// --------------------------------------------------------------------------------
		private void AddField(string className, int flid, string fieldName, string fieldLabel,
			string fieldHelp, string fieldXml, string fieldSignature, CellarPropertyType type,
			FieldSource fsSource, Guid fieldListRoot, int fieldWs)
		{
			// Will throw if class is not in one or the other Dictionaries.
			var clid = m_nameToClid[className];
			var mcr = m_metaClassRecords[clid];
			var mfr = new MetaFieldRec
						{
							m_flid = flid,
							m_fieldLabel = fieldLabel,
							m_fieldHelp = fieldHelp,
							m_fieldXml = fieldXml,
							m_fieldListRoot = fieldListRoot,
							m_fieldWs = fieldWs,
							m_sig = null,
							m_fieldSource = fsSource
						};
			switch (type)
			{
				default:
					break;
				case CellarPropertyType.OwningAtomic: // Fall through
				case CellarPropertyType.OwningCollection: // Fall through
				case CellarPropertyType.OwningSequence: // Fall through
				case CellarPropertyType.ReferenceAtomic: // Fall through
				case CellarPropertyType.ReferenceCollection: // Fall through
				case CellarPropertyType.ReferenceSequence:
					mfr.m_sig = fieldSignature;
					// It may not be present yet when the whole MDC is being initialized via 'Init',
					// or the Constructor, as the case may be.
					// Only mess with setting this after intitialization of the main model.
					// Once all those model classes are in, a client can take his lumps
					// if this throws an exception.
					if (m_initialized)
					{
						if (string.IsNullOrEmpty(fieldSignature))
							throw new KeyNotFoundException("'bstrFieldSignature' is a null or empty key.");
						// Note that m_fieldSource must be set before calling this.
						SetDestClass(mfr, m_nameToClid[fieldSignature]);
					}
					break;
			}
			mfr.m_fieldType = type;
			mfr.m_fieldName = fieldName;
			mfr.m_ownClsid = clid;
			mcr.AddField(mfr);
			m_metaFieldRecords[flid] = mfr;
			m_nameToFlid[MakeFlidKey(clid, fieldName)] = flid;
		}
コード例 #20
0
        /// <summary>
        /// Find fields on a given type.
        /// </summary>
        /// <param name="type">Type to find fields on (class or struct)</param>
        /// <param name="source">Source where to look for fields on the given type</param>
        /// <returns>Collection of fields (identifier and type)</returns>
        public static IEnumerable <(string identifier, Type type)> FindFields(
            this Type type,
            FieldSource source)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (type.IsEnum || type.IsPrimitive)
            {
                throw new ArgumentException("Type has to be a class or a struct", nameof(type));
            }

            switch (source)
            {
            case FieldSource.PublicProperties:
                return(FindProperties(includeNonPublic: false));

            case FieldSource.Properties:
                return(FindProperties(includeNonPublic: true));

            case FieldSource.PublicConstructorParameters:
                return(FindConstructorParameters(includeNonPublic: false));

            case FieldSource.ConstructorParameters:
                return(FindConstructorParameters(includeNonPublic: true));

            default:
                throw new InvalidOperationException($"Unknown field-source: '{source}'");
            }

            IEnumerable <(string, Type)> FindConstructorParameters(bool includeNonPublic)
            {
                return(FindConstructor(includeNonPublic)?.
                       GetParameters().Select(p => (p.Name, p.ParameterType)) ??
                       Array.Empty <(string, Type)>());
            }

            ConstructorInfo FindConstructor(bool includeNonPublic)
            {
                var bindingFlags = GetBindingFlags(includeNonPublic);

                // Return the constructor with the most parameters.
                return(type.GetConstructors(bindingFlags).
                       OrderByDescending(ci => ci.GetParameters().Length).
                       FirstOrDefault());
            }

            IEnumerable <(string, Type)> FindProperties(bool includeNonPublic)
            {
                var bindingFlags = GetBindingFlags(includeNonPublic);

                return(type.GetProperties(bindingFlags).
                       Where(pi => pi.CanRead && pi.CanWrite).
                       Select(pi => (pi.Name, pi.PropertyType)));
            }

            BindingFlags GetBindingFlags(bool includeNonPublic) =>
            includeNonPublic ?
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance :
            BindingFlags.Public | BindingFlags.Instance;
        }
コード例 #21
0
        public QuickEntryPopupDialog2(IHtmlInput inputData, string formTitle, InputFormInfo formInfo, int sizeWidth, int sizeHeight, FieldSource fieldSource, string helpTag, Sessions.Session session, object property)
        {
            InitializeComponent();
            this.Name = formTitle;
            this.Text = formTitle.Replace("pop", "");
            this.Size = new Size(sizeWidth, sizeHeight);
            LoanScreen Screen = new LoanScreen(Session.DefaultInstance);

            this.Controls.Add(Screen);
            Screen.LoadForm(formInfo);
        }
コード例 #22
0
 public static IQueryable <T> FilterByValues <T>(this IQueryable <T> source,
                                                 IEnumerable <KeyValuePair <string, object> > values,
                                                 FieldSource fieldSource = FieldSource.Propety)
 {
     return(FilterByValues(source, values, GetFieldFunc(fieldSource)));
 }
コード例 #23
0
        public void FieldsAreFound(Type type, FieldSource source, FieldCollection expectedFields)
        {
            var fields = type.FindFields(source);

            Assert.Equal(expectedFields, fields);
        }
コード例 #24
0
        /// <summary>
        /// Run the generator tool.
        /// </summary>
        /// <param name="assemblyFile">Assembly to generate the scheme for</param>
        /// <param name="dependencyDirectories">Optional paths to look for dependencies</param>
        /// <param name="rootType">Root type of the tree</param>
        /// <param name="fieldSource">Source to find fields</param>
        /// <param name="typeIgnorePattern">Optional regex pattern for ignoring types</param>
        /// <param name="outputPath">Path where to generate the output scheme to</param>
        /// <returns>Exit code</returns>
        public int Run(
            string assemblyFile,
            IEnumerable <string> dependencyDirectories,
            string rootType,
            FieldSource fieldSource,
            Regex typeIgnorePattern,
            string outputPath)
        {
            if (assemblyFile == null)
            {
                throw new ArgumentNullException(nameof(assemblyFile));
            }
            if (dependencyDirectories == null)
            {
                throw new ArgumentNullException(nameof(dependencyDirectories));
            }
            if (rootType == null)
            {
                throw new ArgumentNullException(nameof(rootType));
            }

            // Load types from given assembly.
            var typeCollection = TypeLoader.TryLoad(assemblyFile, dependencyDirectories, this.logger);

            if (typeCollection == null)
            {
                return(1);
            }

            // Verify that root-type can be found in those types.
            if (!typeCollection.TryGetType(rootType, out _))
            {
                this.logger.LogCritical($"Unable to find root-type: '{rootType}'");
                return(1);
            }

            // Load doc-comment file for providing node comments.
            XmlNodeCommentProvider nodeCommentProvider = null;
            var xmlDocFilePath = Path.ChangeExtension(assemblyFile, "xml");

            if (File.Exists(xmlDocFilePath))
            {
                this.logger.LogInformation($"Using doc-comment file: '{xmlDocFilePath}'");
                using (var stream = new FileStream(xmlDocFilePath, FileMode.Open, FileAccess.Read))
                {
                    if (!XmlNodeCommentProvider.TryParse(stream, out nodeCommentProvider))
                    {
                        this.logger?.LogWarning($"Failed to parse doc-comment file: '{xmlDocFilePath}'");
                    }
                }
            }

            // Create context object containing all the settings for the mapping.
            var context = Context.Create(
                typeCollection,
                fieldSource,
                typeIgnorePattern,
                nodeCommentProvider,
                this.logger.IsEnabled(LogLevel.Debug) ? this.logger : null);

            // Map the tree.
            TreeDefinition tree = null;

            try
            {
                tree = TreeMapper.MapTree(context, rootType);

                this.logger.LogInformation(
                    $"Mapped tree (aliases: '{tree.Aliases.Length}', enums: '{tree.Enums.Length}', nodes: '{tree.Nodes.Length}')");
            }
            catch (Core.Mapping.Exceptions.MappingFailureException e)
            {
                this.logger.LogCritical($"Failed to map: '{e.InnerException.Message}'");
                return(1);
            }

            // Save the result.
            try
            {
                Directory.GetParent(outputPath).Create();
                using (var stream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                {
                    JsonSerializer.WriteJson(tree, JsonSerializer.Mode.Pretty, stream);
                }

                this.logger.LogInformation($"Written scheme to: '{outputPath}'");
            }
            catch (Exception e)
            {
                this.logger.LogCritical($"Failed to save to '{outputPath}': {e.Message}");
                return(1);
            }

            return(0);
        }