public static bool ExcludeKnownAttrsFilter(Attribute x)
 {
     return x.GetType() != typeof(RouteAttribute)
         && x.GetType() != typeof(DescriptionAttribute)
         && x.GetType().Name != "DataContractAttribute"  //Type equality issues with Mono .NET 3.5/4
         && x.GetType().Name != "DataMemberAttribute";
 }
        public ClientValidationRule Translate(Attribute attribute)
        {
            Type type = attribute.GetType();

            if (type == typeof(RegexValidatorAttribute))
            {
                return new RegexClientValidationRule((attribute as RegexValidatorAttribute).Pattern);
            }
            #pragma warning disable 0612
            else if (type == typeof(StringLengthValidatorAttribute))
            {
                return new StringLengthClientValidationRule((attribute as StringLengthValidatorAttribute).LowerBound, (attribute as StringLengthValidatorAttribute).UpperBound);
            }
            #pragma warning restore 0612
            else if (type == typeof(StringSizeValidatorAttribute))
            {
                return new StringLengthClientValidationRule((attribute as StringSizeValidatorAttribute).LowerBound, (attribute as StringSizeValidatorAttribute).UpperBound);
            }

            else if (type == typeof(Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidatorAttribute))
            {
                return new NotNullClientValidationRule();
            }
            else
            {
                throw new InvalidOperationException(string.Format("The attribute type '{0}' is not supported", attribute.GetType()));
            }
        }
        internal static string BuildResourceKey(string keyPrefix, Attribute attribute)
        {
            if(attribute == null)
                throw new ArgumentNullException(nameof(attribute));

            var result = BuildResourceKey(keyPrefix, attribute.GetType());
            if(attribute.GetType().IsAssignableFrom(typeof(DataTypeAttribute)))
                result += ((DataTypeAttribute) attribute).DataType;

            return result;
        }
Esempio n. 4
0
		public static CustomAttributeBuilder CreateCustomAttribute(Attribute attribute)
		{
			Type attType = attribute.GetType();

			ConstructorInfo ci;

			object[] ctorArgs = GetConstructorAndArgs(attType, attribute, out ci);

			PropertyInfo[] properties;

			object[] propertyValues = GetPropertyValues(attType, out properties, attribute);

			FieldInfo[] fields;

			object[] fieldValues = GetFieldValues(attType, out fields, attribute);

			// here we are going to try to initialize the attribute with the collected arguments
			// if we are good (created successfuly) we return it, otherwise, it is ignored.
			try
			{
				Activator.CreateInstance(attType, ctorArgs);
				return new CustomAttributeBuilder(ci, ctorArgs, properties, propertyValues, fields, fieldValues);
			}
			catch
			{
				// there is no real way to log a warning here...
				Trace.WriteLine(@"Dynamic Proxy 2: Unable to find matching parameters for replicating attribute " + attType.FullName +
				                ".");
				return null;
			}
		}
        public static AttributeDeclaration GetAttributeDeclaration(Attribute attribute, ClientCodeGenerator textTemplateClientCodeGenerator, bool forcePropagation)
        {
            Type attributeType = attribute.GetType();

            // Check if this attribute should be blocked
            if (IsAttributeBlocked(attributeType))
            {
                return null;
            }

            ICustomAttributeBuilder cab = GetCustomAttributeBuilder(attributeType);
            AttributeDeclaration attributeDeclaration = null;
            if (cab != null)
            {
                try
                {
                    attributeDeclaration = cab.GetAttributeDeclaration(attribute);
                }
                catch (AttributeBuilderException)
                {
                    return null;
                }
                if (attributeDeclaration != null)
                {
                    if (!forcePropagation)
                    {
                        // Verify attribute's shared type|property|method requirements are met
                        ValidateAttributeDeclarationRequirements(attributeDeclaration, textTemplateClientCodeGenerator);
                    }
                }
            }

            return attributeDeclaration;
        }
        // public methods
        /// <summary>
        /// Apply an attribute to these serialization options and modify the options accordingly.
        /// </summary>
        /// <param name="serializer">The serializer that these serialization options are for.</param>
        /// <param name="attribute">The serialization options attribute.</param>
        public override void ApplyAttribute(IBsonSerializer serializer, Attribute attribute)
        {
            EnsureNotFrozen();
            var itemSerializer = serializer.GetItemSerializationInfo().Serializer;
            if (_itemSerializationOptions == null)
            {
                var itemDefaultSerializationOptions = itemSerializer.GetDefaultSerializationOptions();

                // special case for legacy collections: allow BsonRepresentation on object
                if (itemDefaultSerializationOptions == null &&
                    (serializer.GetType() == typeof(EnumerableSerializer) || serializer.GetType() == typeof(QueueSerializer) || serializer.GetType() == typeof(StackSerializer)) &&
                    attribute.GetType() == typeof(BsonRepresentationAttribute))
                {
                    itemDefaultSerializationOptions = new RepresentationSerializationOptions(BsonType.Null); // will be modified later by ApplyAttribute
                }

                if (itemDefaultSerializationOptions == null)
                {
                    var message = string.Format(
                        "A serialization options attribute of type {0} cannot be used when the serializer is of type {1} and the item serializer is of type {2}.",
                        BsonUtils.GetFriendlyTypeName(attribute.GetType()),
                        BsonUtils.GetFriendlyTypeName(serializer.GetType()),
                        BsonUtils.GetFriendlyTypeName(itemSerializer.GetType()));
                    throw new NotSupportedException(message);
                }

                _itemSerializationOptions = itemDefaultSerializationOptions.Clone();
            }
            _itemSerializationOptions.ApplyAttribute(itemSerializer, attribute);
        }
        public void Initialize(Attribute attribute)
        {
            //Get all parametters of the Attribute: the name and their values.
            //For example:
            //In LengthAttribute the parametter are Min and Max.
            System.Type clazz = attribute.GetType();

            IRuleArgs ruleArgs = attribute as IRuleArgs;

            if (ruleArgs == null)
            {
                throw new ArgumentException("Attribute " + clazz + " doesn't implement IRuleArgs interface.");
            }
            else
            {
                if (ruleArgs.Message == null)
                {
                    throw new ArgumentException(string.Format("The value of the message in {0} attribute is null (nothing for VB.Net Users). Add some message ", clazz) +
            "on the attribute to solve this issue. For Example:\n" +
            "- private string message = \"Error on property Foo\";\n" +
            "Or you can use interpolators with resources files:\n" +
            "-private string message = \"{validator.MyValidatorMessage}\";");
                }

                attributeMessage = ruleArgs.Message;
            }

            foreach (PropertyInfo property in clazz.GetProperties())
            {
                attributeParameters.Add(property.Name.ToLowerInvariant(), property.GetValue(attribute, null));
            }
        }
Esempio n. 8
0
 public int CompareTo(Attribute t)
 {
     if (t.GetType() == typeof(DateAttribute))
         return this._date.CompareTo((DateTime)t.Value);
     else
         return -1;
 }
		public CustomAttributeBuilder Disassemble(Attribute attribute)
		{
			var type = attribute.GetType();

			try
			{
				IConstructorInfo ctor;
				var ctorArgs = GetConstructorAndArgs(type, attribute, out ctor);
				var replicated = (Attribute)Activator.CreateInstance(type, ctorArgs);
				IPropertyInfo[] properties;
				var propertyValues = GetPropertyValues(type, out properties, attribute, replicated);
				IFieldInfo[] fields;
				var fieldValues = GetFieldValues(type, out fields, attribute, replicated);
                
#if !NETFX_CORE
                return new CustomAttributeBuilder(ctor.AsConstructorInfo(), ctorArgs, 
                    DotNetFixup.AsPropertyInfos(properties).ToArray(), propertyValues, 
                    DotNetFixup.AsFieldInfos(fields).ToArray(), fieldValues);
#else
                return new CustomAttributeBuilder(ctor, ctorArgs, properties, propertyValues, fields, fieldValues);
#endif
            }
			catch (Exception ex)
			{
				// there is no real way to log a warning here...
				return HandleError(type, ex);
			}
		}
Esempio n. 10
0
 public Mapping(PropertyInfo propertyInfo, IGenerator <T> generator)
 {
     PropertyName = propertyInfo.Name;
     PropertyInfo = propertyInfo;
     object[] a = propertyInfo.GetCustomAttributes(false);
     foreach (var item in a)
     {
         try
         {
             System.Attribute attr = (System.Attribute)item;
             //TODO: Refactor this out to be more flexible and support more annotations
             if (attr.GetType() == typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute))
             {
                 System.ComponentModel.DataAnnotations.StringLengthAttribute sla = (System.ComponentModel.DataAnnotations.StringLengthAttribute)attr;
                 if (generator.GetType() == typeof(Generators.TextGenerator))
                 {
                     generator = (IGenerator <T>) new Generators.TextGenerator(sla.MaximumLength);
                 }
             }
         }
         catch (Exception)
         {
             throw;
         }
     }
     Generator = generator;
 }
 public NavigationTypeNotSupportedException(Attribute attribute, string elementName)
     : base(string.Format(@"A navigation attribute of '{0}' was found on your page object, " +
                          "but your driver doesn't currently support this navigation method.\r\n" +
                          "Navigating to the element identified by the property '{1}' failed.", 
         attribute.GetType().Name, elementName))
 {
     Attribute = attribute;
 }
Esempio n. 12
0
 internal override void ProcessMethod(XElement element, MethodInfo method, Attribute annotation)
 {
     ProcessorBase processor;
     if (processors.TryGetValue(annotation.GetType().Name, out processor))
     {
         processor.ProcessMethod(element, method, annotation);
     }
 }
Esempio n. 13
0
		public bool Contains (Attribute attr)
		{
			Attribute at = this [attr.GetType ()];
			if (at != null)
				return attr.Equals (at);
			else
				return false;
		}
Esempio n. 14
0
 internal override void ProcessProperty(XElement element, PropertyInfo property, Attribute annotation)
 {
     ProcessorBase processor;
     if (processors.TryGetValue(annotation.GetType().Name, out processor))
     {
         processor.ProcessProperty(element, property, annotation);
     }
 }
Esempio n. 15
0
 internal override void ProcessType(XElement element, Type type, Attribute annotation)
 {
     ProcessorBase processor;
     if (processors.TryGetValue(annotation.GetType().Name, out processor))
     {
         processor.ProcessType(element, type, annotation);
     }
 }
Esempio n. 16
0
 internal override void ProcessParameter(XElement parent, ParameterInfo parameter, Attribute annotation)
 {
     ProcessorBase processor;
     if (processors.TryGetValue(annotation.GetType().Name, out processor))
     {
         processor.ProcessParameter(parent, parameter, annotation);
     }
 }
        private IEnumerable GetActionFilters(Attribute attribute)
        {
            var filterType = typeof(IActionFilter<>).MakeGenericType(attribute.GetType());

            var filters = this.container.Invoke(filterType);

            return filters;
        }
 private DriverBindings.IHandle SelectHandlerForNavigationAttribute(Attribute attr, PropertyInfo property)
 {
     var attributeHandler = _driver.NavigationHandlers.SingleOrDefault(map => attr.GetType() == map.AttributeType);
     if (attributeHandler == null)
     {
         throw new NavigationTypeNotSupportedException(attr, property.Name);
     }
     return attributeHandler;
 }
 /// <summary>
 /// Get all attribute properties with values for a specific attribute type
 /// </summary>
 /// <param name="attribute">attribute to check against</param>
 /// <returns>collection of all properties with values</returns>
 public static IDictionary<string, object> GetAttributeProperties(Attribute attribute)
 {
     Type attributeType = attribute.GetType();
     IDictionary<string, object> attributes = new Dictionary<string, object>();
     foreach(var property in attributeType.GetProperties())
     {
         object value = property.GetValue(attribute, null);
         attributes.Add(property.Name, value);
     }
     return attributes;
 }
Esempio n. 20
0
        private IEnumerable<object> GetMappers(Attribute attribute)
        {
            ConcurrentBag<object> mappers;

            if (_mappersByAttrType.TryGetValue(attribute.GetType(), out mappers))
            {
                return mappers.ToList();
            }

            return Enumerable.Empty<object>();
        }
Esempio n. 21
0
 private static IRegExFacet Create(Attribute attribute, IFacetHolder holder) {
     if (attribute == null) {
         return null;
     }
     if (attribute is RegularExpressionAttribute) {
         return Create((RegularExpressionAttribute) attribute, holder);
     }
     if (attribute is RegExAttribute) {
         return Create((RegExAttribute) attribute, holder);
     }
     throw new ArgumentException("Unexpected attribute type: " + attribute.GetType());
 }
 private static IDescribedAsFacet Create(Attribute attribute, IFacetHolder holder) {
     if (attribute == null) {
         return null;
     }
     if (attribute is DescribedAsAttribute) {
         return Create((DescribedAsAttribute) attribute, holder);
     }
     if (attribute is DescriptionAttribute) {
         return Create((DescriptionAttribute) attribute, holder);
     }
     throw new ArgumentException("Unexpected attribute type: " + attribute.GetType());
 }
 private INamedFacet Create(Attribute attribute, IFacetHolder holder) {
     if (attribute == null) {
         return null;
     }
     if (attribute is NamedAttribute) {
         return new NamedFacetAnnotation(((NamedAttribute) attribute).Value, holder);
     }
     if (attribute is DisplayNameAttribute) {
         return new NamedFacetAnnotation(((DisplayNameAttribute) attribute).DisplayName, holder);
     }
     throw new ArgumentException("Unexpected attribute type: " + attribute.GetType());
 }
 ServiceScope ServiceNameToEnum(Attribute serviceAttr)
 {
     //if (typeName.StartsWith("IClient"))
     //{
     //    return ServiceScope.ServerToClient;
     //}
     //if (typeName.EndsWith("ClientService"))
     //{
     //    return ServiceScope.ClientToServer;
     //}
     return (ServiceScope)serviceAttr.GetType().GetProperty("ServiceScope").GetValue(serviceAttr, null);
 }
 private INamedFacet CreateProperty(Attribute attribute, IFacetHolder holder) {
     if (attribute == null) {
         return SaveDefaultName(holder);
     }
     if (attribute is NamedAttribute) {
         return Create((NamedAttribute) attribute, holder);
     }
     if (attribute is DisplayNameAttribute) {
         return Create((DisplayNameAttribute) attribute, holder);
     }
     throw new ArgumentException("Unexpected attribute type: " + attribute.GetType());
 }
Esempio n. 26
0
        private static IMaxLengthFacet Create(Attribute attribute, IFacetHolder holder) {
            if (attribute == null) {
                return null;
            }
            if (attribute is StringLengthAttribute) {
                return Create((StringLengthAttribute) attribute, holder);
            }
            if (attribute is MaxLengthAttribute) {
                return Create((MaxLengthAttribute) attribute, holder);
            }

            throw new ArgumentException("Unexpected attribute type: " + attribute.GetType());
        }
        protected int GetArgumentSemantic(MethodInfo p)
        {
            if (p == null)
            {
                return(0);
            }

            System.Attribute attr = System.Attribute.GetCustomAttributes(p).FirstOrDefault(x => x.GetType().Name == "ExportAttribute");
            if (attr != null)
            {
                return((int)attr.GetType().GetProperty("ArgumentSemantic").GetValue(attr, null));
            }
            return(0);
        }
 private INamedFacet Create(Attribute attribute, ISpecification holder) {
     if (attribute == null) {
         return null;
     }
     var namedAttribute = attribute as NamedAttribute;
     if (namedAttribute != null) {
         return new NamedFacetAnnotation(namedAttribute.Value, holder);
     }
     var nameAttribute = attribute as DisplayNameAttribute;
     if (nameAttribute != null) {
         return new NamedFacetAnnotation(nameAttribute.DisplayName, holder);
     }
     throw new ArgumentException(Log.LogAndReturn($"Unexpected attribute type: {attribute.GetType()}"));
 }
 private static IDescribedAsFacet Create(Attribute attribute, ISpecification holder) {
     if (attribute == null) {
         return null;
     }
     var asAttribute = attribute as DescribedAsAttribute;
     if (asAttribute != null) {
         return Create(asAttribute, holder);
     }
     var descriptionAttribute = attribute as DescriptionAttribute;
     if (descriptionAttribute != null) {
         return Create(descriptionAttribute, holder);
     }
     throw new ArgumentException(Log.LogAndReturn($"Unexpected attribute type: {attribute.GetType()}"));
 }
 private static IRegExFacet Create(Attribute attribute, ISpecification holder) {
     if (attribute == null) {
         return null;
     }
     var expressionAttribute = attribute as RegularExpressionAttribute;
     if (expressionAttribute != null) {
         return Create(expressionAttribute, holder);
     }
     var exAttribute = attribute as RegExAttribute;
     if (exAttribute != null) {
         return Create(exAttribute, holder);
     }
     throw new ArgumentException(Log.LogAndReturn($"Unexpected attribute type: {attribute.GetType()}"));
 }
Esempio n. 31
0
        protected string GetSelector(MethodInfo p)
        {
            if (p == null)
            {
                return(null);
            }

            System.Attribute attr = System.Attribute.GetCustomAttributes(p).FirstOrDefault(x => x.GetType().Name == "ExportAttribute");
            if (attr != null)
            {
                return((string)attr.GetType().GetProperty("Selector").GetValue(attr, null));
            }
            return(null);
        }
        private static IMaxLengthFacet Create(Attribute attribute, ISpecification holder) {
            if (attribute == null) {
                return null;
            }
            var lengthAttribute = attribute as StringLengthAttribute;
            if (lengthAttribute != null) {
                return Create(lengthAttribute, holder);
            }
            var maxLengthAttribute = attribute as MaxLengthAttribute;
            if (maxLengthAttribute != null) {
                return Create(maxLengthAttribute, holder);
            }

            throw new ArgumentException("Unexpected attribute type: " + attribute.GetType());
        }
        /// <summary>
        /// Get the default name value of an attribute and a specific property
        /// </summary>
        /// <param name="attribute">attribute from where to get the default value</param>
        /// <param name="propertyName">property to get the default value</param>
        /// <returns></returns>
        public static object GetDefaultValue(Attribute attribute, string propertyName)
        {
            Type attributeType = attribute.GetType();
            try
            {
                var property = attributeType.GetProperty(propertyName);
                if (property == null)
                    return null;
                var instance = Activator.CreateInstance(attributeType);

                return property.GetValue(instance, null);
            }
            catch (Exception)
            {
                return null;
            }
        }
Esempio n. 34
0
        private void AnalyzeRelation(FieldInfo fi, XmlElement pc, XmlDocument doc, System.Attribute attr, IList relations)
        {
            XmlElement fn        = doc.CreateElement("Relation");
            bool       isElement = false;

            if (fi.FieldType.Name == "IList" || fi.FieldType.GetInterface("IList") != null)
            {
                fn.SetAttribute("Type", "Liste");
            }
            else
            {
                fn.SetAttribute("Type", "Element");
                isElement = true;
            }

            fn.SetAttribute("DataType", MakeElementTypeName(fi.FieldType));
            if (fi.DeclaringType != fi.ReflectedType)
            {
                fn.SetAttribute("DeclaringType", MakeElementTypeName(fi.DeclaringType));
            }
            fn.SetAttribute("Name", fi.Name);

            Type attrType = attr.GetType();

            string relName     = string.Empty;
            string relTypeName = string.Empty;

            FieldInfo[] fields = attrType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (FieldInfo attrf in fields)
            {
                Type fieldType = attrf.FieldType;
                // RelationName auslesen
                if (fieldType == typeof(string))
                {
                    if (null != attrf)
                    {
                        relName = (string)attrf.GetValue(attr);
                    }
                    fn.SetAttribute("RelationName", relName);
                }
                if (fieldType.Name == "RelationInfo")
                {
                    // RelationInfo auslesen
                    object    relationInfo = attrf.GetValue(attr);
                    FieldInfo riValue      = relationInfo.GetType().GetField("value__", BindingFlags.Public | BindingFlags.Instance);
                    int       val          = (Int16)riValue.GetValue(relationInfo);
                    fn.SetAttribute("RelationInfo", val.ToString());
                }

                if (fieldType.Name == "Type")
                {
                    Type   theType;
                    string assName;
                    if (isElement)
                    {
                        theType = fi.FieldType;
                    }
                    else
                    {
                        theType = (Type)attrf.GetValue(attr);
                    }
                    if (theType != null)
                    {
                        assName = theType.Assembly.FullName;
                        assName = assName.Substring(0, assName.IndexOf(","));
                        if (assName != this.assShortName)
                        {
                            relTypeName = "[" + assName + "]" + theType.FullName;
                        }
                        else
                        {
                            relTypeName = theType.FullName;
                        }
                        fn.SetAttribute("RelatedType", relTypeName);
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine("Field: " + fi.Name + " Type: " + relTypeName + " Name: " + fn.Attributes["RelationName"].Value);
            System.Diagnostics.Debug.Indent();
            int  nr     = 1;
            bool repeat = true;

            while (repeat)
            {
                repeat = false;
                foreach (XmlElement rel in relations)
                {
                    System.Diagnostics.Debug.WriteLine("Name: " + rel.Attributes["Name"].Value + " RelType: " + rel.Attributes["RelatedType"].Value + " Name: " + rel.Attributes["RelationName"].Value);
                    if (rel.Attributes["RelatedType"].Value == relTypeName && rel.Attributes["RelationName"].Value == fn.Attributes["RelationName"].Value)
                    {
                        fn.SetAttribute("RelationName", relName + nr.ToString());
                        nr++;
                        repeat = true;
                        break;
                    }
                }
            }
            System.Diagnostics.Debug.Unindent();
            relations.Add(fn);
            pc.AppendChild(fn);
        }
Esempio n. 35
0
        //Insere tabela e retorna Id da linha adicionada
        public int Insert(T obj)
        {
            try
            {
                //Abre conexão e define variaveis iniciais
                conexao.Open();
                Type   tipo      = typeof(T);
                string pk        = "";
                string tableName = "";
                string query     = "";
                string fields    = "";
                string values    = "";

                //Verifica quantos objetos a excluir existem para tirar isso de virgulas da query
                int objectCount = 0;
                foreach (PropertyInfo info in tipo.GetProperties())
                {
                    System.Attribute tipoAtributo = info.GetCustomAttributes().FirstOrDefault();

                    if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("AttributeExcluir"))
                    {
                        objectCount++;
                    }
                }


                for (int i = 0; i < tipo.GetProperties().Count(); i++)
                {
                    //Verifica se atributo é PK e armazena para dar select depois de inserir
                    System.Attribute tipoAtributo = tipo.GetProperties()[i].GetCustomAttributes().FirstOrDefault();
                    if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("KeyAttribute"))
                    {
                        pk = tipo.GetProperties()[i].Name;
                    }
                    else if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("AttributeTable"))
                    {
                        tableName = tipo.GetProperties()[i].Name;
                    }
                    else
                    {
                        //Verifica atributo excluir, o mesmo não é para inserir no banco
                        if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("AttributeExcluir"))
                        {
                            continue;
                        }

                        //Preenche campos da tabela
                        fields += tipo.GetProperties()[i].Name;

                        //Preenche valores a inserir
                        values += formatValue(tipo.GetProperties()[i].GetValue(obj), tipo.GetProperties()[i].PropertyType);

                        //Adiciona virgula entre os valores ( -2 pois existem dois atributos não utilizados ID e table name) + Objetos não inseridos na query
                        if (i != tipo.GetProperties().Count() - (2 + objectCount))
                        {
                            fields += ",";
                            values += ",";
                        }
                    }
                }

                //Escreve a query para execução
                query += "Insert into " + tableName + "(" + fields + ") values(" + values + ")";

                //Executa query
                conexao.Execute(query);

                //Seleciona ID da linha adicionada
                query = "Select MAX(" + pk + ") from " + tableName;
                return(conexao.Query <int>(query).FirstOrDefault());
            }
            catch
            {
                return(-1);
            }
        }
Esempio n. 36
0
        //Da update no objeto e retorna true or false
        public bool Update(T obj)
        {
            //Abre conexão e define variaveis iniciais
            try
            {
                conexao.Open();
                Type   tipo      = typeof(T);
                string pk        = "";
                string tableName = "";
                string query     = "";
                string pkValue   = "";
                string values    = "";

                //Verifica quantos objetos a excluir existem para tirar isso de virgulas da query
                int objectCount = 0;
                foreach (PropertyInfo info in tipo.GetProperties())
                {
                    System.Attribute tipoAtributo = info.GetCustomAttributes().FirstOrDefault();

                    if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("AttributeExcluir"))
                    {
                        objectCount++;
                    }
                }


                for (int i = 0; i < tipo.GetProperties().Count(); i++)
                {
                    //Verifica se atributo é PK para usar na query
                    System.Attribute tipoAtributo = tipo.GetProperties()[i].GetCustomAttributes().FirstOrDefault();
                    if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("KeyAttribute"))
                    {
                        pk      = tipo.GetProperties()[i].Name;
                        pkValue = formatValue(tipo.GetProperties()[i].GetValue(obj), tipo.GetProperties()[i].GetValue(obj).GetType());
                    }
                    else if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("AttributeTable"))
                    {
                        tableName = tipo.GetProperties()[i].Name;
                    }
                    else
                    {
                        //Verifica atributo excluir, o mesmo não é para inserir no banco
                        if (tipoAtributo != null && tipoAtributo.GetType().ToString().Contains("AttributeExcluir"))
                        {
                            continue;
                        }

                        //Preenche valores a inserir
                        values += tipo.GetProperties()[i].Name + "=" + formatValue(tipo.GetProperties()[i].GetValue(obj), tipo.GetProperties()[i].GetValue(obj).GetType());

                        //Adiciona virgula entre os valores ( -2 pois existem dois atributos não utilizados ID e table name) + Objetos não inseridos na query
                        if (i != tipo.GetProperties().Count() - (2 + objectCount))
                        {
                            values += ", ";
                        }
                    }
                }

                //Escreve a query para execução
                query += "Update " + tableName + " SET " + values + " WHERE " + pk + "=" + pkValue;

                //Executa query
                if (conexao.Execute(query) != 0)
                {
                    return(true);
                }

                return(false);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 37
0
 private static void InternalSetAttribute(System.ComponentModel.MemberDescriptor memb, string property, System.Attribute newattrib, bool on)
 {
     System.Attribute oldattrib = memb.Attributes[newattrib.GetType()];
     System.Reflection.BindingFlags getflags   = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
     System.Reflection.BindingFlags setflags   = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.SetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
     System.Attribute[]             oldattribs = (System.Attribute[]) typeof(System.ComponentModel.MemberDescriptor).InvokeMember("attributes", getflags, null, memb, null);
     if (oldattrib != null)
     {
         if (on)
         {
             for (int i = 0; i < oldattribs.Length; i++)
             {
                 if (oldattribs[i].GetType().FullName == newattrib.GetType().FullName)
                 {
                     oldattribs[i] = newattrib;
                     break;
                 }
             }
             typeof(System.ComponentModel.MemberDescriptor).InvokeMember("attributeCollection", setflags, null, memb, new object[] { new System.ComponentModel.AttributeCollection(oldattribs) });
             typeof(System.ComponentModel.MemberDescriptor).InvokeMember("originalAttributes", setflags, null, memb, new object[] { oldattribs });
             if (newattrib is System.ComponentModel.EditorAttribute)
             {
                 object[] editors = new object[1];
                 System.ComponentModel.EditorAttribute editor = (System.ComponentModel.EditorAttribute)newattrib;
                 editors[0] = Type.GetType(editor.EditorTypeName).GetConstructors()[0].Invoke(new object[] { });
                 typeof(System.ComponentModel.PropertyDescriptor).InvokeMember("editors", setflags, null, memb, new object[] { editors });
                 typeof(System.ComponentModel.PropertyDescriptor).InvokeMember("editorCount", setflags, null, memb, new object[] { 1 });
                 Type[] editorTypes = new Type[1] {
                     Type.GetType(editor.EditorBaseTypeName)
                 };
                 typeof(System.ComponentModel.PropertyDescriptor).InvokeMember("editorTypes", setflags, null, memb, new object[] { editorTypes });
             }
         }
         else
         {
             System.Attribute[] newattribs = new System.Attribute[oldattribs.Length - 1];
             int i = 0;
             foreach (System.Attribute a in oldattribs)
             {
                 if (a.GetType().FullName != newattrib.GetType().FullName)
                 {
                     newattribs[i++] = a;
                 }
             }
             typeof(System.ComponentModel.MemberDescriptor).InvokeMember("attributes", setflags, null, memb, new object[] { newattribs });
             typeof(System.ComponentModel.MemberDescriptor).InvokeMember("originalAttributes", setflags, null, memb, new object[] { newattribs });
             typeof(System.ComponentModel.MemberDescriptor).InvokeMember("attributeCollection", setflags, null, memb, new object[] { new System.ComponentModel.AttributeCollection(newattribs) });
         }
     }
     else if (on)
     {
         System.Attribute[] newattribs = new System.Attribute[oldattribs.Length + 1];
         int i = 0;
         foreach (System.Attribute a in oldattribs)
         {
             newattribs[i++] = a;
         }
         newattribs[i++] = newattrib;
         typeof(System.ComponentModel.MemberDescriptor).InvokeMember("attributes", setflags, null, memb, new object[] { newattribs });
         typeof(System.ComponentModel.MemberDescriptor).InvokeMember("originalAttributes", setflags, null, memb, new object[] { newattribs });
         typeof(System.ComponentModel.MemberDescriptor).InvokeMember("attributeCollection", setflags, null, memb, new object[] { new System.ComponentModel.AttributeCollection(newattribs) });
     }
 }
Esempio n. 38
0
 private static Attribute Instantiate(this CustomAttributeData cad)
 {
     return /*cad.Instantiate ()*/ ((Attribute)Activator.CreateInstance(cad.GetType()));
 }