Creating a view with C#

Advanced find is a great feature, it allow us to create complex views over different entities very easily. However, it has several limitations that lead us to create views in code, as with this approach, there are much less limitations. Below is an example of code to create a simple view with C#:

/* Fetch XML of the custom view.
* Basically, here we'll define the attributes
* to retrieve, as well as the order and the
* conditions(filters)
 string FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
 "<entity name='contact'>" + // Target Entity(Contact)
  "<attribute name='fullname' />" + // Attributes(Full Name)
  "<order descending='false' attribute='fullname' />" + // Order of the records
  "<filter type='and'>" + // Conditions(Filters)
   "<condition attribute='statecode' operator='eq' value='0' />" + // Only Active records condition(Status equals Active)
  "</filter>" + // Conditions(Filters)
  "</entity>" +

* Layout of the view.
* This will allow us to define the size of the columns
* and other visual configurations.
string LayoutXML = @"<grid name='resultset' object='2' jump='fullname' select='1' icon='1' preview='1'>" +
 "<row name='result' id='contactid'>" +
 "<cell name='fullname' width='300' />" + // "Full Name" column width
"</row>" +

// Saved Query object
SavedQuery sq = new SavedQuery(); 

// Name of the view that will be created
sq.Name = "View created in code";

// Description of the view
sq.Description = "Description example";

// Target Entity of the view
sq.ReturnedTypeCode = "contact";

// Fetch XML of the view
sq.FetchXml = FetchXml;

// Layout of the XML
sq.LayoutXml = LayoutXML;

/* Type of view. We can choose one of the following options:
* 0 - Main Application View
* 1 - Advanced Search
* 2 - Associated View
* 4 - Quick find search
* 64 - Lookup View
sq.QueryType = 0;

// Create view in target organization


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s