Introduction:
We can edit Sitemap by using Microsoft Dynamic SiteMap Designer or SiteMap Editor using XrmToolBox. Whereas we can also update SiteMap programmatically, but before updating SiteMap we have to retrieve SiteMap XML programmatically.
So in this blog, we will discuss about how to retrieve SiteMap XML programmatically.
Recently, we came across below scenario, Where user wants to update default as well as app specific SiteMap programmatically. After some research we found the below solution.
Solution:
We can used Fetch Expression, Linq and QueryExpression to retrieve app/default SiteMap XML
1. Retrieve SiteMap using FetchExpression :
In the fetch expression, it will gives only one sitemap i.e. default SiteMap entity into the entity collection.
string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' > <entity name='sitemap' /> <attribute name='sitemapxml' /> </fetch>"; EntityCollection collection = _service.RetrieveMultiple(new FetchExpression(fetchXML));
2. Retrieve SiteMap using Linq:
We can get App specific/default SiteMap using linq. It will give single entity in result set:
Entity sitemapEntity = (from c in _context.CreateQuery("sitemap") select c).ToList().FirstOrDefault();
To retrieve app specific SiteMap, we have to pass app SiteMap name in filter condition (used sitemapnameunique attribute)
Entity sitemapEntity = (from c in _context.CreateQuery("sitemap") Where ((string)c["sitemapnameunique"]).Contains("customerservice") select c).ToList().FirstOrDefault();
Note: – In above linq – “customerservice” is a name of sitemap.
3. Retrieve SiteMap using QueryExpression :
With the help of query expression we can get multiple site map at one time.
Create collection of SiteMap name.
string[] arrofAppSiteMap = { "AppforOutlookSiteMap", "customerservice", "Customerservicehub", "SalesHubSitemap", "SalesSiteMap"};
Create a query expression
QueryExpression query = new QueryExpression("sitemap"); query.ColumnSet = new ColumnSet("sitemapxml"); query.Criteria = new FilterExpression { FilterOperator = LogicalOperator.Or, Conditions = { new ConditionExpression("sitemapnameunique", ConditionOperator.Null), new ConditionExpression("sitemapnameunique", ConditionOperator.In, arrofAppSiteMap) } }; EntityCollection sitemaps = _service.RetrieveMultiple(query);
This will give Default SiteMap as well as app specific site map (which are present in collection of array) in collection.
Note: new ConditionExpression(“sitemapnameunique”, ConditionOperator.Null) this is used to retrieve default SiteMap XML
Conclusion:
To retrieve collection of SiteMap in single query, we can use QueryExpression, to retrieve specific SiteMap (based on name) use linq and to retrieve default SiteMap we can use FetchExpression.