Ejemplo n.º 1
0
        private static TData GetEntityData <TData>(object entity, Type entityType, Action <TData, string, object> action)
            where TData : class, new()
        {
            if (entity == null)
            {
                return(null);
            }

            TData data = Activator.CreateInstance <TData>();//类型TData要求new()约束

            EntityMetadata entityMeta = EntityMetadataCache.GetEntityMetadata(entityType);

            foreach (PropertyMetadata field in entityMeta.Propertys)
            {
                MethodInfo mi = field.PropertyInfo.GetGetMethod();
                if (mi == null)
                {
                    continue;                                           // 无Getter的时候忽略此Property
                }
                string key   = field.FieldName;
                object value = mi.Invoke(entity, null);

                if (value == null)
                {
                    action(data, key, value);
                    continue;
                }

                Type propType = field.PropertyInfo.PropertyType;
                if (propType.IsGenericType)
                {
                    if (propType.IsValueType)
                    {
                        action(data, key, value);
                    }
                    else if (IsIList(propType))//TODO:未处理循环引用情况,此时会导致死循环
                    {
                        Type genericType = propType.GetGenericArguments()[0];
                        if (genericType.IsClass)
                        {
                            IList         entites = value as IList;
                            IList <TData> list    = GetEntityDatas <TData>(entites, genericType, action);
                            action(data, key, list);
                        }
                    }
                    continue;
                }

                if (IsPrimitiveType(propType) || propType.IsEnum)
                {
                    action(data, key, value);
                    continue;
                }

                action(data, key, GetEntityData(value, propType, action));
            }
            return(data);
        }
        public void IsManyToManyTest()
        {
            var cache = new EntityMetadataCache(orgService);

            var isManytoMany  = cache.GetManyToManyEntityDetails("queuemembership");
            var isManyToMany2 = cache.GetManyToManyEntityDetails("queuemembership");

            Assert.IsNotNull(isManytoMany);
            Assert.IsNotNull(isManyToMany2);
        }
Ejemplo n.º 3
0
        public void GetEntityMetadata()
        {
            var orgService   = ConnectionHelper.GetOrganizationalServiceTarget();
            var cache        = new EntityMetadataCache(orgService);
            var contactCache = cache.GetEntityMetadata("contact");

            // this time it shoudl get item from cache
            var cache2        = new EntityMetadataCache(orgService);
            var contactCache2 = cache2.GetEntityMetadata("contact");

            Assert.AreSame(contactCache, contactCache2);
            Assert.AreEqual(contactCache.Keys.Length, contactCache2.Keys.Length);
        }
        public void ObfuscateStringFieldsTest()
        {
            var orgService = ConnectionHelper.GetOrganizationalServiceTarget();
            var cache      = new EntityMetadataCache(orgService);

            List <FieldToBeObfuscated> fiedlsToBeObfuscated = new List <FieldToBeObfuscated>
            {
                new FieldToBeObfuscated()
                {
                    FieldName = "firstname"
                }
            };

            EntityToBeObfuscated entityToBeObfuscated = new EntityToBeObfuscated()
            {
                EntityName = "contact"
            };

            entityToBeObfuscated.FieldsToBeObfuscated.AddRange(fiedlsToBeObfuscated);

            var fieldsToBeObfuscated = new List <EntityToBeObfuscated>
            {
                entityToBeObfuscated
            };

            ObfuscateFieldsProcessor processor = new ObfuscateFieldsProcessor(cache, fieldsToBeObfuscated);

            string beforeFirstName = "Bob";
            string beforeLastName  = "test";

            Entity ent = new Entity("contact");

            ent.Attributes.Add("firstname", beforeFirstName);
            ent.Attributes.Add("lastname", beforeLastName);

            EntityWrapper entWrap = new EntityWrapper(ent);

            processor.ProcessEntity(entWrap, 1, 1);

            Assert.AreNotEqual(beforeFirstName, entWrap.OriginalEntity.Attributes["firstname"]);
            Assert.AreEqual(beforeLastName, entWrap.OriginalEntity.Attributes["lastname"]);
        }
        /// <summary>
        /// Get the metadata for the supplied entity
        /// </summary>
        /// <param name="service">The organization service</param>
        /// <param name="logicalName">The logical name of the entity</param>
        /// <param name="ignoreCache">A value indicating whether to ignore the cache</param>
        /// <returns>The metadata for the supplied entity</returns>
        public static EntityMetadata GetEntityMetadata(IOrganizationService service, string logicalName, bool ignoreCache = false)
        {
            lock (LockEntityMetadataCache)
            {
                string         key = logicalName;
                EntityMetadata entityMetadata;

                if (ignoreCache || DateTime.Now > EntityMetadataCacheExpiry)
                {
                    EntityMetadataCache.TryRemove(key, out entityMetadata);
                    EntityMetadataCacheExpiry = DateTime.Now.AddMinutes(CacheValidMinutes);
                }

                entityMetadata = EntityMetadataCache.GetOrAdd(key, x => ((RetrieveEntityResponse)service.Execute(new RetrieveEntityRequest {
                    LogicalName = logicalName, EntityFilters = EntityFilters.All
                })).EntityMetadata);

                return(entityMetadata);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 实体列表转DataTable
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="entitys">实体集合</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableOfEntitys <TEntity>(IList <TEntity> entitys) where TEntity : class
        {
            if (entitys == null || entitys.Count < 1)
            {
                return(new DataTable());
            }

            // 取实体缓存
            Type           type      = typeof(TEntity);
            EntityMetadata tableMeta = EntityMetadataCache.GetEntityMetadata(type);

            // 无需缓存表结构
            DataTable dt = new DataTable(tableMeta.TableName);

            tableMeta.Propertys.ForEach((pi) =>
            {
                Type columnType = pi.PropertyInfo.PropertyType;
                if (columnType.IsGenericType && columnType.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    columnType = columnType.GetGenericArguments()[0];
                }
                dt.Columns.Add(new DataColumn(pi.FieldName, columnType));
            });

            // 填充数据
            foreach (TEntity entity in entitys)
            {
                DataRow row = dt.NewRow();
                tableMeta.Propertys.ForEach((p) =>
                {
                    object value = p.PropertyInfo.GetValue(entity, null);
                    if (value == null)
                    {
                        value = DBNull.Value;
                    }
                    row[p.FieldName] = value;
                });
                dt.Rows.Add(row);
            }
            return(dt);
        }
Ejemplo n.º 7
0
        private static void AssignToPropertyOrField(object propertyValue, object o, string memberName, JsonSerializer serializer)
        {
            IDictionary dictionary = o as IDictionary;

            if (dictionary != null)
            {
                propertyValue          = ConvertObjectToType(propertyValue, null, serializer);
                dictionary[memberName] = propertyValue;
                return;
            }

            Type             serverType = o.GetType();
            EntityMetadata   typeData   = EntityMetadataCache.GetEntityMetadata(serverType); // 使用缓存性能更好 add by zq 2015-12-30
            PropertyMetadata pMeta      = typeData.Propertys.Find(delegate(PropertyMetadata meta) { return(meta.FieldName.ToLower() == memberName.ToLower()); });

            if (pMeta != null)
            {
                PropertyInfo propInfo = pMeta.PropertyInfo;
                MethodInfo   setter   = propInfo.GetSetMethod();
                if (setter != null)
                {
                    propertyValue = ConvertObjectToType(propertyValue, propInfo.PropertyType, serializer, memberName);
                    if (typeof(IParamPropertySetter).IsAssignableFrom(serverType))
                    {
                        ((IParamPropertySetter)o).PropertySetterBeforeInvoke(propInfo.Name, propertyValue);
                    }
                    setter.Invoke(o, new Object[] { propertyValue });
                    return;
                }
            }

            pMeta = typeData.Fields.Find(delegate(PropertyMetadata meta) { return(meta.FieldName.ToLower() == memberName.ToLower()); });
            if (pMeta != null)
            {
                FieldInfo fieldInfo = pMeta.FieldInfo;
                propertyValue = ConvertObjectToType(propertyValue, fieldInfo.FieldType, serializer, memberName);
                fieldInfo.SetValue(o, propertyValue);
                return;
            }
        }
        public void ObfuscateIntFieldsTest()
        {
            var orgService = ConnectionHelper.GetOrganizationalServiceTarget();
            var cache      = new EntityMetadataCache(orgService);

            List <FieldToBeObfuscated> fiedlsToBeObfuscated = new List <FieldToBeObfuscated>();

            fiedlsToBeObfuscated.Add(new FieldToBeObfuscated()
            {
                FieldName = "numberofchildren"
            });

            EntityToBeObfuscated entityToBeObfuscated = new EntityToBeObfuscated()
            {
                EntityName = "contact", FieldsToBeObfuscated = fiedlsToBeObfuscated
            };

            var fieldsToBeObfuscated = new List <EntityToBeObfuscated>();

            fieldsToBeObfuscated.Add(entityToBeObfuscated);

            ObfuscateFieldsProcessor processor = new ObfuscateFieldsProcessor(cache, fieldsToBeObfuscated);

            string beforeFirstName        = "Bob";
            int    beforeNumberOfChildren = 5;

            Entity ent = new Entity("contact");

            ent.Attributes.Add("firstname", beforeFirstName);
            ent.Attributes.Add("numberofchildren", beforeNumberOfChildren);

            EntityWrapper entWrap = new EntityWrapper(ent);

            processor.ProcessEntity(entWrap, 1, 1);

            Assert.AreEqual(beforeFirstName, entWrap.OriginalEntity.Attributes["firstname"]);
            Assert.AreNotEqual(beforeNumberOfChildren, entWrap.OriginalEntity.Attributes["numberofchildren"]);
        }
Ejemplo n.º 9
0
        private static object GetEntity <TData>(TData data, Type entityType, Func <TData, string, object> getValueAction)
            where TData : class
        {
            if (data == null)
            {
                return(null);
            }

            object         entity     = Activator.CreateInstance(entityType);                                   // 类型entityType要求new()约束
            EntityMetadata entityMeta = EntityMetadataCache.GetEntityMetadata(entityType);

            // 处理属性
            foreach (PropertyMetadata field in entityMeta.Propertys)
            {
                MethodInfo mInfo = field.PropertyInfo.GetSetMethod();;
                if (mInfo == null)
                {
                    continue;                                                                                   // 无Setter的时候忽略此Property
                }
                AssignToPropertyOrField <TData, MethodInfo>(data, entityType, getValueAction, setMethodAction, mInfo, field.FieldName, entity, field.PropertyInfo.PropertyType);
            }

            return(entity);
        }
Ejemplo n.º 10
0
 public void Setup()
 {
     systemUnderTest = new EntityMetadataCache(ConnectionHelper.GetOrganizationalServiceSource());
 }
Ejemplo n.º 11
0
        private void SerializeCustomObject(object o, StringBuilder sb, int depth, Hashtable objectsInUse,
                                           SerializationFormat serializationFormat)
        {
            bool first = true;
            Type type  = o.GetType();

            sb.Append('{');

            if (TypeResolver != null)
            {
                string typeString = TypeResolver.ResolveTypeId(type);
                if (typeString != null)
                {
                    SerializeString(ServerTypeFieldName, sb);
                    sb.Append(':');
                    SerializeValue(typeString, sb, depth, objectsInUse, serializationFormat);
                    first = false;
                }
            }

            EntityMetadata typeData = EntityMetadataCache.GetEntityMetadata(type);// 使用统一缓存方式 add by zq 2015-12-30

            foreach (PropertyMetadata pMeta in typeData.Fields)
            {
                FieldInfo fieldInfo = pMeta.FieldInfo;
                if (fieldInfo.IsDefined(typeof(ScriptIgnoreAttribute), true))
                {
                    continue;
                }

                if (!first)
                {
                    sb.Append(',');
                }
                SerializeString(pMeta.FieldName, sb);
                sb.Append(':');
                SerializeValue(fieldInfo.GetValue(o), sb, depth, objectsInUse, serializationFormat);
                first = false;
            }

            foreach (PropertyMetadata pMeta in typeData.Propertys)
            {
                PropertyInfo propInfo = pMeta.PropertyInfo;
                if (propInfo.IsDefined(typeof(ScriptIgnoreAttribute), true))
                {
                    continue;
                }

                MethodInfo getMethodInfo = propInfo.GetGetMethod();
                if (getMethodInfo == null)
                {
                    continue;
                }

                if (getMethodInfo.GetParameters().Length > 0)
                {
                    continue;
                }

                if (!first)
                {
                    sb.Append(',');
                }
                SerializeString(pMeta.FieldName, sb);
                sb.Append(':');
                SerializeValue(getMethodInfo.Invoke(o, null), sb, depth, objectsInUse, serializationFormat);
                first = false;
            }

            sb.Append('}');
        }
        public void Setup()
        {
            InitializeProperties();

            systemUnderTest = new EntityMetadataCache(MockOrganizationService.Object);
        }