Saturday, May 16, 2015

Paging and Bulk Update in CRM

       private void TestExample()
        {
            getCRMService();
            XrmServiceContext _context = new XrmServiceContext(service);

            int Fetchcount = 3;
            int PageNumber = 1;
            int RecordCount = 0;
            string pagingCookie = null;

            string FetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='account'>
                                    <attribute name='name' />
                                    <attribute name='primarycontactid' />
                                    <attribute name='telephone1' />
                                    <attribute name='accountid' />
                                    <order attribute='name' descending='false' />
                                  </entity>
                                </fetch>";

            while (true)
            {
                string xml = CreateXml(FetchXML, pagingCookie, PageNumber, Fetchcount);
                RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

                EntityCollection entity = ((RetrieveMultipleResponse)service.Execute(fetchRequest)).EntityCollection;

                if (entity.MoreRecords)
                {
                    PageNumber++;
                }
                else
               {
                    BulkUpdate(service, entity);
                    break;
                }

                BulkUpdate(service, entity);
            }

        }
        public static void BulkUpdate(IOrganizationService service, EntityCollection entities)
        {
            ExecuteMultipleRequest req = new ExecuteMultipleRequest();

            req.Requests = new OrganizationRequestCollection();

            req.Settings = new ExecuteMultipleSettings();

            req.Settings.ContinueOnError = true;

            req.Settings.ReturnResponses = true;


            foreach (var entity in entities.Entities)
            {
                entity.Attributes.Remove("telephone1");
                entity.Attributes["telephone1"] ="121454";
                UpdateRequest updateRequest = new UpdateRequest { Target = entity };
           
                req.Requests.Add(updateRequest);
            }

            ExecuteMultipleResponse responseWithNoResults =
                       (ExecuteMultipleResponse)_serviceProxy.Execute(req);

            if (responseWithNoResults.Responses.Count > 0)
            {
                foreach (var responseItem in responseWithNoResults.Responses)
                {
                    if (responseItem.Fault != null)
                    {
                    }
                }
            }
            else
            {
                Console.WriteLine("All account records have been updated successfully.");
            }

        }
        public string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }
        public string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }

Thursday, August 21, 2014

Check Entity and Attribute Exist in CRM or not?

   private bool DoesAttributeExist(string entityName,string attributeName, IOrganizationService service)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
                LogicalName = entityName
            };
            RetrieveEntityResponse response
              = (RetrieveEntityResponse)service.Execute(request);

            return response.EntityMetadata.Attributes.FirstOrDefault(element => element.LogicalName == attributeName && element.AttributeType.Value == AttributeTypeCode.DateTime) != null;
        }

        private bool DoesEntityExist(string entityName, IOrganizationService _service)
        {
            RetrieveAllEntitiesRequest allEntitiesRequest = new RetrieveAllEntitiesRequest();
            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            allEntitiesRequest.RetrieveAsIfPublished = false;
            //allEntitiesRequest.MetadataItems = MetadataItems.EntitiesOnly;

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

            // Iterate through the retrieved entities
            foreach (EntityMetadata entity in allEntitiesResponse.EntityMetadata)
            {
                if (entity.LogicalName == entityName)
                    return true;
            }
            return false;
        }

Thursday, April 24, 2014

How to use ExecuteMultipleRequest with ServiceContext and Linq

The following code is retrieving all the contacts where parent customer id is C6CB814A-BA75-E011-8720-00155DA5304E and updating their phone number.
var ServiceContext = new OrganizationServiceContext(service);
Guid accountid = new Guid("C6CB814A-BA75-E011-8720-00155DA5304E");

// Create an ExecuteMultipleRequest object.
ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
{
    // Assign settings that define execution behavior: continue on error, don't return responses. 
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = false
    }, 
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};
               
requestWithResults.Requests.AddRange(from c in ServiceContext.CreateQuery("contact")
                                    where c["parentcustomerid"].Equals(accountid)
                                    select new UpdateRequest()
                                    {
                                        Target = new Entity("contact")
                                        {
                                            Id = c.Id,
                                            Attributes = { new KeyValuePair<string,object>("telephone1", "+61402234212") }
                                        }
                                    });

// Excute the requests
ExecuteMultipleResponse Response = (ExecuteMultipleResponse)service.Execute(requestWithResults);

Thursday, February 27, 2014

Filtering records in the sub grid in Microsoft Dynamics CRM 2011 and CRM 2013

function updateSubGrid() {
debugger
    //This will get the related products grid details and store in a variable.

    var relatedProducts = document.getElementById("AllActivities");
    //Initializing the lookup field to store in an array.

    var lookupfield = new Array;



    //Get the lookup field

    lookupfield = Xrm.Page.getAttribute("to").getValue();



    //This will get the lookup field guid if there is value present in the lookup

    if (lookupfield != null) {

        var lookupid = lookupfield[0].id;

    }



    //Else the function will return and no code will be executed.

    else {

        return;

    }

     

    //This method is to ensure that grid is loaded before processing.

    if (relatedProducts ==null || relatedProducts.readyState != "complete")

    {



        //This statement is used to wait for 2 seconds and recall the function until the grid is loaded.

        setTimeout('updateSubGrid()', 2000);

        return;

    }  

    //This is the fetch xml code which will retrieve all the order products related to the order selected for the case.

    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";

    fetchXml += "<entity name='activitypointer'>";

    fetchXml += "<attribute name='activitytypecode' />";

    fetchXml += "<attribute name='subject' />";

    fetchXml += "<attribute name='prioritycode' />";

    fetchXml += "<attribute name='activityid' />";

    fetchXml += "<attribute name='instancetypecode' />";

    fetchXml += "<attribute name='regardingobjectid' />";

fetchXml += "<attribute name='scheduledstart' />";

fetchXml += "<attribute name='scheduledend' />";

    fetchXml += "<filter type='and'>";

    fetchXml += "<condition attribute='salesorderid' operator='eq'  value='" + lookupid + "' />";

    fetchXml += "</filter>";

    fetchXml += "</entity>";

    fetchXml += "</fetch>";

     

    //Setting the fetch xml to the sub grid.

    relatedProducts.control.SetParameter("fetchXml", fetchXml);



    //This statement will refresh the sub grid after making all modifications.

    relatedProducts.control.refresh();

}   

Monday, February 3, 2014

Create View in CRM using coding.

 var fetchxml = "<fetch distinct='true' mapping='logical' output-format='xml-platform' version='1.0'><entity name='account'><attribute name='name'/><attribute name='primarycontactid'/><attribute name='telephone1'/><attribute name='accountid'/><order descending='false' attribute='name'/><link-entity name='incident' alias='ac' link-type='outer' to='accountid' from='customerid'/><filter type='and'><condition attribute='customerid' operator='null' entityname='incident'/><condition attribute='statecode' operator='eq' value='0'/></filter></entity></fetch>";

            var savedQuery = new SavedQuery()
            {
                Name = "Acount with no Cases",
                ReturnedTypeCode = "account",
                FetchXml = fetchxml,

                QueryType = 0
            };
            _service.Create(savedQuery);

Friday, January 31, 2014

How to get the Microsoft CRM “Closed Activities” Nav Bar Link Back (if you delete it)

Just export the solution of entity and add following relationship

<NavBarByRelationshipItem RelationshipName="Contact_ActivityPointers" Id="navActivityHistory" TitleResourceId="Tab_Label_History" Icon="/_imgs/ico_18_history.gif" ViewId="21E2B905-6FDB-470d-8517-AD69B4C01268" Sequence="20" Area="Info">
<Privileges>
     <Privilege Entity="" Privilege="ReadActivity" />
</Privileges>
<Titles>
<Title LCID="1033" Text="Closed Activities" />
</Titles>
</NavBarByRelationshipItem>

Here I have set the example of contact entity.

Thursday, December 12, 2013

Pass Custom Parameters to an entity form through a URL in CRM 2013

This blog posted back in 2012, described how to pass custom parameters to an entity in CRM 2011. The other day tried to use the same code to make it in CRM 2013 but unfortunately that would not work. You will be able to pass a single parameter through the URL using the same code as before, but to pass more than one parameters, you need to use the new openEntityForm client API.

In 2011, the parameters would be concatenated to make a string and pass that as the extraqs query string

var extraqs = "Parameter_Source=Hello";
extraqs += "parameter_Source2=8";

//Set features for how the window will appear.
var features = "location=no,menubar=no,status=no,toolbar=no";
// Open the window.
window.open(Xrm.Page.context.getServerUrl() +"/main.aspx?etn=account&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);

Using the new client API to open the record, this would now be presented as follows

var parameters = {};
parameters["myparam_test"] = "1";

parameters["parameter_test"] = "100";

//use the openEntityForm to open the record