範例:使用 JavaScript,擷取實體中繼資料
發佈日期: 2016年11月
適用對象: Dynamics CRM 2015
這個範例程式碼適用於 Microsoft Dynamics CRM 2015 和 Microsoft Dynamics CRM Online 2015 更新。下載 Microsoft Dynamics CRM SDK 套件。 可以在下列位置的下載套件中找到:
SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\MetaDataDemo.htm
SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\Scripts\SDK.MetaData.js
需求
若要使用此程式碼,必須建立每個檔案的 Web 資源。 Web 資源名稱必須依照此格式:
<solution publisher customization prefix>_/MetaDataDemo.htm
<solution publisher customization prefix>_/Scripts/SDK.MetaData.js
如果想要了解此範例運作方式,可以安裝 (匯入) SOAPEndpointforJScript_1_0_0_1_managed.zip 受管理解決方案 (包含在下載檔案的 SDK\SampleCode\JS\SOAPForJScript)。 如果您安裝此受管理的解決方案且要使用此主題中的名稱建立 Web 資源,您的解決方案發行者自訂的首碼不可以是「sample」,除非您解除安裝 (刪除) 受管理的解決方案。
示範
此範例顯示如何使用範例 JavaScript 程式庫,依照 逐步解說:使用現代應用程式 SOAP 端點與 JavaScript描述的程序所建立。 使用非同步 JavaScript,此程式庫支援使用 RetrieveAllEntitiesRequest 和 RetrieveEntityRequest 訊息。
範例
MetaDataDemo.htm 頁面使用在 SDK.MetaData.js 檔案中包含的 SDK.MetaData.RetrieveAllEntities 和 SDK.MetaData.RetrieveEntity 函數來擷取資料。
當頁面載入時,它會擷取系統中任何實體的資訊,然後顯示清單,列出每個實體的 SchemaName。 按一下實體清單項目時,會擷取實體屬性的相關資訊,並顯示屬性 SchemaName。 在屬性擷取之後,按一下實體清單項目,會切換屬性清單的顯示。
<html lang="en-US">
<head>
<title>Metadata Demonstration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
<script src="Scripts/SDK.MetaData.js" type="text/javascript"></script>
<script type="text/javascript">
// An unordered list element to add Entity list items to
var results;
// An area to display messages
var message;
// Alert flag to indicate the changes
var alertFlag;
function startSample() {
///<summary>
/// Initializes the sample when the document is ready
///</summary>
//Assign the global variables
results = document.getElementById("results");
message = document.getElementById("message");
alertFlag = document.getElementById("dispalert");
document.getElementById("btnstartSample").setAttribute("disabled", "disabled");
//Retrieve entities
SDK.Metadata.RetrieveAllEntities(SDK.Metadata.EntityFilters.Entity,
false,
successRetrieveAllEntities,
errorRetrieveAllEntities);
setText(message, "Loading...");
}
function successRetrieveAllEntities(entityMetadataCollection) {
///<summary>
/// Receives the data from SDK.Metadata.RetrieveAllEntities and
/// appends a list item to results for each one.
///</summary>
entityMetadataCollection.sort(function (a, b) {
if (a.LogicalName < b.LogicalName)
{ return -1 }
if (a.LogicalName > b.LogicalName)
{ return 1 }
return 0;
});
for (var i = 0; i < entityMetadataCollection.length; i++) {
var entity = entityMetadataCollection[i];
var entityNode = document.createElement("li");
var entitySpan = document.createElement("span");
setText(entitySpan, entity.SchemaName);
entitySpan.id = entity.LogicalName;
entitySpan.title = "Click to Retrieve Attributes.";
entitySpan.attributesRetrieved = false;
// Add the event handler to retrieve attributes
entitySpan.onclick = retrieveAttributes;
entitySpan.style.cursor = "pointer";
entityNode.appendChild(entitySpan);
results.appendChild(entityNode);
}
setText(message, entityMetadataCollection.length +
" entities retrieved. Click each entity to retrieve the entity attributes.");
if (alertFlag.checked == true)
alert("Entity List Retrieved.");
}
function errorRetrieveAllEntities(error) {
///<summary>
/// Displays the error returned from SDK.Metadata.RetrieveAllEntities if it fails.
///</summary>
setText(message, error.message);
if (alertFlag.checked == true)
alert("An Error occurred.");
}
function retrieveAttributes() {
///<summary>
/// Retrieves attributes for the entity list item that is clicked
///</summary>
if (this.attributesRetrieved == false) {
var entityLogicalName = this.id;
// Display an entity list item level notification while retrieving data.
var notification = document.createElement("span");
setText(notification, " Retrieving attributes for " + getText(this) + "...");
notification.id = entityLogicalName + "Notification";
this.parentElement.appendChild(notification);
SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.Attributes,
this.id,
null,
false,
function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata); },
errorRetrieveEntity);
}
this.attributesRetrieved = true;
this.title = "";
}
function successRetrieveEntity(logicalName, entityMetadata) {
///<summary>
/// Retrieves attributes for the entity list item that is clicked
///</summary>
// Update the entity list item notification when data is retrieved.
entityMetadata.Attributes.sort(function (a, b) {
if (a.LogicalName < b.LogicalName)
{ return -1 }
if (a.LogicalName > b.LogicalName)
{ return 1 }
return 0;
});
var notification = setText(document.getElementById(logicalName +
"Notification"), " Retrieved " + entityMetadata.Attributes.length + " attributes.");
var attributeList = document.createElement("ul");
for (var i = 0; i < entityMetadata.Attributes.length; i++) {
var attribute = entityMetadata.Attributes[i];
var attributeNode = document.createElement("li");
setText(attributeNode, attribute.SchemaName);
attributeList.appendChild(attributeNode);
}
// Access the entity list item element
var entityNode = document.getElementById(logicalName).parentElement;
entityNode.appendChild(attributeList);
entityNode.attributesDisplayed = true;
// Attach event handler to toggle display of attributes.
entityNode.firstChild.onclick = toggleDisplayAttributes;
entityNode.firstChild.title = "Click to hide attributes.";
if (alertFlag.checked == true)
alert(entityMetadata.SchemaName + " attributes retrieved.");
}
function errorRetrieveEntity(error) {
///<summary>
/// Displays the error returned from SDK.Metadata.RetrieveEntity if it fails.
///</summary>
setText(message, error.message);
if (alertFlag.checked == true)
alert("Error!");
}
function toggleDisplayAttributes() {
///<summary>
/// toggles whether the list of attributes is displayed.
///</summary>
if (this.parentElement.attributesDisplayed) {
this.parentElement.lastChild.style.display = "none";
this.parentElement.attributesDisplayed = false;
this.title = "Click to show attributes.";
if (alertFlag.checked == true)
alert("Attributes were hidden.");
}
else {
this.parentElement.lastChild.style.display = "block";
this.parentElement.attributesDisplayed = true;
this.title = "Click to hide attributes.";
if (alertFlag.checked == true)
alert("Attributes are displayed.");
}
}
// setText and getText mitigate differences in how browsers set or get text content.
function setText(node, text) {
if (typeof (node.innerText) != "undefined") {
node.innerText = text;
}
else {
node.textContent = text;
}
}
function getText(node) {
if (typeof (node.innerText) != "undefined") {
return node.innerText;
}
else {
return node.textContent;
}
}
</script>
</head>
<body style="font-family: Segoe UI;">
<h1>
Metadata Demonstration Sample</h1>
<p>
This form requires JavaScript and will update the page dynamically.</p>
<p>
<input id="dispalert" name="dispalert" type="checkbox" value="alert" /><label for="dispalert">Display alert window when data changes.</label></p>
<p>
<label id="lblstartSample" for="btnstartSample">
Click to start the sample:
</label>
<input type="button" id="btnstartSample" name="btnstartSample" value="Start" onclick="startSample()" /></p>
<div id="message">
</div>
<ul id="results">
</ul>
</body>
</html>
範例
SDK.MetaData.js 檔案是 JScript 程式庫,包含呼叫頁面所使用的 SDK.MetaData.RetrieveAllEntities 和 SDK.MetaData.RetrieveEntity 公用函數。 這些函數傳送非同步要求,並針對每個函數,將結果傳送回 successCallBack 參數中指定之函數。
SDK.MetaData.EntityFilters 提供列舉類型,對應於 RetrieveAllEntitiesRequest 和 RetrieveEntityRequest 訊息使用的 EntityFilters 列舉。 其他私用函數是用來剖析要求結果中傳回的 XML。
此範例顯示 SOAP 標頭必須包括 SdkClientVersion 值「6.0」,才能傳回影像屬性,如下列程式碼片段所示。
"<soapenv:Header><a:SdkClientVersion xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">6.0</a:SdkClientVersion></soapenv:Header>",
SDK = window.SDK || { __namespace: true };
SDK.Metadata = SDK.Metadata || { __namespace: true };
(function () {
this.RetrieveAllEntities = function (EntityFilters, RetrieveAsIfPublished, successCallBack, errorCallBack, passThroughObject) {
///<summary>
/// Sends an asynchronous RetrieveAllEntities Request to retrieve all entities in the system
///</summary>
///<returns>entityMetadataCollection</returns>
///<param name="EntityFilters" type="Number">
/// SDK.Metadata.EntityFilters provides an enumeration for the filters available to filter which data is retrieved.
/// Include only those elements of the entity you want to retrieve. Retrieving all parts of all entitities may take significant time.
///</param>
///<param name="RetrieveAsIfPublished" type="Boolean">
/// Sets whether to retrieve the metadata that has not been published.
///</param>
///<param name="successCallBack" type="Function">
/// The function that will be passed through and be called by a successful response.
/// This function must accept the entityMetadataCollection as a parameter.
///</param>
///<param name="errorCallBack" type="Function">
/// The function that will be passed through and be called by a failed response.
/// This function must accept an Error object as a parameter.
///</param>
///<param name="passThroughObject" optional="true" type="Object">
/// An Object that will be passed through to as the second parameter to the successCallBack.
///</param>
if ((typeof EntityFilters != "number") || (EntityFilters < 1 || EntityFilters > 15))
{ throw new Error("SDK.Metadata.RetrieveAllEntities EntityFilters must be a SDK.Metadata.EntityFilters value."); }
if (typeof RetrieveAsIfPublished != "boolean")
{ throw new Error("SDK.Metadata.RetrieveAllEntities RetrieveAsIfPublished must be a boolean value."); }
if (typeof successCallBack != "function")
{ throw new Error("SDK.Metadata.RetrieveAllEntities successCallBack must be a function."); }
if (typeof errorCallBack != "function")
{ throw new Error("SDK.Metadata.RetrieveAllEntities errorCallBack must be a function."); }
var entityFiltersValue = _evaluateEntityFilters(EntityFilters);
var request = [
"<soapenv:Envelope xmlns:soapenv=\"https://schemas.xmlsoap.org/soap/envelope/\">",
//Allows retrieval if ImageAttributeMetadata objects
"<soapenv:Header><a:SdkClientVersion xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">7.0</a:SdkClientVersion></soapenv:Header>",
"<soapenv:Body>",
"<Execute xmlns=\"https://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">",
"<request i:type=\"a:RetrieveAllEntitiesRequest\" xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">",
"<a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">",
"<a:KeyValuePairOfstringanyType>",
"<b:key>EntityFilters</b:key>",
"<b:value i:type=\"c:EntityFilters\" xmlns:c=\"https://schemas.microsoft.com/xrm/2011/Metadata\">" + _xmlEncode(entityFiltersValue) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>RetrieveAsIfPublished</b:key>",
"<b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + _xmlEncode(RetrieveAsIfPublished.toString()) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"</a:Parameters>",
"<a:RequestId i:nil=\"true\" />",
"<a:RequestName>RetrieveAllEntities</a:RequestName>",
"</request>",
"</Execute>",
"</soapenv:Body>",
"</soapenv:Envelope>"].join("");
var req = new XMLHttpRequest();
req.open("POST", _getUrl() + "/XRMServices/2011/Organization.svc/web", true);
try { req.responseType = 'msxml-document'} catch(e){}
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "https://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.onreadystatechange = function () {
if (req.readyState == 4 /* complete */) {
req.onreadystatechange = null; //Addresses potential memory leak issue with IE
if (req.status == 200) {
//Success
var doc = req.responseXML;
try{_setSelectionNamespaces(doc);}catch(e){}
var entityMetadataNodes = _selectNodes(doc, "//c:EntityMetadata");
var entityMetadataCollection = [];
for (var i = 0; i < entityMetadataNodes.length; i++) {
var a = _objectifyNode(entityMetadataNodes[i]);
a._type = "EntityMetadata";
entityMetadataCollection.push(a);
}
successCallBack(entityMetadataCollection, passThroughObject);
}
else {
errorCallBack(_getError(req));
}
}
};
req.send(request);
};
this.RetrieveEntity = function (EntityFilters, LogicalName, MetadataId, RetrieveAsIfPublished, successCallBack, errorCallBack, passThroughObject) {
///<summary>
/// Sends an asynchronous RetrieveEntity Request to retrieve a specific entity
///</summary>
///<returns>entityMetadata</returns>
///<param name="EntityFilters" type="Number">
/// SDK.Metadata.EntityFilters provides an enumeration for the filters available to filter which data is retrieved.
/// Include only those elements of the entity you want to retrieve. Retrieving all parts of all entitities may take significant time.
///</param>
///<param name="LogicalName" optional="true" type="String">
/// The logical name of the entity requested. A null value may be used if a MetadataId is provided.
///</param>
///<param name="MetadataId" optional="true" type="String">
/// A null value or an empty guid may be passed if a LogicalName is provided.
///</param>
///<param name="RetrieveAsIfPublished" type="Boolean">
/// Sets whether to retrieve the metadata that has not been published.
///</param>
///<param name="successCallBack" type="Function">
/// The function that will be passed through and be called by a successful response.
/// This function must accept the entityMetadata as a parameter.
///</param>
///<param name="errorCallBack" type="Function">
/// The function that will be passed through and be called by a failed response.
/// This function must accept an Error object as a parameter.
///</param>
///<param name="passThroughObject" optional="true" type="Object">
/// An Object that will be passed through to as the second parameter to the successCallBack.
///</param>
if ((typeof EntityFilters != "number") || (EntityFilters < 1 || EntityFilters > 15))
{ throw new Error("SDK.Metadata.RetrieveEntity EntityFilters must be a SDK.Metadata.EntityFilters value."); }
if (LogicalName == null && MetadataId == null) {
throw new Error("SDK.Metadata.RetrieveEntity requires either the LogicalName or MetadataId parameter not be null.");
}
if (LogicalName != null) {
if (typeof LogicalName != "string")
{ throw new Error("SDK.Metadata.RetrieveEntity LogicalName must be a string value."); }
MetadataId = "00000000-0000-0000-0000-000000000000";
}
if (MetadataId != null && LogicalName == null) {
if (typeof MetadataId != "string")
{ throw new Error("SDK.Metadata.RetrieveEntity MetadataId must be a string value."); }
}
if (typeof RetrieveAsIfPublished != "boolean")
{ throw new Error("SDK.Metadata.RetrieveEntity RetrieveAsIfPublished must be a boolean value."); }
if (typeof successCallBack != "function")
{ throw new Error("SDK.Metadata.RetrieveEntity successCallBack must be a function."); }
if (typeof errorCallBack != "function")
{ throw new Error("SDK.Metadata.RetrieveEntity errorCallBack must be a function."); }
var entityFiltersValue = _evaluateEntityFilters(EntityFilters);
var entityLogicalNameValueNode = "";
if (LogicalName == null)
{ entityLogicalNameValueNode = "<b:value i:nil=\"true\" />"; }
else
{ entityLogicalNameValueNode = "<b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + _xmlEncode(LogicalName.toLowerCase()) + "</b:value>"; }
var request = [
"<soapenv:Envelope xmlns:soapenv=\"https://schemas.xmlsoap.org/soap/envelope/\">",
//Allows retrieval if ImageAttributeMetadata objects
"<soapenv:Header><a:SdkClientVersion xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">6.0</a:SdkClientVersion></soapenv:Header>",
"<soapenv:Body>",
"<Execute xmlns=\"https://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">",
"<request i:type=\"a:RetrieveEntityRequest\" xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">",
"<a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">",
"<a:KeyValuePairOfstringanyType>",
"<b:key>EntityFilters</b:key>",
"<b:value i:type=\"c:EntityFilters\" xmlns:c=\"https://schemas.microsoft.com/xrm/2011/Metadata\">" + _xmlEncode(entityFiltersValue) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>MetadataId</b:key>",
"<b:value i:type=\"ser:guid\" xmlns:ser=\"https://schemas.microsoft.com/2003/10/Serialization/\">" + _xmlEncode(MetadataId) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>RetrieveAsIfPublished</b:key>",
"<b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + _xmlEncode(RetrieveAsIfPublished.toString()) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>LogicalName</b:key>",
entityLogicalNameValueNode,
"</a:KeyValuePairOfstringanyType>",
"</a:Parameters>",
"<a:RequestId i:nil=\"true\" />",
"<a:RequestName>RetrieveEntity</a:RequestName>",
"</request>",
"</Execute>",
"</soapenv:Body>",
"</soapenv:Envelope>"].join("");
var req = new XMLHttpRequest();
req.open("POST", _getUrl() + "/XRMServices/2011/Organization.svc/web", true);
try { req.responseType = 'msxml-document'} catch(e){}
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "https://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.onreadystatechange = function () {
if (req.readyState == 4 /* complete */) {
req.onreadystatechange = null; //Addresses potential memory leak issue with IE
if (req.status == 200) {
var doc = req.responseXML;
try{_setSelectionNamespaces(doc);}catch(e){}
var a = _objectifyNode(_selectSingleNode(doc, "//b:value"));
a._type = "EntityMetadata";
successCallBack(a, passThroughObject);
}
else {
//Failure
errorCallBack(_getError(req));
}
}
};
req.send(request);
};
this.RetrieveAttribute = function (EntityLogicalName, LogicalName, MetadataId, RetrieveAsIfPublished, successCallBack, errorCallBack, passThroughObject) {
///<summary>
/// Sends an asynchronous RetrieveAttribute Request to retrieve a specific entity
///</summary>
///<returns>AttributeMetadata</returns>
///<param name="EntityLogicalName" optional="true" type="String">
/// The logical name of the entity for the attribute requested. A null value may be used if a MetadataId is provided.
///</param>
///<param name="LogicalName" optional="true" type="String">
/// The logical name of the attribute requested.
///</param>
///<param name="MetadataId" optional="true" type="String">
/// A null value may be passed if an EntityLogicalName and LogicalName is provided.
///</param>
///<param name="RetrieveAsIfPublished" type="Boolean">
/// Sets whether to retrieve the metadata that has not been published.
///</param>
///<param name="successCallBack" type="Function">
/// The function that will be passed through and be called by a successful response.
/// This function must accept the entityMetadata as a parameter.
///</param>
///<param name="errorCallBack" type="Function">
/// The function that will be passed through and be called by a failed response.
/// This function must accept an Error object as a parameter.
///</param>
///<param name="passThroughObject" optional="true" type="Object">
/// An Object that will be passed through to as the second parameter to the successCallBack.
///</param>
if (EntityLogicalName == null && LogicalName == null && MetadataId == null) {
throw new Error("SDK.Metadata.RetrieveAttribute requires either the EntityLogicalName and LogicalName parameters or the MetadataId parameter not be null.");
}
if (MetadataId != null && EntityLogicalName == null && LogicalName == null) {
if (typeof MetadataId != "string")
{ throw new Error("SDK.Metadata.RetrieveEntity MetadataId must be a string value."); }
}
else
{ MetadataId = "00000000-0000-0000-0000-000000000000"; }
if (EntityLogicalName != null) {
if (typeof EntityLogicalName != "string") {
{ throw new Error("SDK.Metadata.RetrieveAttribute EntityLogicalName must be a string value."); }
}
}
if (LogicalName != null) {
if (typeof LogicalName != "string") {
{ throw new Error("SDK.Metadata.RetrieveAttribute LogicalName must be a string value."); }
}
}
if (typeof RetrieveAsIfPublished != "boolean")
{ throw new Error("SDK.Metadata.RetrieveAttribute RetrieveAsIfPublished must be a boolean value."); }
if (typeof successCallBack != "function")
{ throw new Error("SDK.Metadata.RetrieveAttribute successCallBack must be a function."); }
if (typeof errorCallBack != "function")
{ throw new Error("SDK.Metadata.RetrieveAttribute errorCallBack must be a function."); }
var entityLogicalNameValueNode;
if (EntityLogicalName == null) {
entityLogicalNameValueNode = "<b:value i:nil=\"true\" />";
}
else {
entityLogicalNameValueNode = "<b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + _xmlEncode(EntityLogicalName.toLowerCase()) + "</b:value>";
}
var logicalNameValueNode;
if (LogicalName == null) {
logicalNameValueNode = "<b:value i:nil=\"true\" />";
}
else {
logicalNameValueNode = "<b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + _xmlEncode(LogicalName.toLowerCase()) + "</b:value>";
}
var request = [
"<soapenv:Envelope xmlns:soapenv=\"https://schemas.xmlsoap.org/soap/envelope/\">",
//Allows retrieval if ImageAttributeMetadata objects
"<soapenv:Header><a:SdkClientVersion xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">6.0</a:SdkClientVersion></soapenv:Header>",
"<soapenv:Body>",
"<Execute xmlns=\"https://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">",
"<request i:type=\"a:RetrieveAttributeRequest\" xmlns:a=\"https://schemas.microsoft.com/xrm/2011/Contracts\">",
"<a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">",
"<a:KeyValuePairOfstringanyType>",
"<b:key>EntityLogicalName</b:key>",
entityLogicalNameValueNode,
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>MetadataId</b:key>",
"<b:value i:type=\"ser:guid\" xmlns:ser=\"https://schemas.microsoft.com/2003/10/Serialization/\">" + _xmlEncode(MetadataId) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>RetrieveAsIfPublished</b:key>",
"<b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + _xmlEncode(RetrieveAsIfPublished.toString()) + "</b:value>",
"</a:KeyValuePairOfstringanyType>",
"<a:KeyValuePairOfstringanyType>",
"<b:key>LogicalName</b:key>",
logicalNameValueNode,
"</a:KeyValuePairOfstringanyType>",
"</a:Parameters>",
"<a:RequestId i:nil=\"true\" />",
"<a:RequestName>RetrieveAttribute</a:RequestName>",
"</request>",
"</Execute>",
"</soapenv:Body>",
"</soapenv:Envelope>"].join("");
var req = new XMLHttpRequest();
req.open("POST", _getUrl() + "/XRMServices/2011/Organization.svc/web", true);
try { req.responseType = 'msxml-document'} catch(e){}
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "https://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.onreadystatechange = function () {
if (req.readyState == 4 /* complete */) {
req.onreadystatechange = null; //Addresses potential memory leak issue with IE
if (req.status == 200) {
//Success
var doc = req.responseXML;
try{_setSelectionNamespaces(doc);}catch(e){}
var a = _objectifyNode(_selectSingleNode(doc, "//b:value"));
successCallBack(a, passThroughObject);
}
else {
//Failure
errorCallBack(_getError(req));
}
}
};
req.send(request);
};
this.EntityFilters = function () {
/// <summary>SDK.Metadata.EntityFilters enum summary</summary>
/// <field name="Default" type="Number" static="true">enum field summary for Default</field>
/// <field name="Entity" type="Number" static="true">enum field summary for Entity</field>
/// <field name="Attributes" type="Number" static="true">enum field summary for Attributes</field>
/// <field name="Privileges" type="Number" static="true">enum field summary for Privileges</field>
/// <field name="Relationships" type="Number" static="true">enum field summary for Relationships</field>
/// <field name="All" type="Number" static="true">enum field summary for All</field>
throw new Error("Constructor not implemented this is a static enum.");
};
var _arrayElements = ["Attributes",
"ManyToManyRelationships",
"ManyToOneRelationships",
"OneToManyRelationships",
"Privileges",
"LocalizedLabels",
"Options",
"Targets"];
function _getError(resp) {
///<summary>
/// Private function that attempts to parse errors related to connectivity or WCF faults.
///</summary>
///<param name="resp" type="XMLHttpRequest">
/// The XMLHttpRequest representing failed response.
///</param>
//Error descriptions come from https://support.microsoft.com/kb/193625
if (resp.status == 12029)
{ return new Error("The attempt to connect to the server failed."); }
if (resp.status == 12007)
{ return new Error("The server name could not be resolved."); }
var faultXml = resp.responseXML;
var errorMessage = "Unknown (unable to parse the fault)";
if (typeof faultXml == "object") {
var faultstring = null;
var ErrorCode = null;
var bodyNode = faultXml.firstChild.firstChild;
//Retrieve the fault node
for (var i = 0; i < bodyNode.childNodes.length; i++) {
var node = bodyNode.childNodes[i];
//NOTE: This comparison does not handle the case where the XML namespace changes
if ("s:Fault" == node.nodeName) {
for (var j = 0; j < node.childNodes.length; j++) {
var testNode = node.childNodes[j];
if ("faultstring" == testNode.nodeName) {
faultstring = _getNodeText(testNode);
}
if ("detail" == testNode.nodeName) {
for (var k = 0; k < testNode.childNodes.length; k++) {
var orgServiceFault = testNode.childNodes[k];
if ("OrganizationServiceFault" == orgServiceFault.nodeName) {
for (var l = 0; l < orgServiceFault.childNodes.length; l++) {
var ErrorCodeNode = orgServiceFault.childNodes[l];
if ("ErrorCode" == ErrorCodeNode.nodeName) {
ErrorCode = _getNodeText(ErrorCodeNode);
break;
}
}
}
}
}
}
break;
}
}
}
if (ErrorCode != null && faultstring != null) {
errorMessage = "Error Code:" + ErrorCode + " Message: " + faultstring;
}
else {
if (faultstring != null) {
errorMessage = faultstring;
}
}
return new Error(errorMessage);
};
function _Context() {
var errorMessage = "Context is not available.";
if (typeof GetGlobalContext != "undefined")
{ return GetGlobalContext(); }
else {
if (typeof Xrm != "undefined") {
return Xrm.Page.context;
}
else
{ return new Error(errorMessage); }
}
};
function _getUrl() {
var url = _Context().getClientUrl();
return url;
};
function _evaluateEntityFilters(EntityFilters) {
var entityFilterArray = [];
if ((1 & EntityFilters) == 1) {
entityFilterArray.push("Entity");
}
if ((2 & EntityFilters) == 2) {
entityFilterArray.push("Attributes");
}
if ((4 & EntityFilters) == 4) {
entityFilterArray.push("Privileges");
}
if ((8 & EntityFilters) == 8) {
entityFilterArray.push("Relationships");
}
return entityFilterArray.join(" ");
};
function _isMetadataArray(elementName) {
for (var i = 0; i < _arrayElements.length; i++) {
if (elementName == _arrayElements[i]) {
return true;
}
}
return false;
};
function _objectifyNode(node) {
//Check for null
if (node.attributes != null && node.attributes.length == 1) {
if (node.attributes.getNamedItem("i:nil") != null && node.attributes.getNamedItem("i:nil").nodeValue == "true") {
return null;
}
}
//Check if it is a value
if ((node.firstChild != null) && (node.firstChild.nodeType == 3)) {
var nodeName = _getNodeName(node);
switch (nodeName) {
//Integer Values
case "ActivityTypeMask":
case "ObjectTypeCode":
case "ColumnNumber":
case "DefaultFormValue":
case "MaxValue":
case "MinValue":
case "MaxLength":
case "Order":
case "Precision":
case "PrecisionSource":
case "LanguageCode":
return parseInt(node.firstChild.nodeValue, 10);
// Boolean values
case "AutoRouteToOwnerQueue":
case "CanBeChanged":
case "CanTriggerWorkflow":
case "IsActivity":
case "IsAIRUpdated":
case "IsActivityParty":
case "IsAvailableOffline":
case "IsChildEntity":
case "IsCustomEntity":
case "IsCustomOptionSet":
case "IsDocumentManagementEnabled":
case "IsEnabledForCharts":
case "IsGlobal":
case "IsImportable":
case "IsIntersect":
case "IsManaged":
case "IsReadingPaneEnabled":
case "IsValidForAdvancedFind":
case "CanBeSecuredForCreate":
case "CanBeSecuredForRead":
case "CanBeSecuredForUpdate":
case "IsCustomAttribute":
case "IsManaged":
case "IsPrimaryId":
case "IsPrimaryName":
case "IsSecured":
case "IsValidForCreate":
case "IsValidForRead":
case "IsValidForUpdate":
case "IsCustomRelationship":
case "CanBeBasic":
case "CanBeDeep":
case "CanBeGlobal":
case "CanBeLocal":
return (node.firstChild.nodeValue == "true") ? true : false;
//OptionMetadata.Value and BooleanManagedProperty.Value and AttributeRequiredLevelManagedProperty.Value
case "Value":
//BooleanManagedProperty.Value
if ((node.firstChild.nodeValue == "true") || (node.firstChild.nodeValue == "false")) {
return (node.firstChild.nodeValue == "true") ? true : false;
}
//AttributeRequiredLevelManagedProperty.Value
if (
(node.firstChild.nodeValue == "ApplicationRequired") ||
(node.firstChild.nodeValue == "None") ||
(node.firstChild.nodeValue == "Recommended") ||
(node.firstChild.nodeValue == "SystemRequired")
) {
return node.firstChild.nodeValue;
}
var numberValue = parseInt(node.firstChild.nodeValue, 10);
if (isNaN(numberValue)) {
//FormatName.Value
return node.firstChild.nodeValue;
}
else {
//OptionMetadata.Value
return numberValue;
}
break;
//String values
default:
return node.firstChild.nodeValue;
}
}
//Check if it is a known array
if (_isMetadataArray(_getNodeName(node))) {
var arrayValue = [];
for (var i = 0; i < node.childNodes.length; i++) {
var objectTypeName;
if ((node.childNodes[i].attributes != null) && (node.childNodes[i].attributes.getNamedItem("i:type") != null)) {
objectTypeName = node.childNodes[i].attributes.getNamedItem("i:type").nodeValue.split(":")[1];
}
else {
objectTypeName = _getNodeName(node.childNodes[i]);
}
var b = _objectifyNode(node.childNodes[i]);
b._type = objectTypeName;
arrayValue.push(b);
}
return arrayValue;
}
//Null entity description labels are returned as <label/> - not using i:nil = true;
if(node.childNodes.length == 0)
{
return null;
}
//Otherwise return an object
var c = {};
if (node.attributes.getNamedItem("i:type") != null) {
c._type = node.attributes.getNamedItem("i:type").nodeValue.split(":")[1];
}
for (var i = 0; i < node.childNodes.length; i++) {
if (node.childNodes[i].nodeType == 3) {
c[_getNodeName(node.childNodes[i])] = node.childNodes[i].nodeValue;
}
else {
c[_getNodeName(node.childNodes[i])] = _objectifyNode(node.childNodes[i]);
}
}
return c;
};
function _selectNodes(node, XPathExpression) {
if (typeof (node.selectNodes) != "undefined") {
return node.selectNodes(XPathExpression);
}
else {
var output = [];
var XPathResults = node.evaluate(XPathExpression, node, _NSResolver, XPathResult.ANY_TYPE, null);
var result = XPathResults.iterateNext();
while (result) {
output.push(result);
result = XPathResults.iterateNext();
}
return output;
}
};
function _selectSingleNode(node, xpathExpr) {
if (typeof (node.selectSingleNode) != "undefined") {
return node.selectSingleNode(xpathExpr);
}
else {
var xpe = new XPathEvaluator();
var xPathNode = xpe.evaluate(xpathExpr, node, _NSResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return (xPathNode != null) ? xPathNode.singleNodeValue : null;
}
};
function _selectSingleNodeText(node, xpathExpr) {
var x = _selectSingleNode(node, xpathExpr);
if (_isNodeNull(x))
{ return null; }
if (typeof (x.text) != "undefined") {
return x.text;
}
else {
return x.textContent;
}
};
function _getNodeText(node) {
if (typeof (node.text) != "undefined") {
return node.text;
}
else {
return node.textContent;
}
};
function _isNodeNull(node) {
if (node == null)
{ return true; }
if ((node.attributes.getNamedItem("i:nil") != null) && (node.attributes.getNamedItem("i:nil").value == "true"))
{ return true; }
return false;
};
function _getNodeName(node) {
if (typeof (node.baseName) != "undefined") {
return node.baseName;
}
else {
return node.localName;
}
};
function _setSelectionNamespaces(doc)
{
var namespaces = [
"xmlns:s='https://schemas.xmlsoap.org/soap/envelope/'",
"xmlns:a='https://schemas.microsoft.com/xrm/2011/Contracts'",
"xmlns:i='http://www.w3.org/2001/XMLSchema-instance'",
"xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'",
"xmlns:c='https://schemas.microsoft.com/xrm/2011/Metadata'"
];
doc.setProperty("SelectionNamespaces",namespaces.join(" "));
}
function _NSResolver(prefix) {
var ns = {
"s": "https://schemas.xmlsoap.org/soap/envelope/",
"a": "https://schemas.microsoft.com/xrm/2011/Contracts",
"i": "http://www.w3.org/2001/XMLSchema-instance",
"b": "http://schemas.datacontract.org/2004/07/System.Collections.Generic",
"c": "https://schemas.microsoft.com/xrm/2011/Metadata"
};
return ns[prefix] || null;
};
function _xmlEncode(strInput) {
var c;
var XmlEncode = '';
if (strInput == null) {
return null;
}
if (strInput == '') {
return '';
}
for (var cnt = 0; cnt < strInput.length; cnt++) {
c = strInput.charCodeAt(cnt);
if (((c > 96) && (c < 123)) ||
((c > 64) && (c < 91)) ||
(c == 32) ||
((c > 47) && (c < 58)) ||
(c == 46) ||
(c == 44) ||
(c == 45) ||
(c == 95)) {
XmlEncode = XmlEncode + String.fromCharCode(c);
}
else {
XmlEncode = XmlEncode + '&#' + c + ';';
}
}
return XmlEncode;
};
}).call(SDK.Metadata);
//SDK.Metadata.EntityFilters
// this enum is written this way to enable Visual Studio IntelliSense
SDK.Metadata.EntityFilters.prototype = {
Default: 1,
Entity: 1,
Attributes: 2,
Privileges: 4,
Relationships: 8,
All: 15
};
SDK.Metadata.EntityFilters.Default = 1;
SDK.Metadata.EntityFilters.Entity = 1;
SDK.Metadata.EntityFilters.Attributes = 2;
SDK.Metadata.EntityFilters.Privileges = 4;
SDK.Metadata.EntityFilters.Relationships = 8;
SDK.Metadata.EntityFilters.All = 15;
SDK.Metadata.EntityFilters.__enum = true;
SDK.Metadata.EntityFilters.__flags = true;
另請參閱
逐步解說:使用現代應用程式 SOAP 端點與 JavaScript
針對具有 Web 資源的現代應用程式使用現代應用程式 SOAP 端點
在 Web 資源中使用 Web 服務資料 (OData 和現代應用程式 SOAP 端點)
技術文章:使用選項組選項與 REST 端點 - JScript
© 2017 Microsoft. 著作權所有,並保留一切權利。 著作權