Read XML Web resource using C# & SDK in CRM

Let us see a simple example to read XML Web resource using Query Expression in Console Application,

Task: Read books.xml webresource and get all book titles.

books.xml

Solution:

Step 1: Create one Sample XML Webresource and name it as “new_books” in CRM. Click here to get XML.

Step 2: Include the below References in your visual Studio project, you can get the same from Latest SDK.

Goto the path, SDK -> Bin for the dlls

Microsoft.Crm.Sdk.Proxy
Microsoft.Xrm.Sdk

Step 3: Include the below Framework Assemblies in your project,

Reference Manager - ConnectToCRM

Step 4: Add the below namespaces in your class file,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

Step 5: First we have to connect to CRM, for details Click Here

Step 6: Next we have to use GetEntityCollection method to retrieve records, To Know more about this Click Here

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

Step 7: We are going to use GetEntityCollection method as follows,

We are going to retrieve content from webresource entity. If we write the same in SQL it will be like this,

Select name, content from FilteredWebResource where name = ‘new_books’
EntityCollection ec = GetEntityCollection(_service, "webresource", "name", "new_books", new ColumnSet("name", "content"));

Step 8: Below method is useful for converting content binary data to string. Content will be encrypted in database, so we have to convert it into String format.

Note: Include MyOrganizationCrmSdkTypes.cs file in your project for WebResource Class.

You can get the same from the path SDK\SampleCode\CS\HelperCode.

private static string ConvertContentToXMLString(EntityCollection entCol)
{
WebResource webResource = null;
string webResourceContent = string.Empty;
webResource = (WebResource)entCol.Entities[0];
if (webResource.Attributes.Contains("content"))
{
byte[] binary = Convert.FromBase64String(webResource.Attributes["content"].ToString());
webResourceContent = UnicodeEncoding.UTF8.GetString(binary);
}
return webResourceContent;
}

Step 9: Below Method is useful for converting string to XMLDocument and pointing to correct node to get the result.

Note: nodeString parameter is for pointing to XML node. For our Example, we have to get title. So, nodestring will be /catalog/book/title

private static void DisplayXmlNodes(string webResourceContent, string nodeString)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(webResourceContent);
XmlNodeList xnList = xml.SelectNodes(nodeString);
string value = string.Empty;

if (xnList.Count > 0)
{
value += "Book Title\n--------------------------------------\n";
foreach (XmlNode xn in xnList)
{
value += xn.InnerText + "\n";
}
Console.WriteLine(value);
Console.ReadKey();
}
}

Step 10: So the final code is as follows,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Xml;

namespace Read_Webresource
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@XXXXXX.onmicrosoft.com","XXXXXX","https://XXXXXX.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
string content = string.Empty;

if (userid == Guid.Empty) return;//check for CRM Connection Establishe or not, if not return otherwise proceed to next step

EntityCollection ec = GetEntityCollection(_service, "webresource", "name", "new_sampleXMLfile", new ColumnSet("name", "content"));

if (ec.Entities[0].Attributes.Count > 0)
{
content = ConvertContentToXMLString(ec);
if (!string.IsNullOrEmpty(content))
DisplayXmlNodes(content, "/catalog/book/title");
}
}

private static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();
}
}

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

private static string ConvertContentToXMLString(EntityCollection entCol)
{
WebResource webResource = null;
string webResourceContent = string.Empty;
webResource = (WebResource)entCol.Entities[0];
if (webResource.Attributes.Contains("content"))
{
byte[] binary = Convert.FromBase64String(webResource.Attributes["content"].ToString());
webResourceContent = UnicodeEncoding.UTF8.GetString(binary);
}
return webResourceContent;
}

private static void DisplayXmlNodes(string webResourceContent, string nodeString)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(webResourceContent);
XmlNodeList xnList = xml.SelectNodes(nodeString);
string value = string.Empty;

if (xnList.Count > 0)
{
value += "Book Title\n--------------------------------------\n";
foreach (XmlNode xn in xnList)
{
value += xn.InnerText + "\n";
}
Console.WriteLine(value);
Console.ReadKey();
}
}
}
}

Step 11: Final Output is,

Read XML Web resource-Output

Please provide your valuable feedback.


Discover more from Arun Potti's Power Platform blog

Subscribe to get the latest posts to your email.

2 thoughts on “Read XML Web resource using C# & SDK in CRM

Leave a Reply