Thursday 28 January 2016

Story behind Default values of optionset

Some known facts of CRM 





Publisher
While creating a publisher "Option value Prefix" Minimum value is 10000 and Maximum Value is 99999

Form Tabs and Sections
In CRM, a form can support you to insert 100 tabs. In tab, you can insert N number f sections.

Optionset
In an option set field for one option set Label, you can give Maximum 255 characters. And Value is from 0000 to 9999.
For Example in a publisher if you give Option Value Prefix is 10000 then your option set value should be in between 100000000 to 100009999

Wednesday 27 January 2016

Retrieve and Update Existing record

Retrieve and Update Existing record data in an entity


Here I mention using REST service Method

For that we need to add SDK.REST Javascript in your form (For getting this we need to go SampleCode-->JS-->RESTEndpoint-->JavaScriptRESTAssociateDisassociate-->JavaScriptRESTAssociateDisassociate-->Scripts)

Then create your own Javascript with following code

function RetrieveAllRecords(context) {
    var Account= "Your Custom Logic"; //Mention Which fields you want to get. For Example  "$select=new_Name"

///Parameters
//Param Name="Entity Name"-- Give your Entity Schema name based on Odata Query Designer
//For an Account record, use "Account"
///Param Name="Options"
//A String representing the OData System Query Options to control the data returned
//Param Name="SuccessCall Back" Type="function"
//Param Name="Error Call Back" Type="function"
//Param Name="OnComplete" Type="function"


       SDK.REST.retrieveMultipleRecords("Your Entity Name", searchRecords, retrieveAccountsCallBack, errorCallBack, ActiveRetrieveComplete);
}
function retrieveAccountsCallBack(retrievedAccounts, context) {
          for (var i = 0; i < retrievedAccounts.length; i++) {
               var name=retrievedAccounts[i].new_Name;
//Write your own logic here
        }
}
function errorCallBack() {
    alert(error.message);
}
function ProceedingsRetrieveComplete() { }


For updating Existing Record


First get the ID for which record you want to update.

Then again we have a method that  "updateRecord"

function updateRecord() {
var account={}
account.mobilenumber="9876543210";

//Parameters
//Param Name="GUID"
//use the GUID which record you want to update
//Param Name="object"
//based on your condiotion what you want to update
//Param Name="Type"
//The Schema Name of the Entity type record to retrieve.
//Param Name="updateSuccessCallback" , Type="function"
//Param Name="errorHandler" , Type="function"


       SDK.REST.updateRecord("GUID", account, Type, updateSuccessCallback, errorHandler); //Provide Existing Account record GUID
}

function updateSuccessCallback() {
    alert("The account record changes were saved");
}

function errorHandler(error) {
    alert(error.message);
}

Tuesday 19 January 2016

Create Publisher,Solution,Entities Programatically

Create Publisher, Solution, Entities Programmatically

Hi Coders,
Here I wanna Discuss how we can create publisher, Solution, Entities Programmatically In CRM. Purpose of this is we can create multiple Entities at the same time. Here I am explaining that in details.
Note: Here I am using the Early Bound concept so generate XRM File also.
Command for generating early bound class is :

CrmSvcUtil.exe /url:crmorganizationserviceurl    /out:XrmNew.cs /username:yourcrmusername /password:crmpassword     /namespace:Xrm /serviceContextName:XRMServiceContext

  • For creating Publisher we need to access CRM. So we need to give CRM Credentials.

            Uri organizationURL = new Uri("Your CRM Organization URI"); //You will get this from your CRM developer resource under Customization
            //Credentials of your CRM
            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = "your CRM user name";

            credentials.UserName.Password = "CRM login Password";

  • Declare global variables for Publisher Id, SolutionId.
            Guid crmsdkpublisherid = Guid.Empty;
            Guid SamplesolutionId;

            System.String customizedprefix;


  • Now retrieve the service from CRM
            using (var serviceproxy = new OrganizationServiceProxy(organizationURL, null, credentials, null))
            {
                //Getting CRM Service
                serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

                IOrganizationService service = (IOrganizationService)serviceproxy;
                            }

Create a publisher


For creating publisher following fields are required

1) Schema Name
2)Display Name
3)Customized Prefix

So we need to give above values without fail

           Publisher crmsdkpublisher = new Publisher
                {
                    UniqueName = "Publisher Schema Name",
                    FriendlyName = "Publisher Display Name",
                    CustomizationPrefix = "Your Custom Prefix",

                };

So now we need to check whether that publisher is available or not.for that we need to give our custom QueryExpression just like SQL queries

                QueryExpression QE = new QueryExpression
                {
                    EntityName = Publisher.EntityLogicalName,
                    ColumnSet = new ColumnSet("publisherid", "customizationprefix"),
                    Criteria = new FilterExpression(),

                };

//Add Query for checking whether it is duplicate or not
QE.Criteria.AddCondition("uniquename", ConditionOperator.Equal, crmsdkpublisher.UniqueName);

                EntityCollection crmsdkresults = serviceproxy.RetrieveMultiple(QE);


                Publisher sdksamplepublisher = null;

Now we can get publisher is available or not based on QueryExpression.So the publisher already exists then we can use that or else we can create new publisher.


//If publisher already exists then use following code
                if (crmsdkresults.Entities.Count > 0)
                {
                    sdksamplepublisher = (Publisher)crmsdkresults.Entities[0];
                    crmsdkpublisherid = (Guid)sdksamplepublisher.PublisherId;
                    customizedprefix = sdksamplepublisher.CustomizationPrefix;

                }
//If publisher does not exists then use following

                if (crmsdkresults.Entities.Count == 0)
                {
                    crmsdkpublisherid = serviceproxy.Create(crmsdkpublisher);

                }


Creation of solution



This is also the same as the creation of publisher. For creation one solution we need to provide the following values

1)Display Name
2)Schema Name
3)PublisherId(Under which publisher we need to create this solution)
4)Version

                //create a solution

                Solution sol = new Solution
                {
                    UniqueName = "Solution Schema Name",
                    FriendlyName = "Solution DisplayName",
                    PublisherId = new EntityReference(Publisher.EntityLogicalName, crmsdkpublisherid),
                    Version = "CRM Version",

                };

Same as a publisher we need to check whether the solution is already Exists or not. If it is not where we need to create

//Checking solution is existing or not based on your query
                solutionqueryexpression.Criteria.AddCondition("uniquename", ConditionOperator.Equal, sol.UniqueName);
                EntityCollection solutioncollection = serviceproxy.RetrieveMultiple(solutionqueryexpression);
                Solution samplesolutionresults = null;
                //If solution already exists
                if (solutioncollection.Entities.Count > 0)
                {
                    samplesolutionresults = (Solution)solutioncollection.Entities[0];
                    SamplesolutionId = (Guid)samplesolutionresults.SolutionId;
                }

                //If solution does not exists

                if (solutioncollection.Entities.Count == 0)
                {
                    SamplesolutionId = serviceproxy.Create(sol);

                }


Creation of Entity


For creating Entity we need to give Entity Details and Primary Attribute Details.
Entity Details should be following

1)Display Name
2)Plural Name
3)Schema Name
4)OwnershipType
5)Entity-Activity Details

Primary Attribute Details should be

1)Display Name
2)Schema Name
3)Required Level
4)Format Type
5)Length

So code should be

                //Entity Creation

                CreateEntityRequest Request = new CreateEntityRequest
                {
                    SolutionUniqueName = "Solution Schema Name",
                    Entity = new EntityMetadata
                    {
                        DisplayName = new Label("Entity Display Name", 1033),
                        DisplayCollectionName = new Label("Entity Plural Name", 1033),
                        SchemaName = "Entity Schema Name",
                        OwnershipType = OwnershipTypes.UserOwned,
                        IsActivity = false,
                    },

                    PrimaryAttribute = new StringAttributeMetadata
                    {
                        DisplayName = new Label("Field Display Name", 1033),
                        SchemaName = "Field Schema Name",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        FormatName = StringFormatName.Text,
                        MaxLength = 500,
                    }
                };

                service.Execute(Request);
            



SO Final Code is Here


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xrm;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace CustomEntityCreation
{
    public class EntityCreation
    {
        public static void Main(string[] args)
        {
            //getting organizationURL
            Uri organizationURL = new Uri("Your CRM Organization URI"); //You will get this from your CRM developer resource under Customization
            //Credentials of your CRM
            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = "your CRM user name";
            credentials.UserName.Password = "CRM login Password";
            Guid crmsdkpublisherid = Guid.Empty;
            Guid SamplesolutionId;
            System.String customizedprefix;
            using (var serviceproxy = new OrganizationServiceProxy(organizationURL, null, credentials, null))
            {
                //Getting CRM Service
                serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceproxy;
                //create publisher
                Publisher crmsdkpublisher = new Publisher
                {
                    UniqueName = "Publisher Schema Name",
                    FriendlyName = "Publisher Display Name",
                    CustomizationPrefix = "Your Custom Prefix",
                };
                //check that publisher is existing or not
                QueryExpression QE = new QueryExpression
                {
                    EntityName = Publisher.EntityLogicalName,
                    ColumnSet = new ColumnSet("publisherid", "customizationprefix"),
                    Criteria = new FilterExpression(),
                };

                //Add Query for checking whether it is duplicate or not

                QE.Criteria.AddCondition("uniquename", ConditionOperator.Equal, crmsdkpublisher.UniqueName);

                EntityCollection crmsdkresults = serviceproxy.RetrieveMultiple(QE);

                Publisher sdksamplepublisher = null;

                //If the publisher is existing

                if (crmsdkresults.Entities.Count > 0)
                {
                    sdksamplepublisher = (Publisher)crmsdkresults.Entities[0];
                    crmsdkpublisherid = (Guid)sdksamplepublisher.PublisherId;
                    customizedprefix = sdksamplepublisher.CustomizationPrefix;
                }

                //If the publisher is not existing

                if (crmsdkresults.Entities.Count == 0)
                {
                    crmsdkpublisherid = serviceproxy.Create(crmsdkpublisher);
                }
                //create a solution

                Solution sol = new Solution
                {
                    UniqueName = "Solution Schema Name",
                    FriendlyName = "Solution DisplayName",
                    PublisherId = new EntityReference(Publisher.EntityLogicalName, crmsdkpublisherid),
                    Version = "CRM Version",
                };

                //check whether the solution is existing or not

                QueryExpression solutionqueryexpression = new QueryExpression
                {
                    EntityName = Solution.EntityLogicalName,
                    ColumnSet = new ColumnSet(),
                    Criteria = new FilterExpression(),
                };

                //Checking solution is existing or not based on your query
                solutionqueryexpression.Criteria.AddCondition("uniquename", ConditionOperator.Equal, sol.UniqueName);
                EntityCollection solutioncollection = serviceproxy.RetrieveMultiple(solutionqueryexpression);
                Solution samplesolutionresults = null;
                //If solution is existing
                if (solutioncollection.Entities.Count > 0)
                {
                    samplesolutionresults = (Solution)solutioncollection.Entities[0];
                    SamplesolutionId = (Guid)samplesolutionresults.SolutionId;
                }

                //If solution is not existing

                if (solutioncollection.Entities.Count == 0)
                {
                    SamplesolutionId = serviceproxy.Create(sol);
                }



                //Entity Creation

                CreateEntityRequest Request = new CreateEntityRequest
                {
                    SolutionUniqueName = "Solution Schema Name",
                    Entity = new EntityMetadata
                    {
                        DisplayName = new Label("Entity Display Name", 1033),
                        DisplayCollectionName = new Label("Entity Plural Name", 1033),
                        SchemaName = "Entity Schema Name",
                        OwnershipType = OwnershipTypes.UserOwned,
                        IsActivity = false,
                    },

                    PrimaryAttribute = new StringAttributeMetadata
                    {
                        DisplayName = new Label("Field Display Name", 1033),
                        SchemaName = "Field Schema Name",
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        FormatName = StringFormatName.Text,
                        MaxLength = 500,
                    }
                };

                service.Execute(Request);
            }

        }

    }


}