/// <summary>
		/// Helper method to find the Property <c>get</c>.
		/// </summary>
		/// <param name="type">The <see cref="System.Type"/> to find the Property in.</param>
		/// <param name="propertyName">The name of the mapped Property to get.</param>
		/// <returns>
		/// The <see cref="BasicGetter"/> for the Property <c>get</c> or <c>null</c>
		/// if the Property could not be found.
		/// </returns>
		internal static BasicGetter GetGetterOrNull( System.Type type, string propertyName )
		{
			
			if( type==typeof( object ) || type==null )
			{
				// the full inheritance chain has been walked and we could
				// not find the Property get
				return null;
			}

			PropertyInfo property = type.GetProperty( propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly );

			if( property != null )
			{
				return new BasicGetter( type, property, propertyName );
			}
			else
			{
				// recursively call this method for the base Type
				BasicGetter getter = GetGetterOrNull( type.BaseType, propertyName );
				
				// didn't find anything in the base class - check to see if there is 
				// an explicit interface implementation.
				if( getter == null )
				{
					System.Type[ ] interfaces = type.GetInterfaces();
					for( int i = 0; getter == null && i < interfaces.Length; i++ )
					{
						getter = GetGetterOrNull( interfaces[ i ], propertyName );
					}
				}
				return getter;
			}

		}
        private string ResolveName(string name, ref System.Type type)
        {
            if (_caseSensitive)
                return name;

            var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);

            if (property != null)
            {
                type = property.PropertyType;
                return property.Name;
            }

            var field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);

            if (field != null)
            {
                type = field.FieldType;
                return field.Name;
            }

            throw new QueryException(String.Format(
                "Cannot resolve name '{0}' on '{1}'", name, type)
            );
        }
        public FieldPropertyInfo(System.Type type, string fieldPropertyName)
        {
            this.memberInfo = null;
            FieldInfo field = type.GetField(fieldPropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (field != null)
            {
                this.memberInfo = field;
            }
            else
            {
                PropertyInfo property = type.GetProperty(fieldPropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (property != null)
                {
                    this.memberInfo = property;
                }
            }
            
			throw new Exception(string.Concat(new object[] { "FieldPropertyInfo: ", type, ", ", fieldPropertyName }));
		}
        /// <summary>
        /// Resolve a query name to an entity name.
        /// </summary>
        /// <param name="name">The name to map.</param>
        /// <param name="type">The type of the entity to map the name for.</param>
        /// <param name="caseSensitive">Whether the <param name="name"> parameter must be treated case sensitive.</param></param>
        /// <returns>The mapped name and member type or null when the name could not be resolved.</returns>
        public virtual ResolvedName ResolveName(string name, System.Type type, bool caseSensitive)
        {
            var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            if (!caseSensitive)
                bindingFlags |= BindingFlags.IgnoreCase;

            var property = type.GetProperty(name, bindingFlags);

            if (property != null)
                return new ResolvedName(property.PropertyType, property.Name);

            var field = type.GetField(name, bindingFlags);

            if (field != null)
                return new ResolvedName(field.FieldType, field.Name);

            return null;
        }
        public static object GetField(object target, System.Type type, string fieldName)
        {
            PropertyInfo property = type.GetProperty(fieldName);
            FieldInfo field = type.GetField(fieldName);

            if( null == property && null == field){
                XLogger.Log(type.Name + "." + " not contain " + fieldName);
                return null;
            }
            object returnValue = null;
            if( null != property )
                returnValue = property.GetValue(target, null);
            else if( null != field)
                returnValue = field.GetValue(target);
            if( null == returnValue){
                XLogger.Log(type.Name + "." + property.Name + " is null.");
                return null;
            }
            return returnValue;
        }
	// Attempt to locate the member as a property, and deal with it based on the given parameters
	// Returns: boolean indicating whether the command was handled here
	public static bool CallProperty(System.Type targetClass, string propertyName, string parameters) {
		// Attempt to find the property
		PropertyInfo targetProperty = targetClass.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
		object targetInstance = null;
		if(targetProperty == null) {
			targetInstance = GetMainOfClass(targetClass);
			if(targetInstance != null) {
				targetProperty = targetClass.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
			}
		}
		if(targetProperty == null || !IsAccessible(targetProperty)) { return false; } // Fail: Couldn't find property, or it's marked inaccessible
		// If field is found, deal with it appropriately based on the parameters given
		if(parameters == null || parameters.Length < 1) {
			string output = GetPropertyValue(targetInstance, targetProperty);
			if(output == null) { return false; } // Fail: Property is not of a supported type
			Echo(propertyName + " is " + output);
			return true; // Success: Value is printed when no parameters given
		}
		if(IsCheat(targetProperty) && !cheats) {
			PrintCheatMessage(targetProperty.Name);
		} else {
			if(!SetPropertyValue(targetInstance, targetProperty, parameters.SplitUnlessInContainer(' ', '\"'))) {
				Echo("Invalid " + targetProperty.PropertyType.Name + ": " + parameters);
			}
		}
		return true; // Success: Whether or not the field could be set (input was valid/invalid) the user is notified and the case is handled
	}
		/// <summary>
		/// Gets an <see cref="System.Collections.IComparer"/> for the given type and sort expression.
		/// </summary>
		/// <param name="type">The type of object to be sorted.</param>
		/// <param name="sortExpression">A sort expression, e.g., MyProperty ASC, MyProp2 DESC.</param>
		/// <returns>An <see cref="System.Collections.IComparer"/> for the given type and sort expression.</returns>
		protected System.Collections.IComparer GetMultiComparer(System.Type type, string sortExpression)
		{
			// split the sort expression string by the commas
			string[] sorts = sortExpression.Split(',');
			// if no sorts are present, throw an exception
			if (sorts.Length == 0)
				throw new ArgumentException("No sorts were passed in the sort expression.", "sortExpression");
			string typeName = type.FullName;
			// create a unique type name for the comparer based on the type and sort expression
			string comparerName = sortExpression.Replace(",", "").Replace(" ", "") + "Comparer",
				dynamicTypeName = typeName + "DynamicComparers." + comparerName;
			System.Collections.IComparer comparer = null;
			// check the comparers table for an existing comparer for this type and property
			if (!comparers.ContainsKey(dynamicTypeName)) // not found
			{
				object comparerLock;
				bool generate = false;
				// let threads pile up here waiting their turn to look at this collection
				lock (comparerLocks.SyncRoot)
				{
					// First, we see if the comparer lock for this
					// dynamicTypeName exists.
					comparerLock = comparerLocks[dynamicTypeName];
					if (comparerLock == null)
					{
						// This is the first thread in here looking for this
						// dynamicTypeName, so it gets to be the one to 
						// create the comparer for the dynamicTypeName.
						generate = true;
						// Add lock object for any future threads to see and 
						// know that they won't need to generate the comparer.
						comparerLock = new object();
						comparerLocks.Add(dynamicTypeName, comparerLock);
					}
				}
				// comparerLock will be unique per dynamicTypeName and, consequently,
				// per unique comparer.  However, the code above only ensures
				// that only one thread will do the generation of the comparer.
				// We now need to lock the comparerLock for each dynamicTypeName to
				// make non generating threads wait on the thread that is doing the 
				// generation, so we ensure that the comparer is generated for all 
				// threads by the time we exit the following block.
				lock (comparerLock)
				{
					// This ensures only that first thread in actually does any generation.
					if (generate)
					{
						// declare the source code for the dynamic assembly
						string compareCode = @"
using System;
namespace [TypeName]DynamicComparers
{
	public sealed class [ComparerName] : System.Collections.IComparer
	{
		public int Compare(object first, object second)
		{
			[TypeName] firstInstance = first as [TypeName];
			if (firstInstance == null)
				throw new ArgumentNullException(""First object cannot be null."", ""first"");
			[TypeName] secondInstance = second as [TypeName];
			if (secondInstance == null)
				throw new ArgumentNullException(""Second object cannot be null."", ""second"");
			int result = 0;
			[CompareCode]
		}
	}
}

";
						System.Text.StringBuilder compareBuilder = new System.Text.StringBuilder();
						string propertyName;
						bool desc;
						for (int sortIndex = 0; sortIndex < sorts.Length; sortIndex++)
						{
							// check current sort for null, continue if null
							if (sorts[sortIndex] == null)
								continue;
							// split current sort by space to distinguish property from asc/desc
							string[] sortValues = sorts[sortIndex].Trim().Split(' ');
							// if there are no values after split, leave -- should have at least the prop name
							if (sortValues.Length == 0)
								continue;
							// prop name will be first value
							propertyName = sortValues[0].Trim();
							// ensure property exists on specified type
							PropertyInfo prop = type.GetProperty(propertyName);
							if (prop == null)
								throw new ArgumentException(
									String.Format("Specified property '{0}' is not a property of type '{1}'.", 
									propertyName, type.FullName), "sortExpression");
							// if there, the second will be asc/desc; compare to get whether or not this
							// sort is descending
							desc = (sortValues.Length > 1) ? (sortValues[1].Trim().ToUpper() == "DESC") : false;
							// if property type is reference type, we need to do null checking in the compare code
							bool checkForNull = !prop.PropertyType.IsValueType;
							// check for null if the property is a reference type
							if (checkForNull) 
								compareBuilder.Append("\t\t\tif (firstInstance." + propertyName + " != null)\n\t");
							// compare the property
							compareBuilder.Append("\t\t\tresult = firstInstance." + propertyName + 
								".CompareTo(secondInstance." + propertyName + ");");
							// check for null on the second type, if necessary
							if (checkForNull)
							{
								// if second type is also null, return true; otherwise, the first instance is 
								// less than the second because it is null
								compareBuilder.Append("\t\t\telse if (secondInstance." + propertyName + " == null)\n");
								compareBuilder.Append("\t\t\t\tresult = 0;  else result = -1;\n");
							}
							// if the two are not equal, no further comparison is needed, just return the 
							// current compare value and flip the sign, if the current sort is descending
							compareBuilder.Append("\t\t\tif (result !=0) return " + (desc ? "-" : "") + "(result);\n");
						}
						// if all comparisons were equal, we'll need the next line to return that result
						compareBuilder.Append("\t\t\treturn result;");
						// replace the type and comparer name placeholders in the source with real values
						// and insert the property comparisons
						compareCode = compareCode.Replace("[TypeName]", typeName).Replace("[ComparerName]", comparerName)
							.Replace("[CompareCode]", compareBuilder.ToString());
#if TRACE
						System.Diagnostics.Debug.WriteLine(compareCode);
#endif
						// create a C# compiler instance
						ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
						// create a compiler parameters collection
						CompilerParameters parameters = new CompilerParameters();
						// add necessary assembly references for the source to compile
						string primeAssemblyPath = type.Assembly.Location.Replace("file:///", "").Replace("/", "\\");
						parameters.ReferencedAssemblies.Add(primeAssemblyPath);
						foreach (System.Reflection.AssemblyName asm in type.Assembly.GetReferencedAssemblies())
							parameters.ReferencedAssemblies.Add(this.GetAssemblyPath(asm));
						// tell the compiler to generate the IL in memory
						parameters.GenerateInMemory = true;
						// compile the new dynamic assembly using the parameters and source from above
						CompilerResults compiled =
							compiler.CompileAssemblyFromSource(parameters, compareCode);
						// check for compiler errors
						if (compiled.Errors.HasErrors)
						{
							// build error message from compiler errors
							string message = "Could not generate a comparer for '{0}'.  Errors:\n";
							for (int i = 0; i < compiled.Errors.Count; i++)
								message += compiled.Errors[i].ErrorText + "\n";
							// throw an exception with the relevant information
							throw new ApplicationException(
								String.Format(message, dynamicTypeName));
						}
						// get an instance of the new type as IComparer
						comparer = compiled.CompiledAssembly.CreateInstance(dynamicTypeName)
							as System.Collections.IComparer;
						// throw an exception if getting the new instance fails
						if (comparer == null)
							throw new ApplicationException(
								String.Format("Could not instantiate the dynamic type '{0}'.", dynamicTypeName));
						// add the new comparer to the comparers table
						lock (comparers)
							comparers.Add(dynamicTypeName, comparer);
					} // (generate)
				} // comparer lock
			} // comparers cache check

			// At this point, we should be sure that a comparer has been generated for the
			// requested dynamicTypeName and stuck in the cache.  If we're the thread that 
			// did the generating, comparer will not be null, and we can just return it. 
			// If comparer hasn't been assigned (via generating it above), get it from the cache.
			if (comparer == null)
			{
				// get the comparer from the cache
				comparer = comparers[dynamicTypeName] as System.Collections.IComparer;
				// throw an exception if the comparer cannot be retrieved
				if (comparer == null)
					throw new ApplicationException(
						String.Format("Could not retrieve the dynamic type '{0}'.", dynamicTypeName));
			}
			// return the comparer
			return comparer;
		}
 private void ReadValue(TreeViewItem tvi, object obj, System.Type t, PropertyInfo prop)
 {
   var isEvalPropName = "Is" + prop.Name + "Evaluated";
   var isEvalProp = t.GetProperty(isEvalPropName);
   if (isEvalProp == null || (bool)isEvalProp.GetValue(obj, null))
   {
     var value = prop.GetValue(obj, null);
     tvi.Items.Add(ObjectToItem(prop, value));
   }
   else
   {
     var tviNotEval = ObjectToItem(prop, "<not evaluated>");
     tviNotEval.Foreground = Brushes.Red;
     tviNotEval.FontWeight = FontWeights.Bold;
     tvi.Items.Add(tviNotEval);
   }
 }
Example #9
0
        private static void AssertHasPropertyForXPath(System.Type expectedPropetyType, string property, System.Type parentType, string xpathQuery)
        {
            PropertyInfo prop = parentType.GetProperty(property);
            object customer = prop.GetValue(null, null);

            Assert.IsNotNull(customer);

            foreach (XmlNode node in GetSelectNodes(xpathQuery))
            {
                AssertHasMatchingProperty(customer, node, expectedPropetyType);
            }
        }
Example #10
0
        internal static GType LookupGObjectType(System.Type t)
        {
            lock (types) {
                if (gtypes.Contains (t))
                    return (GType) gtypes [t];
            }

            PropertyInfo pi = t.GetProperty ("GType", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
            if (pi != null)
                return (GType) pi.GetValue (null, null);

            return GLib.Object.RegisterGType (t);
        }
Example #11
0
		public static object GetProperty(System.Type t, string propertyName, object objInstance)
		{
			BindingFlags eFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			PropertyInfo p = t.GetProperty(propertyName, eFlags);
			if (p == null)
			{
				throw new ArgumentException("There is no property'" + propertyName + "' for type '" + t.ToString() + "'.");
			}
			return p.GetValue(objInstance, null);
		}
 public override System.Func<object, object> GetToDbConverter(System.Type destType, System.Type SourceType)
 {
     if (SourceType.IsEnumeration())
         return x => SourceType.GetProperty("Value").GetValue(x, new object[] { });
     return base.GetToDbConverter(destType, SourceType);
 }
		/// <summary>
		/// Helper method to find the Property <c>set</c>.
		/// </summary>
		/// <param name="type">The <see cref="System.Type"/> to find the Property in.</param>
		/// <param name="propertyName">The name of the mapped Property to set.</param>
		/// <returns>
		/// The <see cref="BasicSetter"/> for the Property <c>set</c> or <see langword="null" />
		/// if the Property could not be found.
		/// </returns>
		internal static BasicSetter GetSetterOrNull(System.Type type, string propertyName)
		{
			if (type == typeof(object) || type == null)
			{
				// the full inheritance chain has been walked and we could
				// not find the Property get
				return null;
			}

			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;

			if (type.IsValueType)
			{
				// the BindingFlags.IgnoreCase is important here because if type is a struct, the GetProperty method does
				// not ignore case by default. If type is a class, it _does_ ignore case... we're better off explicitly
				// stating that casing should be ignored so we get the same behavior for both structs and classes
				bindingFlags = bindingFlags | BindingFlags.IgnoreCase;
			}

			PropertyInfo property = type.GetProperty(propertyName, bindingFlags);

			if (property != null && property.CanWrite)
			{
				return new BasicSetter(type, property, propertyName);
			}

			// recursively call this method for the base Type
			BasicSetter setter = GetSetterOrNull(type.BaseType, propertyName);

			// didn't find anything in the base class - check to see if there is 
			// an explicit interface implementation.
			if (setter == null)
			{
				System.Type[] interfaces = type.GetInterfaces();
				for (int i = 0; setter == null && i < interfaces.Length; i++)
				{
					setter = GetSetterOrNull(interfaces[i], propertyName);
				}
			}
			return setter;
		}
 public static object GetObjectValueFromPropertyOrMethod(object _inputData, System.Type _inputDataType, string _memberName)
 {
     object result = null;
     //
     if (_memberName.Trim().Length > 0)
     {
         PropertyInfo testProperty = _inputDataType.GetProperty(_memberName,
                                                                     BindingFlags.Instance | BindingFlags.Public);
         if (testProperty != null)
         {
             //test if Propery
             result = testProperty.GetValue(_inputData, null);
         }
         else
         {
             //test if Method
             MethodInfo testMethod = _inputDataType.GetMethod(_memberName,
                                                                     BindingFlags.Instance | BindingFlags.Public);
             if (testMethod != null)
             {
                 result = testMethod.Invoke(_inputData, null);
             }
         }
     }
     //
     return result;
 }
 internal static CodeExpression GenerateConvertExpression(CodeExpression sourceExpression, System.Type sourceType, System.Type targetType)
 {
     if (sourceType == targetType)
     {
         return sourceExpression;
     }
     if (IsSqlType(sourceType))
     {
         if (IsSqlType(targetType))
         {
             throw new InternalException("Cannot perform the conversion between 2 SqlTypes.");
         }
         PropertyInfo property = sourceType.GetProperty("Value");
         if (property == null)
         {
             throw new InternalException("Type does not expose a 'Value' property.");
         }
         System.Type propertyType = property.PropertyType;
         CodeExpression expression = new CodePropertyReferenceExpression(sourceExpression, "Value");
         return GenerateUrtConvertExpression(expression, propertyType, targetType);
     }
     if (IsSqlType(targetType))
     {
         System.Type targetUrtType = targetType.GetProperty("Value").PropertyType;
         CodeExpression expression2 = GenerateUrtConvertExpression(sourceExpression, sourceType, targetUrtType);
         return new CodeObjectCreateExpression(targetType, new CodeExpression[] { expression2 });
     }
     return GenerateUrtConvertExpression(sourceExpression, sourceType, targetType);
 }
Example #16
0
        public static Attrib[] GetClassAttributes(Hashtable attrib, System.Type type)
        {
            System.Collections.Generic.List<Attrib> a = new System.Collections.Generic.List<Attrib>();
            IDictionaryEnumerator enu = attrib.GetEnumerator();
            System.Reflection.PropertyInfo pi = null;
            System.Reflection.FieldInfo fi = null;
            string dt = null;
            string _unsupportedtypes = "";
            bool _nonPrimitiveAttSpecified = false;

            while (enu.MoveNext())
            {
                pi = type.GetProperty(enu.Key.ToString());
                if(pi!=null)
                {
                    dt = pi.PropertyType.FullName;
                }
                if (pi == null)
                {
                    fi = type.GetField(enu.Key.ToString());
                    if(fi!=null)
                    dt = fi.FieldType.FullName;
                }
                if (pi != null || fi != null)
                {
                    Attrib tempAttrib = new Attrib();

                    tempAttrib.Name = (string)enu.Key;
                    tempAttrib.ID = (string)enu.Value;
                    tempAttrib.Type = dt;
                    System.Type currentType =System.Type.GetType(dt);
                    if (currentType != null && !currentType.IsPrimitive && currentType.FullName != "System.DateTime" && currentType.FullName != "System.String" && currentType.FullName != "System.Decimal")
                    {
                        _nonPrimitiveAttSpecified = true;
                        _unsupportedtypes += currentType.FullName + "\n";
                    }
                    if (currentType == null)
                    {
                        _nonPrimitiveAttSpecified = true;
                        _unsupportedtypes += "Unknown Type\n";
                    }
                    a.Add(tempAttrib);
                }
                else
                {
                    string message = "Invalid class attribute(s) specified '" + enu.Key.ToString() + "'.";
                    throw new Exception(message );
                }
                pi = null;
                fi = null;
            }
            if (_nonPrimitiveAttSpecified)
                throw new Exception("NCache Queries only support primitive types. The following type(s) is/are not supported:\n"+_unsupportedtypes);

            return (Attrib[])a.ToArray();
        }
Example #17
0
 bool System.Runtime.Remoting.Contexts.IContextAttribute.IsContextOK(System.Runtime.Remoting.Contexts.Context ctx, System.Runtime.Remoting.Activation.IConstructionCallMessage msg)
 {
     if(ctx.GetProperty("ok ok")==null) return false;
     return true;
 }
 protected void ShowDerivedProperties(System.Type baseType, System.Type superType)
 {
   bool flag = true;
   SerializedProperty iterator = this.serializedObject.GetIterator();
   bool enterChildren = true;
   while (iterator.NextVisible(enterChildren))
   {
     System.Reflection.FieldInfo field = baseType.GetField(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     PropertyInfo property = baseType.GetProperty(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (field == null && superType != null)
       field = superType.GetField(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (property == null && superType != null)
       property = superType.GetProperty(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (field == null && property == null)
     {
       if (flag)
       {
         flag = false;
         EditorGUI.BeginChangeCheck();
         this.serializedObject.Update();
         EditorGUILayout.Separator();
       }
       EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]);
       enterChildren = false;
     }
   }
   if (flag)
     return;
   this.serializedObject.ApplyModifiedProperties();
   EditorGUI.EndChangeCheck();
 }
 private static void AddNewProperties(List<CustomProperty> propCollection, System.Type customActivityType, IServiceProvider serviceProvider, List<CustomProperty> existingProps)
 {
     IMemberCreationService service = serviceProvider.GetService(typeof(IMemberCreationService)) as IMemberCreationService;
     if (service == null)
     {
         throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(IMemberCreationService).FullName }));
     }
     ITypeProvider provider = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
     if (provider == null)
     {
         throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
     }
     foreach (CustomProperty property in propCollection)
     {
         bool flag = (property.oldPropertyName == null) || (property.oldPropertyType == null);
         if (!flag)
         {
             if (!property.IsEvent)
             {
                 flag = customActivityType.GetProperty(property.oldPropertyName, provider.GetType(property.oldPropertyType)) == null;
             }
             else
             {
                 flag = customActivityType.GetEvent(property.oldPropertyName) == null;
             }
         }
         if (flag)
         {
             AttributeInfo[] attributes = CreateCustomPropertyAttributeArray(property, serviceProvider);
             if (property.IsEvent)
             {
                 service.CreateEvent(customActivityType.FullName, property.Name, provider.GetType(property.Type), attributes, property.GenerateDependencyProperty);
             }
             else
             {
                 service.CreateProperty(customActivityType.FullName, property.Name, provider.GetType(property.Type), attributes, property.GenerateDependencyProperty, false, false, null, false);
             }
         }
         else
         {
             CustomProperty oldProperty = null;
             foreach (CustomProperty property3 in existingProps)
             {
                 if ((property3.Name == property.oldPropertyName) && (property3.Type == property.oldPropertyType))
                 {
                     oldProperty = property3;
                 }
             }
             if ((oldProperty == null) || ArePropertiesDifferent(property, oldProperty))
             {
                 AttributeInfo[] infoArray2 = CreateCustomPropertyAttributeArray(property, serviceProvider);
                 CreateCustomPropertyAttributeArray(oldProperty, serviceProvider);
                 System.Type newEventType = provider.GetType(property.Type, false);
                 System.Type type = provider.GetType(property.oldPropertyType, false);
                 if (newEventType != null)
                 {
                     if (property.IsEvent)
                     {
                         service.UpdateEvent(customActivityType.FullName, property.oldPropertyName, type, property.Name, newEventType, infoArray2, property.GenerateDependencyProperty, false);
                     }
                     else
                     {
                         service.UpdateProperty(customActivityType.FullName, property.oldPropertyName, type, property.Name, newEventType, infoArray2, property.GenerateDependencyProperty, false);
                     }
                 }
             }
         }
     }
 }
Example #20
0
 private void CreatSelTreeNode(List<string> lableList, System.Type type)
 {
     foreach (string str in lableList)
     {
         if (type.GetProperty(str) != null)
         {
             this.CreatTreeNodeByProper(type.GetProperty(str));
         }
     }
 }
		/// <summary>
		/// Resolves property title from property attributes
		/// </summary>
		/// <param name="aType">
		/// Type property belongs to <see cref="System.Type"/>
		/// </param>
		/// <param name="aPropertyName">
		/// Property name <see cref="System.String"/>
		/// </param>
		/// <returns>
		/// Property description <see cref="PropertyDescriptionAttribute"/>
		/// </returns>
		public static PropertyDescriptionAttribute GetPropertyDescription (System.Type aType, string aPropertyName)
		{
			if (aType == null)
				return (null);
			PropertyInfo info = aType.GetProperty (aPropertyName);
			if (info == null)
				return (null);
			PropertyDescriptionAttribute[] attrs = (PropertyDescriptionAttribute[]) info.GetCustomAttributes (typeof(PropertyDescriptionAttribute), true);
			if ((attrs == null) || (attrs.Length == 0))
				return (null);
			return ((PropertyDescriptionAttribute) attrs[0]);
		}
        private void SetMappedMembers(System.Type type)
        {
            var propertyMappings = from mapping in mappings
                                   let hbmClasses = from hbmClass in mapping.RootClasses where hbmClass.Name == type.Name select hbmClass
                                   from rootClass in hbmClasses
                                   where rootClass != null
                                   from propertyMapping in rootClass.Items.OfType<IEntityPropertyMapping>()
                                   select propertyMapping;

            foreach (var propertyMapping in propertyMappings)
            {
                if (propertyMapping.Access != null && propertyMapping.Access == "field")
                {
                    var fieldInfo = type.GetField(propertyMapping.Name, BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                    mappedMembers.Add(new LocationInfo(fieldInfo));
                }
                else
                    mappedMembers.Add(new LocationInfo(type.GetProperty(propertyMapping.Name)));
            }
        }
Example #23
0
        /// <summary>
        /// Get Column Info
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        public static Dictionary<string, ColumnInfo> GetColumnInfoLookup(System.Type entityType)
        {
            if (_columnInfo == null)
            {
                _columnInfo = new Dictionary<Type, Dictionary<string, ColumnInfo>>();
            }

            if (!_columnInfo.ContainsKey(entityType))
            {
                _columnInfo[entityType] = new Dictionary<string,ColumnInfo>();
                _columnInfoDefaultValueKeys[entityType] = new List<string>();

                System.Reflection.PropertyInfo property = entityType.GetProperty("TableName", BindingFlags.Public | BindingFlags.Static);

                if (property != null)
                {
                    string tableName = property.GetValue(null, null) as string;

                    string commandText = @"select c.COLUMN_NAME, c.COLUMN_DEFAULT, c.DATA_TYPE, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, ep.value as FriendlyName from INFORMATION_SCHEMA.COLUMNS c
                                                                                                inner join sys.columns sc ON OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME) = sc.[object_id] AND c.COLUMN_NAME = sc.name
                                                                                                LEFT OUTER JOIN sys.extended_properties ep ON sc.[object_id] = ep.major_id AND sc.[column_id] = ep.minor_id AND ep.class = 1 and ep.Name = 'NSFx_FriendlyName'
                                                WHERE c.TABLE_NAME = @TableName";

                    System.Collections.Generic.List<SqlParameter> parameters = new System.Collections.Generic.List<SqlParameter>();

                    parameters.Add(new SqlParameter("@TableName", tableName));

                    try
                    {
                        using (SqlHelper helper = new SqlHelper())
                        {
                            System.Data.IDataReader reader = helper.ExecuteDataReader(commandText, CommandType.Text, parameters);

                            while (reader.Read())
                            {
                                ColumnInfo columnInfo = new ColumnInfo(reader);

                                _columnInfo[entityType].Add(columnInfo.ColumnName, columnInfo);

                                if (columnInfo.Value != null)
                                {
                                    try
                                    {
                                        _columnInfoDefaultValueKeys[entityType].Add(columnInfo.ColumnName);
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                    catch { }
                }
            }

            return _columnInfo[entityType];
        }
Example #24
0
		protected internal static GType LookupGType (System.Type t)
		{
			if (g_types.Contains (t))
				return (GType) g_types [t];
			
			PropertyInfo pi = t.GetProperty ("GType", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
			if (pi != null)
				return (GType) pi.GetValue (null, null);
			
			return RegisterGType (t);
		}
Example #25
0
        public static void Apply(Schema schema, SchemaRegistry schemaRegistry, System.Type type)
        {
            var workStr = type.ToString();

            if (type.IsEnum)
            {
                EnumRegist(schemaRegistry, type);
            }
            if (IsNullableEnumType(type))
            {
                var innerType = type.GetGenericArguments()[0];
                EnumRegist(schemaRegistry, innerType);
            }

            if (schema.type == "array")
            {
                if (type.IsArray)
                {
                    Apply(schema.items, schemaRegistry, type.GetElementType());
                }
                else
                {
                    Apply(schema.items, schemaRegistry, type.GetGenericArguments()[0]);
                }
                return;
            }

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                schema.vendorExtensions.Add("CsType", type.GetGenericArguments()[0].Name + "?");
                schema.vendorExtensions.Add("CsNamespace", type.Namespace);

            }
            else
            {
                schema.vendorExtensions.Add("CsType", type.Name);
                schema.vendorExtensions.Add("CsNamespace", type.Namespace);
            }

            if (schema.properties != null)
            {
                foreach (var prop in schema.properties)
                {
                    var pi = type.GetProperty(prop.Key);
                    if (pi != null)
                    {
                        Apply(prop.Value, schemaRegistry, pi.PropertyType);
                    }
                }
            }
        }
Example #26
0
    private static System.Type GetBindingValueType(string path, System.Type type, GameObject gameObject, bool command, ref string tail)
    {
        tail = string.Empty;

        if (string.IsNullOrEmpty(path))
        {
            Debug.Log("Binding is empty for object " + GetGameObjectPath(gameObject));
            return null;
        }

        var parts = path.Split('.');
        var pathMessage = "";
        for (var i = 0; i < parts.Length; ++i)
        {
            var part = parts[i];
            pathMessage += part;

            if (i < parts.Length - 1)
            {
                int index;
                if (int.TryParse(part, out index))
                {
                    for (var j = i + 1; j < parts.Length; ++j)
                        tail += parts[j] + ".";
                    if (tail.Length > 0)
                        tail = tail.Substring(0, tail.Length - 1);
                    return type;
                }
                else
                {
                    var nodeProperty = type.GetProperty(part);
                    if (nodeProperty == null)
                    {
                        Debug.LogError("Failed to resolve node in binding " + path + " in object " + GetGameObjectPath(gameObject) +
                                       "\nerror at " + pathMessage);
                        return null;
                    }
                    pathMessage += ".";
                    type = nodeProperty.PropertyType;
                }
            }
            else
            {
                if (command)
                {
                    var leafCommand = type.GetMethod(part);
                    if (leafCommand == null)
                    {
                        Debug.LogError("Failed to resolve leaf command in binding " + path + " in object " + GetGameObjectPath(gameObject) +
                                       "\nerror at " + pathMessage);
                        return null;
                    }
                }
                else
                {
                    var leafProperty = type.GetProperty(part);
                    if (leafProperty == null)
                    {
                        Debug.LogError("Failed to resolve leaf property in binding " + path + " in object " + GetGameObjectPath(gameObject) +
                                       "\nerror at " + pathMessage);
                        return null;
                    }
                    type = leafProperty.PropertyType;
                }
            }
        }
        return type;
    }
Example #27
0
		private List<Table> AddArrayedTablesToSelect(List<Table> ret, System.Type type)
		{
            while (pool.Mapping.IsMappableType(type))
            {
                sTable map = pool.Mapping[type];
                string query = "";
                foreach (string prop in map.ArrayProperties)
                {
                    PropertyInfo pi = type.GetProperty(prop, Utility._BINDING_FLAGS);
                    if (pool.Mapping.IsMappableType(pi.PropertyType.GetElementType()) && !Utility.IsEnum(pi.PropertyType.GetElementType()))
                    {
                        foreach (Table t in ret)
                        {
                            List<IDbDataParameter> pars = new List<IDbDataParameter>();
                            sTable external = pool.Mapping[pi.PropertyType.GetElementType()];
                            sTable arMap = pool.Mapping[type, pi.Name];
                            string fields = "";
                            string conditions = "";
                            foreach (sTableField fld in arMap["PARENT"])
                            {
                                conditions += fld.Name + " = " + queryBuilder.CreateParameterName(fld.Name) + " AND ";
                                foreach (sTableField f in map.Fields)
                                {
                                    if (f.Name == fld.ExternalField)
                                    {
                                        pars.Add(CreateParameter(queryBuilder.CreateParameterName(fld.Name), QueryBuilder.LocateFieldValue(t, f, pool)));
                                        break;
                                    }
                                }
                            }
                            foreach (sTableField fld in arMap["CHILD"])
                            {
                                fields += fld.Name + " AS " + fld.ExternalField + ", ";
                            }
                            fields = fields.Substring(0, fields.Length - 2);
                            conditions = conditions.Substring(0, conditions.Length - 4);
                            query = String.Format(queryBuilder.OrderBy, string.Format(queryBuilder.SelectWithConditions, fields, arMap.Name, conditions), Pool.Translator.GetIntermediateIndexFieldName(type, pi));
                            ArrayList values = new ArrayList();
                            ExecuteQuery(query, pars);
                            while (Read())
                            {
                                Table ta = (Table)LazyProxy.Instance(pi.PropertyType.GetElementType().GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]));
                                ta.SetValues(this);
                                ta.LoadStatus = LoadStatus.Partial;
                                values.Add(ta);
                            }
                            Close();
                            Array obj;
                            obj = Array.CreateInstance(pi.PropertyType.GetElementType(), values.Count);
                            for (int x = 0; x < values.Count; x++)
                                ((Array)obj).SetValue(values[x], x);
                            t.SetField(pi.Name, obj);
                        }
                    }
                    else
                    {
                        sTable arMap = Pool.Mapping[type, pi.Name];
                        string conditions = "";
                        foreach (sTableField fld in arMap.Fields)
                        {
                            if (fld.ClassProperty == "PARENT")
                                conditions += fld.Name + " = " + queryBuilder.CreateParameterName(fld.ExternalField) + " AND ";
                        }
                        query = "SELECT " + Pool.Translator.GetIntermediateValueFieldName(type, pi) + " FROM " + arMap.Name + " WHERE " + conditions.Substring(0, conditions.Length - 4) + " ORDER BY " + Pool.Translator.GetIntermediateIndexFieldName(type, pi) + " ASC";
                        foreach (Table t in ret)
                        {
                            List<IDbDataParameter> pars = new List<IDbDataParameter>();
                            foreach (string str in map.PrimaryKeyProperties)
                            {
                                foreach (sTableField fld in map[str])
                                    pars.Add(CreateParameter(queryBuilder.CreateParameterName(fld.Name), QueryBuilder.LocateFieldValue(t, fld, pool)));
                            }
                            ArrayList values = new ArrayList();
                            ExecuteQuery(query, pars);
                            while (Read())
                            {
                                if (Utility.IsEnum(pi.PropertyType.GetElementType()))
                                    values.Add(this.pool.GetEnumValue(pi.PropertyType.GetElementType(), this.GetInt32(0)));
                                else
                                    values.Add(this[0]);
                            }
                            Close();
                            Array obj = Array.CreateInstance(pi.PropertyType.GetElementType(), values.Count);
                            for (int x = 0; x < values.Count; x++)
                                ((Array)obj).SetValue(values[x], x);
                            t.SetField(prop, obj);
                        }
                    }
                }
                type = type.BaseType;
            }
			return ret;
        }