Wednesday, August 17, 2011

CRM 2011 messages using SOAP

Microsoft has provided CRM ODATA service to perform actions on CRM data. However, the ODATA service only allows you to perform basic CRUD operations on CRM entities. If you want to perform other operations like Change state or perhaps read Metadata information, you will need to access the CRM SOAP service.

You can add the reference to CRM SOAP service using the following URL.
http://Server_name/Organization_name/XRMServices/2011/Organization.svc

We have encountered various issues while trying to get our messages executed through SOAP. Here we are going to list out all the messages and the properties that are required to be set to get the SOAP message to execute successfully.

RetrieveAttribute request – This request allows you to read the metadata information of a given attribute.

TestApplication.CrmSdk.OrganizationRequest request = new TestApplication.CrmSdk.OrganizationRequest() { RequestName = "RetrieveAttribute" };

//Set all required parameters of request
request["EntityLogicalName"] = "Account";
request["RetrieveAsIfPublished"] = true;
request["LogicalName"] = "Address1_AddressTypeCode ";
request["MetadataId"] = Guid.Empty;

//Execute the request
service.Execute(request);

In call back function call end execute function to execute request and get response of request as shown in below line of code,

//end the request
TestApplication.CrmSdk.OrganizationResponse response = service.EndExecute(result);

//read the result
CrmSdk.PicklistAttributeMetadata picklist = (CrmSdk.PicklistAttributeMetadata)response["AttributeMetadata"];

In the above request make you to set the MetadataID to Guid.Empty or this message would not execute.


QualifyLead Request – This request allows you to qualify a lead and create Account, Contact and Opportunity from the lead record.

OrganizationRequest _qualifyRequest = new OrganizationRequest() { RequestName = "QualifyLead" };

//Initialize Member of qualify request as shown in below code

//set Account
_qualifyRequest["CreateAccount"] = true;

//set contact
_qualifyRequest["CreateContact"] = true;

//set opportunity
_qualifyRequest["CreateOpportunity"] = true;

//set Status
OptionSetValue status = new OptionSetValue();
status.Value = -1;
_qualifyRequest["Status"] = status;

//set currency
EntityReference currency = new EntityReference();
currency.LogicalName = "transactioncurrency";
currency.Id = new Guid(transactioncurrencyId);
_qualifyRequest["OpportunityCurrencyId"] = currency;


//set customer
EntityReference customer = new EntityReference();
customer .LogicalName = "account";
currency.Id = new Guid(accountId);
_qualifyRequest["OpportunityCustomerId "] = customer;

//set SourceCampaign
_qualifyRequest["SourceCampaignId"] = null;

//Execute the request
_service.BeginExecute(_qualifyRequest, new AsyncCallback(QualifyLeadCallBack), _service);


In call back function call end execute function to execute request and get response of request as shown in below line of code,

OrganizationResponse response = orgService.EndExecute(result);

When request execute successfully it return entityreferencecollection.We get create record using below line of code it return entityreferencecollection

EntityReferenceCollection entityCollection = (EntityReferenceCollection)response

SetState Request – Using this request we can activate/de-activate the record.

To activate/de-activate the record in Silverlight.

To activate/de-activate the record in Silverlight you have to trap “SetStateRequest”.

The member of “SetStateRequest” is given below,you have set this member.
EntityMoniker
State
Status

To trap “SetStateRequest” in Silverlight you have create object of “OrganizationRequest” and set RequestName =”SetState” , as shown in below line of code

SoapServiceReference.OrganizationRequest request = new SoapServiceReference.OrganizationRequest() { RequestName = "SetState" };

After that you have set member of SetStateRequest ,as shown in below lines of code

1. EntityMoniker
-It is of Entity reference type.In EntityMoniker you have set “Id” and “LogicalName” of record as shown in below line of code

SoapServiceReference.EntityReference ServiceActivity = new SoapServiceReference.EntityReference() { Id =accountId, LogicalName = "account" };

2. State - It is of optionset type. In state you have set value as “0” for Active or “1” for InActive. as shown in below line of code
SoapServiceReference.OptionSetValue States = new SoapServiceReference.OptionSetValue();
States.Value = 0; or States.Value = 1;

3. Status - It is of optionset type. In status you have set set value as “1” for Active or “2” for InActive. as shown in below line of code
SoapServiceReference.OptionSetValue Status = new SoapServiceReference.OptionSetValue();
Status.Value = 1; or Status.Value = 2;

Above code collectively return as below.
SoapServiceReference.OrganizationRequest request = new SoapServiceReference.OrganizationRequest() { RequestName = "SetState" };

request["EntityMoniker"] = ServiceActivity;
request["State"] = States;
request["Status"] = Status;

After setting all member execute the request as shown in below line of code.
Sevcie. BeginExecute method -Pass three parameter “Request”,”Async method”,and “Soap Service” as shown below line of code
//Excute request
service.BeginExecute(request, new AsyncCallback(SetActivityStateCompleted), service);
In callback fuction call below line of code,to execute the request.
SoapServiceReference.OrganizationResponse response = service.EndExecute(result);
If request execute successfully.It activate/de-activate the record.

Monday, August 8, 2011

Notify the dialog to end

When you design a Dialog, make sure you explicitly stop the dialog when all the steps of the dialog have completed using the “Stop Dialog” step



Failure to do so might result in you receiving the following error when all steps have been processed.



The above error is pretty misleading and we spent hours trying to identify which data is missing before we finally managed to get this to work after adding the “Stop Dialog” step.

Monday, August 1, 2011

Fault and Exception Handling in Dynamics CRM 2011

Microsoft Dynamics CRM Web service can throw a number of exceptions. When we use Microsoft Dynamics CRM Web service in application development we need to handle service related exceptions. All Web service method calls use a communication channel to the server based on the Windows Communication Foundation (WCF) technology. In WCF terms, exceptions returned from the channel are called faults.
Here we have listed some of the common exceptions that one should handle in the code:
- DiscoveryServiceFault: If you are accessing the discovery Web service, you need to catch DiscoveryServiceFault exception.(See below code)
catch (FaultException< Microsoft.Xrm.Sdk.DiscoveryServiceFault> ex)
{
Console.WriteLine("The application terminated with an error.");
}
- OrganizationServiceFault: If you are accessing the organization Web service, you need to catch OrganizationServiceFault exception.(See below code)

catch (FaultException ex)
{
Console.WriteLine("The application terminated with an error.");
}
- TimeoutException: This will occurred when take long time to execute CRM request.(See below code)
catch (System.TimeoutException ex)
{
Console.WriteLine("The application terminated with an error.");
}
- SecurityAccessDeniedException: When connecting to Microsoft Dynamics CRM Online, SecurityAccessDeniedException exception can be thrown if you use a valid Windows Live ID and your Live account is not associated with any Microsoft Dynamics CRM Online organization.(See below code)
catch (FaultException ex)
{
Console.WriteLine("The application terminated with an error.");
}
- MessageSecurityException: A MessageSecurityException can be thrown if your Windows Live ID is not valid or Windows Live failed to authenticate you.
catch (FaultException ex)
{
Console.WriteLine("The application terminated with an error.");
}

Wednesday, July 27, 2011

Json and Silverlight with ODataService in CRM 2011

Dynamics CRM 2011 now provides the ability to perform data operations on CRM entities using JSON and ODATA service.

Here we have tried to explain the various clauses of JSON that is supported by CRM ODATA and how this service can be used in Silverlight as well as in Scripts. Note not all standard ODATA clauses are supported by CRM.

To use these clauses in silverlight you need to add a reference to the ODataService of the CRM i.e. OrganizationData.svc.

$select: This clause is the Select part of any SQL statement where you can specify the list of attributes to be returned by the query. Note you can also provide the collection property of a 1:N or N:1 relationship.

Using JSON

If you write the following URL to read the opportunity.

http://://xrmservices/2011/organizationdata.svc/OpportunitySet

it will return all columns of the opportunity in XML but if you want to read only the name you can add the select as follows.

http://ad12:5555/crmorg1//xrmservices/2011/organizationdata.svc/OpportunitySet?$select=Name

It will return the folliwng XML



Using Silverlight:

To use the $select in the Silverlight app you need to write the query as follows.

DataServiceQuery query = (DataServiceQuery_context.OpportunitySet.AddQueryOption("$select", "Name");


$expand: Directs that related records should be retrieved in the record or collection being retrieved.

Using JSON:
If you want to read the customer information with the opportunity while we are reading the opportunity by JSON then we can use the expand, and then we can read the customer details with the opportunity. Below we have given the JSON url.

http://://xrmservices/2011/organizationdata.svc/OpportunitySet?$expand=opportunity_customer_accounts,opportunity_customer_contacts&$select=*,opportunity_customer_accounts,opportunity_customer_contacts

Using Silverlight:

To use this with the silverlight you need to write the following query in the silverlight.

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$select", "*,opportunity_customer_accounts,opportunity_customer_contacts")
.AddQueryOption("$expand", "opportunity_customer_accounts")
.AddQueryOption("$expand", "opportunity_customer_contacts");

$filter:

Using JSON:
To set the condition in the JSON query we can use the $filter clause in the url.
Suppose if you want read all accounts of an user the JSON url will be as follows.

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$filter=OwnerId/Id eq (guid'34fca7f5-d556-e011-b9a8-00155d005515')

Using Silverlight:
In silverlight we can use the AddQueryOption to add the $filter as we use for $expand or we can use the Where Condition as shown in the below.

DataServiceQuery query = (DataServiceQuery)_context.AccountSet.Where(a => a.OwnerId.Id == new Guid("34FCA7F5-D556-E011-B9A8-00155D005515"));

To do it through AddQueryOption you can generate the filter in a string and then pass that string a parameter to the filter option. This provides us to create dynamic filters as shown below


filter += "new_testId eq (guid'" + _userid + "') ";

DataServiceQuery query = (DataServiceQuery)

query = query.AddQueryOption("$filter", filter);

$orderby: We can use it to set the sort order. Use it same as $filter.

Using JSON:

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$orderby=Name, Address1_Country.

Using Silverlight:

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$orderby", "Name, Address1_Country")


$top: To define the range that how many record want to read. Max limit is 50.

Using JSON:

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$top=10

Using Silverlight:

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$top", 10)


$skip: To define the that how many record want to skip.
Using JSON:

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$skip=10

Using Silverlight:

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$skip", 10)


NOTE: By default any query executed using ODATA service will only return 50 records at a time. If we want to display All records that exist even if it is more than 50 records, then you can use a combination use of the $skip and $top clauses to read all records.

For this you can recursively call this Query where _top will be const with value 50. And at each recursion we can increase the value of the _skip by 50.

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$skip", _skip).AddQueryOption("$top", _top)

Friday, July 1, 2011

How to Enable and Disable the most recently used items for lookup field only.

In CRM 2011, we have found the new feature for the lookup type fields that you have the ability to see the most recently used items for that lookup while creating the records for entity.
Also you can disable this feature as well by default it is enable for all lookup types fields. If you like to see those items then, during creation of record, you need to “Double Click” on the lookup field.

See the below example for details:
• Below we have shown the account form which has the lookup field “Parent Location” and “Disable most recently used items” option is unchecked for this field as shown in below screen shot.


When you “Double Click” on Parent location field it will show you the below result.



To disable this feature you need to check the “Disable most recently used items” option then Save and publish the Form. It will disable above feature.

Thanks!