Wednesday, 17 February 2016

Get All fields available on MS CRM form using c#

If you want to get all the fields available on a MS CRM form.
You can use below C# code to get  all attributes.

Below code requires entity logical name and formid.

To get the formid open the record in MS CRM form editor and press  F12 (developer tools) use Chrome for better experience, Search formId in Elements tab.

You will get following results.

<input name="formId" type="hidden" value="{b053a39a-041a-4356-acef-ddf00182762b}">

OR

Mscrm.FormEditorVariables.currentFormId = '\x7bb053a39a-041a-4356-acef-ddf00182762b\x7d'

Take this FormId as you wish :) and proceed for the our custom application.

           // Obtain an organization service proxy.
           .
            using (var _orgService = new OrganizationService(connection))
            {

                string formId = "{b053a39a-041a-4356-acef-ddf00182762b}";

                XmlDocument form = RetrieveEntityForms("account", formId, _orgService);

                XmlNodeList nodeList = (form.SelectNodes("//control"));

                StringBuilder sbAttributes = new StringBuilder();;
                                 

                foreach (XmlNode elem in nodeList)
                {
                    if (elem.Attributes["datafieldname"] != null)
                    {
                        string strValue = elem.Attributes["datafieldname"].Value;

                        sbAttributes.AppendLine(strValue);
                    }


                }                

                Console.WriteLine(sbAttributes.ToString());
                
                Console.Write("DONE!!");
                Console.ReadKey();
                

            }

          
 public static XmlDocument RetrieveEntityForms(string logicalName,string formid, IOrganizationService oService)
        {
            QueryByAttribute qba = new QueryByAttribute("systemform");
            qba.Attributes.AddRange("objecttypecode", "type","formid");
            qba.Values.AddRange(logicalName, 2, formid);
            qba.ColumnSet = new ColumnSet(true);

            EntityCollection ec = oService.RetrieveMultiple(qba);

            StringBuilder allFormsXml = new StringBuilder();
            allFormsXml.Append("");

            foreach (Entity form in ec.Entities)
            {
                allFormsXml.Append(form["formxml"]);
            }

            allFormsXml.Append("");

            XmlDocument docAllForms = new XmlDocument();
            docAllForms.LoadXml(allFormsXml.ToString());

            return docAllForms;
        }

No comments:

Post a Comment