예제 #1
0
        public override object Parse(string toParse, Type typeToParse, ITypeParserContainer parserContainer)
        {
            object _returnVal;

            if (!_parseEnumAsArray && typeToParse.GetCustomAttribute <FlagsAttribute>() != null)
            {
                _parseEnumAsArray = true;
                Type        _enumArrayType = typeToParse.MakeArrayType();
                ITypeParser _arrayParser   = parserContainer.GetParser(_enumArrayType);
                Array       _enumArray     = _arrayParser.Parse(toParse, _enumArrayType, parserContainer) as Array;
                int         _totalVal      = 0;
                int         _iter          = 0;

                foreach (object enVal in _enumArray)
                {
                    if (_iter == 0)
                    {
                        _totalVal = (int)enVal;
                    }
                    else
                    {
                        _totalVal = _totalVal | (int)enVal;
                    }
                    _iter++;
                }
                _returnVal        = _totalVal;
                _parseEnumAsArray = false;
            }
            else
            {
                _returnVal = Enum.Parse(typeToParse, toParse, true);
            }
            return(_returnVal);
        }
예제 #2
0
        private void MapImpl(Type targetWorkItemType, IWorkItem sourceWorkItem, TypeAccessor accessor, object targetWorkItem)
        {
#if DEBUG
            Trace.TraceInformation("{0}: Mapping {1}", GetType().Name, sourceWorkItem.Id);
#endif

            foreach (var property in PropertiesOnWorkItemCache(_inspector, sourceWorkItem, targetWorkItemType, typeof(FieldDefinitionAttribute)))
            {
                var a = PropertyInfoFieldCache(_inspector, property);
                if (a == null)
                {
                    continue;
                }

                var fieldName = a.FieldName;
                var convert   = a.RequireConversion;

                try
                {
                    if (convert)
                    {
                        var value = _typeParser.Parse(property.PropertyType, sourceWorkItem[fieldName]);
                        accessor[targetWorkItem, property.Name] = value;
                    }
                    else
                    {
                        accessor[targetWorkItem, property.Name] = sourceWorkItem[fieldName];
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        Trace.TraceWarning(
                            "Could not convert value of field '{0}' ({1}) to type {2}",
                            fieldName,
                            sourceWorkItem[fieldName].GetType().Name,
                            property.PropertyType.Name);
                    }
                    catch (Exception)
                    {
                    }

                    try
                    {
                        Trace.TraceWarning(
                            "Could not map field '{0}' from type '{1}' to type '{2}'. {3}",
                            fieldName,
                            sourceWorkItem.Type.Name,
                            targetWorkItemType.Name,
                            e.Message);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        public async Task <Result> InvokeAsync(TInput context, CancellationToken cancellationToken)
        {
            if (parser.Parse(context).TryGetValue(out var value))
            {
                return(await command.InvokeAsync(value, cancellationToken).ConfigureAwait(false));
            }

            return(Result.None);
        }
예제 #4
0
        public void CreateDocumentation(string outputDirectory, List <Type> typesInNamespaces, XDocument assemblyDocumentation = null)
        {
            List <ContractDescription> contractDescriptions = m_typePaser.Parse(typesInNamespaces, assemblyDocumentation);

            foreach (ContractDescription contractDescription in contractDescriptions)
            {
                m_documentationWriter.WriteDocumenation(contractDescription, outputDirectory);
            }
        }
예제 #5
0
        private object ParseElement(string toParse, Type type, ITypeParserContainer parserContainer)
        {
            ITypeParser _parser = parserContainer.GetParser(type);

            if (_parser == null)
            {
                throw new Exception($"Parsing type '{type.Name}' not handled");
            }
            return(_parser.Parse(toParse, type, parserContainer));
        }
예제 #6
0
        public void CreateDocumentation(string outputDirectory, List <Type> typesInNamespaces, XDocument assemblyDocumentation = null)
        {
            List <ServiceDescription> contractDescriptions = m_TypeParser.Parse(typesInNamespaces, assemblyDocumentation);

            foreach (ServiceDescription contractDescription in contractDescriptions)
            {
                m_DocumentationWriter.WriteDocumenation(contractDescription, outputDirectory);

                m_ContractDocumentationProcesor.CreateDocumentation(outputDirectory, contractDescription.TypesServiceDependsOn, assemblyDocumentation);
            }
        }
예제 #7
0
        private bool TryConvert(Type from, string value, out object parsed)
        {
            parsed = null;
            ITypeParser parser = Parser.GetParserForType(from);

            if (parser == null)
            {
                return(false);
            }
            parsed = parser.Parse(value);
            return(parsed != null);
        }
예제 #8
0
        public async Task <Result> InvokeAsync(TInput context, CancellationToken cancellationToken)
        {
            if (parser.Parse(context).TryGetValue(out var option))
            {
                if (option.TryGetValue(out var value))
                {
                    return(await command.InvokeAsync(value, cancellationToken));
                }

                return(Result.None);
            }

            return(Result.Aborted);
        }
예제 #9
0
        /// <summary>
        /// Generates the data table row collection.
        /// </summary>
        /// <param name="table">The data table.</param>
        /// <param name="className">Name of the class.</param>
        /// <param name="rowInfos">The list of DataTableRow.</param>
        /// <returns>The data collection of data table row.</returns>
        private static List <DataTableRow> GenerateDataTableRowCollection(DataTable table, string namespaceString, string className, List <DataTableRowInfo> rowInfos)
        {
            List <DataTableRow> dataCollection = new List <DataTableRow>();
            string classFullName = className;

            if (!string.IsNullOrEmpty(namespaceString))
            {
                classFullName = string.Format("{0}.{1}", namespaceString, classFullName);
            }

            DataTablePreferences preferencesData = DataTablePreferencesWindow.LoadPreferencesData();

            if (preferencesData)
            {
                int rowCount = table.Rows.Count;

                for (int i = preferencesData.DataRowsStartRow - 1; i < rowCount; ++i)
                {
                    DataTableRow rowData = (DataTableRow)UnityReflectionUtil.CreateInstance(classFullName);

                    for (int j = 0, propertiesCount = rowInfos.Count; j < propertiesCount; ++j)
                    {
                        string cellValue = table.Rows[i][j].ToString().Trim();

                        if (!string.IsNullOrEmpty(cellValue))
                        {
                            DataTableRowInfo rowInfo    = rowInfos[j];
                            ITypeParser      typeParser = GetTypeParser(rowInfo.Type);

                            if (typeParser != null)
                            {
                                object value = typeParser.Parse(cellValue);
                                ReflectionUtil.SetObjectPropertyValue(rowData, rowInfo.PropertyName, value);
                            }
                            else
                            {
                                Debug.LogWarningFormat("Type '{0}' is not supported!", rowInfo.Type);
                            }
                        }
                    }

                    dataCollection.Add(rowData);
                }
            }

            return(dataCollection);
        }
예제 #10
0
 private void SetPropertyValues()
 {
     foreach (SwitchParameterEntity _switch in _inputSwitches)
     {
         if (_switch.MatchException != null)
         {
             continue;
         }
         try
         {
             object _propVal = _typeParser.Parse(_switch.InputValue, _switch.SwitchProperty.PropertyType);
             _switch.SwitchProperty.SetValue(_paramsObject, _propVal, new object[0]);
         }
         catch (Exception ex)
         {
             _switch.PropertySetException = ex;
         }
     }
 }
예제 #11
0
        private CSharpLanguageProvider()
        {
            _identifierComparer                     = new CodeIdentifierComparer(StringComparer.Ordinal);
            _typeEqualityComparerWithoutNRT         = new TypeEqualityComparer(_identifierComparer, _identifierComparer, true, false);
            _typeEqualityComparerWithoutNullability = new TypeEqualityComparer(_identifierComparer, _identifierComparer, true, true);
            _typeEqualityComparerWithNRT            = new TypeEqualityComparer(_identifierComparer, _identifierComparer, false, false);
            _typeParser = new TypeParser(this);
            _builder    = new CodeBuilder(this);

            var aliasedTypes = new Dictionary <IType, string>(_typeEqualityComparerWithoutNullability);

            _aliasedTypes = aliasedTypes;

            // don't use WellKnownTypes here to avoid circular dependency
            aliasedTypes.Add(_typeParser.Parse <byte>(), "byte");
            aliasedTypes.Add(_typeParser.Parse <sbyte>(), "sbyte");
            aliasedTypes.Add(_typeParser.Parse <short>(), "short");
            aliasedTypes.Add(_typeParser.Parse <ushort>(), "ushort");
            aliasedTypes.Add(_typeParser.Parse <int>(), "int");
            aliasedTypes.Add(_typeParser.Parse <uint>(), "uint");
            aliasedTypes.Add(_typeParser.Parse <long>(), "long");
            aliasedTypes.Add(_typeParser.Parse <ulong>(), "ulong");
            aliasedTypes.Add(_typeParser.Parse <decimal>(), "decimal");
            aliasedTypes.Add(_typeParser.Parse <float>(), "float");
            aliasedTypes.Add(_typeParser.Parse <double>(), "double");
            aliasedTypes.Add(_typeParser.Parse <object>(), "object");
            aliasedTypes.Add(_typeParser.Parse <bool>(), "bool");
            aliasedTypes.Add(_typeParser.Parse <char>(), "char");
            aliasedTypes.Add(_typeParser.Parse <string>(), "string");
            aliasedTypes.Add(_typeParser.Parse <nint>(), "nint");
            aliasedTypes.Add(_typeParser.Parse <nuint>(), "nuint");
            aliasedTypes.Add(_typeParser.Parse(typeof(void)), "void");
        }
예제 #12
0
 public Option <object> Parse(TInput input)
 {
     return(typeParser.Parse(input));
 }
예제 #13
0
        protected internal virtual void AssignFieldValue(
            [NotNull] Type targetWorkItemType,
            [NotNull] IWorkItem sourceWorkItem,
            [NotNull] object targetWorkItem,
            [NotNull] PropertyInfo property,
            [NotNull] string fieldName,
            bool convert,
            [CanBeNull] object nullSub,
            [CanBeNull] object fieldValue)
        {
            // Coalesce fieldValue and nullSub

            if (fieldValue == null && nullSub != null)
            {
                fieldValue = nullSub;
            }
            else
            {
                if (fieldValue is string value && string.IsNullOrWhiteSpace(value))
                {
                    fieldValue = nullSub;
                }
            }

            var destType = property.PropertyType;

            if (fieldValue == null && destType.IsValueType)
            {
                // Value types do not accept null; don't do any work
                return;
            }

            if (fieldValue == null && destType.CanAcceptNull())
            {
                // Destination is a nullable or can take null; don't do any work
                return;
            }

            if (convert)
            {
                try
                {
                    fieldValue = _typeParser.Parse(destType, fieldValue);
                }
                catch (Exception e)
                {
                    var tm      = new TypePair(sourceWorkItem, targetWorkItemType);
                    var pm      = new PropertyMap(property, fieldName);
                    var message = $"Unable to convert field value on {sourceWorkItem.Id}.";
                    throw new AttributeMapException(message, e, tm, pm);
                }
            }

            var accessor = TypeAccessor.Create(targetWorkItemType, true);

            try
            {
                accessor[targetWorkItem, property.Name] = fieldValue;
            }
            catch (Exception e)
            {
                var tm      = new TypePair(sourceWorkItem, targetWorkItemType);
                var pm      = new PropertyMap(property, fieldName);
                var message = $"Unable to set field value on {sourceWorkItem.Id}.";
                throw new AttributeMapException(message, e, tm, pm);
            }
        }
예제 #14
0
        private ITypeInfo GetTypeInfoFromTypeFullName([NotNull] IConfigurationFileElement requestingConfigurationFileElement,
                                                      [NotNull] string typeFullName,
                                                      [NotNull][ItemNotNull] IEnumerable <ITypeInfo> genericTypeParameters,
                                                      [CanBeNull] string typeAttributeName,
                                                      [CanBeNull] string assemblyAttributeName)
        {
            ITypeData typeData = null;

            try
            {
                typeData = _typeParser.Parse(typeFullName);
            }
            catch (ParseTypeException e)
            {
                var errorMessage = new StringBuilder();

                errorMessage.AppendLine($"Failed to parse the value of '{typeFullName}' into a valid type name.");

                string errorLocationText;
                if (typeAttributeName != null)
                {
                    errorLocationText = $"Error location: {typeAttributeName}=\"";
                    errorMessage.AppendLine($"{errorLocationText}{typeFullName}\"");
                }
                else
                {
                    errorLocationText = "Error location: ";
                    errorMessage.AppendLine($"{errorLocationText}{typeFullName}");
                }

                errorMessage.Append(new string('_', errorLocationText.Length + e.ErrorIndex));
                // 2191=up arrow. See https://www.key-shortcut.com/en/writing-systems/35-symbols/arrows/
                errorMessage.AppendLine($"{'\u2191'}");

                errorMessage.AppendLine(e.Message);

                throw new ConfigurationParseException(requestingConfigurationFileElement, errorMessage.ToString());
            }

            List <ITypeInfo> genericTypeParametersList;

            ITypeInfo typeInfo;

            if (typeData.GenericTypeParameters.Count == 0)
            {
                genericTypeParametersList = new List <ITypeInfo>(genericTypeParameters ?? Enumerable.Empty <ITypeInfo>());
                typeInfo = GetTypeInfo2(requestingConfigurationFileElement, typeData, assemblyAttributeName, genericTypeParametersList);
            }
            else
            {
                if (genericTypeParameters != null && genericTypeParameters.Any())
                {
                    throw new ConfigurationParseException(requestingConfigurationFileElement, "Child elements with type parameters are not allowed if the type full name already uses generic type parameters.");
                }

                typeInfo = GetTypeInfoRecursivelly(requestingConfigurationFileElement, typeData, assemblyAttributeName);
            }

            if (typeInfo == null)
            {
                throw new ConfigurationParseException(requestingConfigurationFileElement, "Failed to load the type. We should never get here, since an exception should have been thrown before we get here.");
            }

            _pluginAssemblyTypeUsageValidator.Validate(requestingConfigurationFileElement, typeInfo);

            return(typeInfo);
        }
예제 #15
0
 Option <TOutput> ITypeParser <TInput, TOutput> .Parse(TInput input)
 {
     return(typeParser.Parse(func.Invoke(input)));
 }