Pessoal,
O SDK do CRM fornece uma boa documentação a respeito como trabalhar com Web Resources, porém acredito que devido ao volume de informações, talvez atrapalhe um pouco para quem está começando a desenvolver com o Dynamics CRM.
Uma rápida busca, podemos visualizar os seguintes materiais:
- Webpage (HTML) web resources
- Use the Web API with web resources
- Use the OData endpoint with Ajax and JScript web resources
Acredito que isto seja apenas o começo das páginas que iremos encontrar à respeito. Mas minha ideia é ter algo bem simples e usual, de forma que possamos usar o código deste post para realizar consultar via JScript na API do CRM.
Em meu exemplo, fiz um página simples que realiza consultas via SOAP e REST através de um HTML Web Resource.
Para o SOAP, fiz o uso da biblioteca XrmServiceToolkit, pois nativamente não temos esta biblioteca no CRM. Ela vai muito além de fazer SOAP, veja a documentação, pois podemos inclusive só utilizá-la daqui para frente.
Em relação ao REST, utilizei a própria biblioteca que a Microsoft inseriu no SDK, o SDK.REST.js, ela contém diversas funções REST’s atualizadas pela Microsoft.
Bom, mas vamos ao que interessa:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
<!-- *** Download the JS and Create a New Web Resource in Dynamics CRM *** -->
<script type="text/javascript" src="../WebResources/new_XrmServiceToolkit.min.js"></script>
<script type="text/javascript" src="../WebResources/new_SDK.REST.js"></script>
<!-- *** END Download the JS and Create a New Web Resource in Dynamics CRM *** -->
<script type="text/javascript">
function ContactRetrieveMultipleSOAP()
{
document.getElementById("result").innerHTML = "
<h2>Retrieved by SOAP</h2>
";
// FetchXML
var fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='contact'>" +
"<attribute name='fullname' />" +
"<attribute name='telephone1' />" +
"<attribute name='emailaddress1' />" +
"</entity>" +
"</fetch>";
// Execute the FetchXML
var records = XrmServiceToolkit.Soap.Fetch(fetchXML, false, CreateHTMLTable);
}
function ContactRetrieveMultipleREST() {
document.getElementById("result").innerHTML = "
<h2>Retrieved by REST</h2>
";
// ODAta Query
var query = "$select=FullName,Telephone1,EMailAddress1";
// REST
SDK.REST.retrieveMultipleRecords("Contact", query, CreateHTMLTable, function (error) { alert(error.message); }, RetrieveComplete);
}
function RetrieveComplete() {}
function CreateHTMLTable(records) {
// Create HTML Table and Header
var table = "
<table cellspacing='0' border='1'>";
var htmlHeaderTable = "
<thead>
<tr>";
htmlHeaderTable += "
<th style='text-align:left'>FullName</th>
";
htmlHeaderTable += "
<th style='text-align:left'>Telephone</th>
";
htmlHeaderTable += "
<th style='text-align:left'>Email</th>
";
htmlHeaderTable += "</tr>
</thead>
";
var htmlDataTable = "
<tbody>";
// Loop the returned Records
for (var i = 0; i < records.length; i++) {
htmlDataTable += "
<tr>";
var name;
var telephone;
var email;
// If the object Records has "attributes" there is SOAP Request
if (records[i].attributes) {
name = records[i].attributes["fullname"] ? records[i].attributes["fullname"].value : "";
telephone = records[i].attributes["telephone1"] ? records[i].attributes["telephone1"].value : "";
email = records[i].attributes["emailaddress1"] ? records[i].attributes["emailaddress1"].value : "";
}
// Otherwise, there is REST Request
else {
name = records[i].FullName ? records[i].FullName : "";
telephone = records[i].Telephone1 ? records[i].Telephone1 : "";
email = records[i].EMailAddress1 ? records[i].EMailAddress1 : "";
}
htmlDataTable += "
<td>" + name + "</td>
";
htmlDataTable += "
<td>" + telephone + "</td>
";
htmlDataTable += "
<td>" + email + "</td>
";
htmlDataTable += "</tr>
";
}
htmlDataTable += "</tbody>
";
// Add the HTML in a Div
document.getElementById("result").innerHTML += table + htmlHeaderTable + htmlDataTable;
}
</script>
</head>
<body>
<input type="button" value="Retrieve All Contacts (SOAP)" onclick="ContactRetrieveMultipleSOAP()" />
<input type="button" value="Retrieve All Contacts (REST)" onclick="ContactRetrieveMultipleREST()" />
<div id="result"></div>
</body>
</html>
Vale lembrar que estou fazendo duas consultas iguais, utilizando duas tecnologias diferentes (SOAP e REST), mas o resultado será o mesmo. A ideia é dar um exemplo de cada uma para entendermos a lógica! 😉
Ao clicar em cada botão uma consulta será realizada no CRM. Estou fazendo apenas uma consulta simples na entidade Contatos.
O método “CreateHTMLTable” simplesmente recebe o “callback” do SOAP e do REST e cria uma tabela HTML para ser renderizada no HTML.
O tratamento dos resultados do SOAP são diferentes do REST, pois isso temos o “if (records[i].attributes)”, pois apenas o SOAP terá valores nesta propriedade.
Como resultado, teremos algo assim:
[]’s
Tiago Cardoso
