locked
Saved Query in MS CRM 4.0 RRS feed

  • Question

  • Hi,

    I have a requirement like i need to retrieve all the view id's associated with an enity and show those view names with id in a picklist in a form.How to retrieve the view id associated with a particular entity.example i want to list the views of lead entity in a picklist in a custom entity and also with a view id is it possible to fetch the view records and their id.

     

    Thanks

    Divya


    Thanks Divya Ananth Our greatest glory is not in never falling but in rising every time we fall.
    Wednesday, December 29, 2010 5:18 AM

Answers

  • You can indeed.  Just put all your unencoded FetchXML into a string variable, and pass it into the Fetch() function in my Javascript Library .  Here's a snippet with all the code you'll need for this:

    function MischiefMayhemSOAP(serviceUrl, xmlSoapBody, soapActionHeader, suppressError) {
     var xmlReq = "<?xml version='1.0' encoding='utf-8'?>"
      + "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"
      + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
      + " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
      + GenerateAuthenticationHeader()
      + " <soap:Body>"
      + xmlSoapBody
      + " </soap:Body>"
      + "</soap:Envelope>";
    
     var httpObj = new ActiveXObject("Msxml2.XMLHTTP");
    
     httpObj.open("POST", serviceUrl, false);
    
     httpObj.setRequestHeader("SOAPAction", soapActionHeader);
     httpObj.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
     httpObj.setRequestHeader("Content-Length", xmlReq.length);
    
     httpObj.send(xmlReq);
    
     var resultXml = httpObj.responseXML;
    
     var errorCount = resultXml.selectNodes("//error").length;
     if (errorCount != 0) {
      var msg = resultXml.selectSingleNode("//description").nodeTypedValue;
      
      if (typeof(suppressError) == "undefined" || suppressError == null) {
       alert("The following error was encountered: " + msg);
      }
      
      return null;
     } else {
      return resultXml;
     }
    }
    
    // FetchEncode is borrowed from the _HtmlEncode function from Microsoft's CRM scripts
    function FetchEncode(fetchXml) {
     var c;
     var HtmlEncode = '';
     var buffer = '';
     var bufferLength = 500;
     var count = 0;
    
     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 )) {
       buffer += String.fromCharCode(c);
      } else {
       buffer += '&#' + c + ';';
      }
    
      if (++count == bufferLength) {
       HtmlEncode += buffer;
       buffer = '';
       count = 0;
      }
     }
    
     if (buffer.length) {
      HtmlEncode += buffer;
     }
    
     return HtmlEncode;
    }
    
    function Fetch(fetchXml, skipEncoding) {
     var xmlSoapBody = "<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"
      + " <fetchXml>"
      + typeof skipEncoding == true ? fetchXml : FetchEncode(fetchXml)
      + " </fetchXml>"
      + "</Fetch>";
     
     var fetchResponse = MischiefMayhemSOAP("/MSCRMServices/2007/CrmService.asmx", xmlSoapBody, "http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
    
     if (fetchResponse != null) {
      var fetchResults = new ActiveXObject("Msxml2.DOMDocument");
      
      fetchResults.async = false;
      fetchResults.resolveExternals = false;
      fetchResults.loadXML(fetchResponse.text);
      
      return fetchResults;
     } else {
      return null;
     }
    }
    
    

    Now, the tricky part with this code is that the FetchXML returned by the first query will already be encoded for use in another FetchXML call.  Passing it into my function will therefore break it, unless you set the second parameter to true , because it will effectively encode it again.  For convenience, the return of the Fetch call is placed into a DOMDocument object for XML DOM traversal.


    Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.
    Monday, January 3, 2011 4:58 PM
    Moderator

All replies

  • Hi, the below fetchxml retrieves the name and saved query id of the Lead entity (object type code = 4).

    From a javascript (e.g. form onload), you can call this fetchxml, retrieve a list of saved query, and populate the picklist dynamically with the values retrieved from the fetch xml call (refer to the sample in the sdk on dynamic picklist).

    Hope this helps.

    <fetch mapping='logical'>
    	<entity name='savedquery'>
    		<attribute name='name'/>
    		<attribute name='savedqueryid'/>
    		<attribute name='savedqueryidunique'/>
    		<attribute name='fetchxml'/>
    		<attribute name='returnedtypecode'/>
    		<filter type='and'>
    			<condition attribute='returnedtypecode' operator='eq' value='4'/>
    		</filter>
    	</entity>
    </fetch>
    
    Wednesday, December 29, 2010 7:32 AM
  • Thanks ,i will do it can u also tell me how to reterieve the view records with the view id.Example i need the records of the "Active leads", i have the view id with me.How to retrieve it.

     

    Thanks

    Divya


    Thanks Divya Ananth Our greatest glory is not in never falling but in rising every time we fall.
    Wednesday, December 29, 2010 10:41 PM
  • You could use the FetchXML returned in the server's response (in a "fetchxml" node) to the first FetchXML query (the one that looks for savedquery records) to access the records that would be displayed in the view you retrieved.
    Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.
    Thursday, December 30, 2010 3:35 AM
    Moderator
  • If the results of the first query is not cached anywhere on the form, then you'll need to do 2 queries:

    1) Retrieve "fetch xml" from the saved query using your viewid

    <fetch mapping='logical'>
    	<entity name='savedquery'>
    		<attribute name='fetchxml'/>
    		<filter type='and'>
    			<condition attribute='savedqueryid' operator='eq' value='{yourviewid}'/>
    		</filter>
    	</entity>
    </fetch>
    
    

    2) use the fetchxml returned from step 1 to retrieve the records.

    Thursday, December 30, 2010 6:31 AM
  • Thanks guys but can you place the whole code for using fetch in javascript.....
    Thanks Divya Ananth Our greatest glory is not in never falling but in rising every time we fall.
    Monday, January 3, 2011 7:21 AM
  • You can indeed.  Just put all your unencoded FetchXML into a string variable, and pass it into the Fetch() function in my Javascript Library .  Here's a snippet with all the code you'll need for this:

    function MischiefMayhemSOAP(serviceUrl, xmlSoapBody, soapActionHeader, suppressError) {
     var xmlReq = "<?xml version='1.0' encoding='utf-8'?>"
      + "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"
      + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
      + " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
      + GenerateAuthenticationHeader()
      + " <soap:Body>"
      + xmlSoapBody
      + " </soap:Body>"
      + "</soap:Envelope>";
    
     var httpObj = new ActiveXObject("Msxml2.XMLHTTP");
    
     httpObj.open("POST", serviceUrl, false);
    
     httpObj.setRequestHeader("SOAPAction", soapActionHeader);
     httpObj.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
     httpObj.setRequestHeader("Content-Length", xmlReq.length);
    
     httpObj.send(xmlReq);
    
     var resultXml = httpObj.responseXML;
    
     var errorCount = resultXml.selectNodes("//error").length;
     if (errorCount != 0) {
      var msg = resultXml.selectSingleNode("//description").nodeTypedValue;
      
      if (typeof(suppressError) == "undefined" || suppressError == null) {
       alert("The following error was encountered: " + msg);
      }
      
      return null;
     } else {
      return resultXml;
     }
    }
    
    // FetchEncode is borrowed from the _HtmlEncode function from Microsoft's CRM scripts
    function FetchEncode(fetchXml) {
     var c;
     var HtmlEncode = '';
     var buffer = '';
     var bufferLength = 500;
     var count = 0;
    
     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 )) {
       buffer += String.fromCharCode(c);
      } else {
       buffer += '&#' + c + ';';
      }
    
      if (++count == bufferLength) {
       HtmlEncode += buffer;
       buffer = '';
       count = 0;
      }
     }
    
     if (buffer.length) {
      HtmlEncode += buffer;
     }
    
     return HtmlEncode;
    }
    
    function Fetch(fetchXml, skipEncoding) {
     var xmlSoapBody = "<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"
      + " <fetchXml>"
      + typeof skipEncoding == true ? fetchXml : FetchEncode(fetchXml)
      + " </fetchXml>"
      + "</Fetch>";
     
     var fetchResponse = MischiefMayhemSOAP("/MSCRMServices/2007/CrmService.asmx", xmlSoapBody, "http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
    
     if (fetchResponse != null) {
      var fetchResults = new ActiveXObject("Msxml2.DOMDocument");
      
      fetchResults.async = false;
      fetchResults.resolveExternals = false;
      fetchResults.loadXML(fetchResponse.text);
      
      return fetchResults;
     } else {
      return null;
     }
    }
    
    

    Now, the tricky part with this code is that the FetchXML returned by the first query will already be encoded for use in another FetchXML call.  Passing it into my function will therefore break it, unless you set the second parameter to true , because it will effectively encode it again.  For convenience, the return of the Fetch call is placed into a DOMDocument object for XML DOM traversal.


    Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.
    Monday, January 3, 2011 4:58 PM
    Moderator
  • Thanks Berry
    Thanks Divya Ananth Our greatest glory is not in never falling but in rising every time we fall.
    Thursday, January 6, 2011 12:15 AM
  • Hi, Divya

     

                     here is your code. I think it may suitable your requirements.

     

     protected void btnEntitie_Click(object sender, EventArgs e)
        {

            //Method for accessing MSCRN service.
            BasicInformation();

            // Create the request
            RetrieveAllEntitiesRequest allEntitiesRequest = new RetrieveAllEntitiesRequest();

            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            allEntitiesRequest.RetrieveAsIfPublished = true;
            allEntitiesRequest.MetadataItems = MetadataItems.IncludeAttributes;

            // Execute the request
            RetrieveAllEntitiesResponse allEntitiesResponse = (RetrieveAllEntitiesResponse)metadataService.Execute(allEntitiesRequest);

            // Iterate through the retrieved entities
            foreach (EntityMetadata entity in allEntitiesResponse.CrmMetadata)
            {
                if (entity.IsCustomEntity.Value == true)
                {
                    ListItem li = new ListItem(entity.SchemaName.ToString(), entity.MetadataId.Value.ToString());
                    ddlEntities.Items.Add(li);
                   
                }
            }


        }


    S.B.Raju
    Saturday, February 5, 2011 2:10 PM
  • The code I provided above is JavaScript.


    Dave Berry - MVP Dynamics CRM - http:\\crmentropy.blogspot.com Please follow the forum guidelines when inquiring of the dedicated CRM community for assistance.
    Friday, September 30, 2011 8:15 PM
    Moderator