Showing posts with label CRM 2011. Show all posts
Showing posts with label CRM 2011. Show all posts

Friday, May 9, 2014

CRM - Creating an email using REST endpoints

As a CRM developer everyone of us will undergo a scenario where now or tomorrow we may have to create an email record using REST endpoint. Its pretty easy that we can use any one of the REST approach and do that. But the challenge here is that REST endpoint does not support the party list. Because of this we cannot assign them to the email record which we create.

Solution for this is to create an activity (email) first and then create the a party list entity and link that to the created activity. To see how to do that we can refer to this simple but effective blog from "MS CRM Shop". 

Thanks team for this nice blog. 

Hope this helps !!!

Wednesday, February 19, 2014

CRM - Adding an activity through code

There can be scenarios where we have to add activities programmatically to the CRM organization either through a plugin or through a workflow. Below is how we can achieve this.
 
Entity followupActivity = new Entity("phonecall");
followupActivity["subject"] = "Followup Phone call activity";
Entity activityPartyFrom = new Entity("activityparty");
activityPartyFrom.Attributes.Add("partyid", new EntityReference("systemuser", workflowContext.UserId));
followupActivity.Attributes.Add("from", new Entity[] { activityPartyFrom });
Entity activityPartyTo = new Entity("activityparty");
activityPartyTo.Attributes.Add("partyid", new EntityReference("lead", "Lead's Guid"));
followupActivity.Attributes.Add("to", new Entity[] { activityPartyTo });
followupActivity["scheduledend"] = DateTime.Now.AddDays(30);
service.Create(followupActivity);
 
 Here I am trying to add a phone call activity and assuming that this is from the workflow, workflowcontext used is the workflow context to get the owner of the activity. I am here trying to add a phone call and the entity should change according to our need. Due date is set to 30 days from today and the from is the user under which the workflow is running and to is a lead whose Guid we need to pass so as to set the To field.
 
Hope this helps !!!

Monday, February 17, 2014

CRM - Passing data between Plugins

When working with Plugins its quite natural to come across the scenarios where a data needs to be shared by two different plugins. This can be achieved using the shared variables. Below is how it can be done. In the plugin which is going to set the variable write the code as follows,
 
context.SharedVariables["UniqueName"] = "Data to be shared";
 
context is the plugin execution context. Now the data that needs to be shared is available in the shared variable UniqueName.
 
Next step is to consume the data available in the other plugin. For that first check whether the shared variable has the respective UniqueName. If available consume the data in it using the below code.
 
string uniqueName = (string)context.SharedVariables["PrimaryContact"];
 
All done. We have the data from first plugin in second one now. Enjoy !!!

Thursday, February 6, 2014

CRM 2013 - Create a SDK code project in Visual Studio

As a developer, there can be scenarios where we have to use CRM SDK in our code so as to connect to CRM and use the messages from SDK. To make sure our VS project is ready to use we have to follow some steps.

Even though the title says 2013 this is applicable to 2011 as well.
 

Prerequisites

Below are the prerequisites for the same.
  • Any Visual Studio (even the express edition works): CRM SDK is built on .NET 4.0 so even VS 2010 will work in this case.
  • CRM SDK: If CRM SDK is not installed on your computer, it can be downloaded from here (CRM 2011, CRM 2013).
  • Windows Identity Foundation: If you are using windows 8 or Windows server 2012, then we have to just enable already existing WIF. If you are using windows 7 or windows server 2008, we have install the WIF 3.5. For installing, download it from here.
 Once all the prerequisites are in place we can start creating a project which will interact with CRM from our code. Follow the below steps for achieving our target,
  1. Create a console application for either C# or VB according to our comfort level.
  2. Make sure the target framework is set to MS .NET framework 4.0. By default it will be client profile.
  3. Add all the required reference to our project. This includes below references.
    1. System.Data.Linq
    2. System.DirectoryServices.AccountManagement
    3. System.Runtime.Serialization
    4. System.Security
    5. System.ServiceModel
  4. Add the required SDK assembly reference as per our requirement. This is available from the bin folder of respective CRM version SDK.
  5. Add the required identity reference file. We can get this file from the file location in the system at Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5.
We are done with adding the references and now we are ready to go with our development activity.
 
For every project we have to do this. So its better if we can save this as a project template for our future references.
 
For detailed Microsoft documentation please refer the original site here.
Hope this helped everyone. :) !!!
 
 

Tuesday, January 21, 2014

CRM 2011 - Reflexive relationship must specify direction using ReflexiveManyToManyRelationship

When trying to retrieve data for reflexive relationship I was getting the exception which is the title of this post. How I was able to fix the same was by just using once line of code as below which will mention whether the role is referencing or referenced.
 
relationship.PrimaryEntityRole = EntityRole.Referencing;
 
where relationship is the object Relationship.
 
Hope this helped someone. !!!

Saturday, December 21, 2013

CRM 2011 - Using Report Control to add a report to Dashboard

There can be scenarios where we have to create custom reports to the dashboards. This can be achieved easily using the custom tool Report Control. Download the report control solution from here.
 
Import the solution to our organization.
 
Now keep the report ready in our organization either by creating a new report or by reusing an existing report.
 
Get the report's GUID from CRM which needs to be added to the dashboard. Keep that handy for further use.
 
Whether you are planning to create a new dashboard or an existing dash board, add a new web resource to the dashboard.
 
In the properties window, add the web resource "new_ReportControl". Give proper field name and properties for the web resource.
 
If "Restrict cross frame scripting where supported" and "Pass record object type and unique identifier as parameters" check boxes are checked, then uncheck them.
 
In the custom parameters field, add the GUID value for the report to be added.
 
Full article can be read here. There is another approach for this same objective but it didn't work for me though. You can read the article here.
 
That's it we are done with the new report in our dash board.
 
Hope this helps !!!

Monday, November 25, 2013

CRM 2011 - Script loading to Client

What I understood was wrong from UR12 for CRM 2011. JScripts mentioned in the forms in a specific order was not loaded to the client in the same order. Its loaded in the order in which the same is received from the server.

There is no guarantee that the dependent scripts mentioned in the form may be loaded after the script which is calling the same.

Thanks scott for this wonderful post.

CRM 2011 - Hide the footer from notes in different entities

Different entities have the notes in the form where the user can add, delete notes and also attach files. If the users are not giving proper titles for these notes then we could see that when notes are created there will be redundant data in the title and footer of the note, which is the name of the owner and the date when the note was created.
 
This can be fixed, if required in two ways one way is to educate the users to give a proper title so that the redundant data can be removed. Second way is to hide the footer where the same data is displayed again.
 
Second way is not a supported way in CRM 2011. But we can do this. This has some disadvantages though.
 
This can be implemented only (as per my knowledge, please let me know otherwise) when the form loads as the notes attribute cannot be modified or we cannot add any on change event for the same attribute. Because of which when the user adds a new note the footer will be visible for the new note and when the user deletes an existing note then all the hidden rows will be visible again. This will last until the form is reloaded so that our code is triggered.
 
Below is the code which I used to hide the row
 
function HideNotesFooter() {
//Get the iframe which has the table row which needs to be hided.
var iframe = window.document.getElementById('notescontrol');
//Get the inner document from the iframe object.
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
//Get the list of all elements inside the iframe having the class name 'noteHeader'
var noteHeader = innerDoc.getElementsByClassName('noteHeader');
//Checks whether the noteheader contains any element or not. If it doesnt have any element trigger this function after sometime.
if (noteHeader.length == 0) {
setTimeout(DisableNotes, 1000);
} //End if for length
else { //If it has any element loop through them and hide the respective row from the table.
for (i = 0; i < noteHeader.length; i++) {
if (i % 2 != 0) {
noteHeader[i].style.visibility = 'hidden';
} //End if for modulus
} //End for loop
} //End else
} //Function End
 
I have used a call to the setTimeout function because some time I could see that the rows to be hided were not available when the script execution was happening.
 
Hope this helped you.

Friday, October 18, 2013

CRM 2011 - Getting entity name and Id using Javascript

There are different ways to get the entity information from the form using JScript.
 
Let's say we need to get the information from within the form ribbon. We can get it with a simple statement as below,
 
var entityName=Xrm.Page.data.entity.getEntityName();
 
This will return the logical name of the entity for the record. For example, if the record is a contact this will return "contact".
 
If we need to get the entity name from the Homepage ribbon, then we have to do it in another way. Follow the below steps to achieve this,
  1. In the javascript add a parameter to accept this and pass the crmParameter "SelectedControlSelectedItemReferences"
  2. This will get us the below details, the JScript code would be like this.

function GetDetails(selectedControlSelectedItemRefernces)
{
   var Id = selectedControlSelectedItemRefernces[0].Id;
   var Name = selectedControlSelectedItemRefernces[0].Name;
   var TypeCode = selectedControlSelectedItemRefernces[0].TypeCode;
  var TypeName = selectedControlSelectedItemRefernces[0].TypeName;
}

If the user has selected multiple records in the grid then loop the "selectedControlSelectedItemRefernces" object and get the records one after the other.

If you are using ribbon editor you can refer to this blog for a step by step process how to achieve this.

Within the form if we need to get the Id of the record then it is a straight way process,

var recordId = Xrm.Page.data.entity.getId();

This will return a GUID value for the record.

Wednesday, August 14, 2013

CRM 2011 - Plugins - Isolations,Trust & Statistics

In CRM 2011 we can register a plugin in two ways, either within the sandbox (an isolated environment) or outside the sandbox.
 
Termed as partial trust or full trust the features for each of these approaches are as follows,

Partial Trust Full Trust
Within the sandbox Outside the sandbox
For online deployment, plugins should be registered this way. Supported for on premises and Internet Facing Deployments

Advantages of using the isolated mode would be,
  1. Security
  2. Supports runtime monitoring
  3. Statistics Reporting
  4. Supported for all deployments.
One thing to be noted here is that the online deployment of CRM supports custom workflow activities only if the same is registered in sandbox or isolated environment.
 
With all these advantages, the drawback if the plugin is registered in isolated environment is that Access to file system, system event log, certain network protocols, registry and more is prevented in the sandbox. Only exception to this is that it has access to external endpoints like azure.
 
Available statistics on plugin and custom work flow activities is available in the entity PluginTypeStatistic entity. This information can be collected using the request and response messages. These information will be available within 30 minutes to 1 hour after the execution of plugin or custom work flow.

CRM 2011 - Documentation in a single location

Everyone of us might have downloaded the CRM 2011 documentation for our reference to our local machines.
 
If not yet and worrying where all the documentation can be found don't worry, the answer is here.
 
Please follow the below link  below and it will redirect you to a post from the CRM Dynamics community with the link available for different kind of documentation available.
 
Should really appreciate Jarrod Williams for this. Thanks Williams !!!
 
 
When I found this thought of worth sharing with everyone of you. Hope this helped you !!!

CRM 2011 - How to get Entity Object type code?

When we have to get the object type code for an entity normally what we can do is using the JavaScript function for the same in CRM 2011. The sample code for the same will be as follows,

var objectTypeCode= Xrm.Page.context.getQueryStringParameters().etc;

Above code should return the object type code for the respective entity.

Another way to get the object code for an entity is using the SQL query from the CRM DB. This can be achieved using below query.

SELECT Name,LogicalName,ObjectTypeCode
FROM
EntityView
ORDER BY ObjectTypeCode

If you want to get the object type code via C# below is the snippet for the same,

RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
                entityRequest.LogicalName = entityName;
                RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)service.Execute(entityRequest);

                objectTypeCode = entityResponse.EntityMetadata.ObjectTypeCode.Value;

For your reference the result for the above query is listed below.

Name Logical Name Object Type Code
Account account 1
Contact contact 2
Opportunity opportunity 3
Lead lead 4
Annotation annotation 5
BusinessUnitMap businessunitmap 6
Owner owner 7
SystemUser systemuser 8
Team team 9
BusinessUnit businessunit 10
PrincipalObjectAccess principalobjectaccess 11
RolePrivileges roleprivileges 12
SystemUserLicenses systemuserlicenses 13
SystemUserPrincipals systemuserprincipals 14
SystemUserRoles systemuserroles 15
AccountLeads accountleads 16
ContactInvoices contactinvoices 17
ContactQuotes contactquotes 18
ContactOrders contactorders 19
ServiceContractContacts servicecontractcontacts 20
ProductSalesLiterature productsalesliterature 21
ContactLeads contactleads 22
TeamMembership teammembership 23
LeadCompetitors leadcompetitors 24
OpportunityCompetitors opportunitycompetitors 25
CompetitorSalesLiterature competitorsalesliterature 26
LeadProduct leadproduct 27
RoleTemplatePrivileges roletemplateprivileges 28
Subscription subscription 29
FilterTemplate filtertemplate 30
PrivilegeObjectTypeCodes privilegeobjecttypecodes 31
SalesProcessInstance salesprocessinstance 32
SubscriptionSyncInfo subscriptionsyncinfo 33
SubscriptionTrackingDeletedObject subscriptiontrackingdeletedobject 35
ClientUpdate clientupdate 36
SubscriptionManuallyTrackedObject subscriptionmanuallytrackedobject 37
TeamRoles teamroles 40
PrincipalEntityMap principalentitymap 41
SystemUserBusinessUnitEntityMap systemuserbusinessunitentitymap 42
PrincipalAttributeAccessMap principalattributeaccessmap 43
PrincipalObjectAttributeAccess principalobjectattributeaccess 44
PrincipalObjectAccessReadSnapshot principalobjectaccessreadsnapshot 90
RecordCountSnapshot recordcountsnapshot 91
Incident incident 112
Competitor competitor 123
DocumentIndex documentindex 126
KbArticle kbarticle 127
Subject subject 129
BusinessUnitNewsArticle businessunitnewsarticle 132
ActivityParty activityparty 135
UserSettings usersettings 150
ActivityMimeAttachment activitymimeattachment 1001
Attachment attachment 1002
InternalAddress internaladdress 1003
CompetitorAddress competitoraddress 1004
CompetitorProduct competitorproduct 1006
Contract contract 1010
ContractDetail contractdetail 1011
Discount discount 1013
KbArticleTemplate kbarticletemplate 1016
LeadAddress leadaddress 1017
Organization organization 1019
OrganizationUI organizationui 1021
PriceLevel pricelevel 1022
Privilege privilege 1023
Product product 1024
ProductAssociation productassociation 1025
ProductPriceLevel productpricelevel 1026
ProductSubstitute productsubstitute 1028
SystemForm systemform 1030
UserForm userform 1031
Role role 1036
RoleTemplate roletemplate 1037
SalesLiterature salesliterature 1038
SavedQuery savedquery 1039
StringMap stringmap 1043
UoM uom 1055
UoMSchedule uomschedule 1056
SalesLiteratureItem salesliteratureitem 1070
CustomerAddress customeraddress 1071
SubscriptionClients subscriptionclients 1072
StatusMap statusmap 1075
DiscountType discounttype 1080
KbArticleComment kbarticlecomment 1082
OpportunityProduct opportunityproduct 1083
Quote quote 1084
QuoteDetail quotedetail 1085
UserFiscalCalendar userfiscalcalendar 1086
SalesOrder salesorder 1088
SalesOrderDetail salesorderdetail 1089
Invoice invoice 1090
InvoiceDetail invoicedetail 1091
SavedQueryVisualization savedqueryvisualization 1111
UserQueryVisualization userqueryvisualization 1112
RibbonTabToCommandMap ribbontabtocommandmap 1113
RibbonContextGroup ribboncontextgroup 1115
RibbonCommand ribboncommand 1116
RibbonRule ribbonrule 1117
RibbonCustomization ribboncustomization 1120
RibbonDiff ribbondiff 1130
ReplicationBacklog replicationbacklog 1140
FieldSecurityProfile fieldsecurityprofile 1200
FieldPermission fieldpermission 1201
SystemUserProfiles systemuserprofiles 1202
TeamProfiles teamprofiles 1203
AnnualFiscalCalendar annualfiscalcalendar 2000
SemiAnnualFiscalCalendar semiannualfiscalcalendar 2001
QuarterlyFiscalCalendar quarterlyfiscalcalendar 2002
MonthlyFiscalCalendar monthlyfiscalcalendar 2003
FixedMonthlyFiscalCalendar fixedmonthlyfiscalcalendar 2004
Template template 2010
ContractTemplate contracttemplate 2011
UnresolvedAddress unresolvedaddress 2012
Territory territory 2013
Queue queue 2020
License license 2027
QueueItem queueitem 2029
UserEntityUISettings userentityuisettings 2500
UserEntityInstanceData userentityinstancedata 2501
IntegrationStatus integrationstatus 3000
ConnectionRole connectionrole 3231
ConnectionRoleAssociation connectionroleassociation 3232
ConnectionRoleObjectTypeCode connectionroleobjecttypecode 3233
Connection connection 3234
Equipment equipment 4000
Service service 4001
Resource resource 4002
Calendar calendar 4003
CalendarRule calendarrule 4004
ResourceGroup resourcegroup 4005
ResourceSpec resourcespec 4006
ConstraintBasedGroup constraintbasedgroup 4007
Site site 4009
ResourceGroupExpansion resourcegroupexpansion 4010
InterProcessLock interprocesslock 4011
EmailHash emailhash 4023
DisplayStringMap displaystringmap 4101
DisplayString displaystring 4102
Notification notification 4110
ActivityPointer activitypointer 4200
Appointment appointment 4201
Email email 4202
Fax fax 4204
IncidentResolution incidentresolution 4206
Letter letter 4207
OpportunityClose opportunityclose 4208
OrderClose orderclose 4209
PhoneCall phonecall 4210
QuoteClose quoteclose 4211
Task task 4212
ServiceAppointment serviceappointment 4214
Commitment commitment 4215
UserQuery userquery 4230
RecurrenceRule recurrencerule 4250
RecurringAppointmentMaster recurringappointmentmaster 4251
EmailSearch emailsearch 4299
List list 4300
ListMember listmember 4301
Campaign campaign 4400
CampaignResponse campaignresponse 4401
CampaignActivity campaignactivity 4402
CampaignItem campaignitem 4403
CampaignActivityItem campaignactivityitem 4404
BulkOperationLog bulkoperationlog 4405
BulkOperation bulkoperation 4406
Import import 4410
ImportMap importmap 4411
ImportFile importfile 4412
ImportData importdata 4413
DuplicateRule duplicaterule 4414
DuplicateRecord duplicaterecord 4415
DuplicateRuleCondition duplicaterulecondition 4416
ColumnMapping columnmapping 4417
PickListMapping picklistmapping 4418
LookUpMapping lookupmapping 4419
OwnerMapping ownermapping 4420
ImportLog importlog 4423
BulkDeleteOperation bulkdeleteoperation 4424
BulkDeleteFailure bulkdeletefailure 4425
TransformationMapping transformationmapping 4426
TransformationParameterMapping transformationparametermapping 4427
ImportEntityMapping importentitymapping 4428
RelationshipRole relationshiprole 4500
RelationshipRoleMap relationshiprolemap 4501
CustomerRelationship customerrelationship 4502
CustomerOpportunityRole customeropportunityrole 4503
Audit audit 4567
EntityMap entitymap 4600
AttributeMap attributemap 4601
PluginType plugintype 4602
PluginTypeStatistic plugintypestatistic 4603
PluginAssembly pluginassembly 4605
SdkMessage sdkmessage 4606
SdkMessageFilter sdkmessagefilter 4607
SdkMessageProcessingStep sdkmessageprocessingstep 4608
SdkMessageRequest sdkmessagerequest 4609
SdkMessageResponse sdkmessageresponse 4610
SdkMessageResponseField sdkmessageresponsefield 4611
SdkMessagePair sdkmessagepair 4613
SdkMessageRequestField sdkmessagerequestfield 4614
SdkMessageProcessingStepImage sdkmessageprocessingstepimage 4615
SdkMessageProcessingStepSecureConfig sdkmessageprocessingstepsecureconfig 4616
ServiceEndpoint serviceendpoint 4618
AsyncOperation asyncoperation 4700
WorkflowWaitSubscription workflowwaitsubscription 4702
Workflow workflow 4703
WorkflowDependency workflowdependency 4704
IsvConfig isvconfig 4705
WorkflowLog workflowlog 4706
ApplicationFile applicationfile 4707
OrganizationStatistic organizationstatistic 4708
SiteMap sitemap 4709
ProcessSession processsession 4710
WebWizard webwizard 4800
WizardPage wizardpage 4802
WizardAccessPrivilege wizardaccessprivilege 4803
TimeZoneDefinition timezonedefinition 4810
TimeZoneRule timezonerule 4811
TimeZoneLocalizedName timezonelocalizedname 4812
Solution solution 7100
Publisher publisher 7101
PublisherAddress publisheraddress 7102
SolutionComponent solutioncomponent 7103
Dependency dependency 7105
DependencyNode dependencynode 7106
InvalidDependency invaliddependency 7107
Post post 8000
PostRole postrole 8001
PostRegarding postregarding 8002
PostFollow postfollow 8003
PostComment postcomment 8005
PostLike postlike 8006
Report report 9100
ReportEntity reportentity 9101
ReportCategory reportcategory 9102
ReportVisibility reportvisibility 9103
ReportLink reportlink 9104
TransactionCurrency transactioncurrency 9105
MailMergeTemplate mailmergetemplate 9106
ImportJob importjob 9107
WebResource webresource 9333
SharePointSite sharepointsite 9502
SharePointDocumentLocation sharepointdocumentlocation 9508
Goal goal 9600
GoalRollupQuery goalrollupquery 9602
Metric metric 9603
RollupField rollupfield 9604
ComplexControl complexcontrol 9650

Configuration for CRM Plugins

CRM plugins are always great feature where we can automate many functionality which we cannot automate from user interface. But almost eve...