Пример #1
0
		public XamlObjectReader (object instance, XamlSchemaContext schemaContext, XamlObjectReaderSettings settings)
		{
			if (schemaContext == null)
				throw new ArgumentNullException ("schemaContext");
			// FIXME: special case? or can it be generalized? In .NET, For Type instance Instance returns TypeExtension at root StartObject, while for Array it remains to return Array.
			if (instance is Type)
				instance = new TypeExtension ((Type) instance);

			// See also Instance property for this weirdness.
			this.root_raw = instance;
			instance = TypeExtensionMethods.GetExtensionWrapped (instance);
			this.root = instance;

			sctx = schemaContext;
//			this.settings = settings;

			// check type validity. Note that some checks also needs done at Read() phase. (it is likely FIXME:)
			if (instance != null) {
				var type = new InstanceContext (instance).GetRawValue ().GetType ();
				if (!type.IsPublic)
					throw new XamlObjectReaderException (String.Format ("instance type '{0}' must be public and non-nested.", type));
				var xt = SchemaContext.GetXamlType (type);
				if (xt.ConstructionRequiresArguments && !xt.GetConstructorArguments ().Any () && xt.TypeConverter == null)
					throw new XamlObjectReaderException (String.Format ("instance type '{0}' has no default constructor.", type));
			}

			value_serializer_context = new ValueSerializerContext (new PrefixLookup (sctx), sctx, null);
			new XamlObjectNodeIterator (instance, sctx, value_serializer_context).PrepareReading ();
		}
Пример #2
0
		public XamlObjectReader (object instance, XamlSchemaContext schemaContext, XamlObjectReaderSettings settings)
		{
			if (schemaContext == null)
				throw new ArgumentNullException ("schemaContext");
			// FIXME: special case? or can it be generalized? In .NET, For Type instance Instance returns TypeExtension at root StartObject, while for Array it remains to return Array.
			if (instance is Type)
				instance = new TypeExtension ((Type) instance);

			this.root = instance;
			sctx = schemaContext;
			this.settings = settings;

			prefix_lookup = new PrefixLookup (sctx);

			// check type validity. Note that some checks also needs done at Read() phase. (it is likely FIXME:)
			if (instance != null) {
				var type = new InstanceContext (instance).GetWrappedValue ().GetType ();
				if (!type.IsPublic)
					throw new XamlObjectReaderException (String.Format ("instance type '{0}' must be public and non-nested.", type));
				var xt = SchemaContext.GetXamlType (type);
				if (xt.ConstructionRequiresArguments && !xt.GetConstructorArguments ().Any () && xt.TypeConverter == null)
					throw new XamlObjectReaderException (String.Format ("instance type '{0}' has no default constructor.", type));
			}

			new XamlObjectNodeIterator (instance, sctx, prefix_lookup).CollectNamespaces ();
		}
Пример #3
0
        public override bool GetInheritanceDiscriminator(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (IsLinqObject(member.TypeAccessor.Type))
            {
                var a = member.GetAttribute <ColumnAttribute>();

                if (a != null && !string.IsNullOrEmpty(a.Name))
                {
                    isSet = true;
                    return(a.IsDiscriminator);
                }
            }

            return(base.GetInheritanceDiscriminator(typeExtension, member, out isSet));
        }
Пример #4
0
        public override string GetFieldStorage(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (IsLinqObject(member.TypeAccessor.Type))
            {
                var a = member.GetAttribute <ColumnAttribute>();

                if (a != null && !string.IsNullOrEmpty(a.Name))
                {
                    isSet = true;
                    return(a.Storage);
                }
            }

            return(base.GetFieldStorage(typeExtension, member, out isSet));
        }
Пример #5
0
        public override NonUpdatableAttribute GetNonUpdatableAttribute(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet)
        {
            if (IsLinqObject(member.TypeAccessor.Type))
            {
                var a = member.GetAttribute <ColumnAttribute>();

                if (a != null)
                {
                    isSet = true;
                    return(a.IsDbGenerated ? new IdentityAttribute() : null);
                }
            }

            return(base.GetNonUpdatableAttribute(type, typeExt, member, out isSet));
        }
Пример #6
0
        public override int GetPrimaryKeyOrder(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet)
        {
            if (IsLinqObject(type))
            {
                ColumnAttribute a = member.GetAttribute <ColumnAttribute>();

                if (a != null && a.IsPrimaryKey)
                {
                    isSet = true;
                    return(0);
                }
            }

            return(base.GetPrimaryKeyOrder(type, typeExt, member, out isSet));
        }
Пример #7
0
        public override bool GetNullable(MappingSchema mappingSchema, TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (IsLinqObject(member.TypeAccessor.Type))
            {
                var attr = member.GetAttribute <ColumnAttribute>();

                if (attr != null)
                {
                    isSet = true;
                    return(attr.CanBeNull);
                }
            }

            return(base.GetNullable(mappingSchema, typeExtension, member, out isSet));
        }
Пример #8
0
            Type GetObjectType(Type originalType, MappingSchema mappingSchema)
            {
                for (var type = originalType.BaseType; type != null && type != typeof(object); type = type.BaseType)
                {
                    var extension = TypeExtension.GetTypeExtension(type, mappingSchema.Extensions);
                    var mapping   = mappingSchema.MetadataProvider.GetInheritanceMapping(type, extension);

                    if (mapping.Length > 0)
                    {
                        return(type);
                    }
                }

                return(OriginalType);
            }
Пример #9
0
        /// <summary>
        /// Creates a new instance of DbParameter[] with ParameterName, Value and IsNullable properties
        /// sets to value's properties.
        /// </summary>
        /// <typeparam name="T">Type of object with properties to convert in Parameters</typeparam>
        /// <typeparam name="U">DbParameter type (SqlParameter, ...)</typeparam>
        /// <param name="command"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static IEnumerable <DbParameter> ToParameters <T, U>(DbCommand command, T value) where U : DbParameter
        {
            if (TypeExtension.IsPrimitive(typeof(T)))
            {
                throw new ArgumentException("The value can not be a simple type (string, int, ...), but an object with simple properties.", "value");
            }
            else
            {
                List <DbParameter> parameters = new List <DbParameter>();
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    if (TypeExtension.IsPrimitive(property.PropertyType))
                    {
                        // Data type
                        Type propType = TypeExtension.GetNullableSubType(property.PropertyType);

                        // Value
                        DbParameter parameter = command != null?
                                                command.CreateParameter() :
                                                    Activator.CreateInstance(typeof(U)) as DbParameter;

                        parameter.Value      = typeof(T).GetProperty(property.Name).GetValue(value, null);
                        parameter.IsNullable = TypeExtension.IsNullable(property.PropertyType);
                        parameter.DbType     = DbTypeMap.FirstDbType(propType);

                        if (parameter.IsNullable && parameter.Value == null)
                        {
                            parameter.Value = DBNull.Value;
                        }

                        // Parameter name
                        string attribute = Apps72.Dev.Data.Annotations.ColumnAttribute.GetColumnAttributeName(property);
                        if (string.IsNullOrEmpty(attribute))
                        {
                            parameter.ParameterName = property.Name;
                        }
                        else
                        {
                            parameter.ParameterName = attribute;
                        }

                        parameters.Add(parameter);
                    }
                }

                return(parameters.AsEnumerable());
            }
        }
Пример #10
0
        /// <summary>
        /// Selects all rows.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="whereClause">The where clause.</param>
        /// <returns></returns>
        public List <T> SelectAllRows <T>(string whereClause = "") where T : new()
        {
            var objectList          = new List <T>();
            SQLiteDataReader reader = null;

            try
            {
                var objectType = typeof(T);
                var properties = objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                string sqlQuery = SQLiteQuery.SelectAllFrom(objectType.Name, whereClause);
                reader = SQLiteQuery.ExecuteReader(sqlQuery, this.Connection);

                while (reader.Read())
                {
                    var newObject = new T();

                    foreach (var property in properties)
                    {
                        if (property.IsDataMember())
                        {
                            if (reader[property.Name].HaveContent() || property.PropertyType.IsString())
                            {
                                Type type = property.PropertyType;
                                TypeExtension.GetDataType(type, out type);

                                object  propertyValue = reader[property.Name];
                                dynamic changedObject = Convert.ChangeType(propertyValue, type);
                                property.SetValue(newObject, changedObject, null);
                            }
                        }
                    }

                    objectList.Add(newObject);
                }
            }
            catch (Exception exception)
            {
                APILog.Error(this, "SelectAllRows", exception);
            }
            finally
            {
                reader.Close();
                reader = null;
            }

            return(objectList);
        }
Пример #11
0
        public void GenerateType_Interface_Get()
        {
            ProxyGenerator proxy = new ProxyGenerator("Test", "TestClass");

            proxy.InheritInterface <IGS>();
            var type = proxy.GenerateType();
            var obj  = type.CreateInstance() as IGS;

            Assert.IsNotNull(obj);
            Assert.IsNull(obj.Name);
            obj.Birthday = DateTime.Now;
            Console.WriteLine("dobj.Birthday:" + TypeExtension.ToDateTimeString(obj.Birthday));
            dynamic dobj = obj;

            dobj.Name = "123;";
        }
Пример #12
0
        public override bool GetMapIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (member.GetAttribute <AssociationAttribute>() != null)
            {
                isSet = true;
                return(true);
            }

            if (IsLinqObject(member.TypeAccessor.Type))
            {
                isSet = true;
                return(member.GetAttribute <ColumnAttribute>() == null);
            }

            return(base.GetMapIgnore(typeExtension, member, out isSet));
        }
Пример #13
0
        public override Association GetAssociation(TypeExtension typeExtension, MemberAccessor member)
        {
            var aa = member.GetAttribute <AssociationAttribute>();

            if (aa == null)
            {
                return(base.GetAssociation(typeExtension, member));
            }

            return(new Association(
                       member,
                       aa.GetThisKeys(),
                       aa.GetOtherKeys(),
                       aa.Storage,
                       aa.CanBeNull));
        }
Пример #14
0
        public static bool CanSerialize(object graph)
        {
            if (graph == null)
            {
                return(false);
            }

            if (TypeExtension.IsAssignableFrom(typeof(ISerializable), graph.GetType()))
            {
                return(true);
            }

            var attribute = (SerializerAttribute)graph.GetType().GetCustomAttribute(typeof(SerializerAttribute));

            return(attribute != null && attribute.Type != null);
        }
Пример #15
0
        protected SqlQueryInfo CreateInsertSqlText(DbManager db, Type type)
        {
            TypeExtension        typeExt = TypeExtension.GetTypeExtension(type, Extensions);
            ObjectMapper         om      = db.MappingSchema.GetObjectMapper(type);
            List <MemberMapper>  list    = new List <MemberMapper>();
            StringBuilder        sb      = new StringBuilder();
            SqlQueryInfo         query   = new SqlQueryInfo(om);
            MetadataProviderBase mp      = MappingSchema.MetadataProvider;

            sb.AppendFormat("INSERT INTO {0} (\n",
                            db.DataProvider.Convert(GetTableName(type), ConvertType.NameToQueryTable));

            foreach (MemberMapper mm in GetFieldList(om))
            {
                // IT: This works incorrectly for complex mappers.
                //
                bool isSet;

                if (!mp.GetNonUpdatableFlag(type, typeExt, mm.ComplexMemberAccessor, out isSet) || !isSet)
                {
                    sb.AppendFormat("\t{0},\n",
                                    db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryField));
                    list.Add(mm);
                }
            }

            sb.Remove(sb.Length - 2, 1);

            sb.Append(") VALUES (\n");

            foreach (MemberMapper mm in list)
            {
                SqlQueryParameterInfo p = query.AddParameter(
                    db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryParameter).ToString(),
                    mm.Name);

                sb.AppendFormat("\t{0},\n", p.ParameterName);
            }

            sb.Remove(sb.Length - 2, 1);

            sb.Append(")");

            query.QueryText = sb.ToString();

            return(query);
        }
Пример #16
0
        public virtual System.Type GetElementType(System.Type p_type)
        {
            System.Type v_returnedType = null;
            if (p_type != null)
            {
                if (p_type.IsArray)
                {
                    v_returnedType = p_type.GetElementType();
                }
                else if (TypeExtension.IsSameOrSubClassOrImplementInterface(p_type, typeof(IArrayList)))
                {
                    v_returnedType = p_type;
                    string v_typeSafeName = v_returnedType != null ? v_returnedType.FullName : "";
                    while (v_returnedType != null && !v_typeSafeName.Contains("ArrayList`1"))
                    {
                        v_returnedType = v_returnedType.BaseType;
                        v_typeSafeName = v_returnedType != null ? v_returnedType.FullName : "";
                    }
                    try
                    {
                        v_returnedType = v_returnedType.GetGenericArguments()[0];
                    }
                    catch { v_returnedType = null; }
                }
                else
                {
                    System.Type[] v_interfaceTypes = p_type.GetInterfaces();
                    foreach (System.Type v_interfaceType in v_interfaceTypes)
                    {
                        string v_interfaceSafeName = v_interfaceType != null ? v_interfaceType.FullName : ""; //SerializableTypeCache.GetSafeTypedNameInAssembly(v_interfaceType);
                        if (v_interfaceSafeName.Contains("IList`1") ||
                            v_interfaceSafeName.Contains("ICollection`1") ||
                            v_interfaceSafeName.Contains("IEnumerable`1"))

                        {
                            try
                            {
                                v_returnedType = v_interfaceType.GetGenericArguments()[0];
                                break;
                            }
                            catch { }
                        }
                    }
                }
            }
            return(v_returnedType);
        }
Пример #17
0
        public SqlTable([JetBrains.Annotations.NotNull] MappingSchema mappingSchema, Type objectType) : this()
        {
            if (mappingSchema == null)
            {
                throw new ArgumentNullException("mappingSchema");
            }

            bool isSet;

            Database     = mappingSchema.MetadataProvider.GetDatabaseName(objectType, mappingSchema.Extensions, out isSet);
            Owner        = mappingSchema.MetadataProvider.GetOwnerName(objectType, mappingSchema.Extensions, out isSet);
            Name         = mappingSchema.MetadataProvider.GetTableName(objectType, mappingSchema.Extensions, out isSet);
            ObjectType   = objectType;
            PhysicalName = Name;

            var typeExt = TypeExtension.GetTypeExtension(objectType, mappingSchema.Extensions);

            foreach (MemberMapper mm in mappingSchema.GetObjectMapper(objectType))
            {
                if (mm.MapMemberInfo.SqlIgnore == false)
                {
                    var ua =
                        mappingSchema.MetadataProvider.GetNonUpdatableAttribute(objectType, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                    var order = mappingSchema.MetadataProvider.GetPrimaryKeyOrder(objectType, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                    Fields.Add(new SqlField(
                                   mm.Type,
                                   mm.MemberName,
                                   mm.Name,
                                   mm.MapMemberInfo.Nullable,
                                   isSet ? order : int.MinValue,
                                   ua,
                                   mm));
                }
            }

            var identityField = GetIdentityField();

            if (identityField != null)
            {
                var om = mappingSchema.GetObjectMapper(ObjectType);
                var mm = om[identityField.Name, true];

                _sequenceAttributes = mm.MapMemberInfo.MemberAccessor.GetAttributes <SequenceNameAttribute>();
            }
        }
Пример #18
0
        private static object GetEnumDefaultValueFromExtension(TypeExtension typeExt, Type type)
        {
            FieldInfo[] fields = type.GetFields();

            foreach (FieldInfo fi in fields)
            {
                if ((fi.Attributes & EnumField) == EnumField)
                {
                    if (typeExt[fi.Name]["DefaultValue"].Value != null)
                    {
                        return(Enum.Parse(type, fi.Name));
                    }
                }
            }

            return(null);
        }
Пример #19
0
        public override bool GetTrimmable(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (member.Type == typeof(string))
            {
                foreach (var p in _list)
                {
                    var trimmable = p.GetTrimmable(typeExtension, member, out isSet);

                    if (isSet)
                    {
                        return(trimmable);
                    }
                }
            }

            return(base.GetTrimmable(typeExtension, member, out isSet));
        }
Пример #20
0
 /// <summary>
 /// Execute the query and return an array of new instances of typed results filled with data table result.
 /// </summary>
 /// <typeparam name="T">Object type</typeparam>
 /// <param name="itemOftype"></param>
 /// <returns>Array of typed results</returns>
 /// <example>
 /// <code>
 ///   Employee emp = new Employee();
 ///   var x = cmd.ExecuteTable(new { emp.Age, emp.Name });
 ///   var y = cmd.ExecuteTable(new { Age = 0, Name = "" });
 /// </code>
 /// <remarks>
 ///   Result object property (ex. Employee.Name) may be tagged with the ColumnAttribute
 ///   to set which column name (ex. [Column("Name")] must be associated to this property.
 /// </remarks>
 /// </example>
 public async virtual Task <IEnumerable <T> > ExecuteTableAsync <T>(T itemOftype)
 {
     return(await ExecuteInternalCommand(async() =>
     {
         using (DbDataReader dr = await this.Command.ExecuteReaderAsync())
         {
             if (TypeExtension.IsPrimitive(typeof(T)))
             {
                 return await DataReaderConvertor.ToPrimitivesAsync <T>(dr);
             }
             else
             {
                 return await DataReaderConvertor.ToAnonymousAsync <T>(dr);
             }
         }
     }));
 }
Пример #21
0
        public override bool GetSqlIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            var attr = member.GetAttribute <SqlIgnoreAttribute>();

            if (attr == null)
            {
                attr = (SqlIgnoreAttribute)TypeHelper.GetFirstAttribute(member.Type, typeof(SqlIgnoreAttribute));
            }

            if (attr != null)
            {
                isSet = true;
                return(attr.Ignore);
            }

            return(base.GetSqlIgnore(typeExtension, member, out isSet));
        }
Пример #22
0
        public override bool GetMapIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (member.IsDefined <NotMappedAttribute>() || member.IsDefined <ScaffoldColumnAttribute>() ||
                member.IsDefined <System.ComponentModel.DataAnnotations.AssociationAttribute>())
            {
                isSet = true;
                return(true);
            }

            if (member.IsDefined <ColumnAttribute>())
            {
                isSet = true;
                return(false);
            }

            return(base.GetMapIgnore(typeExtension, member, out isSet));
        }
Пример #23
0
        public override int GetPrimaryKeyOrder(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet)
        {
            var keyAttr = member.GetAttribute <KeyAttribute>();

            if (keyAttr != null)
            {
                isSet = true;
                var colAttr = member.GetAttribute <ColumnAttribute>();
                if (colAttr != null)
                {
                    return(colAttr.Order);
                }
                return(0);
            }

            return(base.GetPrimaryKeyOrder(type, typeExt, member, out isSet));
        }
Пример #24
0
 /// <summary>
 /// Execute the query and return an array of new instances of typed results filled with data table result.
 /// </summary>
 /// <typeparam name="T">Object type</typeparam>
 /// <param name="itemOftype"></param>
 /// <returns>Array of typed results</returns>
 /// <example>
 /// <code>
 ///   Employee emp = new Employee();
 ///   var x = cmd.ExecuteTable(new { emp.Age, emp.Name });
 ///   var y = cmd.ExecuteTable(new { Age = 0, Name = "" });
 /// </code>
 /// <remarks>
 ///   Result object property (ex. Employee.Name) may be tagged with the ColumnAttribute
 ///   to set which column name (ex. [Column("Name")] must be associated to this property.
 /// </remarks>
 /// </example>
 public virtual IEnumerable <T> ExecuteTable <T>(T itemOftype)
 {
     return(ExecuteInternalCommand(() =>
     {
         using (DbDataReader dr = this.Command.ExecuteReader())
         {
             if (TypeExtension.IsPrimitive(typeof(T)))
             {
                 return DataReaderConvertor.ToPrimitives <T>(dr);
             }
             else
             {
                 return DataReaderConvertor.ToAnonymous <T>(dr);
             }
         }
     }));
 }
Пример #25
0
        protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo)
        {
            var sequence = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]));
            var table    = sequence as TableBuilder.TableContext;

            if (table != null && table.InheritanceMapping.Count > 0)
            {
                var objectType = methodCall.Type.GetGenericArguments()[0];

                if (TypeHelper.IsSameOrParent(table.ObjectType, objectType))
                {
                    var predicate = builder.MakeIsPredicate(table, objectType);

                    if (predicate.GetType() != typeof(SqlQuery.Predicate.Expr))
                    {
                        sequence.SqlQuery.Where.SearchCondition.Conditions.Add(new SqlQuery.Condition(false, predicate));
                    }
                }
            }
            else
            {
                var toType   = methodCall.Type.GetGenericArguments()[0];
                var gargs    = TypeHelper.GetGenericArguments(methodCall.Arguments[0].Type, typeof(IQueryable <>));
                var fromType = gargs == null ? typeof(object) : gargs[0];

                if (toType.IsSubclassOf(fromType))
                {
                    for (var type = toType.BaseType; type != null && type != typeof(object); type = type.BaseType)
                    {
                        var extension = TypeExtension.GetTypeExtension(type, builder.MappingSchema.Extensions);
                        var mapping   = builder.MappingSchema.MetadataProvider.GetInheritanceMapping(type, extension);

                        if (mapping.Length > 0)
                        {
                            var predicate = MakeIsPredicate(builder, sequence, fromType, toType);

                            sequence.SqlQuery.Where.SearchCondition.Conditions.Add(new SqlQuery.Condition(false, predicate));

                            return(new OfTypeContext(sequence, methodCall));
                        }
                    }
                }
            }

            return(sequence);
        }
Пример #26
0
        public void Test()
        {
            Map.Extensions = TypeExtension.GetExtensions("Mapping.xml");

            object o = Map.Extensions["TriState"]["Yes"]["MapValue"].Value;

            Assert.AreEqual("yes", o);

            Source s = new Source();
            Dest   d = (Dest)Map.ObjectToObject(s, typeof(Dest));

            Assert.AreEqual(TriState.No, d.Field1);
            Assert.AreEqual(1, d.Field2);
            Assert.AreEqual(2, d.Field3);
            Assert.AreEqual(54, d.Field4);
            Assert.AreEqual(TriState.NotApplicable, Map.ValueToEnum("1234", typeof(TriState)));
        }
Пример #27
0
        /// <summary>
        /// Property Level: Removes the existing mapped property handler from a data entity type property (via <see cref="Field"/> object).
        /// </summary>
        /// <typeparam name="TEntity">The target .NET CLR type.</typeparam>
        /// <param name="field">The instance of <see cref="Field"/> object to be mapped.</param>
        public static void Remove <TEntity>(Field field)
            where TEntity : class
        {
            // Validates
            ThrowNullReferenceException(field, "Field");

            // Get the property
            var property = TypeExtension.GetProperty <TEntity>(field.Name);

            if (property == null)
            {
                throw new PropertyNotFoundException($"Property '{field.Name}' is not found at type '{typeof(TEntity).FullName}'.");
            }

            // Add to the mapping
            Remove <TEntity>(property);
        }
Пример #28
0
        public double?ToNumberX(int idx)
        {
            Object val = stack.Get(idx);

            if (TypeExtension.TypeEqual <double>(val))
            {
                return((double)val);
            }
            else if (TypeExtension.TypeEqual <long>(val))
            {
                return(Convert.ToDouble(((long)val)));
            }
            else
            {
                return(null);
            }
        }
Пример #29
0
        protected internal virtual void SerializeElement(XmlWriter writer)
        {
            var elementName = this.ElementProperty != null ? this.ElementProperty.Name : string.Empty;

            if (!string.IsNullOrEmpty(elementName))
            {
                writer.WriteStartElement(elementName);
            }

            object value;
            var    elements = new List <OptionConfigurationElement>();

            foreach (var property in this.Properties)
            {
                if (TypeExtension.IsAssignableFrom(typeof(OptionConfigurationElement), property.Type))
                {
                    if (_values.TryGetValue(property, out value))
                    {
                        elements.Add((OptionConfigurationElement)value);
                    }
                }
                else
                {
                    if (_values.TryGetValue(property, out value))
                    {
                        writer.WriteStartAttribute(property.Name);
                        writer.WriteString(OptionConfigurationUtility.GetValueString(value, property.Converter));
                        writer.WriteEndAttribute();
                    }
                }
            }

            if (elements.Count > 0)
            {
                foreach (var element in elements)
                {
                    element.SerializeElement(writer);
                }
            }

            if (!string.IsNullOrEmpty(elementName))
            {
                writer.WriteEndElement();
            }
        }
Пример #30
0
        public override object GetDefaultValue(TypeExtension typeExt, Type type, out bool isSet)
        {
            object value = null;

            if (type.IsEnum)
            {
                value = GetEnumDefaultValueFromExtension(typeExt, type);
            }

            if (value == null)
            {
                value = typeExt.Attributes["DefaultValue"].Value;
            }

            isSet = value != null;

            return(TypeExtension.ChangeType(value, type));
        }
Пример #31
0
        public string ToString(int idx)
        {
            Object val = stack.Get(idx);

            if (TypeExtension.TypeEqual <string>(val))
            {
                return((string)val);
            }
            else if (TypeExtension.TypeEqual <long>(val) ||
                     TypeExtension.TypeEqual <double>(val))
            {
                return(val.ToString());
            }
            else
            {
                return(null);
            }
        }
Пример #32
0
        public override MapValue[] GetMapValues(TypeExtension typeExt, Type type, out bool isSet)
        {
            List <MapValue> list = null;

            if (type.IsEnum)
            {
                list = GetEnumMapValues(typeExt, type);
            }

            if (list == null)
            {
                list = GetTypeMapValues(typeExt, type);
            }

            isSet = list != null;

            return(isSet? list.ToArray(): null);
        }
        public override Association GetAssociation(TypeExtension typeExtension, MemberAccessor member)
        {
            if (member.Type.IsClass && !member.Type.FullName.StartsWith("System"))
            {
                bool canBeNull = !member.IsDefined<RequiredAttribute>();
                Type otherType = member.Type;
                if(otherType.IsGenericType)
                    otherType = otherType.GetGenericArguments()[0];
                string[] otherKeys = null;
                string[] thisKeys = null;
                if (member.IsDefined<System.ComponentModel.DataAnnotations.AssociationAttribute>())
                {
                    var asAttr = member.GetAttribute<System.ComponentModel.DataAnnotations.AssociationAttribute>();
                    thisKeys = asAttr.ThisKeyMembers.ToArray();
                    otherKeys = asAttr.OtherKeyMembers.ToArray();
                }
                else if (member.IsDefined<ForeignKeyAttribute>())
                {
                    var fkAttr = member.GetAttribute<ForeignKeyAttribute>();
                    otherKeys = GetTypeKeyNames(otherType);
                    thisKeys = fkAttr.Name.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    otherKeys = GetTypeKeyNames(otherType);
                    thisKeys = otherKeys;
                }

                if (thisKeys != null && otherKeys != null && thisKeys.Length == otherKeys.Length && thisKeys.Length > 0)
                {
                    return new Association(
                        member,
                        thisKeys,
                        otherKeys,
                        string.Format("FK_{0}_{1}", member.TypeAccessor.Type, otherType),
                        canBeNull);
                }
            }
            return base.GetAssociation(typeExtension, member);
        }
Пример #34
0
			public override string GetFieldName(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
			{
				string name = string.Empty;

				foreach (char c in member.Name)
				{
					if (char.IsUpper(c))
					{
						if (name.Length > 0)
							name += '_';
						name += c;
					}
					else
					{
						name += char.ToUpper(c);
					}
				}

				isSet = true;

				return name;
			}
Пример #35
0
		public void Read_TypeExtension ()
		{
			var tx = new TypeExtension (typeof (int));
			var r = new XamlObjectReader (tx);
			Read_TypeOrTypeExtension (r);
		}
        internal void SerializeContents(WorkflowMarkupSerializationManager serializationManager, object obj, XmlWriter writer, bool dictionaryKey)
        {
            if (serializationManager == null)
                throw new ArgumentNullException("serializationManager");
            if (obj == null)
                throw new ArgumentNullException("obj");
            if (writer == null)
                throw new ArgumentNullException("writer");

            WorkflowMarkupSerializer serializer = null;
            try
            {
                //Now get the serializer to persist the properties, if the serializer is not found then we dont serialize the properties
                serializer = serializationManager.GetSerializer(obj.GetType(), typeof(WorkflowMarkupSerializer)) as WorkflowMarkupSerializer;

            }
            catch (Exception e)
            {
                serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                return;

            }

            if (serializer == null)
            {
                serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerNotAvailableForSerialize, obj.GetType().FullName)));
                return;
            }

            try
            {
                serializer.OnBeforeSerialize(serializationManager, obj);
            }
            catch (Exception e)
            {
                serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                return;
            }

            Hashtable allProperties = new Hashtable();
            ArrayList complexProperties = new ArrayList();

            IDictionary<DependencyProperty, object> dependencyProperties = null;
            List<PropertyInfo> properties = new List<PropertyInfo>();
            List<EventInfo> events = new List<EventInfo>();
            Hashtable designTimeTypeNames = null;

            // Serialize the extended properties for primitive types also
            if (obj.GetType().IsPrimitive || obj.GetType() == typeof(string) || obj.GetType() == typeof(decimal) ||
                obj.GetType() == typeof(DateTime) || obj.GetType() == typeof(TimeSpan) || obj.GetType().IsEnum ||
                obj.GetType() == typeof(Guid))
            {
                if (obj.GetType() == typeof(char) || obj.GetType() == typeof(byte) ||
                    obj.GetType() == typeof(System.Int16) || obj.GetType() == typeof(decimal) ||
                    obj.GetType() == typeof(DateTime) || obj.GetType() == typeof(TimeSpan) ||
                    obj.GetType().IsEnum || obj.GetType() == typeof(Guid))
                {
                    //These non CLS-compliant are not supported in the XmlWriter 
                    if ((obj.GetType() != typeof(char)) || (char)obj != '\0')
                    {
                        //These non CLS-compliant are not supported in the XmlReader 
                        string stringValue = String.Empty;
                        if (obj.GetType() == typeof(DateTime))
                        {
                            stringValue = ((DateTime)obj).ToString("o", CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            TypeConverter typeConverter = TypeDescriptor.GetConverter(obj.GetType());
                            if (typeConverter != null && typeConverter.CanConvertTo(typeof(string)))
                                stringValue = typeConverter.ConvertTo(null, CultureInfo.InvariantCulture, obj, typeof(string)) as string;
                            else
                                stringValue = Convert.ToString(obj, CultureInfo.InvariantCulture);
                        }

                        writer.WriteValue(stringValue);
                    }
                }
                else if (obj.GetType() == typeof(string))
                {
                    string attribValue = obj as string;
                    attribValue = attribValue.Replace('\0', ' ');
                    if (!(attribValue.StartsWith("{", StringComparison.Ordinal) && attribValue.EndsWith("}", StringComparison.Ordinal)))
                        writer.WriteValue(attribValue);
                    else
                        writer.WriteValue("{}" + attribValue);
                }
                else
                {
                    writer.WriteValue(obj);
                }
                // For Key properties, we don;t want to get the extended properties
                if (!dictionaryKey)
                    properties.AddRange(serializationManager.GetExtendedProperties(obj));
            }
            else
            {
                // Serialize properties
                //We first get all the properties, once we have them all, we start distinguishing between
                //simple and complex properties, the reason for that is XmlWriter needs to write attributes
                //first and elements later

                // Dependency events are treated as the same as dependency properties.


                try
                {
                    if (obj is DependencyObject && ((DependencyObject)obj).UserData.Contains(UserDataKeys.DesignTimeTypeNames))
                        designTimeTypeNames = ((DependencyObject)obj).UserData[UserDataKeys.DesignTimeTypeNames] as Hashtable;
                    dependencyProperties = serializer.GetDependencyProperties(serializationManager, obj);
                    properties.AddRange(serializer.GetProperties(serializationManager, obj));
                    // For Key properties, we don;t want to get the extended properties
                    if (!dictionaryKey)
                        properties.AddRange(serializationManager.GetExtendedProperties(obj));
                    events.AddRange(serializer.GetEvents(serializationManager, obj));
                }
                catch (Exception e)
                {
                    serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                    return;
                }
            }
            if (dependencyProperties != null)
            {
                // For attached properties that does not have a corresponding real property on the object, if the value is a design time
                // type, it may not be set through dependency property SetValue, therefore will not be present in the dependencyProperties
                // collection, we'll have to get the dependency property object ourselves.
                if (designTimeTypeNames != null)
                {
                    foreach (object key in designTimeTypeNames.Keys)
                    {
                        DependencyProperty dependencyProperty = key as DependencyProperty;
                        if (dependencyProperty != null && !dependencyProperties.ContainsKey(dependencyProperty))
                            dependencyProperties.Add(dependencyProperty, designTimeTypeNames[dependencyProperty]);
                    }
                }

                // Add all dependency properties to the master collection.
                foreach (DependencyProperty dependencyProperty in dependencyProperties.Keys)
                {
                    string propertyName = String.Empty;
                    if (dependencyProperty.IsAttached)
                    {
                        string prefix = String.Empty;
                        XmlQualifiedName qualifiedName = serializationManager.GetXmlQualifiedName(dependencyProperty.OwnerType, out prefix);
                        propertyName = qualifiedName.Name + "." + dependencyProperty.Name;
                    }
                    else
                    {
                        propertyName = dependencyProperty.Name;
                    }

                    if (dependencyProperty.IsAttached || !dependencyProperty.DefaultMetadata.IsMetaProperty)
                        allProperties.Add(propertyName, dependencyProperty);
                }
            }

            if (properties != null)
            {
                foreach (PropertyInfo propInfo in properties)
                {
                    // Do not serialize properties that have corresponding dynamic properties.
                    if (propInfo != null && !allProperties.ContainsKey(propInfo.Name))
                        allProperties.Add(propInfo.Name, propInfo);
                }
            }

            if (events != null)
            {
                foreach (EventInfo eventInfo in events)
                {
                    // Do not serialize events that have corresponding dynamic properties.
                    if (eventInfo != null && !allProperties.ContainsKey(eventInfo.Name))
                        allProperties.Add(eventInfo.Name, eventInfo);
                }
            }

            using (ContentProperty contentProperty = new ContentProperty(serializationManager, serializer, obj))
            {
                foreach (object propertyObj in allProperties.Values)
                {
                    string propertyName = String.Empty;
                    object propertyValue = null;
                    Type propertyInfoType = null;

                    try
                    {
                        if (propertyObj is PropertyInfo)
                        {
                            PropertyInfo property = propertyObj as PropertyInfo;

                            // If the property has parameters we can not serialize it , we just move on.
                            ParameterInfo[] indexParameters = property.GetIndexParameters();
                            if (indexParameters != null && indexParameters.Length > 0)
                                continue;

                            propertyName = property.Name;
                            propertyValue = null;
                            if (property.CanRead)
                            {
                                propertyValue = property.GetValue(obj, null);
                                if (propertyValue == null && TypeProvider.IsAssignable(typeof(Type), property.PropertyType))
                                {
                                    // See if we have a design time value for the property
                                    DependencyProperty dependencyProperty = DependencyProperty.FromName(property.Name, property.ReflectedType);
                                    if (dependencyProperty != null)
                                        propertyValue = Helpers.GetDesignTimeTypeName(obj, dependencyProperty);

                                    if (propertyValue == null)
                                    {
                                        string key = property.ReflectedType.FullName + "." + property.Name;
                                        propertyValue = Helpers.GetDesignTimeTypeName(obj, key);
                                    }
                                    if (propertyValue != null)
                                        propertyValue = new TypeExtension((string)propertyValue);
                                }
                            }
                            propertyInfoType = property.PropertyType;
                        }
                        else if (propertyObj is EventInfo)
                        {
                            EventInfo evt = propertyObj as EventInfo;
                            propertyName = evt.Name;
                            propertyValue = WorkflowMarkupSerializationHelpers.GetEventHandlerName(obj, evt.Name);
                            if ((propertyValue == null || (propertyValue is string && string.IsNullOrEmpty((string)propertyValue)))
                                && obj is DependencyObject)
                            {
                                // The object is not created through deserialization, we should check to see if the delegate is 
                                // created and added to list.  We can only serialize the handler if its target type is the same
                                // as the activity type that's be designed.
                                DependencyProperty dependencyProperty = DependencyProperty.FromName(propertyName, obj.GetType());
                                if (dependencyProperty != null)
                                {
                                    Activity activity = serializationManager.Context[typeof(Activity)] as Activity;
                                    Delegate handler = ((DependencyObject)obj).GetHandler(dependencyProperty) as Delegate;
                                    if (handler != null && activity != null && TypeProvider.Equals(handler.Target.GetType(), Helpers.GetRootActivity(activity).GetType()))
                                        propertyValue = handler;
                                }
                            }
                            propertyInfoType = evt.EventHandlerType;
                        }
                        else if (propertyObj is DependencyProperty)
                        {
                            DependencyProperty dependencyProperty = propertyObj as DependencyProperty;
                            propertyName = dependencyProperty.Name;
                            propertyValue = dependencyProperties[dependencyProperty];
                            propertyInfoType = dependencyProperty.PropertyType;
                        }
                    }
                    catch (Exception e)
                    {
                        while (e is TargetInvocationException && e.InnerException != null)
                            e = e.InnerException;

                        serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerPropertyGetFailed, new object[] { propertyName, obj.GetType().FullName, e.Message })));
                        continue;
                    }

                    if (propertyObj is PropertyInfo && contentProperty.Property == (PropertyInfo)propertyObj)
                        continue;

                    Type propertyValueType = null;
                    if (propertyValue != null)
                    {
                        propertyValue = GetMarkupExtensionFromValue(propertyValue);
                        propertyValueType = propertyValue.GetType();
                    }
                    else if (propertyObj is PropertyInfo)
                    {
                        propertyValue = new NullExtension();
                        propertyValueType = propertyValue.GetType();
                        Attribute[] attributes = Attribute.GetCustomAttributes(propertyObj as PropertyInfo, typeof(DefaultValueAttribute), true);
                        if (attributes.Length > 0)
                        {
                            DefaultValueAttribute defaultValueAttr = attributes[0] as DefaultValueAttribute;
                            if (defaultValueAttr.Value == null)
                                propertyValue = null;
                        }
                    }
                    if (propertyValue != null)
                        propertyValueType = propertyValue.GetType();

                    //Now get the serializer to persist the properties, if the serializer is not found then we dont serialize the properties
                    serializationManager.Context.Push(propertyObj);
                    WorkflowMarkupSerializer propValueSerializer = null;
                    try
                    {
                        propValueSerializer = serializationManager.GetSerializer(propertyValueType, typeof(WorkflowMarkupSerializer)) as WorkflowMarkupSerializer;
                    }
                    catch (Exception e)
                    {
                        serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                        serializationManager.Context.Pop();
                        continue;
                    }
                    if (propValueSerializer == null)
                    {
                        serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerNotAvailableForSerialize, propertyValueType.FullName)));
                        serializationManager.Context.Pop();
                        continue;
                    }

                    // ask serializer if we can serialize
                    try
                    {
                        if (propValueSerializer.ShouldSerializeValue(serializationManager, propertyValue))
                        {
                            //NOTE: THE FOLLOWING CONDITION ABOUT propertyInfoType != typeof(object) is VALID AS WE SHOULD NOT SERIALIZE A PROPERTY OF TYPE OBJECT TO STRING
                            //IF WE DO THAT THEN WE DO NOT KNOWN WHAT WAS THE TYPE OF ORIGINAL OBJECT AND SERIALIZER WONT BE ABLE TO GET THE STRING BACK INTO THE CORRECT TYPE,
                            //AS THE TYPE INFORMATION IS LOST
                            if (propValueSerializer.CanSerializeToString(serializationManager, propertyValue) && propertyInfoType != typeof(object))
                            {
                                using (new SafeXmlNodeWriter(serializationManager, obj, propertyObj, XmlNodeType.Attribute))
                                {
                                    //This is a work around to special case the markup extension serializer as it writes to the stream using writer
                                    if (propValueSerializer is MarkupExtensionSerializer)
                                    {
                                        propValueSerializer.SerializeToString(serializationManager, propertyValue);
                                    }
                                    else
                                    {
                                        string stringValue = propValueSerializer.SerializeToString(serializationManager, propertyValue);
                                        if (!string.IsNullOrEmpty(stringValue))
                                        {
                                            stringValue = stringValue.Replace('\0', ' ');
                                            if (propertyValue is MarkupExtension || !(stringValue.StartsWith("{", StringComparison.Ordinal) && stringValue.EndsWith("}", StringComparison.Ordinal)))
                                                writer.WriteString(stringValue);
                                            else
                                                writer.WriteString("{}" + stringValue);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                complexProperties.Add(propertyObj);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerNoSerializeLogic, new object[] { propertyName, obj.GetType().FullName }), e));
                    }
                    finally
                    {
                        Debug.Assert(serializationManager.Context.Current == propertyObj, "Serializer did not remove an object it pushed into stack.");
                        serializationManager.Context.Pop();
                    }
                }

                try
                {
                    serializer.OnBeforeSerializeContents(serializationManager, obj);
                }
                catch (Exception e)
                {
                    serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                    return;
                }

                // serialize compound properties as child elements of the current node.
                foreach (object propertyObj in complexProperties)
                {
                    // get value and check for null
                    string propertyName = String.Empty;
                    object propertyValue = null;
                    Type ownerType = null;
                    bool isReadOnly = false;

                    try
                    {
                        if (propertyObj is PropertyInfo)
                        {
                            PropertyInfo property = propertyObj as PropertyInfo;
                            propertyName = property.Name;
                            propertyValue = property.CanRead ? property.GetValue(obj, null) : null;
                            ownerType = obj.GetType();
                            isReadOnly = (!property.CanWrite);
                        }
                        else if (propertyObj is DependencyProperty)
                        {
                            DependencyProperty dependencyProperty = propertyObj as DependencyProperty;
                            propertyName = dependencyProperty.Name;
                            propertyValue = dependencyProperties[dependencyProperty];
                            ownerType = dependencyProperty.OwnerType;
                            isReadOnly = ((dependencyProperty.DefaultMetadata.Options & DependencyPropertyOptions.ReadOnly) == DependencyPropertyOptions.ReadOnly);
                        }
                    }
                    catch (Exception e)
                    {
                        while (e is TargetInvocationException && e.InnerException != null)
                            e = e.InnerException;

                        serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerPropertyGetFailed, propertyName, ownerType.FullName, e.Message)));
                        continue;
                    }

                    if (propertyObj is PropertyInfo && (PropertyInfo)propertyObj == contentProperty.Property)
                        continue;

                    if (propertyValue != null)
                    {
                        propertyValue = GetMarkupExtensionFromValue(propertyValue);

                        WorkflowMarkupSerializer propValueSerializer = serializationManager.GetSerializer(propertyValue.GetType(), typeof(WorkflowMarkupSerializer)) as WorkflowMarkupSerializer;
                        if (propValueSerializer != null)
                        {
                            using (new SafeXmlNodeWriter(serializationManager, obj, propertyObj, XmlNodeType.Element))
                            {
                                if (isReadOnly)
                                    propValueSerializer.SerializeContents(serializationManager, propertyValue, writer, false);
                                else
                                    propValueSerializer.SerializeObject(serializationManager, propertyValue, writer);
                            }
                        }
                        else
                        {
                            serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerNotAvailableForSerialize, propertyValue.GetType().FullName)));
                        }
                    }
                }

                // serialize the contents
                try
                {
                    object contents = contentProperty.GetContents();
                    if (contents != null)
                    {
                        contents = GetMarkupExtensionFromValue(contents);

                        WorkflowMarkupSerializer propValueSerializer = serializationManager.GetSerializer(contents.GetType(), typeof(WorkflowMarkupSerializer)) as WorkflowMarkupSerializer;
                        if (propValueSerializer == null)
                        {
                            serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerNotAvailableForSerialize, contents.GetType())));
                        }
                        else
                        {
                            //



                            //NOTE: THE FOLLOWING CONDITION ABOUT contentProperty.Property.PropertyType != typeof(object) is VALID AS WE SHOULD NOT SERIALIZE A PROPERTY OF TYPE OBJECT TO STRING
                            //IF WE DO THAT THEN WE DO NOT KNOWN WHAT WAS THE TYPE OF ORIGINAL OBJECT AND SERIALIZER WONT BE ABLE TO GET THE STRING BACK INTO THE CORRECT TYPE,
                            //AS THE TYPE INFORMATION IS LOST
                            if (propValueSerializer.CanSerializeToString(serializationManager, contents) &&
                                (contentProperty.Property == null || contentProperty.Property.PropertyType != typeof(object)))
                            {
                                string stringValue = propValueSerializer.SerializeToString(serializationManager, contents);
                                if (!string.IsNullOrEmpty(stringValue))
                                {
                                    stringValue = stringValue.Replace('\0', ' ');
                                    if (contents is MarkupExtension || !(stringValue.StartsWith("{", StringComparison.Ordinal) && stringValue.EndsWith("}", StringComparison.Ordinal)))
                                        writer.WriteString(stringValue);
                                    else
                                        writer.WriteString("{}" + stringValue);
                                }
                            }
                            else if (CollectionMarkupSerializer.IsValidCollectionType(contents.GetType()))
                            {
                                if (contentProperty.Property == null)
                                {
                                    IEnumerable enumerableContents = contents as IEnumerable;
                                    foreach (object childObj in enumerableContents)
                                    {
                                        if (childObj == null)
                                        {
                                            SerializeObject(serializationManager, new NullExtension(), writer);
                                        }
                                        else
                                        {
                                            object childObj2 = childObj;
                                            bool dictionaryEntry = (childObj2 is DictionaryEntry);
                                            try
                                            {
                                                if (dictionaryEntry)
                                                {
                                                    serializationManager.WorkflowMarkupStack.Push(childObj);
                                                    childObj2 = ((DictionaryEntry)childObj2).Value;
                                                }
                                                childObj2 = GetMarkupExtensionFromValue(childObj2);
                                                WorkflowMarkupSerializer childObjectSerializer = serializationManager.GetSerializer(childObj2.GetType(), typeof(WorkflowMarkupSerializer)) as WorkflowMarkupSerializer;
                                                if (childObjectSerializer != null)
                                                    childObjectSerializer.SerializeObject(serializationManager, childObj2, writer);
                                                else
                                                    serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerNotAvailableForSerialize, childObj2.GetType())));
                                            }
                                            finally
                                            {
                                                if (dictionaryEntry)
                                                    serializationManager.WorkflowMarkupStack.Pop();
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    propValueSerializer.SerializeContents(serializationManager, contents, writer, false);
                                }
                            }
                            else
                            {
                                propValueSerializer.SerializeObject(serializationManager, contents, writer);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                    return;
                }
            }

            try
            {
                serializer.OnAfterSerialize(serializationManager, obj);
            }
            catch (Exception e)
            {
                serializationManager.ReportError(new WorkflowMarkupSerializationException(SR.GetString(SR.Error_SerializerThrewException, obj.GetType().FullName, e.Message), e));
                return;
            }
        }
		public void ProvideValueWithType ()
		{
			var x = new TypeExtension (typeof (int));
			Assert.AreEqual (typeof (int), x.ProvideValue (null), "#1"); // serviceProvider is not required.
		}
        public override bool GetTrimmable(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (member.Type == typeof(string))
            {
                isSet = true;
                return true;
            }

            return base.GetTrimmable(typeExtension, member, out isSet);
        }
		/// <summary>
		///     Initializes a new instance of the TypeConverterExtension class with the specified source and target types.
		/// </summary>
		/// <param name="sourceType">
		///     The source type for the <see cref="TypeConverter" />.
		/// </param>
		/// <param name="targetType">
		///     The target type for the <see cref="TypeConverter" />.
		/// </param>
		public TypeConverterExtension(Type sourceType, Type targetType)
		{
			sourceTypeExtension = new TypeExtension(sourceType);
			targetTypeExtension = new TypeExtension(targetType);
		}
Пример #40
0
        // The end of the constructor parameter section has been reached.  Create an
        // instance of the object after finding the appropriate constructor and converting 
        // all of the objects held on the stack. 
        internal virtual void ReadConstructorParametersEndRecord()
        { 
            Type   elementType = ParentContext.ExpectedType;
            short  positiveElementTypeId = (short)-ParentContext.ExpectedTypeId;

            object param = null; 
            ArrayList paramList = null;
            int paramCount; 
            object instance = null; 
            bool foundInstance = false;
 
            if( TraceMarkup.IsEnabled )
            {
                TraceMarkup.Trace( TraceEventType.Start,
                                 TraceMarkup.CreateMarkupExtension, 
                                 elementType );
            } 
 
            if (CurrentContext.CheckFlag(ReaderFlags.SingletonConstructorParam))
            { 
                param = CurrentContext.ObjectData;
                paramCount = 1;

                // Fast code path for [static/dynamic] resource extensions & 
                // Type/Static/TemplateBinding extensions
                switch (positiveElementTypeId) 
                { 
                    case (short)KnownElements.TypeExtension:
 
                        // Note that this assumes that TypeExtension has a
                        // constructor with one param of type Type or String.
                        Type t = param as Type;
                        if (t != null) 
                        {
                            instance = new TypeExtension(t); 
                        } 
                        else
                        { 
                            Debug.Assert(param is String);
                            instance = new TypeExtension((String)param);
                        }
 
                        foundInstance = true;
                        break; 
 
                    case (short)KnownElements.StaticResourceExtension:
 
                        // Note that this assumes that StaticResourceExtension has a
                        // constructor with one param of type object.
                        instance = new StaticResourceExtension(param);
                        foundInstance = true; 
                        break;
 
                    case (short)KnownElements.DynamicResourceExtension: 

                        // Note that this assumes that DynamicResourceExtension has a 
                        // constructor with one param of type object.
                        instance = new DynamicResourceExtension(param);
                        foundInstance = true;
                        break; 

                    case (short)KnownElements.StaticExtension: 
 
                        // Note that this assumes that StaticExtension has a default
                        // constructor and one public property of type string and one 
                        // internal property of type object for optimized member info.
                        instance = new StaticExtension((string)param);
                        foundInstance = true;
                        break; 

                    case (short)KnownElements.TemplateBindingExtension: 
 
                        // Note that this assumes that TemplateBindingExtension has a
                        // constructor with one param of type DependencyProperty. If a 
                        // string is passed in due to there being other attributes like
                        // converter being set, then that needs to be converted now first.
                        DependencyProperty dp = param as DependencyProperty;
                        if (dp == null) 
                        {
                            string paramString = param as string; 
                            Type ownerType = ParserContext.TargetType; 
                            Debug.Assert(paramString != null);
 
                            dp = XamlTypeMapper.ParsePropertyName(ParserContext,
                                                                  paramString.Trim(),
                                                                  ref ownerType);
 
                            if (dp == null)
                            { 
                                ThrowException(SRID.ParserNoDPOnOwner, paramString, ownerType.FullName); 
                            }
                        } 

                        instance = new TemplateBindingExtension(dp);
                        foundInstance = true;
                        break; 
                }
            } 
            else 
            {
                paramList = (ArrayList)CurrentContext.ObjectData; 
                paramCount = paramList.Count;
            }

            if (!foundInstance) 
            {
                // Find the constructor based on the number of parameters stored in paramList 
                XamlTypeMapper.ConstructorData data = XamlTypeMapper.GetConstructors(elementType); 
                ConstructorInfo[] infos = data.Constructors;
                for (int i=0; i<infos.Length; i++) 
                {
                    ConstructorInfo info = infos[i];
                    ParameterInfo[] paramInfos = data.GetParameters(i);
                    if (paramInfos.Length == paramCount) 
                    {
                        object[] paramArray = new object[paramInfos.Length]; 
 
                        if (paramCount == 1)
                        { 
                            Debug.Assert(param != null && paramList == null, "Must have a single param");
                            ProcessConstructorParameter(paramInfos[0], param, ref paramArray[0]);

                            // Fast code path for other markupextensions 
                            if (positiveElementTypeId == (short)KnownElements.RelativeSource)
                            { 
                                // Note that this assumes that RelativeSource has a 
                                // constructor with one param of type RelativeSourceMode.
                                instance = new System.Windows.Data.RelativeSource((System.Windows.Data.RelativeSourceMode)paramArray[0]); 
                                foundInstance = true;
                            }
                        }
                        else 
                        {
                            Debug.Assert(param == null && paramList != null, "Must have a paramList"); 
 
                            // Check each type and attempt to convert the paramList using
                            // the type converter associated with each parameter type. 
                            for (int j=0; j<paramInfos.Length; j++)
                            {
                                ProcessConstructorParameter(paramInfos[j], paramList[j], ref paramArray[j]);
                            } 
                        }
 
                        if (!foundInstance) 
                        {
                            // If we make it to here we have a list of converted parameters, so 
                            // invoke the constructor with that list.
#if !STRESS
                            try
                            { 
#endif
                                instance = info.Invoke(paramArray); 
                                foundInstance = true; 
#if !STRESS
                            } 
                            catch (Exception e)
                            {
                                if (CriticalExceptions.IsCriticalException(e) || e is XamlParseException)
                                { 
                                    throw;
                                } 
 
                                TargetInvocationException tie = e as TargetInvocationException;
                                if( tie != null ) 
                                {
                                    e = tie.InnerException;
                                }
 
                                ThrowExceptionWithLine(SR.Get(SRID.ParserFailedToCreateFromConstructor, info.DeclaringType.Name),  e);
 
                            } 
#endif
                        } 
                    }
                }
            }
 
            if (foundInstance)
            { 
                ParentContext.ObjectData = instance; 
                ParentContext.ExpectedType = null;
                PopContext(); 
            }
            else
            {
                // If we get to here, then no matching constructor was found, so complain 
                ThrowException(SRID.ParserBadConstructorParams, elementType.Name, paramCount.ToString(CultureInfo.CurrentCulture));
            } 
 
            if( TraceMarkup.IsEnabled )
            { 
                TraceMarkup.Trace( TraceEventType.Stop,
                                 TraceMarkup.CreateMarkupExtension,
                                 elementType,
                                 instance ); 
            }
 
        } 
Пример #41
0
		private static TypeExtension ParseType(XmlNode typeNode)
		{
			TypeExtension ext = new TypeExtension();

			if (typeNode.Attributes != null)
			{
				foreach (XmlAttribute attr in typeNode.Attributes)
				{
					if (attr.LocalName == AttrName.Name)
						ext.Name = attr.Value;
					else
						ext.Attributes.Add(attr.LocalName, attr.Value);
				}
			}

			foreach (XmlNode node in typeNode.ChildNodes)
			{
				if (node.LocalName == NodeName.Member)
					ext.Members.Add(ParseMember(node));
				else
					ext.Attributes.Add(ParseAttribute(node));
			}

			return ext;
		}
        public override bool GetSqlIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            var ignoreAttr = member.GetAttribute<NotMappedAttribute>();
            if (ignoreAttr != null)
            {
                isSet = true;
                return true;
            }

            var scAttr = member.GetAttribute<ScaffoldColumnAttribute>();
            if (scAttr != null)
            {
                isSet = true;
                return true;
            }

            return base.GetSqlIgnore(typeExtension, member, out isSet);
        }
		public void ProvideValueWithNameWithProviderNoResolver ()
		{
			var x = new TypeExtension ("System.Int32");
			x.ProvideValue (new Resolver (false, false));
		}
				public override bool GetMapIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
				{
					if (member.Type == typeof(CustomString))
					{
						isSet = true;
						return false;
					}

					return base.GetMapIgnore(typeExtension, member, out isSet);
				}
Пример #45
0
		object GetCorrectlyTypedValue (XamlType xt, object value)
		{
			// FIXME: this could be generalized by some means, but I cannot find any.
			if (xt.UnderlyingType == typeof (Type))
				xt = XamlLanguage.Type;
			if (xt == XamlLanguage.Type && value is string)
				value = new TypeExtension ((string) value);
			
			if (value is MarkupExtension)
				value = ((MarkupExtension) value).ProvideValue (service_provider);

			if (IsAllowedType (xt, value))
				return value;

			if (xt.TypeConverter != null && value != null) {
				var tc = xt.TypeConverter.ConverterInstance;
				if (tc != null && tc.CanConvertFrom (value.GetType ()))
					value = tc.ConvertFrom (value);
				if (IsAllowedType (xt, value))
					return value;
			}

			throw new XamlObjectWriterException (String.Format ("Value '{1}' (of type {2}) is not of or convertible to type {0}", xt, value, value != null ? (object) value.GetType () : "(null)"));
		}
Пример #46
0
		public void Add(TypeExtension typeInfo)
		{
			_types[typeInfo.Name] = typeInfo;
		}
 public override object GetDefaultValue(MappingSchema mappingSchema, TypeExtension typeExtension, MemberAccessor member, out bool isSet)
 {
     return GetDefaultValue(mappingSchema, typeExtension, member.Type, out isSet);
 }
Пример #48
0
		// It expects that it is not invoked when there is no value to 
		// assign.
		// When it is passed null, then it returns a default instance.
		// For example, passing null as Int32 results in 0.
		object DoGetCorrectlyTypedValue (XamlType xt, object value)
		{
			if (value == null)
				return xt.Invoker.CreateInstance (new object [0]);

			// FIXME: this could be generalized by some means, but I cannot find any.
			if (xt.UnderlyingType == typeof (Type))
				xt = XamlLanguage.Type;
			if (xt == XamlLanguage.Type && value is string)
				value = new TypeExtension ((string) value);

			// FIXME: this could be generalized by some means, but I cannot find any.
			if (xt.UnderlyingType == typeof (XamlType) && value is string) {
				var nsr = (IXamlNamespaceResolver) service_provider.GetService (typeof (IXamlNamespaceResolver));
				value = sctx.GetXamlType (XamlTypeName.Parse ((string) value, nsr));
			}
			
			if (value is MarkupExtension)
				value = ((MarkupExtension) value).ProvideValue (service_provider);

			if (IsAllowedType (xt, value))
				return value;

			if (xt.TypeConverter != null && value != null) {
				var tc = xt.TypeConverter.ConverterInstance;
				if (tc != null && tc.CanConvertFrom (value.GetType ()))
					value = tc.ConvertFrom (value);
				return value;
			}

			throw new XamlObjectWriterException (String.Format ("Value '{1}' (of type {2}) is not of or convertible to type {0}", xt, value, value != null ? (object) value.GetType () : "(null)"));
		}
Пример #49
0
		// It expects that it is not invoked when there is no value to 
		// assign.
		// When it is passed null, then it returns a default instance.
		// For example, passing null as Int32 results in 0.
		// But do not immediately try to instantiate with the type, since the type might be abstract.
		object DoGetCorrectlyTypedValue (XamlMember xm, XamlType xt, object value)
		{
			if (value == null) {
				if (xt.IsContentValue (service_provider)) // it is for collection/dictionary key and item
					return null;
				else
					return xt.IsNullable ? null : xt.Invoker.CreateInstance (new object [0]);
			}
			if (xt == null)
				return value;

			// Not sure if this is really required though...
			var vt = sctx.GetXamlType (value.GetType ());
			if (vt.CanAssignTo (xt))
				return value;

			// FIXME: this could be generalized by some means, but I cannot find any.
			if (xt.UnderlyingType == typeof (XamlType) && value is string)
				value = ResolveTypeFromName ((string) value);

			// FIXME: this could be generalized by some means, but I cannot find any.
			if (xt.UnderlyingType == typeof (Type))
				value = new TypeExtension ((string) value).ProvideValue (service_provider);
			if (xt == XamlLanguage.Type && value is string)
				value = new TypeExtension ((string) value);
			
			if (IsAllowedType (xt, value))
				return value;

			var xtc = xm?.TypeConverter ?? xt.TypeConverter;
			if (xtc != null && value != null) {
				var tc = xtc.ConverterInstance;
				if (tc != null && tc.CanConvertFrom (value.GetType ()))
					value = tc.ConvertFrom (service_provider, null, value);
				return value;
			}

			throw new XamlObjectWriterException (String.Format ("Value '{0}' (of type {1}) is not of or convertible to type {0} (member {3})", value, value != null ? (object) value.GetType () : "(null)", xt, xm));
		}
        public override string GetFieldName(TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            var colAttr = member.GetAttribute<ColumnAttribute>();
            if (colAttr != null)
            {
                if (!string.IsNullOrEmpty(colAttr.Name))
                {
                    isSet = true;
                    return colAttr.Name;
                }
            }

            return base.GetFieldName(typeExtension, member, out isSet);
        }
		/// <summary>
		///     Initializes a new instance of the TypeConverterExtension class.
		/// </summary>
		public TypeConverterExtension()
		{
			sourceTypeExtension = new TypeExtension();
			targetTypeExtension = new TypeExtension();
		}
Пример #52
0
 /// <summary>
 /// Assign a type
 /// </summary>
 /// <param name="assignment"><see cref="Assignment"/> to assign to</param>
 /// <param name="callback"><see cref="Action{TypeExtension}"/> that gets called to build the type</param>
 /// <returns>The <see cref="Assignment"/> to build on</returns>
 public static Assignment WithType(this Assignment assignment, Action<TypeExtension> callback)
 {
     var typeExtension = new TypeExtension();
     assignment.Value = typeExtension;
     callback(typeExtension);
     return assignment;
 }
		/// <summary>
		///     Initializes a new instance of the TypeConverterExtension class with the specified source and target types.
		/// </summary>
		/// <param name="sourceTypeName">
		///     The source type name for the <see cref="TypeConverter" />.
		/// </param>
		/// <param name="targetTypeName">
		///     The target type name for the <see cref="TypeConverter" />.
		/// </param>
		public TypeConverterExtension(string sourceTypeName, string targetTypeName)
		{
			sourceTypeExtension = new TypeExtension(sourceTypeName);
			targetTypeExtension = new TypeExtension(targetTypeName);
		}
Пример #54
0
		private static TypeExtension ParseType(XElement typeNode)
		{
			var ext = new TypeExtension();

			foreach (var attr in typeNode.Attributes())
			{
				if (attr.Name.LocalName == AttrName.Name)
					ext.Name = attr.Value;
				else
					ext.Attributes.Add(attr.Name.LocalName, attr.Value);
			}

			foreach (var node in typeNode.Elements())
			{
				if (node.Name.LocalName == NodeName.Member)
					ext.Members.Add(ParseMember(node));
				else
					ext.Attributes.Add(ParseAttribute(node));
			}

			return ext;
		}
		public void ProvideValueWithNameWithProviderResolveSuccess ()
		{
			var x = new TypeExtension ("System.Int32");
			x.ProvideValue (new Resolver (true, true));
		}
 public override object GetDefaultValue(MappingSchema mappingSchema, TypeExtension typeExtension, Type type, out bool isSet)
 {
     return base.GetDefaultValue(mappingSchema, typeExtension, type, out isSet);
 }
		public void ProvideValueWithNameWithoutResolver ()
		{
			var x = new TypeExtension ("System.Int32");
			x.ProvideValue (null); // serviceProvider is required.
		}
        public override object GetNullValue(MappingSchema mappingSchema, TypeExtension typeExtension, MemberAccessor member, out bool isSet)
        {
            if (member.Type == typeof(string))
            {
                isSet = true;
                return null;
            }

            if (TypeHelper.IsNullableType(member.Type))
            {
                isSet = true;
                return null;
            }

            if (member.Type.IsEnum)
            {
                var value = CheckNullValue(mappingSchema.GetNullValue(member.Type), member);

                if (value != null)
                {
                    isSet = true;
                    return value;
                }
            }

            return base.GetNullValue(mappingSchema, typeExtension, member, out isSet);
        }
		public void ProvideValueWithNameWithProviderResolveFail ()
		{
			var x = new TypeExtension ("System.Int32");
			x.ProvideValue (new Resolver (true, false)); // raise an error (do not return null)
		}
        public override int GetPrimaryKeyOrder(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet)
        {
            var keyAttr = member.GetAttribute<KeyAttribute>();
            if (keyAttr != null)
            {
                isSet = true;
                var colAttr = member.GetAttribute<ColumnAttribute>();
                if (colAttr != null)
                    return colAttr.Order;
                return 0;
            }

            return base.GetPrimaryKeyOrder(type, typeExt, member, out isSet);
        }