Working with CRM 4.0

Microsoft Dynamics CRM 4.0 is a complete Business Application Platform that is open for customization as well as extension to suit sophisticated as well as trivial business needs. One way to extend the functionality available for this platform is to use the SDK and write code to call the CRM standard Web services to perform queries and update data operations on CRM Entities, etc.

Working with Web Services
To access the classes and methods available from the Microsoft CRM Web services, you need to add a Web reference for each required Web service to your project. The following Web services were used by us for development CRM web parts:
http://<servername[:port]>/mscrmservices/2007/crmservice.asmx
http://<servername[:port]>/mscrmservices/2006/metadataservice.asmx
CrmService Methods
The main Web service for the Microsoft Dynamics CRM SDK is CrmService. This Web service contains the methods that you need to write code against all the entities in Microsoft Dynamics CRM. There are six common methods that are used to access entity instances. For every other operation the Execute method is used.
The following table gives a description for common methods.
Method Description
Create Creates an instance of any entity that supports the Create message, including custom entities.
Retrieve Retrieves an instance of an entity.
RetrieveMultiple Uses a custom query (QueryExpression) to retrieve strongly typed results.
Update Updates an existing entity instance.
Delete Deletes an existing entity instance.
Fetch Use a custom query (FetchXML) to retrieve results in XML format
For detail kindly refer CRM SDK documentation.
CrmService Entities
The following table lists all the entities available in a default system. Note that the display name of an entity may be changed and new entities added through system customization.
Class Display name Description
account Account A person or business to whom the salesperson tries to sell a product or service. This is the entity that is billed in business transactions.
activitymimeattachment E-Mail Attachment A MIME attachment for an e-mail activity.
activityparty Activity Party A person or group associated with an activity. An activity can have multiple activity parties.
activitypointer Activity A task performed, or to be performed, by a user. An activity can be thought of as any action for which an entry can be made on a calendar.
annotation Note A mechanism for attaching notes to records. A note can be attached to multiple objects, including other notes.
annualfiscalcalendar Annual Fiscal Calendar The year long fiscal calendar of an organization. This represents a span of time during which the financial activities of an organization are calculated.
appointment Appointment A commitment that represents a time interval with start/end times and duration.
bulkoperation Quick Campaign An asynchronous marketing campaign.
bulkoperationlog Bulk Operation Log A log file for quick campaigns.
businessunit Business Unit A business, division, or department in the Microsoft CRM database. Business units own all objects implicitly. The database maintains this ownership on behalf of the platform.
businessunitnewsarticle Announcement An announcement associated with an organization.
calendar Calendar A calendar used by the scheduling system to define when an appointment or activity is to occur.
calendarrule Calendar Rule The definition of free and busy times for a service and for resources or resource groups (for example, working, non-working, vacation, and blocked).
campaign Campaign A container into which a business can attach campaign activities, campaign responses, sales literature, products, and lists to create, plan, execute and track the results of a specific marketing campaign through its life.
campaignactivity Campaign Activity The steps of a campaign with owner, partner, budget, timelines and other information. Can be created for planning as well running a campaign.
campaignactivityitem Campaign Activity Item A work item of a campaign activity, such as a list or sales literature.
campaignitem Campaign Item A work item of a campaign, such as a list or sales literature.
campaignresponse Campaign Response A response from an existing or a potential new customer for a campaign.
competitor Competitor Another business that competes for the sale represented by a lead or opportunity.
constraintbasedgroup Resource Group A group or collection of people, equipment, and/or facilities that can be scheduled.
contact Contact A person with whom a business unit has a relationship, for example, a customer, a supplier, or a colleague.
contract Contract An agreement to provide customer service during specified coverage dates, for a specified number of cases or an amount of time.
contractdetail Contract Line A line item detail in a contract that specifies the type of service a customer is entitled to.
contracttemplate Contract Template A template for a contract that contains the standard attributes of a contract.
customeraddress Address The address and shipping information for a customer. This entity is used to store additional addresses for an account.
customeropportunityrole Opportunity Relationship The relationship between an account or contact and an opportunity.
customerrelationship Customer Relationship The relationship between a customer (account or contact) and a partner (account, or contact).
discount Discount A price reduction made from the list price of a product or service based on the quantity purchased, specified as a percentage or monetary amount.
discounttype Discount List The type of price reduction made from the list price of a product or service based on the quantity purchased, specified as a percentage or monetary amount.
displaystring Display String Customized messages for an entity that has been renamed.
email E-mail An activity that is delivered using e-mail protocols.
equipment Facility/Equipment A resource that can be scheduled.
fax Fax An activity that tracks call outcome and number of pages. This entity optionally stores the electronic copy of the actual document.
fixedmonthlyfiscalcalendar Fixed Monthly Fiscal Calendar The fixed monthly fiscal calendar of an organization. This represents a span of time during which the financial activities of an organization are calculated.
incident Case A service incident associated with a contract.
incidentresolution Case Resolution A special type of activity that includes such information as the description of the resolution, billing status, and the duration of the incident.
invoice Invoice An order that has been billed.
invoicedetail Invoice Product A line item in an invoice that contains detailed billing information.
kbarticle Article Structured content that is part of the knowledge base.
kbarticlecomment Article Comment A comment on a knowledge base article.
kbarticletemplate Article Template A template for a knowledge base article that contains the standard attributes of an article.
lead Lead A prospect or potential sales opportunity. Leads will be converted into accounts, contacts, or opportunities if they are qualified. Otherwise, they are deleted or archived.
letter Letter An activity that tracks the delivery of a letter. The activity can contain the electronic copy of the letter.
license License Information about a Microsoft CRM license.
list Marketing List A group of existing or potential customers created for a marketing campaign or other sales purposes.
listmember Member An item in a marketing list.
monthlyfiscalcalendar Monthly Fiscal Calendar The monthly fiscal calendar of an organization. This represents a span of time during which the financial activities of an organization are calculated.
opportunity Opportunity A potential revenue-generating event, or sale to an account, that needs to be tracked through a sales process to completion.
opportunityclose Opportunity Close A special activity that is created when an opportunity is closed. It includes such information as the description of the closing and actual revenue.
opportunityproduct Opportunity Product An association between an opportunity and a product.
orderclose Order Close An activity generated when closing an order.
organization Organization The top level of the Microsoft CRM business hierarchy. The organization can be a specific business, holding company, or corporation.
phonecall Phone Call An activity to track a telephone call.
plugintype Plug-in Type A registry for dynamic common language runtime (CLR) types that may be loaded by the scheduling expression evaluation logic.
pricelevel Price List The pricing levels.
privilege Privilege A permission to perform an action in Microsoft CRM. The platform checks for the privilege and rejects the attempt if the user does not hold the privilege.
product Product Information about products and their pricing information.
productpricelevel Price List Item Information about how to price a product in the specified price level, including pricing method, rounding option and discount type based on specified product unit.
quarterlyfiscalcalendar Quarterly Fiscal Calendar The quarterly fiscal calendar of an organization. This represents a span of time during which the financial activities of an organization are calculated.
queue Queue An ordered list containing activities or incidents (cases).
queueitem Queue Item An item in a queue that specifies an activity or incident (case).
quote Quote A formal offer for products and/or services, proposed at specific prices and related payment terms, which is sent to a prospective customer.
quoteclose Quote Close The quarterly fiscal calendar of an organization. This represents a span of time during which the financial activities of an organization are calculated.
quotedetail Quote Product A line item in a quote. The details include such information as product ID, description, quantity, and cost.
relationshiprole Relationship Role A relationship between an account or contact and an opportunity. RelationshipRole is needed when a CustomerRelationship or CustomerOpportunityRole object is created.
relationshiprolemap Relationship Role Map The primary object code and associated entity type code between which the relationship role is valid.
resource Resource A resource that can be scheduled for a service. Users and Facility/Equipment entities are both resources.
resourcegroup Scheduling Group A resource group or team whose members can be scheduled for a service.
resourcespec Resource Specification A selection rule that allows the scheduling engine to select a number of resources from a pool of resources. The rules can be associated with a service.
role Role A grouping of security privileges. Users are assigned roles that authorize their access to the Microsoft CRM system.
salesliterature Sales Literature Sales literature. One sales literature entity may contain multiple documents.
salesliteratureitem Document An item in the sales literature collection.
salesorder Order An order is a quote that has been accepted.
salesorderdetail Order Product A line item in a sales order.
savedquery View A stored database query against the logical database. The SavedQuery also holds presentation information for the application grid controls.
semiannualfiscalcalendar Semi Annual Fiscal Calendar A calendar that represents the semiannual span of time during which the financial activities of an organization are calculated.
service Service An activity that represents work done to satisfy a customer's need.
serviceappointment Service Activity An activity offered by the organization to satisfy its customer's needs. Each service appointment includes date, time, duration, and required resources.
site Site A location or branch office where an organization does business. An organization can have multiple sites.
subject Subject Information about subjects available in the system.
systemuser User A person with access to the Microsoft CRM system and who owns objects in the Microsoft CRM database.
task Task A generic activity that represents work needed to be done.
team Team A group of otherwise unrelated users. Teams can be used to control access to specific objects.
template E-mail Template A template for an e-mail message that contains the standard attributes of an e-mail message.
territory Territory This entity stores territories to represent sales regions.
uom Unit A unit of measure.
uomschedule Unit Group A grouping of units of measures.
userquery Saved View A saved database query that is owned by a user.
usersettings User Settings A user's preferred settings.
wfprocess Process A group of interrelated steps, or actions, and the rules that drive the transition between these steps.
wfprocessinstance Process Instance A running instance of a workflow process. A process is instantiated either by a system event on its associated object or manually by a user or caller.
** follow the links for entities to see their details
Sample Code
The following code sample explains how to use CrmService. CrmService requires Authentication token to make any call to the CRM Server. Authentication token can be generated using CrmAuthenticationToken object. Following code explain how to use it.
//Create Instance of CrmAuthenticationToken
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "ORG";
//Create Instance of CrmService
CrmService service = new CrmService();
//Associate CrmAuthenticationToken to CrmService object
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.Url = "http://rsv-crm02:5555/mscrmservices/2007/CrmService.asmx";
//create a request object
RetrievePrivilegeSetRequest retPrivSetReq = new RetrievePrivilegeSetRequest();
//use the response object to get the result from webservice
RetrievePrivilegeSetResponse retPrivSetResp = (RetrievePrivilegeSetResponse)service.Execute(retPrivSetReq);
List<privilege> prevset = new List<privilege>();
foreach (privilege prev in retPrivSetResp.BusinessEntityCollection.BusinessEntities)
{
prevset.Add(prev);
Response.Write(prev.name + "</br>");
}

Metadata service
Metadata service classes provide access to the metadata describing entities, attributes, and relationships for an organization.
MetadataService Classes
Class Description
ApplicationOrigin Specifies that the origin of the Web service call is the Microsoft Dynamics CRM application.
AsyncServiceOrigin Specifies that the origin of the Web service call is the aynchronous service.
AttributeMetadata Contains all the metadata for an entity attribute.
BooleanAttributeMetadata Contains the metadata for an attribute of type Boolean.
CallerOrigin Specifies the abstract base class used to determine the origin of the call to the Web service.
CallerOriginToken Represents a token containing the caller origin.
CanBeReferencedRequest Specifies the request class for the CanBeReferenced message.
CanBeReferencedResponse Specifies the response class for the CanBeReferenced message.
CanBeReferencingRequest Specifies the request class for the CanBeReferencing message.
CanBeReferencingResponse Specifies the response class for the CanBeReferencing message.
CanManyToManyRequest Specifies the request class for the CanManyToMany message.
CanManyToManyResponse Specifies the response class for the CanManyToMany message.
CreateAttributeRequest Specifies the request class for the CreateAttribute message.
CreateAttributeResponse Specifies the response class for the CreateAttribute message.
CreateEntityRequest Specifies the request class for the CreateEntity message.
CreateEntityResponse Specifies the response class for the CreateEntity message.
CreateManyToManyRequest Specifies the request class for the CreateManyToMany message.
CreateManyToManyResponse Specifies the response class for the CreateManyToMany message.
CreateOneToManyRequest Specifies the request class for the CreateOneToMany message.
CreateOneToManyResponse Specifies the response class for the CreateOneToMany message.
CrmAssociatedMenuBehavior Specifies what to show for the associated menu for a one-to-many relationship.
CrmAssociatedMenuGroup Specifies the group in which to display the associated menu for a one-to-many relationship.
CrmAttributeRequiredLevel Specifies the data entry requirement level of data entry enforced for the attribute.
CrmAttributeType Specifies the type for an attribute.
CrmAuthenticationToken Specifies authentication information that you must have to use the Web service.
CrmBoolean Represents an entity attribute of type Boolean.
CrmCascadeType Specifies the type of cascading for an action such as assign.
CrmDateTime Represents an entity of type date/time.
CrmDateTimeFormat Specifies the display format for a date/time attribute.
CrmDisplayMasks Specifies the display masks for an attribute, which determines when to display the attribute.
CrmDouble Represents an entity attribute of type double.
CrmFloat Represents an entity attribute of type float.
CrmImeMode Specifies the mode for the input method editor for an attribute.
CrmIntegerFormat Specifies the display format for an integer attribute.
CrmLabel Contains a collection of translations for a label.
CrmMetadata Specifes the base class for classes that contains metadata information.
CrmNullable Represents the abstract base class for an attribute where you can distinguish between and empty value and a null value.
CrmNumber Represents an entity attribute of type number (integer).
CrmOwnershipTypes Specifies the ownership types for an attribute.
CrmPrivilegeType Specifies the privilege type for an attribute.
CrmStringFormat Specifies the display format for a string attribute.
DateTimeAttributeMetadata Contains the metadata for an attribute of type date/time.
DecimalAttributeMetadata Contains the metadata for an attribute of type Decimal.
DeleteAttributeRequest Specifies the request class for the DeleteAttribute message.
DeleteAttributeResponse Specifies the response class for the DeleteAttribute message.
DeleteEntityRequest Specifies the request class for the DeleteEntity message.
DeleteEntityResponse Specifies the response class for the DeleteEntity message.
DeleteOptionValueRequest Specifies the request class for the DeleteOptionValue message.
DeleteOptionValueResponse Specifies the response class for the DeleteOptionValue message.
DeleteRelationshipRequest Specifies the request class for the DeleteRelationship message.
DeleteRelationshipResponse Specifies the response class for the DeleteRelationship message.
EntityMetadata Contains the metadata for an entity.
ExecuteCompletedEventArgs Enables asynchronous execution of the Web service methods.
ExecuteCompletedEventHandler Enables asynchronous execution of the Web service methods.
FloatAttributeMetadata Contains the metadata for an attribute of type float.
GetValidManyToManyRequest Specifies the request class for the GetValidManyToMany message.
GetValidManyToManyResponse Specifies the response class for the GetValidManyToMany message.
GetValidReferencedEntitiesRequest Specifies the request class for the GetValidReferencedEntities message.
GetValidReferencedEntitiesResponse Specifies the response class for the GetValidReferencedEntities message.
GetValidReferencingEntitiesRequest Specifies the request class for the GetValidReferencingEntities message.
GetValidReferencingEntitiesResponse Specifies the response class for the GetValidReferencingEntities message.
InsertOptionValueRequest Specifies the request class for the InsertOptionValue message.
InsertOptionValueResponse Specifies the response class for the InsertOptionValue message.
InsertStatusValueRequest Specifies the request class for the InsertStatusValue message.
InsertStatusValueResponse Specifies the response class for the InsertStatusValue message.
IntegerAttributeMetadata Contains the metadata for an attribute of type integer.
Key Represents a primary key attribute.
LocLabel Contains a localized label including the label string and the language code.
LookupAttributeMetadata Contains the metadata for an attribute of type lookup.
ManyToManyMetadata Contains the metadata for a many-to-any relationship between two entities.
MemoAttributeMetadata Contains the metadata for an attribute of type memo.
MetadataService Contains the methods to retrieve data from the metadata database.
MetadataServiceRequest Specifies the base class for all metadata service requests.
MetadataServiceResponse Specifies the base class for all metadata service responses.
MoneyAttributeMetadata Contains the metadata for an attribute of type money.
OfflineOrigin Specifies that the origin of the Web service call is offline.
OneToManyMetadata Contains the metadata for a one-to-many or many-to-one relationship between two entities.
Option Specifies the base class for picklist, state and status values.
OrderOptionRequest Specifies the request class for the OrderOption message.
OrderOptionResponse Specifies the response class for the OrderOption message.
PicklistAttributeMetadata Contains the metadata for an attribute of type picklist.
RelationshipMetadata Contains the metadata describing the relationships for an entity.
RetrieveAllEntitiesRequest Specifies the request class for the RetrieveAllEntities message.
RetrieveAllEntitiesResponse Specifies the response class for the RetrieveAllEntities message.
RetrieveAttributeRequest Specifies the request class for the RetrieveAttribute message.
RetrieveAttributeResponse Specifies the response class for the RetrieveAttribute message.
RetrieveEntityRequest Specifies the request class for the RetrieveEntity message.
RetrieveEntityResponse Specifies the response class for the RetrieveEntity message.
RetrieveRelationshipRequest Specifies the request class for the RetrieveRelationship message.
RetrieveRelationshipResponse Specifies the response class for the RetrieveRelationship message.
RetrieveTimestampRequest Specifies the request class for the RetrieveTimestamp message.
RetrieveTimestampResponse Specifies the response class for the RetrieveTimestamp message.
SecurityPrivilegeMetadata Contains the metadata that describes a security privilege for access to an entity
StateAttributeMetadata Contains the metadata for an attribute of type state.
StateOption Contains one of the possible values for an attribute of type state.
StatusAttributeMetadata Contains the metadata for an attribute of type status.
StatusOption Contains one of the possible values for an attribute of type status.
StringAttributeMetadata Contains the metadata for an attribute of type string.
UpdateAttributeRequest Specifies the request class for the UpdateAttribute message.
UpdateAttributeResponse Specifies the response class for the UpdateAttribute message.
UpdateEntityRequest Specifies the request class for the UpdateEntity message.
UpdateEntityResponse Specifies the response class for the UpdateEntity message.
UpdateOptionValueRequest Specifies the request class for the UpdateOptionValue message.
UpdateOptionValueResponse Specifies the response class for the UpdateOptionValue message.
UpdateRelationshipRequest Specifies the request class for the UpdateRelationship message.
UpdateRelationshipResponse Specifies the response class for the UpdateRelationship message.
WebServiceApiOrigin Specifies that the origin of the call is via the Web service.
**follow the links to get more details about each class
Sample Code
The following code sample explains details about how to consume MetadataService
// create instance of MetadataService
            MetadataService service = new MetadataService();
// pass network credentials and service url
            service.Credentials = System.Net.CredentialCache.DefaultCredentials;
            service.Url = "http://rsv-crm02:5555/mscrmservices/2006/metadataservice.asmx";
            List<Option> pickListValues = new List<Option>();
// use RetrieveEntityMetadata method to get entity metadata
            EntityMetadata entity = service.RetrieveEntityMetadata(EntityName.account.ToString(), EntityFlags.IncludeAttributes);           
            List<AttributeMetadata> attibuteList = new List<AttributeMetadata>(entity.Attributes);
            foreach (AttributeMetadata obj in attibuteList)
            {
                if (obj.Type != AttributeType.Picklist)
                {
                    Response.Write(obj.Name + ", " + obj.DisplayName);
                }
                Response.Write("</br>");
            }

CRM Authourization
The privileges you are assigned regulate the functions you can perform on particular Records or objects. Your access levels determine which Records these privileges apply to. In other words, although your privileges may include the capability to delete Account Records, it is your access level that determines exactly which Records you are able to delete.
Microsoft CRM includes four distinct access levels presented in order of increasing authority.
User (basic)
User Access is the most restrictive of all the access levels. With User Access rights, a User can perform actions on the following:
· Records he owns
· Records owned by another User but which have been shared with him
· Records owned or shared by a Team of which he is a member
Business Unit (local)
Business Unit Access is a step above the basic User level. It includes all the User Access rights, but it also provides access to Records that are owned by or shared with other Users who belong to the same Business Unit. The term local really corresponds to one distinct Business Unit of which the User is a member.
For example, if Moe has local Opportunity read rights, he can review the Records for all prospects interested in signing up for the beta tester program at his company. If Moe had only User Access, he could see only those Records that he had created himself or Records that other Users had decided to share with him.
Parent: Child Business Units (deep)
A User with Parent: Child Access rights has Business Unit Access plus the ability to access objects or Records from any Business Unit that's subordinate to the unit he is assigned to. If you think of an organizational chart for the divisions of your company, a deep view enables you to see your Business Unit and all those directly below it.
Organizational (global)
Organizational Access rights are the least restrictive of all the categories. With Organizational Access, you can perform actions on any Record within the system, regardless of the Business Unit you belong to and regardless of sharing issues.
Code Sample
The code sample below provide whether user has permission to add new entity based on User Privileges
//Create Instance of CrmAuthenticationToken
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "SCAG";
//Create Instance of CrmService
CrmService service = new CrmService();
//Associate CrmAuthenticationToken to CrmService object
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.Url = "http://rsv-crm02:5555/mscrmservices/2007/CrmService.asmx";
// Create the request object.
WhoAmIRequest userRequest = new WhoAmIRequest();
// Execute the request.
WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);
RetrievePrivilegeSetRequest retPrivSetReq = new RetrievePrivilegeSetRequest();
RetrievePrivilegeSetResponse retPrivSetResp = (RetrievePrivilegeSetResponse)service.Execute(retPrivSetReq);
List<privilege> prevset = new List<privilege>();
foreach (privilege prev in retPrivSetResp.BusinessEntityCollection.BusinessEntities)
{
prevset.Add(prev);
}
string access = "prvWrite" + entityName;
privilege objPrivilege = prevset.Find(delegate(privilege p) { return (p.name.ToLower() == access.ToLower()); });
QueryExpression qe = new QueryExpression();
qe.EntityName = "role";
qe.ColumnSet = new AllColumns();
// Set up the join between the "role" entity and the intersect table "systemuserroles".
LinkEntity le = new LinkEntity();
le.LinkFromEntityName = "role";
le.LinkFromAttributeName = "roleid";
le.LinkToEntityName = "systemuserroles";
le.LinkToAttributeName = "roleid";
// Set up the join between the intersect table "systemuserroles" and the "systemuser" entity.
LinkEntity le2 = new LinkEntity();
le2.LinkFromEntityName = "systemuserroles";
le2.LinkFromAttributeName = "systemuserid";
le2.LinkToEntityName = "systemuser";
le2.LinkToAttributeName = "systemuserid";
// The condition is WHERE user ID = myUserId.
ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values = new object[] { user.UserId };
le2.LinkCriteria = new FilterExpression();
le2.LinkCriteria.Conditions = new ConditionExpression[] { ce };
le.LinkEntities = new LinkEntity[] { le2 };
qe.LinkEntities = new LinkEntity[] { le };
BusinessEntityCollection bec = service.RetrieveMultiple(qe);
foreach (BusinessEntity refEntity in bec.BusinessEntities)
{
role myRoles = (role)refEntity;
RetrieveRolePrivilegesRoleRequest rprreq = new RetrieveRolePrivilegesRoleRequest();
rprreq.RoleId = myRoles.roleid.Value;
RetrieveRolePrivilegesRoleResponse rpresp = (RetrieveRolePrivilegesRoleResponse)service.Execute(rprreq);
List<RolePrivilege> lstRolePrivleges = new List<RolePrivilege>(rpresp.RolePrivileges);
RolePrivilege rp = new RolePrivilege();
if (objPrivilege != null)
{
rp = lstRolePrivleges.Find(delegate(RolePrivilege p) { return (p.PrivilegeId == objPrivilege.privilegeid.Value); });
}
if (rp != null && rp.PrivilegeId != null)
{
result = true;
}
}

Comments