示例#1
0
   /// <summary>
   /// Initializes a new instance of the OutlinerPluginData class.
   /// </summary>
   /// <param name="type">The type to create the metadata for.</param>
   public OutlinerPluginData(Type type)
   {
      Throw.IfNull(type, "type");
      this.Type = type;

      OutlinerPluginAttribute pluginAttr = type.GetAttribute<OutlinerPluginAttribute>();
      Throw.IfNull(pluginAttr, "OutlinerPlugin attribute not found on type.");
      this.PluginType = pluginAttr.PluginType;

      DisplayNameAttribute dispAtrr = type.GetAttribute<DisplayNameAttribute>();
      if (dispAtrr != null)
         this.DisplayName = dispAtrr.DisplayName;
      else
         this.DisplayName = type.Name;

      LocalizedDisplayImageAttribute imgAttr = type.GetAttribute<LocalizedDisplayImageAttribute>();
      if (imgAttr != null)
      {
         this.DisplayImageSmall = imgAttr.DisplayImageSmall;
         this.DisplayImageLarge = imgAttr.DisplayImageLarge;
      }
      else
      {
         this.DisplayImageSmall = null;
         this.DisplayImageLarge = null;
      }
   }
示例#2
0
        private ITypeLoader CreateTypeLoader(Type suiteBaseType, IEnumerable<ITestExtension> testExtensions)
        {
            var typeLoaderType = suiteBaseType.GetAttribute<TypeLoaderAttribute>().AssertNotNull().TypeLoaderType;
              var operationOrdering = suiteBaseType.GetAttribute<OperationOrderingAttribute>().AssertNotNull().OperationDescriptors;

              var builder = new ContainerBuilder();
              builder.RegisterModule<UtilitiesModule>();
              builder.RegisterModule(new ExtensibilityModule(typeLoaderType, operationOrdering));
              builder.RegisterInstance(testExtensions).As<IEnumerable<ITestExtension>>();
              var container = builder.Build();

              return (ITypeLoader) container.Resolve(typeLoaderType);
        }
        /// <summary>
        /// 生成控制器及视图
        /// </summary>
        /// <param name="type">要生成代码的模型类</param>
        /// <param name="gen">生成内容选项</param>
        public static void GenerateCommonCode(Type type, string gen)
        {
            if (type.FullName == null) return;
            var packageName = type.FullName.Split('.')[3];
            // var packageName = type.FullName.Substring(15, 2);
            var modelName = type.Name;
            var tableAttribute = type.GetAttribute<TableAttribute>();
            var moduleName = tableAttribute != null ? tableAttribute.DisplayName : "未命名";

            if (gen.Contains("Controller"))
                GenContollerCode(packageName, modelName, moduleName);
            if (gen.Contains("Index"))
                GenIndexCode(packageName, modelName);
            var inputForList = GetInputForList(type);
            if (gen.Contains("Create"))
            {
                GenCreateCode(packageName, modelName, inputForList);
            }
            if (gen.Contains("Edit"))
            {
                GenEditCode(packageName, modelName, inputForList);
            }
            var addlist = GetAddList(type);
            if (gen.Contains("QuickSearch"))
            {
                GenQuickSearchCode(packageName, modelName, addlist);
            }
            if (gen.Contains("Delete"))
                GenDeleteCode(packageName, modelName, addlist);
            if (gen.Contains("Details"))
                GenDetailsCode(packageName, modelName, addlist);
        }
示例#4
0
文件: Sheet.cs 项目: naokirin/Buffet
        public static Sheet GetSheet(Type t)
        {
            var sheetAttr = (SheetAttribute)t.GetAttribute(typeof(SheetAttribute));
            var sheetName = sheetAttr != null ? sheetAttr.Name : t.Name;
            var definedColumn = sheetAttr != null ? sheetAttr.DefinedColumn : "";
            var startingComments = sheetAttr != null && sheetAttr.StartingComments != null ? sheetAttr.StartingComments.ToList() : new List<string>();

            var properties = from property in t.GetRuntimeProperties()
                    where (property.GetMethod != null && property.GetMethod.IsPublic)
                || (property.SetMethod != null && property.SetMethod.IsPublic)
                || (property.GetMethod != null && property.GetMethod.IsStatic)
                || (property.SetMethod != null && property.SetMethod.IsStatic)
                select property;

            var columns = new List<Column>();
            foreach(var property in properties)
            {
                var ignore = property.GetCustomAttribute(typeof(IgnoredColumnAttribute), true);

                if (property.CanWrite && ignore == null)
                {
                    columns.Add(new Column(property));
                }
            }

            return new Sheet(sheetName, columns, definedColumn, startingComments);
        }
示例#5
0
        /// <summary>
        /// 构造模型绑定器
        /// </summary>
        /// <param name="name">成员名称</param>
        /// <param name="type">成员类型</param>
        /// <param name="defaultValue">缺省值</param>
        public BindingInfo(string name, Type type, object defaultValue)
        {
            Name = name;
            Type = type;
            DefaultValue = new Lazy<object>(() => defaultValue);

            BindAttribute attr = type.GetAttribute<BindAttribute>(false);
            if (attr == null)
                Exclude = Include = new string[0];
            else
            {
                if (string.IsNullOrEmpty(attr.Prefix))
                    IsNullPrefix = false;
                else
                    Prefix = attr.Prefix.ToLower() + ".";

                Exclude = new ReadOnlyCollection<string>(SplitString(attr.Exclude));
                Include = new ReadOnlyCollection<string>(SplitString(attr.Include));
            }

            var binderAttr = type.GetAttribute<CustomModelBinderAttribute>(false);
            if (binderAttr != null)
                ModelBinder = binderAttr.GetBinder();
            if (ModelBinder == null)
                ModelBinder = ModelBinders.GetBinder(type);
            if (ModelBinder == null)
                ModelBinder = _DefaultModelBinder;
        }
示例#6
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ConnectorInfo"/>.
		/// </summary>
		/// <param name="adapterType">The type of transaction or market data adapter.</param>
		public ConnectorInfo(Type adapterType)
		{
			if (adapterType == null)
				throw new ArgumentNullException("adapterType");

			if (!typeof(IMessageAdapter).IsAssignableFrom(adapterType))
				throw new ArgumentException("adapterType");

			AdapterType = adapterType;
			Name = adapterType.GetDisplayName();
			Description = adapterType.GetDescription();
			Category = adapterType.GetCategory(LocalizedStrings.Str1559);

			var targetPlatform = adapterType.GetAttribute<TargetPlatformAttribute>();
			if (targetPlatform != null)
			{
				PreferLanguage = targetPlatform.PreferLanguage;
				Platform = targetPlatform.Platform;
			}
			else
			{
				PreferLanguage = Languages.English;
				Platform = Platforms.AnyCPU;
			}
		}
        public IObjectInfo CreateObjectInfo(Type forType)
        {
            if (forType == null)
            {
                throw new ArgumentNullException("forType");
            }

            var tableAttribute = forType.GetAttribute<TableAttribute>(inherit: false);

            if (tableAttribute == null)
            {
                throw new MappingException(ExceptionMessages.AttributeMappingConvention_NoTableAttribute.FormatWith(forType.FullName));
            }

            var identifierStrategy = IdentifierStrategy.DbGenerated;
            var columns = this.CreateColumnInfos(forType, ref identifierStrategy);

            var tableInfo = new TableInfo(columns, identifierStrategy, tableAttribute.Name, tableAttribute.Schema);

            if (this.log.IsDebug)
            {
                this.log.Debug(LogMessages.MappingConvention_MappingTypeToTable, forType.FullName, tableInfo.Schema, tableInfo.Name);
            }

            return new PocoObjectInfo(forType, tableInfo);
        }
示例#8
0
        /// <summary>
        /// 获取生命周期
        /// </summary>
        public static Lifecycle GetLifecycle(Type type)
        {
            if (!type.IsDefined(typeof(LifeCycleAttribute), false))
                return Lifecycle.Singleton;

            return type.GetAttribute<LifeCycleAttribute>(false).Lifetime;
        }
示例#9
0
 /// <summary>Creates a new <see cref="Descriptor"/> instance from a given type.</summary>
 /// <param name="type">The type from which the descriptor will be created.</param>
 public Descriptor(Type type) {
    var attr = type.GetAttribute<DescriptorAttribute>();
    if (attr != null) {
       ParseXml(attr.Markup);
    }
    Subject = type;
 }
 internal static string Get(Type type)
 {
     var result = type.GetAttribute<SchemaAttribute>(false);
     if(result == null)
         return null;
     return result._name;
 }
示例#11
0
 public static IPropertyEditor TryCreateEditor(Type editedType, Type editorType)
 {
     CustomPropertyEditorAttribute attribute = editorType.GetAttribute<CustomPropertyEditorAttribute>();
     if (attribute == null || !attribute.Inherit)
     {
         return PropertyEditorTools.TryCreateSpecificEditor(editedType, editedType, editorType);
     }
     for (Type type = editedType; type != null; type = type.BaseType)
     {
         IPropertyEditor propertyEditor = PropertyEditorTools.TryCreateSpecificEditor(type, editedType, editorType);
         if (propertyEditor != null)
         {
             return propertyEditor;
         }
         Type[] interfaces = type.GetInterfaces();
         for (int i = 0; i < interfaces.Length; i++)
         {
             Type usedEditedType = interfaces[i];
             propertyEditor = PropertyEditorTools.TryCreateSpecificEditor(usedEditedType, editedType, editorType);
             if (propertyEditor != null)
             {
                 return propertyEditor;
             }
         }
     }
     return null;
 }
示例#12
0
        private bool Match(Type bhvType, string searchString)
        {
            var bhvAttr = bhvType.GetAttribute<Behaviors.BehaviorModelAttribute>();

            return CultureInfo.CurrentCulture.CompareInfo.IndexOf(bhvAttr.DefaultName, searchString, CompareOptions.IgnoreCase) >= 0
                   || CultureInfo.CurrentCulture.CompareInfo.IndexOf(bhvType.FullName, searchString, CompareOptions.IgnoreCase) >= 0;
        }
示例#13
0
        /// <summary>
        ///   Gets inspector data such as name and description for the
        ///   specified type.
        /// </summary>
        /// <param name="type">Type to get inspector data for.</param>
        /// <param name="conditionalInspectors">Dictionary to be filled with conditions for inspectors to be shown.</param>
        /// <returns>Inspector data for the specified type.</returns>
        public static InspectorType GetInspectorType(
            Type type,
            ref Dictionary<InspectorPropertyAttribute, InspectorConditionalPropertyAttribute> conditionalInspectors)
        {
            List<InspectorPropertyAttribute> inspectorProperties = InspectorUtils.CollectInspectorProperties(
                type, ref conditionalInspectors);

            var inspectorTypeAttribute = type.GetAttribute<InspectorTypeAttribute>();

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

            var inspectorTypeData = new InspectorType
                {
                    Attribute = inspectorTypeAttribute,
                    Name = type.Name,
                    Description = inspectorTypeAttribute.Description,
                    Properties = inspectorProperties,
                    Type = type,
                };

            return inspectorTypeData;
        }
        public AttributeDrivenPatternSchema(Type patternProviderInterface, Type patternClientInterface)
        {
            if (!patternProviderInterface.IsInterface)
                throw new ArgumentException("Provided pattern provider type should be an interface", "patternProviderInterface");
            if (!patternClientInterface.IsInterface)
                throw new ArgumentException("Provided pattern client type should be an interface", "patternClientInterface");
            _patternProviderInterface = patternProviderInterface;
            _patternClientInterface = patternClientInterface;

            var patternClientName = _patternClientInterface.Name;
            if (!patternClientName.EndsWith("Pattern") || !patternClientName.StartsWith("I"))
                throw new ArgumentException("Pattern client interface named incorrectly, should be IXxxPattern", "patternClientInterface");
            var baseName = patternClientName.Substring(1, patternClientName.Length - "I".Length - "Pattern".Length);
            if (_patternProviderInterface.Name != string.Format("I{0}Provider", baseName))
                throw new ArgumentException(string.Format("Pattern provider interface named incorrectly, should be I{0}Provider", baseName));
            _patternName = string.Format("{0}Pattern", baseName);

            var patternGuidAttr = _patternProviderInterface.GetAttribute<PatternGuidAttribute>();
            if (patternGuidAttr == null) throw new ArgumentException("Provided type should be marked with PatternGuid attribute");
            _patternGuid = patternGuidAttr.Value;

            _methods = patternProviderInterface.GetMethodsMarkedWith<PatternMethodAttribute>().Select(GetMethodHelper).ToArray();
            _properties = patternProviderInterface.GetPropertiesMarkedWith<PatternPropertyAttribute>().Select(GetPropertyHelper).ToArray();
            ValidateClientInterface();
            _handler = new AttributeDrivenPatternHandler(this);
        }
 public byte GetDeliveryMode(Type messageType)
 {
     Preconditions.CheckNotNull(messageType, "messageType");
     var deliveryModeAttribute = messageType.GetAttribute<DeliveryModeAttribute>();
     if (deliveryModeAttribute == null)
         return GetDeliveryModeInternal(connectionConfiguration.PersistentMessages);
     return GetDeliveryModeInternal(deliveryModeAttribute.IsPersistent);
 }
示例#16
0
 string GetCommandName(Type commandType)
 {
     string defaultName = commandType.Name.Replace("Command", "");
     string commandName = commandType.HasAttribute<CommandNameAttribute>() ?
         commandType.GetAttribute<CommandNameAttribute>().Name :
         defaultName;
     return commandName;
 }
 public string LabelForTypeConvention(Type type)
 {
     if (type.AttributeExists<LabelAttribute>())
     {
         return type.GetAttribute<LabelAttribute>().Label;
     }
     return type.Name.ToSeparatedWords();
 }
示例#18
0
 public static string GetUsage(Type t)
 {
     var usage = t.GetAttribute<CommandUsageAttribute>(false);
     if (usage != null)
     {
         return usage.Usage;
     }
     return "";
 }
        public void Process(Type type, Registry registry)
        {
            if(!_shouldAutoNotify(type))
                return;

            logger.InfoFormat("Registering autonotify for {0}", type.Name);

            var fireOption = type.GetAttribute<AutoNotifyAttribute>().Fire;

            var dependencyMap = new DependencyMap()
                .Tap(m => m.Map.AddRange(GetDependencyMap(type.GetAttribute<AutoNotifyAttribute>().DependencyMap).Map))
                .Tap(m => m.Map.AddRange(GetDependencyMapFromProps(type).Map));

            if(type.IsInterface)
                ConfigureInterface(type, registry, fireOption, dependencyMap);
            else if(!type.IsAbstract)
                ConfigureClass(type, registry, fireOption, dependencyMap);
        }
 internal CommandMetadata(Type commandType)
 {
     Name = commandType.GetFullCommandName();
     var displayAttribute = commandType.GetAttribute<CommandDisplayAttribute>();
     if (displayAttribute != null)
     {
         Description = displayAttribute.GetLocalizedDescription();
         Usage = displayAttribute.GetLocalizedUsage();
     }
 }
示例#21
0
		/// <summary>
		/// Gets the type of the base.
		/// </summary>
		/// <param name="wrapperType">Type of the wrapper.</param>
		/// <returns></returns>
		public static Type GetBaseType(Type wrapperType)
		{
			var @interfaces =
				from @interface in wrapperType.GetInterfaces()
				where @interface.QueryAttribute<CppClassAttribute>(attr => attr.Type != ClassType.Interface)
				select @interface;

			if (@interfaces.Count() <= 1)
				return @interfaces.SingleOrDefault();

			return wrapperType.GetAttribute<CppClassAttribute>(true).BaseType;
		}
        public static BehaviorChain ChainForType(Type type)
        {
            if (type.HasAttribute<UrlPatternAttribute>())
            {
                var route = type.GetAttribute<UrlPatternAttribute>().BuildRoute(type);
                return new RoutedChain(route, type, type);
            }
            var chain = BehaviorChain.ForResource(type);
            chain.IsPartialOnly = true;

            return chain;
        }
 public static string GetBehaviorName(Type behaviorModelType)
 {
     if (behaviorModelType == null)
     {
         throw new ArgumentNullException("behaviorModelType");
     }
     var bhvAttr = behaviorModelType.GetAttribute<Behaviors.BehaviorModelAttribute>();
     if (bhvAttr == null || bhvAttr.HideFromEditor)
     {
         throw new ArgumentException("behaviorModelType");
     }
     return bhvAttr.DefaultName;
 }
            public void ReturnsAttributeForTypes(Type type, Type expectedAttributeType, bool isNotNull)
            {
                var attribute = type.GetAttribute(expectedAttributeType);

                if (isNotNull)
                {
                    Assert.IsNotNull(attribute);
                }
                else
                {
                    Assert.IsNull(attribute);
                }
            }
示例#25
0
 private static TypeConverter RegisterTypeConverterFor(Type type)
 {
     var converter_attr = type.GetAttribute<TypeConverterAttribute>();
     if ( converter_attr != null ) {
         // What is the difference between these two conditions?
         TypeConverterSpecified[type] = true;
         var converterType = TypeUtils.GetType(converter_attr.ConverterTypeName);
         return TypeConverters[type] = Activator.CreateInstance(converterType) as TypeConverter;
     } else {
         // What is the difference between these two conditions?
         TypeConverterSpecified[type] = false;
         return TypeConverters[type] = TypeDescriptor.GetConverter(type);
     }
 }
        private void CreateAppliesToFilter(Type modifierClass)
        {
            if (!typeof(InvocationHandler).IsAssignableFrom(modifierClass))
            {
                this.appliesToFilter = new TypedModifierAppliesToFilter();

                if (modifierClass.IsAbstract)
                {
                    this.appliesToFilter = new AndAppliesToFilter(this.appliesToFilter, new ImplementsMethodAppliesToFilter());
                }
            }

            var appliesTo = modifierClass.GetAttribute<AppliesToAttribute>();
            if (appliesTo != null)
            {
                foreach (Type appliesToClass in appliesTo.AppliesToTypes)
                {
                    AppliesToFilter filter;
                    if (typeof(AppliesToFilter).IsAssignableFrom(appliesToClass))
                    {
                        try
                        {
                            filter = (AppliesToFilter)appliesToClass.NewInstance();
                        }
                        catch (Exception e)
                        {
                            throw; //new ConstructionException( e );
                        }
                    }
                    else if (typeof(Attribute).IsAssignableFrom(appliesToClass))
                    {
                        filter = new AnnotationAppliesToFilter(appliesToClass);
                    }
                    else // Type check
                    {
                        filter = new TypeCheckAppliesToFilter(appliesToClass);
                    }

                    this.appliesToFilter = this.appliesToFilter == null ? filter : new AndAppliesToFilter(this.appliesToFilter, filter);
                }
            }

            if (this.appliesToFilter == null)
            {
                this.appliesToFilter = AppliesToEverything.Instance;
            }
        }
示例#27
0
        string DumpData(Type type, object data)
        {
            var dumpData = type.GetAttribute<DumpDataClassAttribute>(false);
            if(dumpData != null)
                return dumpData.Dump(type, data);

            var memberCheck = Configuration.GetMemberCheck(type);
            var results = type
                .GetFields(AnyBinding)
                .Cast<MemberInfo>()
                .Concat(type.GetProperties(AnyBinding))
                .Where(memberInfo => IsRelevant(memberInfo, type, data))
                .Where(memberInfo => memberCheck(memberInfo, data))
                .Select(memberInfo => Format(memberInfo, data))
                .ToArray();
            return FormatMemberDump(results);
        }
        internal static RuntimeSerializableAttribute GetRuntimeSerializableAttribute(Type _objectType)
        {
            RuntimeSerializableAttribute _serializableAttr	= null;

            lock (serializableAttributeCache)
            {
                // If cached value doesnt exist, then check if object implements RuntimeSerializableAttribute
                if (!serializableAttributeCache.TryGetValue(_objectType, out _serializableAttr))
                {
                    _serializableAttr						= _objectType.GetAttribute<RuntimeSerializableAttribute>(false);

                    // Add it to cache collection
                    serializableAttributeCache[_objectType]	= _serializableAttr;
                }
            }

            return _serializableAttr;
        }
示例#29
0
        void ConfigureDlg()
        {
            OrmMain.Count++;
            number = OrmMain.Count;
            logger.Debug("Открытие {0}", number);
            Mode       = OrmReferenceMode.Normal;
            ButtonMode = ReferenceButtonMode.CanAll;
            IOrmObjectMapping map = OrmMain.GetObjectDescription(objectType);

            if (map != null)
            {
                map.ObjectUpdated += OnRefObjectUpdated;
                TableView          = map.TableView;
                if (map.RefFilterClass != null)
                {
                    FilterClass = map.RefFilterClass;
                }
            }
            else
            {
                throw new InvalidOperationException(String.Format("Для использования диалога, класс {0} должен быть добавлен в мапинг OrmMain.ClassMappingList.", objectType));
            }
            object[] att = objectType.GetCustomAttributes(typeof(AppellativeAttribute), true);
            if (att.Length > 0)
            {
                this.TabName = (att [0] as AppellativeAttribute).NominativePlural.StringToTitleCase();
            }
            var defaultMode = objectType.GetAttribute <DefaultReferenceButtonModeAttribute>(true);

            if (defaultMode != null)
            {
                ButtonMode = defaultMode.ReferenceButtonMode;
            }

            if (!String.IsNullOrWhiteSpace(map.EditPermisionName))
            {
                if (!QSMain.User.Permissions [map.EditPermisionName])
                {
                    ButtonMode &= ~ReferenceButtonMode.CanAll;
                }
            }
            UpdateObjectList();
            ytreeviewRef.Selection.Changed += OnTreeviewSelectionChanged;
        }
示例#30
0
        public FormHelper(Type formModelType, Dictionary<T4DataType, string> fieldTypeTemplates, string defaultHtmlTemplate, string tag)
        {
            this.FormModelType = formModelType;
            this.FieldTypeTemplates = fieldTypeTemplates;
            this.DefaultHtmlTemplate = defaultHtmlTemplate;
            this.Tag = tag;
            //组特性
            var t4FormGroupAttribute = formModelType.GetAttribute<T4FormGroupAttribute>(false);
            if (t4FormGroupAttribute != null)
                this.IsEnableFormGroup = true;

            this.T4PropertyInfos = formModelType.GetT4PropertyInfos();
            if (this.IsEnableFormGroup)
            {
                this.DefaultGroupName = t4FormGroupAttribute.GroupName;
                this.Groups = this.T4PropertyInfos.Where(p => p.T4GroupInfo != null).Select(p => p.T4GroupInfo.Name).Distinct().ToList();
                if (!this.Groups.Contains(t4FormGroupAttribute.GroupName)) this.Groups.Add(t4FormGroupAttribute.GroupName);
            }
        }
示例#31
0
        public ISuiteProvider Load(Type suiteType, IDictionary<Type, Lazy<IAssemblySetup>> assemblySetups, IIdentity assemblyIdentity)
        {
            var uninitializedSuite = FormatterServices.GetUninitializedObject(suiteType);

              var subjectAttribute = suiteType.GetAttributeData<SuiteAttributeBase>();
              var displayFormatAttribute = subjectAttribute.Constructor.GetAttributeData<DisplayFormatAttribute>();

              var text = _introspectionPresenter.Present(displayFormatAttribute.ToCommon(), suiteType.ToCommon(), subjectAttribute.ToCommon());
              var identity = assemblyIdentity.CreateChildIdentity(suiteType.FullName);
              var resources = suiteType.GetAttribute<ResourcesAttribute>().GetValueOrDefault(x => x.Resources, () => new string[0]);
              var provider = SuiteProvider.Create(identity, text, ignored: false, resources: resources);

              InitializeAssemblySetupFields(uninitializedSuite, assemblySetups);
              InitializeTypeSpecificFields(uninitializedSuite, provider);

              InvokeConstructor(uninitializedSuite);

              return provider;
        }
示例#32
0
文件: Exec.cs 项目: njmube/lazaro
        private static object ExecCrearEditar(bool crear, string comando)
        {
            string SubComando = Lfx.Types.Strings.GetNextToken(ref comando, " ").Trim();

            System.Type TipoLbl = Lbl.Instanciador.InferirTipo(SubComando);
            Lbl.Atributos.Nomenclatura AtrNombre = TipoLbl.GetAttribute <Lbl.Atributos.Nomenclatura>();

            if (crear && Lbl.Sys.Config.Actual.UsuarioConectado.TienePermiso(TipoLbl, Lbl.Sys.Permisos.Operaciones.Crear) == false)
            {
                return(new Lfx.Types.NoAccessOperationResult());
            }

            if (Lbl.Sys.Config.Actual.UsuarioConectado.TienePermiso(TipoLbl, Lbl.Sys.Permisos.Operaciones.Ver) == false)
            {
                return(new Lfx.Types.NoAccessOperationResult());
            }

            var ConnEditar = Lfx.Workspace.Master.GetNewConnection("Editar " + (AtrNombre == null ? SubComando : AtrNombre.NombreSingular)) as Lfx.Data.Connection;

            Lbl.IElementoDeDatos Elemento = null;
            if (crear)
            {
                Elemento = Lbl.Instanciador.Instanciar(TipoLbl, ConnEditar);
                Elemento.Crear();
            }
            else
            {
                int ItemId = Lfx.Types.Parsing.ParseInt(Lfx.Types.Strings.GetNextToken(ref comando, " "));
                Elemento = Lbl.Instanciador.Instanciar(TipoLbl, ConnEditar, ItemId);
            }

            Lfc.FormularioEdicion FormularioDeEdicion = Lfc.Instanciador.InstanciarFormularioEdicion(Elemento);
            FormularioDeEdicion.DisposeConnection = true;

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

            return(FormularioDeEdicion);
        }
示例#33
0
        void ConfigureDlg()
        {
            Mode              = OrmReferenceMode.Normal;
            ButtonMode        = ReferenceButtonMode.CanAll;
            buttonAdd.Visible = buttonEdit.Visible = buttonDelete.Visible = objectType != null;
            if (objectType != null)
            {
                object[] att = objectType.GetCustomAttributes(typeof(AppellativeAttribute), true);
                if (att.Length > 0)
                {
                    this.TabName = (att[0] as AppellativeAttribute).NominativePlural.StringToTitleCase();
                }

                var defaultMode = objectType.GetAttribute <DefaultReferenceButtonModeAttribute>(true);
                if (defaultMode != null)
                {
                    ButtonMode = defaultMode.ReferenceButtonMode;
                }
            }
            ormtableview.Selection.Changed += OnTreeviewSelectionChanged;
        }
示例#34
0
        public void BindEntity()
        {
            persistentClass.IsAbstract = annotatedClass.IsAbstract;
            persistentClass.ClassName  = annotatedClass.Name;
            persistentClass.NodeName   = name;
            //TODO:review this
            //persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
            persistentClass.EntityName = (annotatedClass.Name);
            BindDiscriminatorValue();

            persistentClass.IsLazy = lazy;
            if (proxyClass != null)
            {
                persistentClass.ProxyInterfaceName = proxyClass.Name;
            }
            persistentClass.DynamicInsert = dynamicInsert;
            persistentClass.DynamicUpdate = dynamicUpdate;

            if (persistentClass is RootClass)
            {
                RootClass rootClass = (RootClass)persistentClass;
                bool      mutable   = true;
                //priority on @Immutable, then @Entity.mutable()
                if (annotatedClass.IsAttributePresent <ImmutableAttribute>())
                {
                    mutable = false;
                }
                else
                {
                    var entityAnn = annotatedClass.GetAttribute <EntityAttribute>();
                    if (entityAnn != null)
                    {
                        mutable = entityAnn.IsMutable;
                    }
                }
                rootClass.IsMutable = mutable;
                rootClass.IsExplicitPolymorphism = ExplicitPolymorphismConverter.Convert(polymorphismType);
                if (StringHelper.IsNotEmpty(where))
                {
                    rootClass.Where = where;
                }

                if (cacheConcurrentStrategy != null)
                {
                    rootClass.CacheConcurrencyStrategy = cacheConcurrentStrategy;
                    rootClass.CacheRegionName          = cacheRegion;
                    //TODO: LazyPropertiesCacheable
                    //rootClass.LazyPropertiesCacheable =  cacheLazyProperty ;
                }
                rootClass.IsForceDiscriminator = annotatedClass.IsAttributePresent <ForceDiscriminatorAttribute>();
            }
            else
            {
                if (explicitHibernateEntityAnnotation)
                {
                    log.WarnFormat("[NHibernate.Annotations.Entity] used on a non root entity: ignored for {0}", annotatedClass.Name);
                }
                if (annotatedClass.IsAttributePresent <ImmutableAttribute>())
                {
                    log.WarnFormat("[Immutable] used on a non root entity: ignored for {0}", annotatedClass.Name);
                }
            }
            persistentClass.OptimisticLockMode = OptimisticLockModeConverter.Convert(optimisticLockType);
            persistentClass.SelectBeforeUpdate = selectBeforeUpdate;

            //set persister if needed
            //[Persister] has precedence over [Entity.persister]
            var persisterAnn = annotatedClass.GetAttribute <PersisterAttribute>();

            System.Type persister = null;
            if (persisterAnn != null)
            {
                persister = persisterAnn.Implementation;
            }
            else
            {
                var entityAnn = annotatedClass.GetAttribute <EntityAttribute>();
                if (entityAnn != null && !BinderHelper.IsDefault(entityAnn.Persister))
                {
                    try
                    {
                        persister = ReflectHelper.ClassForName(entityAnn.Persister);
                    }
                    catch (TypeLoadException tle)
                    {
                        throw new AnnotationException("Could not find persister class: " + persister, tle);
                    }
                }
            }
            if (persister != null)
            {
                persistentClass.EntityPersisterClass = persister;
            }
            persistentClass.BatchSize = batchSize;

            //SQL overriding
            var sqlInsert    = annotatedClass.GetAttribute <SQLInsertAttribute>();
            var sqlUpdate    = annotatedClass.GetAttribute <SQLUpdateAttribute>();
            var sqlDelete    = annotatedClass.GetAttribute <SQLDeleteAttribute>();
            var sqlDeleteAll = annotatedClass.GetAttribute <SQLDeleteAllAttribute>();
            var loader       = annotatedClass.GetAttribute <LoaderAttribute>();

            if (sqlInsert != null)
            {
                persistentClass.SetCustomSQLInsert(sqlInsert.Sql.Trim(), sqlInsert.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlInsert.Check));
            }
            if (sqlUpdate != null)
            {
                persistentClass.SetCustomSQLUpdate(sqlUpdate.Sql.Trim(), sqlUpdate.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlUpdate.Check));
            }
            if (sqlDelete != null)
            {
                persistentClass.SetCustomSQLDelete(sqlDelete.Sql, sqlDelete.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlDelete.Check));
            }
            if (sqlDeleteAll != null)
            {
                persistentClass.SetCustomSQLDelete(sqlDeleteAll.Sql, sqlDeleteAll.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlDeleteAll.Check));
            }
            if (loader != null)
            {
                persistentClass.LoaderName = loader.NamedQuery;
            }

            //tuplizers
            if (annotatedClass.IsAttributePresent <TuplizerAttribute>())
            {
                foreach (TuplizerAttribute tuplizer in annotatedClass.GetAttributes <TuplizerAttribute>())
                {
                    var mode = EntityModeConverter.Convert(tuplizer.EntityMode);
                    persistentClass.AddTuplizer(mode, tuplizer.Implementation.Name);
                }
            }
            if (annotatedClass.IsAttributePresent <TuplizerAttribute>())
            {
                var tuplizer = annotatedClass.GetAttribute <TuplizerAttribute>();
                var mode     = EntityModeConverter.Convert(tuplizer.EntityMode);
                persistentClass.AddTuplizer(mode, tuplizer.Implementation.Name);
            }

            if (!inheritanceState.HasParents)
            {
                var iter = filters.GetEnumerator();
                while (iter.MoveNext())
                {
                    var    filter     = iter.Current;
                    String filterName = filter.Key;
                    String cond       = filter.Value;
                    if (BinderHelper.IsDefault(cond))
                    {
                        FilterDefinition definition = mappings.GetFilterDefinition(filterName);
                        cond = definition == null ? null : definition.DefaultFilterCondition;
                        if (StringHelper.IsEmpty(cond))
                        {
                            throw new AnnotationException("no filter condition found for filter " + filterName + " in " + name);
                        }
                    }
                    persistentClass.AddFilter(filterName, cond);
                }
            }
            else
            {
                if (filters.Count > 0)
                {
                    log.WarnFormat("@Filter not allowed on subclasses (ignored): {0}", persistentClass.EntityName);
                }
            }
            log.DebugFormat("Import with entity name {0}", name);

            try
            {
                mappings.AddImport(persistentClass.EntityName, name);
                String entityName = persistentClass.EntityName;
                if (!entityName.Equals(name))
                {
                    mappings.AddImport(entityName, entityName);
                }
            }
            catch (MappingException me)
            {
                throw new AnnotationException("Use of the same entity name twice: " + name, me);
            }
        }
 protected override bool ValidateClassAttribute(System.Type type)
 {
     return(type.GetAttribute <TC>() != null);
 }
示例#36
0
        private InstanceBox AutoResolveExpectType(Type expectType, bool singletonMode = false)
        {
            if (this.DisabledAutoResolving)
            {
                return(null);
            }

            Type actualType;
            var  defaultMappingAttr = expectType.GetAttribute <DefaultMappingAttribute>();

            if (defaultMappingAttr != null)
            {
                actualType = defaultMappingAttr.ActualType;
            }
            else
            {
                //- 智能解析方式,不支持基类或值类型
                if ((expectType.IsClass && expectType.IsAbstract) || expectType.IsValueType)
                {
                    return(null);
                }
                if (!expectType.IsInterface)
                {
                    return(this.InnerMapType(expectType, null, singletonMode));
                }

                //- 从映射事件获取
                var instance = this.OnMapResolve(expectType);
                if (instance != null)
                {
                    this.Map(expectType, instance);
                    return(instance);
                }

                actualType = null;

                //- 从智能映射表中获取(当前程序集)
                var fullNames = DefaultMapFilter.GetAllActualType(expectType);
                foreach (var fullName in fullNames)
                {
                    actualType = expectType.Assembly.GetType(fullName, false);
                    if (actualType != null)
                    {
                        break;
                    }
                }

                //- 从智能映射表中获取(所有程序集)
                if (actualType == null)
                {
                    actualType = DefaultMapFilter.FindActualType(ObjectFactory.AllTypes, expectType, fullNames);
                    if (actualType == null)
                    {
                        return(null);
                    }
                }
                //- 判定实际类型是否已注册
                if (this.CacheType.TryGetValue(actualType, out instance))
                {
                    this.Map(expectType, instance);
                    return(instance);
                }
            }
            //- 解析实际类型和预期类型
            return(this.InnerMapType(actualType, expectType, singletonMode));
        }