Tag Cloud

CRM 2011 (161) CRM 4.0 (144) C# (116) JScript (109) Plugin (92) Registry (90) Techpedia (77) PyS60 (68) WScript (43) Plugin Message (31) Exploit (27) ShellCode (26) FAQ (22) JavaScript (21) Killer Codes (21) Hax (18) VB 6.0 (17) Commands (16) VBScript (16) Quotes (15) Turbo C++ (13) WMI (13) Security (11) 1337 (10) Tutorials (10) Asp.Net (9) Safe Boot (9) Python (8) Interview Questions (6) video (6) Ajax (5) VC++ (5) WebService (5) Workflow (5) Bat (4) Dorks (4) Sql Server (4) Aptitude (3) Picklist (3) Tweak (3) WCF (3) regex (3) Config (2) LINQ (2) PHP (2) Shell (2) Silverlight (2) TSql (2) flowchart (2) serialize (2) ASHX (1) CRM 4.0 Videos (1) Debug (1) FetchXml (1) GAC (1) General (1) Generics (1) HttpWebRequest (1) InputParameters (1) Lookup (1) Offline Plug-ins (1) OutputParameters (1) Plug-in Constructor (1) Protocol (1) RIA (1) Sharepoint (1) Walkthrough (1) Web.config (1) design patterns (1) generic (1) iframe (1) secure config (1) unsecure config (1) url (1)

Pages

Friday, May 03, 2013

Create a Marketing Automation List

The following code example demonstrates how to create a Marketing Automation list and add a member to it.



   1:  //# [Create a Marketing Automation List ]

   2:  using System;

   3:  using CrmSdk;

   4:  using Microsoft.Crm.Sdk.Utility;

   5:   

   6:  namespace Microsoft.Crm.Sdk.HowTo

   7:  {

   8:        /// <summary>

   9:        /// Summary description for MarketingAutomationListCreation.

  10:        /// </summary>

  11:        public class MarketingAutomationListCreation

  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:                    MarketingAutomationListCreation.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:                    account accountCreate = new account();

  26:                    accountCreate.name = "Fourth Coffee";

  27:                    accountCreate.description = "Coffee House";

  28:   

  29:                    Guid createdId = service.Create(accountCreate);

  30:                    #endregion

  31:   

  32:                    #region Create List

  33:   

  34:                    list autoList = new list();

  35:                    autoList.listname = "Test List";

  36:                    autoList.membertype = new CrmNumber();

  37:                    autoList.membertype.Value = 1;

  38:                    autoList.createdfromcode = new Picklist();

  39:                    autoList.createdfromcode.Value = 1;

  40:   

  41:                    Guid listId = service.Create(autoList);

  42:   

  43:                    #endregion

  44:   

  45:                    #region Add Member to List

  46:                    AddMemberListRequest addRequest = new AddMemberListRequest();

  47:                    addRequest.EntityId = createdId;

  48:                    addRequest.ListId = listId;

  49:   

  50:                    AddMemberListResponse response = (AddMemberListResponse) service.Execute(addRequest);

  51:                    #endregion

  52:   

  53:                    #region check success

  54:   

  55:                    bool success = false;

  56:   

  57:                    if (response.Id != Guid.Empty)

  58:                    {

  59:                          success = true;

  60:                    }

  61:                    #endregion

  62:              

  63:                    #region Remove Data Required for this Sample

  64:                    service.Delete(EntityName.account.ToString(), createdId);

  65:                    service.Delete(EntityName.list.ToString(), listId);

  66:                    #endregion

  67:   

  68:                    return success;

  69:              }

  70:        }

  71:  }

Schedule a Resource

This sample code shows how to schedule a resource with the following scenario. A plumber and van need to be scheduled to investigate and fix a leak at a customer site. The earliest available appointment needs to be made. In order for this to be accomplished, all preliminary records must be created. The default 24-hour calendars will be used. No sites are created for this sample.



   1:  //# [Schedule a Resource ]

   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 schedule a resource.

  10:     /// </summary>

  11:     public class ServiceManagement

  12:     {

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

  14:        {

  15:           // Set up the CRM Service.

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

  17:   

  18:           #region Setup Data Required for this Sample

  19:           bool success = false;

  20:   

  21:           #endregion

  22:   

  23:           try

  24:           {

  25:              // Get the current user's information.

  26:              WhoAmIRequest userRequest = new WhoAmIRequest();

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

  28:   

  29:              // Create the van resource.

  30:              equipment van = new equipment();

  31:              van.name = "Van 1";

  32:              van.timezonecode = new CrmNumber();

  33:              van.timezonecode.Value = 1;

  34:              van.businessunitid = new Lookup();

  35:              van.businessunitid.type = EntityName.businessunit.ToString();

  36:              van.businessunitid.Value = user.BusinessUnitId;

  37:   

  38:              // Create the van object.

  39:              Guid vanId = service.Create(van);

  40:   

  41:              // Create the plumber resource group.

  42:              constraintbasedgroup group = new constraintbasedgroup();

  43:              group.businessunitid = new Lookup();

  44:              group.businessunitid.type = EntityName.businessunit.ToString();

  45:              group.businessunitid.Value = user.BusinessUnitId;

  46:              group.name = "Plumber with Van 1";

  47:              System.Text.StringBuilder builder = new System.Text.StringBuilder("<Constraints>");

  48:              builder.Append("<Constraint>");

  49:              builder.Append("<Expression>");

  50:              builder.Append("<Body>resource[\"Id\"] == ");

  51:              builder.Append(user.UserId.ToString("B"));

  52:              builder.Append(" || resource[\"Id\"] == ");

  53:              builder.Append(vanId.ToString("B"));

  54:              builder.Append("</Body>");

  55:              builder.Append("<Parameters>");

  56:              builder.Append("<Parameter name=\"resource\" />");

  57:              builder.Append("</Parameters>");

  58:              builder.Append("</Expression>");

  59:              builder.Append("</Constraint>");

  60:              builder.Append("</Constraints>");

  61:              group.constraints = builder.ToString();

  62:              group.grouptypecode = new Picklist();

  63:              group.grouptypecode.Value = 0;

  64:   

  65:              Guid groupId = service.Create(group);

  66:   

  67:              // Create the resource specification.

  68:              resourcespec spec = new resourcespec();

  69:              spec.businessunitid = new Lookup();

  70:              spec.businessunitid.type = EntityName.businessunit.ToString();

  71:              spec.businessunitid.Value = user.BusinessUnitId;

  72:              spec.objectiveexpression = @"

  73:                 <Expression>

  74:                    <Body>udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)</Body>

  75:                    <Parameters>

  76:                       <Parameter name=""factory"" />

  77:                       <Parameter name=""resource"" />

  78:                       <Parameter name=""appointment"" />

  79:                       <Parameter name=""request"" />

  80:                       <Parameter name=""leftoffset"" />

  81:                       <Parameter name=""rightoffset"" />

  82:                    </Parameters>

  83:                    <Properties EvaluationInterval=""P0D"" evaluationcost=""0"" />

  84:                 </Expression>";

  85:              spec.requiredcount = new CrmNumber();

  86:              spec.requiredcount.Value = 1;

  87:              spec.name = "Test Spec";

  88:              spec.groupobjectid = new UniqueIdentifier();

  89:              spec.groupobjectid.Value = groupId;

  90:   

  91:              Guid specId = service.Create(spec);

  92:   

  93:              // Create the plumber required resource object.

  94:              RequiredResource plumberReq = new RequiredResource();

  95:              plumberReq.ResourceId = user.UserId;// assume current user is the plumber

  96:              plumberReq.ResourceSpecId = specId;

  97:   

  98:              // Create the van required resource object.

  99:              RequiredResource vanReq = new RequiredResource();

 100:              vanReq.ResourceId = vanId;

 101:              vanReq.ResourceSpecId = specId;

 102:   

 103:              // Create the service.

 104:              service plumberService = new service();

 105:              plumberService.name = "Plumber1";

 106:              plumberService.duration = new CrmNumber();

 107:              plumberService.duration.Value = 60;

 108:              plumberService.initialstatuscode = new Status();

 109:              plumberService.initialstatuscode.Value = 1;

 110:              plumberService.granularity = "FREQ=MINUTELY;INTERVAL=15;";

 111:              plumberService.resourcespecid = new Lookup();

 112:              plumberService.resourcespecid.type = EntityName.resourcespec.ToString();

 113:              plumberService.resourcespecid.Value = specId;

 114:              plumberService.strategyid = new Lookup();

 115:              // This is a known GUID for the default strategy.

 116:              plumberService.strategyid.Value = new Guid("07F7DC72-1671-452D-812C-7172D3CA881F");

 117:              

 118:              Guid plumberServiceId = service.Create(plumberService);

 119:   

 120:              // Create the appointment request.

 121:              AppointmentRequest appointmentReq = new AppointmentRequest();

 122:              appointmentReq.RequiredResources = new RequiredResource[] {vanReq};

 123:              appointmentReq.Direction = SearchDirection.Forward;

 124:              appointmentReq.Duration = 60;

 125:              appointmentReq.NumberOfResults = 10;

 126:              appointmentReq.NumberOfResults = 1;

 127:              appointmentReq.ServiceId = plumberServiceId;

 128:   

 129:              // The search window describes the time when the resouce can be scheduled.

 130:              // It must be set.

 131:              appointmentReq.SearchWindowStart = new CrmDateTime();

 132:              appointmentReq.SearchWindowStart.Value = DateTime.Now.ToUniversalTime().ToString();

 133:              appointmentReq.SearchWindowEnd = new CrmDateTime();

 134:              appointmentReq.SearchWindowEnd.Value = DateTime.Now.AddDays(7).ToUniversalTime().ToString();

 135:              appointmentReq.UserTimeZoneCode = 1;

 136:   

 137:              // Create the request object.

 138:              SearchRequest search = new SearchRequest();

 139:   

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

 141:              search.AppointmentRequest = appointmentReq;

 142:   

 143:              // Execute the request.

 144:              SearchResponse searched = (SearchResponse)service.Execute(search);

 145:   

 146:              #region check success

 147:   

 148:              if (searched.SearchResults.Proposals.Length > 0)

 149:              {

 150:                 success = true;

 151:              }

 152:   

 153:              #endregion

 154:   

 155:              #region Remove Data Required for this Sample

 156:   

 157:              service.Delete(EntityName.service.ToString(), plumberServiceId);

 158:              service.Delete(EntityName.equipment.ToString(), vanId);

 159:                 

 160:              #endregion

 161:           }

 162:           catch (System.Web.Services.Protocols.SoapException ex)

 163:           {

 164:              // Add your error handling code here.

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

 166:              success = false;

 167:           }

 168:   

 169:           return success;

 170:        }

 171:     }

 172:  }

Thursday, May 02, 2013

Retrieve the Roles for a User

This sample shows how to build a QueryExpression to for use with RetrieveMultiple to find all the roles for a user. To do this, you have to build a query for roles where you join 'role' to 'systemuserroles', and then join systemuserroles' to 'systemuser' and add a condition where systemuser.systemuserid equals the attribute UserId.




// Retrieve the GUID of the logged on user.
WhoAmIRequest whoReq = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse) service.Execute(whoReq);
Guid userid = whoResp.UserId;

// Create a QueryExpression.
QueryExpression qe = new QueryExpression();
qe.EntityName = "role";
// 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.
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 to find the user ID.
ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values = new object[]{userid};

le2.LinkCriteria = new FilterExpression();
le2.LinkCriteria.Conditions = new ConditionExpression[]{ce};

le.LinkEntities = new LinkEntity[]{le2};
qe.LinkEntities = new LinkEntity[]{le};

// Execute the query.
BusinessEntityCollection bec = service.RetrieveMultiple(qe);





Retrieve the Roles for a User

This sample shows how to build a QueryExpression to for use with RetrieveMultiple to find all the roles for a user. To do this, you have to build a query for roles where you join 'role' to 'systemuserroles', and then join systemuserroles' to 'systemuser' and add a condition where systemuser.systemuserid equals the attribute UserId.



   1:  //# Retrieve the Roles for a User #//

   2:   

   3:  // Retrieve the GUID of the logged on user.

   4:  WhoAmIRequest whoReq = new WhoAmIRequest();

   5:  WhoAmIResponse whoResp = (WhoAmIResponse) service.Execute(whoReq);

   6:  Guid userid = whoResp.UserId;

   7:   

   8:  // Create a QueryExpression.

   9:  QueryExpression qe = new QueryExpression();

  10:  qe.EntityName = "role";

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

  12:  // performance and cause unwanted cascading in subsequent 

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

  14:  // data required.

  15:  qe.ColumnSet = new AllColumns();

  16:   

  17:  // Set up the join between the role entity

  18:  // and the intersect table systemuserroles.

  19:  LinkEntity le = new LinkEntity();

  20:  le.LinkFromEntityName = "role";

  21:  le.LinkFromAttributeName = "roleid";

  22:  le.LinkToEntityName = "systemuserroles";

  23:  le.LinkToAttributeName = "roleid";

  24:   

  25:  // Set up the join between the intersect table

  26:  // systemuserroles and the systemuser entity.

  27:  LinkEntity le2 = new LinkEntity();

  28:  le2.LinkFromEntityName = "systemuserroles";

  29:  le2.LinkFromAttributeName = "systemuserid";

  30:  le2.LinkToEntityName = "systemuser";

  31:  le2.LinkToAttributeName = "systemuserid";

  32:   

  33:  // The condition is to find the user ID.

  34:  ConditionExpression ce = new ConditionExpression();

  35:  ce.AttributeName = "systemuserid";

  36:  ce.Operator = ConditionOperator.Equal;

  37:  ce.Values = new object[]{userid};

  38:   

  39:  le2.LinkCriteria = new FilterExpression();

  40:  le2.LinkCriteria.Conditions = new ConditionExpression[]{ce};

  41:   

  42:  le.LinkEntities = new LinkEntity[]{le2};

  43:  qe.LinkEntities = new LinkEntity[]{le};

  44:   

  45:  // Execute the query.

  46:  BusinessEntityCollection bec = service.RetrieveMultiple(qe);

Wednesday, May 01, 2013

Promote an E-mail Message to Microsoft Dynamics CRM

This sample code shows how to create an e-mail activity instance from the specified e-mail message.



   1:  //# Promote an E-mail Message to Microsoft Dynamics CRM

   2:  using System;

   3:  using CrmSdk;

   4:  using Microsoft.Crm.Sdk.Utility;

   5:   

   6:  namespace Microsoft.Crm.Sdk.HowTo.Email

   7:  {

   8:     public class DeliverPromoteEmail

   9:     {

  10:        public DeliverPromoteEmail()

  11:        {

  12:   

  13:        }

  14:   

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

  16:        {

  17:           bool success = false;

  18:   

  19:           try

  20:           {

  21:              // Set up the CRM Service.  

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

  23:              service.PreAuthenticate = true;

  24:   

  25:              #region Setup Data Required for this Sample

  26:              

  27:              // Create a user to send an e-mail message to (To: field).

  28:              contact emailContact = new contact();

  29:              emailContact.firstname = "Adam";

  30:              emailContact.lastname = "Carter";

  31:              emailContact.emailaddress1 = "adam.carter@example.com";

  32:   

  33:              // Create the contact.

  34:              Guid emailContactId = service.Create(emailContact);

  35:   

  36:              // Get a system user to send the e-mail (From: field)

  37:              WhoAmIRequest systemUserRequest = new WhoAmIRequest();

  38:              WhoAmIResponse systemUserResponse = service.Execute(systemUserRequest) as WhoAmIResponse;

  39:              

  40:              ColumnSet selectClause = new ColumnSet();

  41:              selectClause.Attributes = new string[] { "internalemailaddress" };

  42:   

  43:              // Execute the request.

  44:              systemuser emailSender = service.Retrieve(EntityName.systemuser.ToString(), systemUserResponse.UserId, selectClause) as systemuser;

  45:   

  46:              #endregion

  47:   

  48:              // Create the request.

  49:              DeliverPromoteEmailRequest deliverEmailRequest = new DeliverPromoteEmailRequest();

  50:              

  51:              // Set all required fields

  52:              deliverEmailRequest.Subject = "SDK Sample Email";

  53:              deliverEmailRequest.To = emailContact.emailaddress1;

  54:              deliverEmailRequest.From = emailSender.internalemailaddress;

  55:              deliverEmailRequest.Bcc = String.Empty;

  56:              deliverEmailRequest.Cc = String.Empty;

  57:              deliverEmailRequest.Importance = "high";

  58:              deliverEmailRequest.Body = "This message will create an email activity.";

  59:              deliverEmailRequest.MessageId = Guid.NewGuid().ToString();

  60:              deliverEmailRequest.SubmittedBy = "";

  61:              deliverEmailRequest.ReceivedOn = new CrmDateTime();

  62:              deliverEmailRequest.ReceivedOn.Value = DateTime.Now.ToString();

  63:              

  64:              // We will not attach a file to the e-mail, but the Attachments property is required.

  65:              deliverEmailRequest.Attachments = new BusinessEntityCollection();

  66:              deliverEmailRequest.Attachments.EntityName = EntityName.activitymimeattachment.ToString();

  67:              deliverEmailRequest.Attachments.BusinessEntities = new activitymimeattachment[0];

  68:   

  69:              // Execute the request.

  70:              DeliverPromoteEmailResponse deliverEmailResponse = (DeliverPromoteEmailResponse)service.Execute(deliverEmailRequest);

  71:   

  72:              #region check success

  73:              

  74:              // Query for the delivered e-mail and verify the status code is "Sent".

  75:              ColumnSet deliveredMailColumns = new ColumnSet();

  76:              deliveredMailColumns.Attributes = new string[] { "statuscode" };

  77:   

  78:              email deliveredEmail = service.Retrieve(EntityName.email.ToString(), deliverEmailResponse.EmailId, deliveredMailColumns) as email;

  79:   

  80:              if (deliveredEmail.statuscode.Value == EmailStatus.Sent)

  81:              {

  82:                 success = true;

  83:              }

  84:   

  85:              #endregion

  86:   

  87:              #region Remove Data Required for this Sample

  88:   

  89:              // Delete the sent e-mail messages. 

  90:              service.Delete(EntityName.email.ToString(), deliveredEmail.activityid.Value);

  91:   

  92:              // Delete the contacts created for e-mail messages.

  93:              service.Delete(EntityName.contact.ToString(), emailContactId);

  94:   

  95:              #endregion

  96:           }

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

  98:           {

  99:              // Perform error handling here.

 100:              throw;

 101:           }

 102:           catch (Exception)

 103:           {

 104:              throw;

 105:           }

 106:           

 107:           return success;

 108:        }

 109:     }

 110:  }

Send a Bulk E-mail and Monitor the Job

This sample code shows how to send a bulk e-mail and monitor its progress.



   1:  //# Send a Bulk E-mail and Monitor the Job

   2:  using System;

   3:  using CrmSdk;

   4:  using Microsoft.Crm.Sdk.Utility;

   5:   

   6:  namespace Microsoft.Crm.Sdk.HowTo.BulkOperation

   7:  {

   8:     public class SendBulkEmailAndMonitor

   9:     {

  10:        public SendBulkEmailAndMonitor()

  11:        {

  12:   

  13:        }

  14:   

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

  16:        {

  17:           bool success = false;

  18:   

  19:           try

  20:           {

  21:              // Set up the CRM Service.  

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

  23:              service.PreAuthenticate = true;

  24:   

  25:              // Create some contacts to send a bulk e-mail to.

  26:              // Typically, this would be an existing list of customers, such as a marketing list.

  27:              object[] contactIds = new object[2];

  28:              

  29:              contact emailContact1 = new contact();

  30:              emailContact1.firstname = "Adam";

  31:              emailContact1.lastname = "Carter";

  32:              emailContact1.emailaddress1 = "adam.carter@example.com";

  33:   

  34:              // Create the contact.

  35:              contactIds[0] = service.Create(emailContact1);

  36:              

  37:              contact emailContact2 = new contact();

  38:              emailContact2.firstname = "Adina";

  39:              emailContact2.lastname = "Hagege";

  40:              emailContact2.emailaddress1 = "adina.hagege@example.com";

  41:   

  42:              // Create the contact.

  43:              contactIds[1] = service.Create(emailContact2);

  44:              

  45:              // Create the bulk mail request.

  46:              SendBulkMailRequest bulkMailRequest = new SendBulkMailRequest();

  47:   

  48:              // Create a query expression for the bulk operation to use to retrieve 

  49:              // the contacts in our e-mail list.

  50:              ConditionExpression condition = new ConditionExpression();

  51:              condition.AttributeName = "contactid";

  52:              condition.Operator = ConditionOperator.In;

  53:              condition.Values = contactIds;

  54:   

  55:              FilterExpression filterExpression = new FilterExpression();

  56:              filterExpression.Conditions = new ConditionExpression[] { condition };

  57:   

  58:              ColumnSet returnColumns = new ColumnSet();

  59:              returnColumns.Attributes = new string[] { "contactid" };

  60:   

  61:              QueryExpression queryRequest = new QueryExpression();

  62:              queryRequest.ColumnSet = returnColumns;

  63:              queryRequest.EntityName = EntityName.contact.ToString();

  64:              queryRequest.Criteria = filterExpression;

  65:   

  66:              // Attach the contact query to the bulk e-mail request.

  67:              bulkMailRequest.Query = queryRequest;

  68:   

  69:              // Get a system user to use as the sender.

  70:              bulkMailRequest.Sender = GetEmailSenderMoniker(service);

  71:   

  72:              // Set the RegardingId to the e-mail sender.

  73:              bulkMailRequest.RegardingId = bulkMailRequest.Sender.Id;

  74:              bulkMailRequest.RegardingType = EntityName.systemuser.ToString();

  75:   

  76:              // Use a built-in e-mail template.

  77:              // NOTE: The e-mail template's 'template type' must match the type of customers

  78:              // in the e-mail list. Our list contains contacts, so our template must be for contacts.

  79:              bulkMailRequest.TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6");

  80:   

  81:              // Create a tracking ID for the bulk operation to monitor its progress.

  82:              RequestIdOptionalParameter trackingId = new RequestIdOptionalParameter();

  83:              trackingId.Value = Guid.NewGuid();

  84:              

  85:              // Attach the tracking ID to the bulk e-mail request.

  86:              bulkMailRequest.OptionalParameters = new OptionalParameter[] { trackingId };

  87:   

  88:              // Execute the async bulk e-mail request.

  89:              service.Execute(bulkMailRequest);

  90:              

  91:              // Now that we have executed the bulk operation, we have to retrieve it using our tracking ID.

  92:              ColumnSet asyncColumns = new ColumnSet();

  93:              asyncColumns.Attributes = new string[] { "requestid", "statecode" };

  94:   

  95:              QueryByAttribute bulkQuery = new QueryByAttribute();

  96:              bulkQuery.ColumnSet = asyncColumns;

  97:              bulkQuery.EntityName = EntityName.asyncoperation.ToString();

  98:              bulkQuery.Attributes = new string[] { "requestid" };

  99:              bulkQuery.Values = new object[1];

 100:              bulkQuery.Values[0] = trackingId.Value;

 101:   

 102:              // Retrieve the bulk e-mail async operation.

 103:              BusinessEntityCollection aResponse = service.RetrieveMultiple(bulkQuery);

 104:   

 105:              // Monitor the async operation through polling.

 106:              const int ARBITRARY_MAX_POLLING_TIME = 60;

 107:              int secondsTicker = ARBITRARY_MAX_POLLING_TIME;

 108:   

 109:              asyncoperation createdBulkMailOperation = null;

 110:              

 111:              while (secondsTicker > 0)

 112:              {

 113:                 // Make sure that the async operation was retrieved.

 114:                 if (aResponse.BusinessEntities.Length > 0)

 115:                 {

 116:                    // Grab the one bulk operation that was created.

 117:                    createdBulkMailOperation = (asyncoperation)aResponse.BusinessEntities[0];

 118:   

 119:                    // Check the operation's state.

 120:                    if (createdBulkMailOperation.statecode.Value != AsyncOperationState.Completed)

 121:                    {

 122:                       // The operation has not yet completed.  Wait a second for the status to change.

 123:                       System.Threading.Thread.Sleep(1000);

 124:                       secondsTicker--;

 125:   

 126:                       // Retrieve a fresh version the bulk delete operation.

 127:                       aResponse = service.RetrieveMultiple(bulkQuery);

 128:                    }

 129:                    else

 130:                    {

 131:                       // Stop polling because the operation's state is now completed.

 132:                       secondsTicker = 0;

 133:                    }

 134:                 }

 135:                 else

 136:                 {

 137:                    // Wait a second for the async operation to become active.

 138:                    System.Threading.Thread.Sleep(1000);

 139:                    secondsTicker--;

 140:   

 141:                    // Retrieve the entity again.

 142:                    aResponse = service.RetrieveMultiple(bulkQuery);

 143:                 }

 144:              }

 145:              

 146:              // When the bulk e-mail operation has finished, all sent e-mail messages will have a status of "Pending Send" and 

 147:              // will be picked up by your e-mail router. Or, you can then use BackgroundSendEmail to download

 148:              // all the e-mail messages that were created by using the SendBulkEmail message. See the BackgroundSendEmail sample for an example.

 149:   

 150:              #region check success

 151:              

 152:              // Validate async operation succeeded.

 153:              if (createdBulkMailOperation.statecode.Value == AsyncOperationState.Completed)

 154:              {

 155:                 success = true;

 156:              }

 157:   

 158:              #endregion

 159:   

 160:              #region Remove Data Required for this Sample.

 161:              

 162:              // Delete the sent e-mail messages. 

 163:              ColumnSet sentMailColumns = new ColumnSet();

 164:              sentMailColumns.Attributes = new string[] { "statuscode" };

 165:   

 166:              ConditionExpression statusCondition = new ConditionExpression();

 167:              statusCondition.AttributeName = "statuscode";

 168:              statusCondition.Operator = ConditionOperator.Equal;

 169:              statusCondition.Values = new object[] { EmailStatus.PendingSend };

 170:   

 171:              // Create the query filter.

 172:              FilterExpression emailFilter = new FilterExpression();

 173:              emailFilter.Conditions = new ConditionExpression[] { statusCondition };

 174:              emailFilter.FilterOperator = LogicalOperator.And;

 175:   

 176:              // Query for e-mail activity.

 177:              QueryExpression emailsQuery = new QueryExpression();

 178:              emailsQuery.ColumnSet = sentMailColumns;

 179:              emailsQuery.EntityName = EntityName.email.ToString();

 180:              emailsQuery.Criteria = emailFilter;

 181:   

 182:              // Retrieve the e-mail activity.

 183:              BusinessEntityCollection emails = service.RetrieveMultiple(emailsQuery);

 184:   

 185:              foreach (email sentMail in emails.BusinessEntities)

 186:              {

 187:                 service.Delete(EntityName.email.ToString(), sentMail.activityid.Value);

 188:              }

 189:              

 190:              // Delete the contacts created for e-mails.

 191:              foreach (Guid createdContactId in contactIds)

 192:              {

 193:                 service.Delete(EntityName.contact.ToString(), createdContactId);

 194:              }

 195:   

 196:              #endregion

 197:           }

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

 199:           {

 200:              // Perform error handling here.

 201:              throw;

 202:           }

 203:           catch (Exception)

 204:           {

 205:              throw;

 206:           }

 207:   

 208:           return success;

 209:        }

 210:   

 211:        /// <summary>

 212:        /// Retrieves a systemuser to use as the sender of an e-mail.

 213:        /// </summary>

 214:        /// <param name="service">The CRM service</param>

 215:        /// <returns>Moniker to use as e-mail sender</returns>

 216:        public static Moniker GetEmailSenderMoniker(CrmService service)

 217:        {

 218:           Moniker emailSender = new Moniker();

 219:           

 220:           ColumnSet selectClause = new ColumnSet();

 221:           selectClause.Attributes = new string[] {"fullname"};

 222:           

 223:           QueryExpression allSystemUsersQuery = new QueryExpression();

 224:           allSystemUsersQuery.EntityName = EntityName.systemuser.ToString();

 225:           allSystemUsersQuery.ColumnSet = selectClause;

 226:   

 227:           // Create the query request.

 228:           RetrieveMultipleRequest allSystemUsersRequest = new RetrieveMultipleRequest();

 229:           allSystemUsersRequest.Query = allSystemUsersQuery;

 230:   

 231:           // Execute the request.

 232:           RetrieveMultipleResponse allSystemUsersResponse = (RetrieveMultipleResponse)service.Execute(allSystemUsersRequest);

 233:   

 234:           // Grab a system user for the bulk e-mail.

 235:           if (allSystemUsersResponse.BusinessEntityCollection.BusinessEntities.Length > 0)

 236:           {

 237:              // For demonstration, grab the first system user.

 238:              systemuser emailUser = (systemuser)allSystemUsersResponse.BusinessEntityCollection.BusinessEntities[0];

 239:              emailSender.Id = emailUser.systemuserid.Value;

 240:              emailSender.Name = EntityName.systemuser.ToString();

 241:           }

 242:           else

 243:           {

 244:              // If no system user was found, we cannot continue with bulk e-mail.

 245:              throw (new Exception("No system user found to send e-mail."));

 246:           }

 247:           

 248:           return emailSender;

 249:        }

 250:     }

 251:  }

Route an Incident from a User to a Queue

The following code example demonstrates how to route an incident from a user's work-in-progress queue to another queue.

The following code example shows how to route an incident from a user's Work In Progress (WIP) queue into a public queue. Similar code could be used to route an incident from a public queue into a WIP queue.



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

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

public static bool Run(string crmServerUrl, string orgName)
{
bool success = false;

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

// Get the ID of the system user.
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

#region Setup Data Required for this Sample
// Create a new customer account.
account myAccount = new account();
myAccount.name = "A Bike Store";
Guid accountID = service.Create(myAccount);

// Create a new subject.
subject mySubject = new subject();
mySubject.title = "Bicycles";
Guid subjectID = service.Create(mySubject);

// Create a new incident.
incident incident = new incident();

Customer myCustomer = new Customer();
myCustomer.Value = accountID;
myCustomer.type = EntityName.account.ToString();
incident.customerid = myCustomer;

Lookup subjectLookup = new Lookup();
subjectLookup.Value = subjectID;
subjectLookup.type = EntityName.subject.ToString();
incident.subjectid = subjectLookup;

incident.title = "Broken Chain";
Guid incidentID = service.Create(incident);

// Create a new public Bicycle Cases queue.
queue publicQueue = new queue();

Lookup businessLookup = new Lookup();
businessLookup.Value = user.BusinessUnitId;
businessLookup.type = EntityName.businessunit.ToString();
publicQueue.businessunitid = businessLookup;

Lookup userLookup = new Lookup();
userLookup.Value = user.UserId;
userLookup.type = EntityName.systemuser.ToString();
publicQueue.primaryuserid = userLookup;

Picklist plist = new Picklist();
plist.name = "Public";
plist.Value = 1;
publicQueue.queuetypecode = plist;

publicQueue.name = "Bicycle Cases";
Guid publicQueueID = service.Create(publicQueue);
#endregion

// Find the WIP queue for the user who currently owns the incident.
// The queue type code for a WIP queue is 3.
QueryByAttribute query = new QueryByAttribute();
// 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.
query.ColumnSet = new AllColumns();
query.EntityName = EntityName.queue.ToString();
query.Attributes = new string[] { "primaryuserid", "queuetypecode" };
query.Values = new string[] { user.UserId.ToString(), "3" };
BusinessEntityCollection results = service.RetrieveMultiple(query);

queue wipQueue = (queue)results.BusinessEntities[0];

// Create a Target object that refers to the incident.
TargetQueuedIncident target = new TargetQueuedIncident();
// SDK:target.EntityId = new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC");
target.EntityId = incidentID;

// Route the incident from the WIP queue to the public queue.
RouteRequest route = new RouteRequest();
route.Target = target;
route.RouteType = RouteType.Queue;
// SDK:route.EndpointId = new Guid("A0F2D8FE-6468-DA11-C748-000D9DD8CDAC");
route.EndpointId = publicQueueID;
// SDK:route.SourceQueueId = new Guid("A0F2D8FE-6468-DA11-D748-000D9DD8CDAC");
route.SourceQueueId = wipQueue.queueid.Value;

RouteResponse routed = null;
routed = (RouteResponse)service.Execute(route);

#region check success

if (routed != null) success = true;

#endregion

#region Remove Data Required for this Sample

service.Delete(EntityName.incident.ToString(), incidentID);
service.Delete(EntityName.queue.ToString(), publicQueueID);
service.Delete(EntityName.subject.ToString(), subjectID);
service.Delete(EntityName.account.ToString(), accountID);

#endregion
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(String.Format("{0}. {1}", ex.Message, ex.Detail.InnerText));
}

return success;
}
}
}