Exemplo n.º 1
0
        /// <summary>
        /// Returns the set of authority tokens defined by all plugins.
        /// </summary>
        /// <returns></returns>
        public static AuthorityTokenDefinition[] GetAuthorityTokens()
        {
            var tokens = new List <AuthorityTokenDefinition>();

            // scan all plugins for token definitions
            foreach (var plugin in Platform.PluginManager.Plugins)
            {
                var assembly = plugin.Assembly.Resolve();
                var resolver = new ResourceResolver(assembly);
                foreach (var type in plugin.Assembly.Resolve().GetTypes())
                {
                    // look at public fields
                    foreach (var field in type.GetFields())
                    {
                        var attr = AttributeUtils.GetAttribute <AuthorityTokenAttribute>(field, false);
                        if (attr != null)
                        {
                            var token            = (string)field.GetValue(null);
                            var description      = resolver.LocalizeString(attr.Description);
                            var formerIdentities = (attr.Formerly ?? "").Split(';');

                            tokens.Add(new AuthorityTokenDefinition(token, assembly.FullName, description, formerIdentities));
                        }
                    }
                }
            }
            return(tokens.ToArray());
        }
        private void SetDiceThrowLabel(ICaste caste, IRace race, string propertyName, Label label)
        {
            var casteAttributes          = caste.GetCustomAttributes(propertyName);
            var diceThrow                = AttributeUtils.GetAttribute <DiceThrowAttribute>(casteAttributes);
            var diceThrowModifier        = AttributeUtils.GetAttribute <DiceThrowModifierAttribute>(casteAttributes);
            var specialTrainingAttribute = AttributeUtils.GetAttribute <SpecialTrainingAttribute>(casteAttributes);

            label.Text = Lng.Elem(EnumUtils.GetDescription(diceThrow.DiceThrowType));
            if (diceThrowModifier != null)
            {
                label.Text += $" + {diceThrowModifier.Modifier}";
            }
            if (specialTrainingAttribute != null)
            {
                label.Text += $" + {Lng.Elem("St")}";
            }
            if (diceThrow.DiceThrowType.ToString().EndsWith("2_Times"))
            {
                label.Text += " (2x)";
            }
            var raceModifier = race.GetPropertyShortValue(propertyName);

            if (raceModifier != 0)
            {
                label.Text += raceModifier < 0 ? $" - {Math.Abs(raceModifier)}" : $" + {raceModifier}";
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the set of authority tokens defined by all plugins.
        /// </summary>
        /// <returns></returns>
        public static AuthorityTokenDefinition[] GetAuthorityTokens()
        {
            List <AuthorityTokenDefinition> tokens = new List <AuthorityTokenDefinition>();

            // scan all plugins for token definitions
            foreach (PluginInfo plugin in Platform.PluginManager.Plugins)
            {
                IResourceResolver resolver = new ResourceResolver(plugin.Assembly);
                foreach (Type type in plugin.Assembly.GetTypes())
                {
                    // look at public fields
                    foreach (FieldInfo field in type.GetFields())
                    {
                        AuthorityTokenAttribute attr = AttributeUtils.GetAttribute <AuthorityTokenAttribute>(field, false);
                        if (attr != null)
                        {
                            string token       = (string)field.GetValue(null);
                            string description = resolver.LocalizeString(attr.Description);

                            tokens.Add(new AuthorityTokenDefinition(token, description));
                        }
                    }
                }
            }
            return(tokens.ToArray());
        }
Exemplo n.º 4
0
        /// <summary>
        /// Promotes the exception to a fault, if the exception type has a corresponding fault contract.
        /// Otherwise returns null.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="serviceInstance"></param>
        /// <param name="method"></param>
        /// <param name="fault"></param>
        /// <returns></returns>
        private static bool PromoteExceptionToFault(Exception e, object serviceInstance, MethodInfo method, out Exception fault)
        {
            fault = null;

            // get the service contract
            var serviceContractAttr = AttributeUtils.GetAttribute <ServiceImplementsContractAttribute>(serviceInstance.GetType(), false);

            // this should never happen, but if it does, there's nothing we can do
            if (serviceContractAttr == null)
            {
                return(false);
            }

            // find a fault contract for this exception type
            var faultContract = AttributeUtils.GetAttribute <FaultContractAttribute>(method, true, a => a.DetailType.Equals(e.GetType()));

            if (faultContract != null)
            {
                // from Juval Lowey
                var faultBoundedType = typeof(FaultException <>).MakeGenericType(e.GetType());
                fault = (FaultException)Activator.CreateInstance(faultBoundedType, e, new FaultReason(e.Message));
                return(true);
            }

            return(false);               // no fault contract for this exception
        }
Exemplo n.º 5
0
        /// <summary>
        /// Attempts to instantiate a script engine for the specified language.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Internally, this class looks for an extension of <see cref="ScriptEngineExtensionPoint"/>
        /// that is capable of running scripts in the specified language.
        /// In order to be considered a match, extensions must be decorated with a
        /// <see cref="LanguageSupportAttribute"/> matching the <paramref name="language"/> parameter.
        /// </para>
        /// <para>
        /// If the engine is marked as a singleton, and a cached instance already exists, that instance will
        /// be returned.
        /// </para>
        /// <para>
        /// This method can safely be called by multiple threads.
        /// </para>
        /// </remarks>
        /// <param name="language">The case-insensitive script language, so jscript is equivalent to JScript.</param>
        public static IScriptEngine GetEngine(string language)
        {
            lock (_syncLock)
            {
                // check for a cached singleton engine instance for this language
                IScriptEngine engine;
                if (_singletonEngineInstances.TryGetValue(language, out engine))
                {
                    return(engine);
                }

                // create a new engine instance
                engine = CreateEngine(language);

                var optionsAttr = AttributeUtils.GetAttribute <ScriptEngineOptionsAttribute>(engine.GetType());
                if (optionsAttr != null)
                {
                    // if the engine requires synchronization, wrap it
                    if (optionsAttr.SynchronizeAccess)
                    {
                        engine = new SynchronizedScriptEngineWrapper(engine);
                    }

                    // if the engine is a singleton, cache this instance
                    if (optionsAttr.Singleton)
                    {
                        _singletonEngineInstances.Add(language, engine);
                    }
                }
                return(engine);
            }
        }
Exemplo n.º 6
0
        private EnumerationInfo ReadHardEnum(Type enumValueClass, Table table)
        {
            Type enumType = _mapClassToEnum[enumValueClass];

            int displayOrder = 1;

            // note that we process the enum constants in order of the underlying value assigned
            // so that the initial displayOrder reflects the natural ordering
            // (see msdn docs for Enum.GetValues for details)
            return(new EnumerationInfo(enumValueClass.FullName, table.Name, true,
                                       CollectionUtils.Map <object, EnumerationMemberInfo>(Enum.GetValues(enumType),
                                                                                           delegate(object value)
            {
                string code = Enum.GetName(enumType, value);
                FieldInfo fi = enumType.GetField(code);

                EnumValueAttribute attr = AttributeUtils.GetAttribute <EnumValueAttribute>(fi);
                return new EnumerationMemberInfo(
                    code,
                    attr != null ? attr.Value : null,
                    attr != null ? attr.Description : null,
                    displayOrder++,
                    false);
            })));
        }
Exemplo n.º 7
0
        private void InitPrivate(int tag, DataFormat dataFormat, bool isOptional, MemberInfo member, Delegate getValue, Delegate setValue, object defaultValue)
        {
            if (this.prefix != 0)
            {
                throw new InvalidOperationException("Can only initialise a property once");
            }

            if (member != null)
            {
                MemberSerializationOptions options;
                if (!Serializer.TryGetTag(member, out tag, out name, out dataFormat, out options))
                {
                    throw new ArgumentException(member.Name + " cannot be used for serialization", "member");
                }
                isOptional = !PropertyFactory.HasOption(options, MemberSerializationOptions.Required);
                {
                    DefaultValueAttribute dva = AttributeUtils.GetAttribute <DefaultValueAttribute>(member);
                    defaultValue = dva == null ? null : dva.Value;
                }
#if CF
                this.description = null; // not used in CF; assigned to get rid of warning
#else
                {
                    DescriptionAttribute da = AttributeUtils.GetAttribute <DescriptionAttribute>(member);
                    this.description = da == null ? null : da.Description;
                }
#endif
            }
            this.isOptional   = isOptional;
            this.defaultValue = defaultValue;
            this.dataFormat   = dataFormat; // set initial format, and use the *field* for the "ref" so either usage is valid
            OnBeforeInit(member, getValue, setValue, tag, ref this.dataFormat);
            this.prefix = Serializer.GetFieldToken(tag, WireType);
            OnAfterInit();
        }
Exemplo n.º 8
0
        static string GetGroupName(DefaultUserGroup group)
        {
            string    fieldName = Enum.GetName(typeof(DefaultUserGroup), group);
            FieldInfo field     = typeof(DefaultUserGroup).GetField(fieldName);
            UserGroupDefinitionAttribute definition = AttributeUtils.GetAttribute <UserGroupDefinitionAttribute>(field);

            return(definition.Name);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Checks whether validation is enabled on the specified domain class.
        /// </summary>
        /// <param name="domainClass"></param>
        /// <returns></returns>
        public static bool IsValidationEnabled(Type domainClass)
        {
            // then check the attributes
            var a = AttributeUtils.GetAttribute <ValidationAttribute>(domainClass, true);

            // if no attribute present, then by default validation is enabled
            return((a == null) || a.EnableValidation);
        }
Exemplo n.º 10
0
        internal AttributeUsageAttribute GetAttributeUsage(ITypeInfo attributeType)
        {
            return(attributeUsageMemoizer.Memoize(attributeType, () =>
            {
                if (attributeType.FullName == @"System.AttributeUsageAttribute")
                {
                    // Note: Avoid indefinite recursion when determining whether AttributeUsageAttribute itself is inheritable.
                    return new AttributeUsageAttribute(AttributeTargets.Class)
                    {
                        Inherited = true
                    };
                }

                Type resolvedAttributeType = attributeType.Resolve(false);
                if (!Reflector.IsUnresolved(resolvedAttributeType))
                {
                    // We use the resolved type when possible primarily because ReSharper's Metadata reflection
                    // policy cannot resolve types in System and mscorlib which causes problems ironically when
                    // trying to resolve AttributeUsageAttribute itself.  However this is also a useful optimization
                    // in the case where the type can be resolved. -- Jeff.
                    var attributeUsages = (AttributeUsageAttribute[])resolvedAttributeType.GetCustomAttributes(
                        typeof(AttributeUsageAttribute), true);

                    if (attributeUsages.Length != 0)
                    {
                        return attributeUsages[0];
                    }
                }
                else
                {
                    try
                    {
                        var attributeUsage = AttributeUtils.GetAttribute <AttributeUsageAttribute>(attributeType, true);
                        if (attributeUsage != null)
                        {
                            return attributeUsage;
                        }
                    }
                    catch (TargetParameterCountException)
                    {
                        // This is a hack to work around the fact that ReSharper does not correctly handle
                        // attribute parameters with enum values.  In particular, this affects the first
                        // parameter of AttributeUsageAttribute. -- Jeff.
                        return new AttributeUsageAttribute(AttributeTargets.All)
                        {
                            Inherited = true,
                            AllowMultiple = true
                        };
                    }
                }

                return new AttributeUsageAttribute(AttributeTargets.All)
                {
                    Inherited = true
                };
            }));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Internal method used by the framework to discover extension points and extensions declared in a plugin.
        /// </summary>
        /// <param name="asm"></param>
        /// <param name="points"></param>
        /// <param name="extensions"></param>
        internal static void DiscoverExtensionPointsAndExtensions(Assembly asm, List <ExtensionPointInfo> points, List <ExtensionInfo> extensions)
        {
            foreach (var type in asm.GetTypes())
            {
                var epAttr = AttributeUtils.GetAttribute <ExtensionPointAttribute>(type, false);
                if (epAttr != null)
                {
                    if (IsValidExtensionPointClass(type))
                    {
                        points.Add(new ExtensionPointInfo(type, GetExtensionInterface(type), epAttr.Name, epAttr.Description));
                    }
                    else
                    {
                        Platform.Log(LogLevel.Error, SR.ExceptionExtensionPointMustSubclassExtensionPoint, type.FullName);
                    }
                }

                var attrs = AttributeUtils.GetAttributes <ExtensionOfAttribute>(type, false);
                foreach (var a in attrs)
                {
                    // is the extension a concrete class?
                    if (!IsConcreteClass(type))
                    {
                        Platform.Log(LogLevel.Error, SR.ExceptionExtensionMustBeConcreteClass, type.FullName);
                        continue;
                    }

                    var extensionPointClass = a.ExtensionPointClass;
                    if (!IsValidExtensionPointClass(extensionPointClass))
                    {
                        Platform.Log(LogLevel.Error, SR.ExceptionExtensionDoesNotExtendValidExtensionPointClass, type.FullName);
                        continue;
                    }

                    // does the extension implement the required interface?
                    var extensionInterface = GetExtensionInterface(extensionPointClass);
                    if (!extensionInterface.IsAssignableFrom(type))
                    {
                        Platform.Log(LogLevel.Error, SR.ExceptionExtensionDoesNotImplementRequiredInterface,
                                     type.FullName,
                                     extensionInterface);

                        continue;
                    }
                    extensions.Add(
                        new ExtensionInfo(
                            type,
                            extensionPointClass,
                            a.Name,
                            a.Description,
                            ExtensionSettings.Default.IsEnabled(type, a.Enabled),
                            a.FeatureToken
                            )
                        );
                }
            }
        }
 public EditContractJsmlSerializerHook()
 {
     _contractMap = (from p in Platform.PluginManager.Plugins
                     from t in p.Assembly.Resolve().GetTypes()
                     let a = AttributeUtils.GetAttribute <EditTypeAttribute>(t)
                             where (a != null)
                             select new { a.ContractId, Contract = t })
                    .ToDictionary(entry => entry.ContractId, entry => entry.Contract);
 }
Exemplo n.º 13
0
 public CustomHook()
 {
     _contractMap = (from p in Platform.PluginManager.Plugins
                     from t in p.Assembly.Resolve().GetTypes()
                     let a = AttributeUtils.GetAttribute <ImageServerExternalRequestTypeAttribute>(t)
                             where (a != null)
                             select new { a.ContractId, Contract = t })
                    .ToDictionary(entry => entry.ContractId, entry => entry.Contract);
 }
        public static void RegisterKnownType(Type type)
        {
            var a = AttributeUtils.GetAttribute <T>(type);

            if (a == null)
            {
                throw new ArgumentException(string.Format("Specified type must be decorated with {0}", typeof(T).FullName));
            }
            _contractMap.Add(a.ContractId, type);
        }
 static PolymorphicDataContractHook()
 {
     // build the contract map by finding all types having a T attribute
     _contractMap = (from p in Platform.PluginManager.Plugins
                     from t in p.Assembly.Resolve().GetTypes()
                     let a = AttributeUtils.GetAttribute <T>(t)
                             where (a != null)
                             select new { a.ContractId, Contract = t })
                    .ToDictionary(entry => entry.ContractId, entry => entry.Contract);
 }
Exemplo n.º 16
0
        private static Type[] InternalGetRequestRuntimeTypes()
        {
            var types = (from p in Platform.PluginManager.Plugins
                         from t in p.Assembly.Resolve().GetTypes()
                         let a = AttributeUtils.GetAttribute <WorkItemRequestAttribute>(t)
                                 where (a != null)
                                 select t);

            return(types.ToArray());
        }
        public static IResponseDataCachingStrategy Get(MethodInfo method)
        {
            var cacheAttribute = AttributeUtils.GetAttribute <ResponseDataCachingStrategyAttribute>(method, true);

            if (cacheAttribute != null)
            {
                return((IResponseDataCachingStrategy)Activator.CreateInstance(cacheAttribute.Type));
            }

            return(new DefaultResponseCachingStrategy());
        }
Exemplo n.º 18
0
        /// <summary>
        /// Obtains the default value of a setting from the <see cref="DefaultSettingValueAttribute"/>.
        /// </summary>
        /// <remarks>
        /// If translate is true, and the value is the name of an embedded resource, it is automatically translated.
        /// </remarks>
        public static string GetDefaultValue(PropertyInfo property, bool translate)
        {
            var a = AttributeUtils.GetAttribute <DefaultSettingValueAttribute>(property, false);

            if (a == null)
            {
                return("");
            }

            return(!translate ? a.Value : TranslateDefaultValue(property.ReflectedType, a.Value));
        }
        public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
        {
            var a = AttributeUtils.GetAttribute <T>(type);

            if (a != null)
            {
                var dictionary = new XmlDictionary();
                typeName      = dictionary.Add(_contractNamePrefix + a.ContractId);
                typeNamespace = dictionary.Add(_contractNamespace);
                return(true);
            }
            return(knownTypeResolver.TryResolveType(type, declaredType, knownTypeResolver, out typeName, out typeNamespace));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets the description for the specified worklist class, as specified by
        /// the <see cref="WorklistCategoryAttribute"/>, or null if not specified.
        /// </summary>
        /// <param name="worklistClass"></param>
        /// <returns></returns>
        public static string GetDescription(Type worklistClass)
        {
            var a = AttributeUtils.GetAttribute <WorklistClassDescriptionAttribute>(worklistClass, true);

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

            var resolver = new ResourceResolver(worklistClass, true);

            return(resolver.LocalizeString(a.Description));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Gets the display name for the specified worklist class, obtained either from
        /// the <see cref="WorklistClassDisplayNameAttribute"/>, otherwise via the
        /// <see cref="TerminologyTranslator"/> class.
        /// </summary>
        /// <param name="worklistClass"></param>
        /// <returns></returns>
        public static string GetDisplayName(Type worklistClass)
        {
            var a = AttributeUtils.GetAttribute <WorklistClassDisplayNameAttribute>(worklistClass, true);

            if (a == null)
            {
                return(TerminologyTranslator.Translate(worklistClass));
            }

            var resolver = new ResourceResolver(worklistClass, true);

            return(resolver.LocalizeString(a.DisplayName));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the category for the specified worklist class, as specified by
        /// the <see cref="WorklistCategoryAttribute"/>, or null if not specified.
        /// </summary>
        /// <param name="worklistClass"></param>
        /// <returns></returns>
        public static string GetCategory(Type worklistClass)
        {
            var a = AttributeUtils.GetAttribute <WorklistCategoryAttribute>(worklistClass, true);

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

            var resolver = new ResourceResolver(worklistClass, true);

            return(resolver.LocalizeString(a.Category));
        }
        public EditContractJsmlSerializerHook()
        {
            var assemblies = Platform.PluginManager.Plugins.Select(p => p.Assembly.Resolve()).ToList();

            assemblies.Add(typeof(Edit).Assembly);

            _contractMap = (from t in assemblies.SelectMany(a => a.GetTypes()).Distinct()
                            let a = AttributeUtils.GetAttribute <EditTypeAttribute>(t)
                                    let b = AttributeUtils.GetAttribute <DataContractAttribute>(t)
                                            where (a != null && b != null)
                                            select new { a.ContractId, Contract = t })
                           .ToDictionary(entry => entry.ContractId, entry => entry.Contract);
        }
Exemplo n.º 24
0
        private static bool IsChangeSetPublishable(DomainObject domainObject)
        {
            // ignore changes to enum values for now
            // TODO: should probably record changes to enum values
            if (domainObject is EnumValue)
            {
                return(false);
            }

            // check for an attribute - if no attribute, then default is publishable
            var a = AttributeUtils.GetAttribute <PublishInChangeSetsAttribute>(domainObject.GetClass(), true);

            return(a == null || a.IsPublishable);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Returns a list of data-classes for which an Imex extension exists.
        /// </summary>
        /// <returns></returns>
        public static string[] ListImexDataClasses()
        {
            List <string> dataClasses = new List <string>();

            foreach (ExtensionInfo info in new XmlDataImexExtensionPoint().ListExtensions())
            {
                ImexDataClassAttribute a = AttributeUtils.GetAttribute <ImexDataClassAttribute>(info.ExtensionClass);
                if (a != null)
                {
                    dataClasses.Add(a.DataClass);
                }
            }
            return(dataClasses.ToArray());
        }
Exemplo n.º 26
0
        /// <summary>
        /// Returns the <see cref="EnumInfoAttribute"/> of an enum value, if it's defined.
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static EnumInfoAttribute GetEnumInfo <TEnum>(TEnum value)
            where TEnum : struct
        {
            FieldInfo field = typeof(TEnum).GetField(value.ToString());

            if (field != null)
            {
                return(AttributeUtils.GetAttribute <EnumInfoAttribute>(field));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 27
0
        public IList <TEntity> FindAll(bool includeDeactivated, EntityFindOptions options)
        {
            var where = new TSearchCriteria();

            // if the entity class supports deactivation, apply this condition
            if (!includeDeactivated && AttributeUtils.HasAttribute <DeactivationFlagAttribute>(typeof(TEntity)))
            {
                var propertyName = AttributeUtils.GetAttribute <DeactivationFlagAttribute>(typeof(TEntity)).PropertyName;
                var c            = new SearchCondition <bool>(propertyName);
                c.EqualTo(false);
                where.SetSubCriteria(c);
            }

            return(Find(where, options));
        }
        bool IJsmlSerializerHook.Serialize(IJsmlSerializationContext context)
        {
            var data = context.Data;

            if (data != null)
            {
                // if we have an attribute, write out the contract ID as an XML attribute
                var a = AttributeUtils.GetAttribute <T>(data.GetType());
                if (a != null)
                {
                    context.Attributes.Add("contract", a.ContractId);
                }
            }

            // always return false - we don't handle serialization ourselves
            return(false);
        }
Exemplo n.º 29
0
        protected static Dictionary <string, string> GetColumnMap(Type entityType)
        {
            ObjectWalker walker = new ObjectWalker();
            Dictionary <string, string> propMap = new Dictionary <string, string>();

            foreach (IObjectMemberContext member in walker.Walk(entityType))
            {
                EntityFieldDatabaseMappingAttribute map =
                    AttributeUtils.GetAttribute <EntityFieldDatabaseMappingAttribute>(member.Member);
                if (map != null)
                {
                    propMap.Add(member.Member.Name, map.ColumnName);
                }
            }

            return(propMap);
        }
Exemplo n.º 30
0
        private static Dictionary <string, PropertyInfo> LoadMap(Type entityType)
        {
            ObjectWalker walker = new ObjectWalker();
            Dictionary <string, PropertyInfo> propMap = new Dictionary <string, PropertyInfo>();

            foreach (IObjectMemberContext member in walker.Walk(entityType))
            {
                EntityFieldDatabaseMappingAttribute map =
                    AttributeUtils.GetAttribute <EntityFieldDatabaseMappingAttribute>(member.Member);
                if (map != null)
                {
                    propMap.Add(map.ColumnName, member.Member as PropertyInfo);
                }
            }

            return(propMap);
        }