获取CRM中所有Entity及Attribute元数据

最近客户提出需求:他们以往查出过竞争对手进行商业间谍活动的情况(另一家公司对他们的月生产计划了如指掌),要求自己对不同角色的访问权限进行控制,按照需求,要把系统中所有可以自定义的Entity及Attribute取出,导入到Excel中,由客户自定义,再将定义好的表在系统中进行配置,如图:

我使用了两种方法读取数据,第一种通过winform程序连接,然后调用RetrieveAllEntitiesMetaDataRequest获取数据进行处理,这种是比较合适的,但使用起来相对比较麻烦OrganizationService

第二种,直接使用Excel连接数据库读取数据库信息,这种方式相对很方便,但不是MS所推荐的,直接访问SQL SERVER数据库一旦出现错误,会很难发现,不过我们现在只是读取数据,还是可以用用的

 

一:winform通过WCF调用OrganizationService,关键代码如下:

public static List<EntityMetadata> GetAllEntities()
{
List<EntityMetadata> results = new List<EntityMetadata>();
try
{
//using (OrganizationServiceClient service = new OrganizationServiceClient())
{
System.ServiceModel.Description.ClientCredentials credentials = new System.ServiceModel.Description.ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("administrator","password","domain");
Uri orgUri = new Uri("http://servername/organizationname/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
OrganizationServiceProxy orgService = new OrganizationServiceProxy(orgUri, homeRealmUri, credentials, null);
RetrieveAllEntitiesRequest req=new RetrieveAllEntitiesRequest()
{
EntityFilters=EntityFilters.Attributes,
RetrieveAsIfPublished=true
};
RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)orgService.Execute(req);
foreach (var currentEntity in response.EntityMetadata)
{
if ((currentEntity.IsCustomEntity == true))
{
results.Add(currentEntity);
}
}
}
}
catch (Exception e)
{
throw;
}

return results;
}

这段代码获取了所有的Entity元数据,也可以根据LogicalName只获取某一实体的元数据

RetrieveEntityRequest req = new RetrieveEntityRequest()
{
EntityFilters = EntityFilters.Attributes,
LogicalName = _EntityName,
RetrieveAsIfPublished = true
};
RetrieveEntityResponse resp = (RetrieveEntityResponse)orgService.Execute(req);
EntityMetadata entity = resp.EntityMetadata;

 

二:通过Excel直接访问数据库

使用Excel的数据向导,创建一个Microsoft Query,连接到SQl SERVER,就可以通过SQL语句获取相应的数据了,元数据信息在MetaData.Attribute和MetaData.Entity中,要查看中文名,可以连接LocalizeLabel表,它与前面两个表是通过ObjectId连接的

 

 

 

posted @ 2012-04-10 14:09  随乄风  阅读(1508)  评论(0编辑  收藏  举报