Tuesday, 28 July 2015

PartyList

PartyList : This is a  data type available in MS crm.
It  is almost  a lookup  that can have references to more than one records of an entity for a single field.

A partylist  has certain attributes like   name, id, type,typename etc.

To retrieve values by jscript:
 
var partylistItem = new Array;
 
//get the items/values in a field named"resources"
partylistItem  = Xrm.Page.getAttribute("resources").getValue();
 
Thus now the array  holds all the items/record  referenced for a single field
 
.
we may  have a  loop through this array  to retrieve the values like,
 
partylistItem.length - gives how many records are referenced.
partylistItem[0].id - the guid of the item.


To set values by  jscript :
To set  values we also  need to  get an  array.
var partlistset= new Array();
partlistset[0] = new Object();
partlistset[0].id = id; // provide a guid type value
partlistset[0].name = name; // provide a suitable name
partlistset[0].entityType = entityType; // provide the entity  name  of the item  ie account/ contact etc .
Xrm.Page.getAttribute("resource").setValue(partlistset);



The following table lists the activity party types that are supported for each activity, and the corresponding activity properties to specify those activity party types.

 

Activity entity name Supported activity party type Activity attribute
Appointment
OptionalAttendee
Organizer
RequiredAttendee
Appointment.OptionalAttendees
Appointment.Organizer
Appointment.RequiredAttendees
CampaignActivity
Partner
Sender
CampaignActivity.Partners
CampaignActivity.From
CampaignResponse
Customer
Partner
From
CampaignResponse.Customer
CampaignResponse.Partner
CampaignResponse.From
Email
BccRecipient
CcRecipient
Sender
ToRecipient
Email.Bcc
Email.Cc
Email.From
Email.To
Fax
Sender
ToRecipient
Fax.From
Fax.To
Letter
BccRecipient
Sender
ToRecipient
Letter.Bcc
Letter.From
Letter.To
PhoneCall
Sender
ToRecipient
PhoneCall.From
PhoneCall.To
RecurringAppointmentMaster
OptionalAttendee
Organizer
RequiredAttendee
RecurringAppointmentMaster.OptionalAttendees
RecurringAppointmentMaster.Organizer
RecurringAppointmentMaster.RequiredAttendees
ServiceAppointment
Customer
Resource
ServiceAppointment.Customers
ServiceAppointment.Resources
 

Thanks.

Wednesday, 22 July 2015

Get and Set lookup value using javascript in CRM 2011



In this article , I am going to explain how to set and get CRM lookup attribute value using javascript

Get a lookup value
var lookup = new Array();
lookup = Xrm.Page.getAttribute("attributename").getValue();
if (lookup != null) {
    var name = lookup[0].name;
    var id = lookup[0].id;
    var entityType = lookup[0].entityType;
}

Set a lookup value
var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = recorid;
lookup[0].name = recordname;
lookup[0].entityType = entityname;
Xrm.Page.getAttribute("attributename").setValue(lookup);

Alternate method to set lookup value
Xrm.Page.getAttribute("attributename").setValue([{ id: recorid, name: recordname, entityType: entityname}]);

Tuesday, 28 April 2015

Query FetchXml thorugh Soap Request

FetchXml can be query using Soap call. There are plenty of libraries available that you can use to make this task work but i will explain you how to make it own library.

There are three steps to that, which are as follows:
1) Build your XML and Encode them in XML Document object, for example

 var fetchQuery="<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\"><entity name=\"lead\"><attribute name=\"fullname\" /><attribute name=\"companyname\" /><attribute name=\"telephone1\" /><attribute name=\"leadid\" /><order attribute=\"fullname\" descending=\"false\" /><link-entity name=\"account\" from=\"accountid\" to=\"parentaccountid\" alias=\"ad\"><filter type=\"and\"><condition attribute=\"accountid\" operator=\"eq\" uiname=\"A. Datum Corporation (sample)\" uitype=\"account\" value=\"{A9D32F2F-58D4-E411-
80F0-C4346BAC094C}\" /></filter></link-entity></entity></fetch>";

    var encodedFetchQuery = _xmlEncode(fetchQuery);
 
 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;
 }
 
2) Make a Soap Envelop, for example
 
var request = [
        '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><
s:Body>',
            '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >',
                '<request i:type="a:RetrieveMultipleRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts">',
                    '<a:Parameters xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic">',
                        '<a:KeyValuePairOfstringanyType>',
                            '<b:key>Query</b:key>',
                            '<b:value i:type="a:FetchExpression">',
                                '<a:Query>', encodedFetchQuery , '</a:Query>',
                            '</b:value>',
                        '</a:KeyValuePairOfstringanyType>',
                    '</a:Parameters>',
                    '<a:RequestId i:nil="true"/>',
                    '<a:RequestName>RetrieveMultiple</a:RequestName>',
                '</request>',
            '</Execute>',
        '</s:Body></s:Envelope>'
    ].join("");
 
3) Make a soap Request, for example
 
//Synchronous XMLHttpRequest to retrieve contact records
    var req = new XMLHttpRequest();
    req.open("POST", encodeURI(Xrm.Page.context.
getClientUrl() + "/XRMServices/2011/Organization.svc/web"), false);
    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",     "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");  
      req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null; //Addresses potential memory leak issue with IE
            if (this.status == 200  /*success*/) {
                var doc = req.responseXML;
                successCallback(doc);
            }
            else {
                errorCallback(accountId);
            }
        }
    }
    req.send(request);
 
You will get your output in  req.responseXML.xml in XML format. its your choice how you wish to use it.

Thanks.
 
 

Wednesday, 15 April 2015

Calling Actions through java script

Action is a new and very powerful feature of Microsoft Dynamics CRM. Action can be called through Soap Call which goes like following some steps which goes like this.
            1) You are require create soap envelop.
            2) calling soap service.

Complete Js to call your Action

function CallActionFromJavaScript() {
   debugger;
    var entityId = Xrm.Page.data.entity.getId();;
    var entityName = Entity name;
    var requestName = Action Name;

    ExecuteActionCreateProject(entityId, entityName, requestName);

}

function ExecuteActionCreateProject(EntityId,entityId, entityName, requestName) {
    // Creating the request XML for calling the Action
    var requestXML = ""
    requestXML += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestXML += "  <s:Body>";
    requestXML += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestXML += "      <request xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
    requestXML += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestXML += "          <a:KeyValuePairOfstringanyType>";
    requestXML += "            <b:key>Target</b:key>";
    requestXML += "            <b:value i:type=\"a:EntityReference\">";
    requestXML += "              <a:Id>"+entityId+"</a:Id>";
    requestXML += "              <a:LogicalName>"+entityName+"</a:LogicalName>";
    requestXML += "              <a:Name i:nil=\"true\">";
    requestXML += "            </a:Name></b:value>";
    requestXML += "          </a:KeyValuePairOfstringanyType>";

    requestXML += "          <a:KeyValuePairOfstringanyType>";
    requestXML += "            <b:key>EntityId</b:key>";
    requestXML += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">"+EntityId+"</b:value>";
    requestXML += "          </a:KeyValuePairOfstringanyType>";

    requestXML += "        </a:Parameters>";
    requestXML += "        <a:RequestId i:nil=\"true\">";
    requestXML += "         </a:RequestId>";
    requestXML += "        <a:RequestName>"+requestName+"</a:RequestName>";
    requestXML += "      </request>";
    requestXML += "    </Execute>";
    requestXML += "  </s:Body>";
    requestXML += "</s:Envelope>";

    var req = new XMLHttpRequest();

    req.open("POST", GetClientUrl(), false)
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction",     "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    req.send(requestXML);
    //Get the Response from the CRM Execute method
    //var response = req.responseXML.xml;
    req.onerror = function (e) {
        alert(req.statusText);
    };

    if (req.status === 200) {
        alert(req.responseText);
    }
}

function GetClientUrl() {
    if (typeof Xrm.Page.context == "object") {
        clientUrl = Xrm.Page.context.getClientUrl();
    }
    var ServicePath = "/XRMServices/2011/Organization.svc/web";
    return clientUrl + ServicePath;
}

Thanks.

Wednesday, 11 March 2015

Web Resource creation through SDK message

For a web resource creation through SDK, i referred one msdn page click. In this page they read a text file convert them into binary content and then converted into base64 string.

In my case i had HTML on CRM form Fields, so i fetch the field in Plugin and converted its content into binary format and finally into base64 string. the code for which goes as follows

               string JSContent = TileConfiguration.Attributes["livetile_jscontent"].ToString();
                string HTMLContent = TileConfiguration.Attributes["livetile_htmlcontent"].ToString();

                var bytes = Encoding.UTF8.GetBytes(JSContent + HTMLContent);
                var base64 = Convert.ToBase64String(bytes);

                //Set the Web Resource properties
                WebResource wr = new WebResource
                {
                    Content = base64,
                    DisplayName = "Test1",
                    Description ="Sample Test",
                    Name = "livetile_" +"test1",
                    LogicalName = WebResource.EntityLogicalName,

                   //you can specify type for web resource format
                   Webpage (HTML) .htm, .html 1
                    Style Sheet (CSS) .css 2
                    Script (JScript) .js 3
                    Data (XML) .xml 4
                    Image (PNG) .png 5
                    Image (JPG) .jpg 6
                    Image (GIF) .gif 7
                    Silverlight (XAP) .xap 8
                   StyleSheet (XSL) .xsl, .xslt 9
                     Image (ICO) .ico 10

                    WebResourceType = new OptionSetValue(1)
                };

                CreateRequest cr = new CreateRequest
                {
                    Target = wr
                };
                //Set the SolutionUniqueName optional parameter so the Web Resources will be
                // created in the context of a specific solution.
                //cr.Parameters.Add("SolutionUniqueName", _ImportWebResourcesSolutionUniqueName);

                CreateResponse cresp = (CreateResponse)service.Execute(cr);

To update the same web resource, You can do it using UpdateRequest, the code for which goes like below

                WebResource wr = new WebResource
                {
                   //Just pass the web resource ID
                    Id = new Guid(TileConfiguration.Attributes["livetile_webresourceid"].ToString()),
                    Content = base64,
                    DisplayName = "Test1",
                    Description = "Sample Test",
                    Name = "livetile_" + "test1",
                    LogicalName = WebResource.EntityLogicalName,
                    WebResourceType = new OptionSetValue(1)
                };

                UpdateRequest up = new UpdateRequest
                {
                    Target = wr
                };

             
                service.Execute(up);

Thanks.

Sunday, 1 March 2015

Retrieve CRM Entity Attributes List

To retrieve CRM Entity Attributes Listyou will be require to retrieve metadata information through RetrieveAllEntitiesRequest.

After retrieving the metadata, you will get complete list of attributes listed for Entity that you have pass. You can use the following code given below:

            // Retrieve the MetaData.
            RetrieveEntityRequest metaDataRequest = new RetrieveEntityRequest();

            RetrieveEntityResponse metaDataResponse = new RetrieveEntityResponse();

            metaDataRequest.EntityFilters = EntityFilters.Attributes;

            metaDataRequest.LogicalName = LOGICAL NAME;
                                          // your entity logical name goes here like "account"

            metaDataResponse = (RetrieveEntityResponse)service.Execute(metaDataRequest);

            EntityMetadata currentEntity = metaDataResponse.EntityMetadata;

            //AttributeMetadata contains all the metadata for an entity attribute.

            foreach (AttributeMetadata attribute in currentEntity.Attributes)
            {

                var attributeName = attribute.LogicalName;


            }

Thanks.

Wednesday, 25 February 2015

Retrieve CRM business Entities

To retrieve CRM business entities, you will be require to retrieve metadata information through RetrieveAllEntitiesRequest. 
 After retrieving the metadata, you will get complete list of entities listed in CRM whether it is system, business or custom entity. You can use the following code given below:

               RetrieveAllEntitiesRequest req = new RetrieveAllEntitiesRequest();

               req.EntityFilters = EntityFilters.Entity;

               req.RetrieveAsIfPublished = true;
       
               RetrieveAllEntitiesResponse response=
                                     (RetrieveAllEntitiesResponse)service.Execute(req);


                foreach (EntityMetadata currentEntity in response.EntityMetadata)
                          {
                                 string oEntity = "";
                                  // oEntity will provide you the name of Entities
                                  oEntity = currentEntity.SchemaName;                          
                           }

As you might be aware there are 325 entities(approx) in default CRM so you must not be interested in each and every Entities to list in. For this purpose there are many properties which are available in class
RetrieveAllEntitiesRequest which we can use as to filter the list, such as


               foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                           //property used to filter the entities list
                            if (currentEntity.IsValidForAdvancedFind.HasValue &&
                                currentEntity.IsValidForAdvancedFind.Value &&
                                currentEntity.CanBeRelatedEntityInRelationship.Value &&
                                currentEntity.CanBePrimaryEntityInRelationship.Value &&
                                currentEntity.CanTriggerWorkflow.Value &&
                                currentEntity.CanCreateViews.Value &&
                                currentEntity.CanCreateForms.Value &&
                                currentEntity.CanCreateCharts.Value &&
                                currentEntity.CanCreateAttributes.Value)
                            {
                                string oEntity = "";
                                oEntity = currentEntity.SchemaName;
                             }
                        }

If you can see i have used some of the filters such as IsValidForAdvancedFind, CanCreateViews, CanCreateForms etc which basically filter your list to almost 40 42 list of business entities. you can use more filters if you wish to filter the list further.

Thanks