How to create CRM Entity View programmatically?

Note: In this article, I am creating a view in CRM Plugin.

1.      Create instance of IOrganizatinoService class to communicate with CRM

var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

service = factory.CreateOrganizationService(context.UserId);

2.      Fetch ObjectTypeCode of an entity for which view needs to be created

RetrieveEntityRequest entityTypeCodeRequest = new RetrieveEntityRequest

{

LogicalName = “<name of entity for which view to be created>”,

EntityFilters = EntityFilters.All

};

RetrieveEntityResponse entityTypeCodeResponse = (RetrieveEntityResponse)service.Execute(entityTypeCodeRequest);

EntityMetadata objectTypeCode = (EntityMetadata)(entityTypeCodeResponse.EntityMetadata);

String entityObjectTypeValue = objectTypeCode.ObjectTypeCode.ToString();

3.      Create view

a.      Add ‘MyOrganizationCrmSdkTypes.cs’ class from CRM SDK in the solution. You will find this class at location: ‘..\CRM 2013\SDK\SampleCode\CS\HelperCode\’.

b.      Prepare LayoutXML string for view as below:

String layoutXML = @”<grid name=’resultset’ object='” + <entity type code which is fetched in step 2> + @”‘ jump='<Logical name of Name field of entity>’ select=’1′ preview=’1′ icon=’1′>

  <row name=’result’ id='<logical name of ID column of entity>’>

    <cell name=’column1′ width=’100′ />

    <cell name=’column2′ width=’100′ />

    <cell name=’column3′ width=’100′ />

  </row>

</grid>”;

c.       Prepare FetchXML string for view as below:

String fetchXML = @”<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’>

  <entity name='” + <name of entity for which view to be created> + @”‘>

    $attributes$

    <attribute name='<logical name of ID column of entity>’ />

    <attribute name=’column1′ />

    <attribute name=’column2′ />

  </entity>

</fetch>”

d.      Create an instance of SavedQuery class as below:

SavedQuery createViewRequest = new SavedQuery

{

Name = “Name of view”,

       Description = “Description of view”,

       ReturnedTypeCode = “<entity type code which is fetched in step 2>”,

       FetchXml = fetchXML,

       LayoutXml = layoutXML,

       QueryType = 0,

       IsDefault = true

};

e.      Send above request for execution as below:

service.Create(createViewRequest);

For more details, you can visit:

http://msdn.microsoft.com/en-us/library/gg594431.aspx

http://msdn.microsoft.com/en-us/library/gg328457.aspx