Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Entity PrimaryKey using Metadata Service

Sometimes we need to get the Entity ID for the any custom entity, by default the entityid equals to +"id". So we can get the id for any dynamic entity as

Entity.Properties["entitylogicalname"+"id"];
But this is a snippet for achieving the same using metadata service.


// Get the Primary key from CRM Entity
public string GetEntityPrimaryKey(String EntityName)
{
// Metadata Service
Func myMetaService = () =>
{
// Create an authentication token.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = "OrgName";
token.AuthenticationType = 0;

// Create the metadata Web service;
MetadataService metadataService = new MetadataService();
metadataService.Url = "http://:/MSCRMServices/2007/MetadataService.asmx";
metadataService.CrmAuthenticationTokenValue = token;
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
metadataService.PreAuthenticate = true;
return metadataService;
};

// Create the request
RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
entityRequest.RetrieveAsIfPublished = false;
entityRequest.LogicalName = EntityName;
entityRequest.EntityItems = EntityItems.EntityOnly;

// Execute the request
RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)myMetaService().Execute(entityRequest);

// Access the retrieved entity
EntityMetadata retrievedEntityMetadata = entityResponse.EntityMetadata;
return retrievedEntityMetadata.PrimaryKey;
}

C# Code for Sending Email to Unresolved Recipients

This code will send email to unresolved recipient.
private void SendEmailToUnresolvedRecent(IOrganizationService prmCrmService, string 
             prmToRecipientEmailAddress, Guid prmSenderUserId, string prmSubject, string prmMessageBody)
        {

            // Email record id
            Guid wod_EmailId = Guid.Empty;

            // Creating Email 'to' recipient activity party entity object
            Entity wod_EmailToReciepent = new Entity("activityparty");

            // Creating Email 'from' recipient activity party entity object
            Entity wod_EmailFromReciepent = new Entity("activityparty");

            // Assigning receiver email address to activity party addressused attribute
            //wod_EmailToReciepent["participationtypemask"] = new OptionSetValue(0);
            wod_EmailToReciepent["addressused"] = prmToRecipientEmailAddress;

            // Setting from user account
            wod_EmailFromReciepent["partyid"] = new EntityReference("systemuser", prmSenderUserId);

            // Creating Email entity object
            Entity wod_EmailEntity = new Entity("email");

            // Setting email entity 'to' attribute value
            wod_EmailEntity["to"] = new Entity[] { wod_EmailToReciepent };

            // Setting email entity 'from' attribute value
            wod_EmailEntity["from"] = new Entity[] { wod_EmailFromReciepent };

            // Setting email subject and description
            wod_EmailEntity["subject"] = prmSubject;

            wod_EmailEntity["description"] = prmMessageBody;

            // Creating email record
            wod_EmailId = prmCrmService.Create(wod_EmailEntity);

            // Creating SendEmailRequest object for sending email
            SendEmailRequest wod_SendEmailRequest = new SendEmailRequest();

            // Creating Email tracking token request object
            GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();

            // Creating Email tracking token response object to get tracking token value
            GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = null;

            // Setting email record if for sending email
            wod_SendEmailRequest.EmailId = wod_EmailId;

            wod_SendEmailRequest.IssueSend = true;

            // Getting tracking token value
            wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
                                                 prmCrmService.Execute (wod_GetTrackingTokenEmailRequest);

            // Setting tracking token value
            wod_SendEmailRequest.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;

            // Sending email
            prmCrmService.Execute(wod_SendEmailRequest);

        }

RevokeAccess Message

Revokes access rights to the entity instance for the specified security principal (user or team).

Remarks

To use this message, pass an instance of the RevokeccessRequest class as the request parameter in the Execute method.

This method also applies to all child instances of the target instance. For all child instances, if the caller does not have share privileges for those entity types or share rights to the instances, access to the child instances is not revoked. As a result, the owner of the instance or a user who shares the instance with share rights automatically has share rights to all child instances of the target instance. In this case, only the lack of privileges to a particular entity type prevents access to the child instances from being revoked.

For a description of how actions on a parent instance affect child instances, see Cascading Rules.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see RevokeAccess Privileges.

 
//#The following code example shows how to use the RevokeAccess message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the SecurityPrincipal.
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.User;

// PrincipalId is the GUID of the user whose access is being revoked.
principal.PrincipalId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");

// Create the target for the request.
TargetOwnedAccount target = new TargetOwnedAccount();

// EntityId is the GUID of the account to which access is being revoked.
target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the request object.
RevokeAccessRequest revoke = new RevokeAccessRequest();

// Set the properties of the request object.
revoke.Revokee = principal;
revoke.Target = target;

// Execute the request.
RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revoke);





Send a Custom E-mail for a Campaign Activity

The following sample shows how to send an e-mail for a campaign activity.



[C#]
public void SendEmail(Guid campaignActivityID)
{
CrmService service = new CrmService();
service.Credentials =
System.Net.CredentialCache.DefaultCredentials;

service.CallerIdValue = new CallerId();
// Replace the GUID with the GUID of your Microsoft Dynamics CRM
// Administrator.
service.CallerIdValue.CallerGuid =
new Guid("FD80F8E8-C852-DA11-B1FB-0007E94D105B");

SendEmailRequest req = new SendEmailRequest();
req.EmailId = campaignActivityID;
req.TrackingToken = "";
req.IssueSend = true;

try
{
SendEmailResponse res =
(SendEmailResponse)service.Execute(req);
}
catch (System.Web.Services.Protocols.SoapException er)
{
//Process any error messages here.
}
}




Common Context

This section describes the information that is available in the InputParameters and OutputParameters properties of IPluginExecutionContext. To understand the nature of this information, the relationship between an application making Web service calls and the context that a plug-in receives because of those calls must be described.

The following source code sample shows some typical calls to the Microsoft Dynamics CRM Web service.

[C#]
// Set up the CRM Service.
CrmService service = new CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the account object.
account account = new account();
account.name = "Fourth Coffee";

// Create the target object for the request.
TargetCreateAccount target = new TargetCreateAccount();
target.Account = account;

// Create the request object.
CreateRequest createRequest = new CreateRequest();
createRequest.Target = target;

// Execute the request.
CreateResponse createResponse = (CreateResponse)service.Execute(createRequest);
Guid accountID = createResponse.id;


Although this example uses Request/Response messages and the Execute method, you can use the other CrmService methods such as Create, Update, and Deleteto work with your business entities. The Microsoft Dynamics CRM system takes the information from those CrmService methods and transforms it intoRequest/Response messages that are processed by the event execution pipeline. The information on input/output parameters that follows still applies.

The following documentation relates the Web service calls in the example code to the context that a plug-in is passed. For the examples described herein, assume that a plug-in is registered to execute during the post-event of account creation so that the sample code causes the plug-in to execute.

Input Parameters


The InputParameters property bag contains all the information specified in the Request class whose message caused the plug-in to execute. The keys used to obtain values from the property bag are named according to the name of the Request class instance properties. An example of this is described next.

In the code sample, an account is created by using the CreateRequest class. The Target property of CreateRequest refers to a TargetCreateAccount object, which refers to an account object. This is shown in the following diagram.

CreateRequest and associated classes

When the plug-in is executed, the information that is in the Request object is passed to the plug-in in the InputParameters property of IPluginExecutionContext. For this example, the InputParameters property bag contains two key/value pairs. The first key is named "Target" and its associated value is the target of the request, namely the account object. The second key is named "OptionalParameters" and its associated value is the OptionalParameters instance property that is defined in the Request class from which CreateRequest is derived. In the sample code, no optional parameters were added to the CreateRequest, so that the optional parameters value in InputParameters is null.

The following figure shows an example plug-in that is being debugged in Visual Studio 2005.

Viewing the InputParameters property bag in a debugger

The figure shows the contents of the InputParameters property bag that has been passed in the context to the plug-in. Two key/value pairs are shown: Target andOptionalParameters.

The recommended way to specify these key names in code is to use the predefined names in the ParameterName class. For example, you can useParameterName.Target instead of "Target". Doing this reduces the possibility of a typing mistake in the key name when coding.

InputParameters contains Object types. Therefore, you must cast the property bag values to their appropriate types. The following sample plug-in code shows how to obtain the original account object.

[C#] DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target]

The account attributes can then be accessed in the plug-in.

[C#] string accountName = entity["name"]

Note The dynamic entity obtained from the InputParameters of the context contains only those attributes that are set to a value or null.

Output Parameters


For a post-event, the OutputParameters property bag contains the result of the core operation that is returned in the Response message. The key names that are used to access the values in the OutputParameters property bag match the names of the Response class instance properties.

CreateResponse class

In the source code example, the CreateResponse object contains the GUID of the new account instance after the Execute method is called. A post-event registered plug-in can obtain the GUID from the OutputParameters property bag by using the "id" key name or ParameterName.Id.

//[C#] 
Guid regardingobjectid = (Guid)context.OutputParameters[ParameterName.Id]

If a plug-in is registered for a pre-event, the OutputParameters property bag would not contain a value for the "id" key because the core operation would not yet have occurred.

Retrive Dynamic Entity based on Entity name & Guid



public DynamicEntity retriveEntity(string EntityName, string recordGuid)
{
TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

// Set the properties of the target.
targetRetrieve.EntityName = "contact";
targetRetrieve.EntityId = new Guid(rec_guid);

// Create the request object.
RetrieveRequest retrieve = new RetrieveRequest();

// Set the properties of the request object.
retrieve.Target = targetRetrieve;
retrieve.ColumnSet = new AllColumns();

// Indicate that the BusinessEntity should be retrieved as a DynamicEntity.
retrieve.ReturnDynamicEntities = true;

// Execute the request.
RetrieveResponse retrieved = (RetrieveResponse)_svc.Execute(retrieve);

// Extract the DynamicEntity from the request.
DynamicEntity R_entity = (DynamicEntity)retrieved.BusinessEntity;
return R_entity;
}




Convert a Fax to a Task

This sample code shows how to convert a fax to a task. The code first creates an incoming Fax activity, and then converts it to a Follow-up Task with a due date a week after it was received.



[C#]
using System;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
// Microsoft Dynamics CRM namespaces.
using CrmSdk;

///
/// This sample shows how to convert a fax into a task.
///

public class ConvertFaxToTask
{
static void Main(string[] args)
{
// TODO: Change the server URL and organization to match your Microsoft Dynamics CRM server and Microsoft Dynamics CRM organization.
ConvertFaxToTask.Run("http://localhost:5555", "CRM_Organization");
}

public static bool Run(string crmServerUrl, string orgName)
{
#region Setup Data Required for this sample.

bool success = false;

#endregion

try
{
// Set up the CRM service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
service.PreAuthenticate = true;

// Get the current user.
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

// Create the fax object.
fax fax = new fax();

// Set the properties of the fax.
fax.subject = "Test Fax";
fax.description = "New Fax";

// Create the party sending and receiving the fax.
activityparty party = new activityparty();

// Set the properties of the activity party.
party.partyid = new Lookup();
party.partyid.type = EntityName.systemuser.ToString();
party.partyid.Value = user.UserId;

// The party sends and receives the fax.
fax.from = new activityparty[] { party };
fax.to = new activityparty[] { party };

// Create the fax.
Guid createdFaxId = service.Create(fax);

// Retrieve the created fax.
// Be aware that using AllColumns may adversely affect
// performance and cause unwanted cascading in subsequent
// updates. A best practice is to retrieve the least amount of
// data required.
fax newFax = (fax)service.Retrieve(EntityName.fax.ToString(), createdFaxId, new AllColumns());

// Create the task object.
task task = new task();

// Set the properties of the task.
task.subject = "Follow Up: " + newFax.subject;

// Set the due date of the task.
task.scheduledend = new CrmDateTime();

// Get the date that the fax was received.
CrmDateTime endDate = newFax.createdon;

// Set the due date of the task to one week later.
task.scheduledend.Value = endDate.UniversalTime.AddDays(7).ToString();

// Create the task.
Guid createdTaskId = service.Create(task);

#region check success

if (createdTaskId != Guid.Empty)
{
success = true;
}

#endregion

#region Remove Data Required for this Sample

service.Delete(EntityName.fax.ToString(), createdFaxId);
service.Delete(EntityName.task.ToString(), createdTaskId);

#endregion
}
catch (System.Web.Services.Protocols.SoapException)
{
// Add your error handling code here.
}

return success;
}
}
}





CrmService.Execute Method

The Execute method executes a message that represents either a specialized method or specific business logic.

Syntax

public Response Execute(
  Request  Request
);



 

Parameters

Request

Specifies a specific Request instance.

Return Value

Returns an instance of a Response. You must cast the return value of the Execute method to the specific instance of the response that corresponds to the Request parameter.

Remarks

To perform this action, the caller must have the necessary privileges to the entity type specified in the request class. The caller must also have access rights on the entity instances specified in the request class.

Example

The following example demonstrates the use of the Execute method.


   1:  //# [CrmService.Execute Method]
   2:  // Set up the CRM Service.
   3:  CrmAuthenticationToken token = new CrmAuthenticationToken();
   4:  // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
   5:  token.AuthenticationType = 0; 
   6:  token.OrganizationName = "AdventureWorksCycle";
   7:   
   8:  CrmService service = new CrmService();
   9:  service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
  10:  service.CrmAuthenticationTokenValue = token;
  11:  service.Credentials = System.Net.CredentialCache.DefaultCredentials;
  12:   
  13:  // Create the request object.
  14:  AddItemCampaignRequest add = new AddItemCampaignRequest();
  15:   
  16:  // Set the properties of the request object.
  17:  add.CampaignId = campaignId;
  18:  add.EntityId = productId;
  19:  add.EntityName = EntityName.product;
  20:   
  21:  // Execute the request.
  22:  AddItemCampaignResponse added = (AddItemCampaignResponse) service.Execute(add);

CrmService.Create Method

Creates an instance of an entity.

Syntax

public Guid Create(
  BusinessEntity  entity
);






Parameters

entity

Specifies an instance of a class derived from BusinessEntity of the type of entity to create.

Return Value

Returns a Guid type that contains the ID of the newly created entity.

Remarks

Use this method to create an instance of any Microsoft Dynamics CRM entity that supports the Create message.

For better performance, use this method instead of using the Execute method with the Create message.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see Create Privileges.

The owner of the newly created instance should also have the Read privilege for the entity type.

Example

The following example demonstrates the use of the Create method.



   1:  //# [CrmService.Create Method]

   2:  // Set up the CRM Service.

   3:  CrmAuthenticationToken token = new CrmAuthenticationToken();

   4:  // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.

   5:  token.AuthenticationType = 0; 

   6:  token.OrganizationName = "AdventureWorksCycle";

   7:   

   8:  CrmService service = new CrmService();

   9:  service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";

  10:  service.CrmAuthenticationTokenValue = token;

  11:  service.Credentials = System.Net.CredentialCache.DefaultCredentials;

  12:   

  13:  // Create the contact object.

  14:  contact contact = new contact();

  15:   

  16:  // Create the properties for the contact object.

  17:  contact.firstname = "Jesper";

  18:  contact.lastname = "Aaberg";

  19:  contact.address1_line1 = "23 Market St.";

  20:  contact.address1_city = "Sammamish";

  21:  contact.address1_stateorprovince = "MT";

  22:  contact.address1_postalcode = "99999";

  23:  contact.donotbulkemail = new CrmBoolean();

  24:  contact.donotbulkemail.Value = true;

  25:   

  26:  // Create the contact in Microsoft Dynamics CRM.

  27:  Guid contactGuid = service.Create(contact);

CrmService.Delete Method

Deletes an entity instance.

Syntax

public void Delete(
  string  entityName,
  Guid  id
);



Parameters

entityName

Specifies a String containing the name of the entity. For more information, see Using Entity Names.

id

Specifies a GUID containing the ID of the entity instance you want to delete.

Return Value

No return value.

Remarks

Use this method to delete any instance of a Microsoft Dynamics CRM entity that supports the Delete message.

For better performance, use this method instead of using the Execute method with the Delete message.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see Delete Privileges.

For a description of how actions on a parent instance affect child instances, see Cascading Rules.

Example

The following example demonstrates the use of the Delete method.

   1:  //# [CrmService.Delete Method]
   2:  // Set up the CRM Service.
   3:  CrmAuthenticationToken token = new CrmAuthenticationToken();
   4:  // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
   5:  token.AuthenticationType = 0; 
   6:  token.OrganizationName = "AdventureWorksCycle";
   7:   
   8:  CrmService service = new CrmService();
   9:  service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
  10:  service.CrmAuthenticationTokenValue = token;
  11:  service.Credentials = System.Net.CredentialCache.DefaultCredentials;
  12:   
  13:  // contactGuid is the GUID of the record being deleted.
  14:  Guid contactGuid = new Guid("4D507FFE-ED25-447B-80DE-00AE3EB18B84");
  15:   
  16:  // Delete the contact.
  17:  // The EntityName indicates the EntityType of the object being deleted.
  18:  service.Delete(EntityName.contact.ToString(), contactGuid);

CrmService.Fetch Method

[Applies to: Microsoft Dynamics CRM 4.0]

Retrieves entity instances in XML format based on the specified query expressed in the FetchXML query language.

Syntax

 public string Fetch(
  string  fetchXml
 );



Parameters

fetchXml

Specifies a String that contains the fetch query string to be executed.

Return Value

Returns an XML String type that contains the results of the query.

Remarks

Use this method to execute a query expressed in the FetchXML query language.

To perform this action, the caller must have the Read privilege to the entity types being retrieved and access rights on the entity instances retrieved.

Example

The following example demonstrates the use of the Fetch method.

   1:  //# [CrmService.Fetch Method]
   2:  // Set up the CRM Service.
   3:  CrmAuthenticationToken token = new CrmAuthenticationToken();
   4:  // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory Authentication.
   5:  token.AuthenticationType = 0; 
   6:  token.OrganizationName = "AdventureWorksCycle";
   7:   
   8:  CrmService service = new CrmService();
   9:  service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
  10:  service.CrmAuthenticationTokenValue = token;
  11:  service.Credentials = System.Net.CredentialCache.DefaultCredentials;
  12:   
  13:  // Retrieve all attributes for all accounts.
  14:  // Be aware that using all-attributes may adversely affect
  15:  // performance and cause unwanted cascading in subsequent 
  16:  // updates. A best practice is to retrieve the least amount of 
  17:  // data required.
  18:  string fetch1 = @"   <fetch mapping=""logical"">
  19:                    <entity name=""account"">
  20:                       <all-attributes/>
  21:                    </entity>
  22:                 </fetch>";
  23:   
  24:  // Fetch the results.
  25:  String result1 = service.Fetch(fetch1);
  26:   
  27:  // Retrieve the name and account ID for all accounts where
  28:  // the account owner's last name is not Cannon.
  29:  string fetch2 = @"<fetch mapping=""logical"">
  30:                    <entity name=""account"">
  31:                       <attribute name=""accountid""/>
  32:                       <attribute name=""name""/>
  33:                       <link-entity name=""systemuser"" to=""owninguser"">
  34:                          <filter type=""and"">
  35:                             <condition attribute=""lastname"" operator=""ne"" value=""Cannon""/>
  36:                          </filter>
  37:                       </link-entity>
  38:                    </entity>
  39:                 </fetch>";
  40:   
  41:  // Fetch the results.
  42:  String result2 = service.Fetch(fetch2);

How to Retrieve a List of Messages and Entities that Support Plug-ins

The following code displays a list of messages and entities that support plug-ins. This sample code can be found in the following file in the SDK download:



   1:  //# [How to Retrieve a List of Messages and Entities that Support Plug-ins ]

   2:  using System;

   3:  using System.Collections;

   4:  using CrmSdk;

   5:  using MetadataServiceSdk;

   6:  using Microsoft.Crm.Sdk.Utility;

   7:   

   8:  namespace Microsoft.Crm.Sdk.HowTo

   9:  {

  10:     public class RetrieveSupportedMessages

  11:     {

  12:        public static bool Run(string crmServerUrl, string orgName)

  13:        {

  14:           bool success = true;

  15:           

  16:           // Store all Create, Retrieve, Update, and Delete sdk messages supported by the account entity for verification.

  17:           ArrayList crudMessagesForVerification = new ArrayList();

  18:   

  19:           try

  20:           {

  21:              // Set up the CRM Services.  

  22:              CrmService service = 

  23:                  Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(

  24:                  crmServerUrl, orgName);

  25:              service.PreAuthenticate = true;

  26:   

  27:              MetadataService metadataService =

  28:                  Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetMetadataService(

  29:                  crmServerUrl, orgName);

  30:              metadataService.PreAuthenticate = true;

  31:   

  32:              // Retrieve a list of all entities.

  33:              RetrieveAllEntitiesRequest allEntitiesRequest = 

  34:                  new RetrieveAllEntitiesRequest();

  35:              allEntitiesRequest.RetrieveAsIfPublished = true;

  36:              allEntitiesRequest.MetadataItems = MetadataItems.EntitiesOnly;

  37:   

  38:              // Execute the request.

  39:              RetrieveAllEntitiesResponse allEntitiesResponse =

  40:              (RetrieveAllEntitiesResponse)metadataService.Execute(allEntitiesRequest);

  41:   

  42:              // Create a query to get all related sdk messages. 

  43:              // An example SQL query that will be built for every entity:

  44:              // SELECT sdkmessage.name

  45:              // FROM   sdkmessage

  46:              // INNER JOIN sdkmessagefilter ON sdkmessagefilter.skdmessageid = sdkmessage.skdmessageid

  47:              // WHERE  sdkmessagefilter.primaryobjecttypecode = entity.LogicalName;

  48:              QueryExpression supportedMessagesQuery = new QueryExpression();

  49:              

  50:              // Iterate through the retrieved entities.

  51:              foreach (EntityMetadata entity in allEntitiesResponse.CrmMetadata)

  52:              {

  53:                 // Retrieve the supported message name for this entity.

  54:                 ColumnSet sdkMessageColumns = new ColumnSet();

  55:                 sdkMessageColumns.Attributes = new string[] { "name" };

  56:                 

  57:                 // Build the WHERE clause condition.

  58:                 ConditionExpression schemaNameCondition = new ConditionExpression();

  59:                 schemaNameCondition.AttributeName = "primaryobjecttypecode";

  60:                 schemaNameCondition.Operator = ConditionOperator.Equal;

  61:                 schemaNameCondition.Values = new object[1];

  62:                 schemaNameCondition.Values[0] = entity.LogicalName;

  63:                 

  64:                 // Create the WHERE clause filter.

  65:                 FilterExpression whereExpression = new FilterExpression();

  66:                 whereExpression.Conditions = 

  67:                     new ConditionExpression[] { schemaNameCondition };

  68:                 

  69:                 // Create the inner join link.

  70:                 LinkEntity innerJoinAccount = new LinkEntity();

  71:                 innerJoinAccount.JoinOperator = JoinOperator.Inner;

  72:                 innerJoinAccount.LinkCriteria = whereExpression;

  73:                 innerJoinAccount.LinkFromAttributeName = "sdkmessageid";

  74:                 innerJoinAccount.LinkFromEntityName =

  75:                     EntityName.sdkmessage.ToString();

  76:                 innerJoinAccount.LinkToAttributeName = "sdkmessageid";

  77:                 innerJoinAccount.LinkToEntityName =

  78:                     EntityName.sdkmessagefilter.ToString();

  79:   

  80:                 // Set the query properties.

  81:                 supportedMessagesQuery.EntityName = EntityName.sdkmessage.ToString();

  82:                 supportedMessagesQuery.ColumnSet = sdkMessageColumns;

  83:                 supportedMessagesQuery.LinkEntities = 

  84:                     new LinkEntity[] { innerJoinAccount };

  85:   

  86:                 // Retrieve all sdkmessage names for this entity.

  87:                 BusinessEntityCollection coll =

  88:                     service.RetrieveMultiple(supportedMessagesQuery);

  89:                 

  90:                 // Output the supported messages for this entity

  91:                 Console.WriteLine("============================================================================");

  92:                 Console.WriteLine("Entity: " + entity.LogicalName);

  93:                 if (coll.BusinessEntities.Length > 0)

  94:                 {

  95:                    Console.WriteLine("Supported Messages:");

  96:                 }

  97:                 else

  98:                 {

  99:                    Console.WriteLine("No Messages Supported.");

 100:                 }

 101:                 string sdkMessageName = string.Empty;

 102:                 foreach(BusinessEntity anSdkMessage in coll.BusinessEntities)

 103:                 {

 104:                    sdkMessageName = ((sdkmessage)anSdkMessage).name;

 105:                    Console.WriteLine("\t\t" + sdkMessageName);

 106:                    

 107:                    // Verify that the account entity supports create, retrieve, update, delete.

 108:                    if (entity.LogicalName == EntityName.account.ToString())

 109:                    {

 110:                       // Store all Create, Retrieve, Update, and Delete messages.

 111:                       if (sdkMessageName == "Create" || sdkMessageName == "Retrieve" ||

 112:                          sdkMessageName == "Update" || sdkMessageName == "Delete")

 113:                       {

 114:                          crudMessagesForVerification.Add(sdkMessageName);

 115:                       }

 116:                    }

 117:                 }

 118:              }

 119:   

 120:              #region check success

 121:   

 122:              // Validate that the 4 Create, Retrieve, Update, and Delete messages were found.

 123:              if (crudMessagesForVerification.Count != 4)

 124:              {

 125:                 success = false;

 126:              }

 127:   

 128:              #endregion

 129:           }

 130:           catch (System.Web.Services.Protocols.SoapException)

 131:           {

 132:              // Perform error handling here.

 133:              throw;

 134:           }

 135:           catch (Exception)

 136:           {

 137:              throw;

 138:           }

 139:   

 140:           return success;

 141:        }

 142:     }

 143:  }

Use the Methods in the Outlook SDK Assembly

This sample shows how to use the methods and properties in the assembly Microsoft.Crm.Outlook.Sdk. Before running this sample, you should start Microsoft Dynamics CRM for Outlook.



   1:  //# [Use the Methods in the Outlook SDK Assembly ]

   2:  using System;

   3:  using CrmSdk;

   4:  using Microsoft.Crm.Sdk.Utility;

   5:  using Microsoft.Crm.Outlook.Sdk;

   6:   

   7:  namespace Microsoft.Crm.Sdk.HowTo.Outlook

   8:  {

   9:     public class CrmOutlookMethodsSample

  10:     {

  11:        public CrmOutlookMethodsSample()

  12:        {

  13:   

  14:        }

  15:        

  16:        // NOTE:  Before running this sample, you should start the Microsoft Dynamics CRM for Outlook.

  17:        

  18:        public static bool Run(string crmServerUrl, string orgName)

  19:        {

  20:           bool success = true;

  21:   

  22:           try

  23:           {

  24:              // Set up the CRM Service.  

  25:              CrmOutlookService outlookService = new CrmOutlookService();

  26:   

  27:              // Determine if the Outlook client is running.

  28:              if (outlookService.IsCrmClientLoaded)

  29:              {

  30:                 if (outlookService.IsCrmDesktopClient)

  31:                 {

  32:                    // Microsoft Dynamics CRM for Outlook cannot go offline.

  33:                    Console.WriteLine("CRM Client Desktop URL: " + outlookService.ServerUri.AbsoluteUri);

  34:                    Console.WriteLine("CRM Client state: " + outlookService.State.ToString());

  35:                 }

  36:                 else

  37:                 {

  38:                    // See if Microsoft Dynamics CRM for Outlook with Offline Access is offline.

  39:                    if (outlookService.IsCrmClientOffline)

  40:                    {

  41:                       Console.WriteLine("CRM Client Offline URL: " + outlookService.ServerUri.AbsoluteUri);

  42:                       Console.WriteLine("CRM Client state: " + outlookService.State.ToString());

  43:                       

  44:                       // Take Microsoft Dynamics CRM for Outlook online.

  45:                       Console.WriteLine("Going Online...");

  46:                       outlookService.GoOnline();

  47:                       

  48:                       // Sync up with Microsoft Dynamics CRM database.

  49:                       Console.WriteLine("Synchronizing with CRM...");

  50:                       outlookService.Sync(OutlookSyncType.Outlook);

  51:   

  52:                       Console.WriteLine("CRM Client state: " + outlookService.State.ToString());

  53:                    }

  54:                    else

  55:                    {

  56:                       Console.WriteLine("CRM Client Online URL: " + outlookService.ServerUri.AbsoluteUri);

  57:                       Console.WriteLine("CRM Client state: " + outlookService.State.ToString());

  58:                       

  59:                       // Before going offline, sync up with the Microsoft Dynamics CRM database.

  60:                       Console.WriteLine("Synchronizing with CRM...");

  61:                       outlookService.Sync(OutlookSyncType.Outlook);

  62:                       

  63:                       // Take Microsoft Dynamics CRM for Outlook offline.

  64:                       Console.WriteLine("Going Offline...");

  65:                       outlookService.GoOffline();

  66:   

  67:                       Console.WriteLine("CRM Client state: " + outlookService.State.ToString());

  68:                    }

  69:                 }

  70:              }

  71:           }

  72:           catch (System.Web.Services.Protocols.SoapException)

  73:           {

  74:              // Perform error handling here.

  75:              throw;

  76:           }

  77:           catch (Exception)

  78:           {

  79:              throw;

  80:           }

  81:           

  82:           return success;

  83:        }

  84:     }

  85:  }

Use Filtered Views

This sample shows how to use filtered views to retrieve all invoices where the lead source was "Employee Referral".

Note    Access to the SQL database is not supported in Microsoft Dynamics CRM Online

Example

The following code shows how to connect to the Microsoft Dynamics CRM SQL database directly and query this database securely using a filtered view.


   1:  //# [Use Filtered Views ]

   2:  using System;

   3:  using System.Data;

   4:  using System.Data.SqlClient;

   5:  using Microsoft.Crm.Sdk.Utility;

   6:  using System.Web.Services.Protocols;

   7:   

   8:  namespace Microsoft.Crm.Sdk.HowTo

   9:  {

  10:      using CrmSdk;

  11:     public class FilteredViews

  12:     {

  13:          static void Main(string[] args)

  14:          {

  15:              bool success = false;

  16:   

  17:              try

  18:              {

  19:                  // TODO: Change the service URL, organization and database server name to match

  20:                  // your Microsoft Dynamics CRM server installation.

  21:                  success = FilteredViews.Run("http://localhost:5555", "AdventureWorksCycle", "localhost");

  22:              }

  23:              catch (SoapException ex)

  24:              {

  25:                  Console.WriteLine("The application terminated with an error.");

  26:                  Console.WriteLine(ex.Message);

  27:                  Console.WriteLine(ex.Detail.InnerText);

  28:              }

  29:              catch (System.Exception ex)

  30:              {

  31:                  Console.WriteLine("The application terminated with an error.");

  32:                  Console.WriteLine(ex.Message);

  33:   

  34:                  // Display the details of the inner exception.

  35:                  if (ex.InnerException != null)

  36:                  {

  37:                      Console.WriteLine(ex.InnerException.Message);

  38:   

  39:                      SoapException se = ex.InnerException as SoapException;

  40:                      if (se != null)

  41:                          Console.WriteLine(se.Detail.InnerText);

  42:                  }

  43:              }

  44:              finally

  45:              {

  46:                  Console.WriteLine("Completed successfully? {0}", success);

  47:                  Console.WriteLine("Press <Enter> to exit.");

  48:                  Console.ReadLine();

  49:              }

  50:          }

  51:   

  52:        public static bool Run(string crmServerUrl, string orgName, string databaseServer)

  53:        {

  54:              bool success = false;

  55:              

  56:           try

  57:           {

  58:                  #region Setup Data Required for this Sample

  59:   

  60:                  CrmService service = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

  61:                  service.PreAuthenticate = true;

  62:   

  63:                  WhoAmIRequest userRequest = new WhoAmIRequest();

  64:                  WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

  65:   

  66:                  #endregion

  67:   

  68:                  //SDK: Guid userid = new Guid("{12765E27-7572-4e88-A7DB-AF2A80DD4A3B}");

  69:                  Guid userId = user.UserId;

  70:   

  71:              // Define the SQL Query that selects the top 10 leads that were modified

  72:              // by the current user. Because this queries against a filtered view,

  73:              // this query returns only records that the calling user has Read

  74:              // access to.

  75:                  string sqlQuery = @"SELECT Top 10 FullName 

  76:                          FROM FilteredLead 

  77:                          WHERE modifiedby = '" + userId.ToString() + "'";

  78:   

  79:              // Connect to the Microsoft Dynamics CRM database server. You must use Windows Authentication;

  80:              // SQL Authentication will not work.

  81:                  SqlConnection connection = new SqlConnection("Data Source=" + databaseServer + ";Initial Catalog=" + orgName + "_MSCRM;Integrated Security=SSPI");

  82:                  // Create a DataTable to store the results of the query.

  83:              DataTable table = new DataTable();

  84:   

  85:              // Create and configure the SQL Data Adapter that will fill the DataTable.

  86:              SqlDataAdapter adapter = new SqlDataAdapter();

  87:              adapter.SelectCommand = new SqlCommand(sqlQuery, connection);

  88:   

  89:              // Execute the query by filling the DataTable.

  90:              adapter.Fill(table);

  91:   

  92:                  #region check success

  93:   

  94:                  if(table.Rows.Count > 0)

  95:                      success = true;

  96:   

  97:                  #endregion

  98:              }

  99:              catch

 100:              {

 101:                  // You can handle an exception here or pass it back to the calling method.

 102:                  throw;

 103:              }

 104:              

 105:   

 106:              return success;

 107:        }

 108:     }

 109:  }

Use a Join to Retrieve Activities by Participant

This sample demonstrates doing a simple JOIN to the activityparty entity using a query expression.



   1:  //# [Use a Join to Retrieve Activities by Participant ]

   2:  using System;

   3:  using CrmSdk;

   4:  using Microsoft.Crm.Sdk.Utility;

   5:   

   6:  namespace Microsoft.Crm.Sdk.HowTo

   7:  {

   8:        /// <summary>

   9:        /// This sample shows how to retrieve all activities where the user is a participant.

  10:        /// </summary>

  11:        public class RetrieveActivitiesByParticipant

  12:        {

  13:              static void Main(string[] args)

  14:              {

  15:                    // TODO: Change the server URL and Organization to match your CRM Server and CRM Organization

  16:                    RetrieveActivitiesByParticipant.Run("http://localhost:5555", "CRM_SDK");

  17:              }

  18:   

  19:              public static bool Run(string crmServerUrl, string orgName)

  20:              {

  21:                    // Set up the CRM Service.

  22:                    CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

  23:   

  24:                    #region Setup Data Required for this Sample

  25:   

  26:                    bool success = false;

  27:   

  28:                    #endregion

  29:   

  30:                    try

  31:                    {

  32:                          // Get the user information.

  33:                          WhoAmIRequest userRequest = new WhoAmIRequest();

  34:                          WhoAmIResponse user = (WhoAmIResponse) service.Execute(userRequest);

  35:   

  36:                          // Create the ConditionExpression.

  37:                          ConditionExpression condition = new ConditionExpression();

  38:   

  39:                          // Set the condition for the retrieval to retrieve all activities that belong to the current user.

  40:                          condition.AttributeName = "partyid";

  41:                          condition.Operator = ConditionOperator.Equal;

  42:                          condition.Values = new string [] {user.UserId.ToString()};

  43:   

  44:                          // Build the filter based on the condition.

  45:                          FilterExpression filter = new FilterExpression();

  46:                          filter.FilterOperator = LogicalOperator.And;

  47:                          filter.Conditions = new ConditionExpression[] {condition};

  48:   

  49:                          // Create a LinkEntity to link the activity participant to the activity.

  50:                          LinkEntity link = new LinkEntity();

  51:   

  52:                          // Set the properties of the LinkEntity.

  53:                          link.LinkCriteria = filter;

  54:   

  55:                          // Set the linking entity to be the activity.

  56:                          link.LinkFromEntityName = EntityName.activitypointer.ToString();

  57:   

  58:                          // Set the attribute being linked to to be the activityid.

  59:                          link.LinkFromAttributeName = "activityid";

  60:   

  61:                          // Set the entity being linked to to be the activityparty.

  62:                          link.LinkToEntityName = EntityName.activityparty.ToString();

  63:                    

  64:                          // Set the attribute linking to the activityparty to be the activityid.

  65:                          link.LinkToAttributeName = "activityid";

  66:                    

  67:                          // Create the query.

  68:                          QueryExpression query = new QueryExpression();

  69:   

  70:                          // Set the properties of the query.

  71:                          query.EntityName = EntityName.activitypointer.ToString();

  72:                          // Be aware that using AllColumns may adversely affect

  73:                          // performance and cause unwanted cascading in subsequent 

  74:                          // updates. A best practice is to retrieve the least amount of 

  75:                          // data required.

  76:                          query.ColumnSet = new AllColumns();

  77:                          query.LinkEntities = new LinkEntity[] {link};

  78:   

  79:                          // Create the request object.

  80:                          RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();

  81:   

  82:                          // Set the properties of the request object.

  83:                          retrieve.Query = query;

  84:              

  85:                          // Execute the request.

  86:                          RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse) service.Execute(retrieve);

  87:   

  88:                          #region check success

  89:   

  90:                          if ((retrieved.BusinessEntityCollection.EntityName.ToLower().Equals("activitypointer")))

  91:                          {

  92:                                success = true;

  93:                          }

  94:   

  95:                          #endregion

  96:                    }

  97:                    catch (System.Web.Services.Protocols.SoapException)

  98:                    {

  99:                          // Add your error handling code here.

 100:                    }

 101:   

 102:                    return success;

 103:              }

 104:        }

 105:  }