This documentation is archived and is not being maintained.

Schedule a Resource

Dynamics
banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

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.

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\Entities\ServiceManagement.cs
Server\HowTo\VB\Entities\ServiceManagement.vb

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

Example

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

namespace Microsoft.Crm.Sdk.HowTo
{
   /// <summary>
   /// This sample shows how to schedule a resource.
   /// </summary>
   public class ServiceManagement
   {
      public static bool Run(string crmServerUrl, string orgName)
      {
         // Set up the CRM Service.
         CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

         #region Setup Data Required for this Sample
         bool success = false;

         #endregion

         try
         {
            // Get the current user's information.
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse user = (WhoAmIResponse) service.Execute(userRequest);

            // Create the van resource.
            equipment van = new equipment();
            van.name = "Van 1";
            van.timezonecode = new CrmNumber();
            van.timezonecode.Value = 1;
            van.businessunitid = new Lookup();
            van.businessunitid.type = EntityName.businessunit.ToString();
            van.businessunitid.Value = user.BusinessUnitId;

            // Create the van object.
            Guid vanId = service.Create(van);

            // Create the plumber resource group.
            constraintbasedgroup group = new constraintbasedgroup();
            group.businessunitid = new Lookup();
            group.businessunitid.type = EntityName.businessunit.ToString();
            group.businessunitid.Value = user.BusinessUnitId;
            group.name = "Plumber with Van 1";
            System.Text.StringBuilder builder = new System.Text.StringBuilder("<Constraints>");
            builder.Append("<Constraint>");
            builder.Append("<Expression>");
            builder.Append("<Body>resource[\"Id\"] == ");
            builder.Append(user.UserId.ToString("B"));
            builder.Append(" || resource[\"Id\"] == ");
            builder.Append(vanId.ToString("B"));
            builder.Append("</Body>");
            builder.Append("<Parameters>");
            builder.Append("<Parameter name=\"resource\" />");
            builder.Append("</Parameters>");
            builder.Append("</Expression>");
            builder.Append("</Constraint>");
            builder.Append("</Constraints>");
            group.constraints = builder.ToString();
            group.grouptypecode = new Picklist();
            group.grouptypecode.Value = 0;

            Guid groupId = service.Create(group);

            // Create the resource specification.
            resourcespec spec = new resourcespec();
            spec.businessunitid = new Lookup();
            spec.businessunitid.type = EntityName.businessunit.ToString();
            spec.businessunitid.Value = user.BusinessUnitId;
            spec.objectiveexpression = @"
               <Expression>
                  <Body>udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)</Body>
                  <Parameters>
                     <Parameter name=""factory"" />
                     <Parameter name=""resource"" />
                     <Parameter name=""appointment"" />
                     <Parameter name=""request"" />
                     <Parameter name=""leftoffset"" />
                     <Parameter name=""rightoffset"" />
                  </Parameters>
                  <Properties EvaluationInterval=""P0D"" evaluationcost=""0"" />
               </Expression>";
            spec.requiredcount = new CrmNumber();
            spec.requiredcount.Value = 1;
            spec.name = "Test Spec";
            spec.groupobjectid = new UniqueIdentifier();
            spec.groupobjectid.Value = groupId;

            Guid specId = service.Create(spec);

            // Create the plumber required resource object.
            RequiredResource plumberReq = new RequiredResource();
            plumberReq.ResourceId = user.UserId;// assume current user is the plumber
            plumberReq.ResourceSpecId = specId;

            // Create the van required resource object.
            RequiredResource vanReq = new RequiredResource();
            vanReq.ResourceId = vanId;
            vanReq.ResourceSpecId = specId;

            // Create the service.
            service plumberService = new service();
            plumberService.name = "Plumber1";
            plumberService.duration = new CrmNumber();
            plumberService.duration.Value = 60;
            plumberService.initialstatuscode = new Status();
            plumberService.initialstatuscode.Value = 1;
            plumberService.granularity = "FREQ=MINUTELY;INTERVAL=15;";
            plumberService.resourcespecid = new Lookup();
            plumberService.resourcespecid.type = EntityName.resourcespec.ToString();
            plumberService.resourcespecid.Value = specId;
            plumberService.strategyid = new Lookup();
            // This is a known GUID for the default strategy.
            plumberService.strategyid.Value = new Guid("07F7DC72-1671-452D-812C-7172D3CA881F");
            
            Guid plumberServiceId = service.Create(plumberService);

            // Create the appointment request.
            AppointmentRequest appointmentReq = new AppointmentRequest();
            appointmentReq.RequiredResources = new RequiredResource[] {vanReq};
            appointmentReq.Direction = SearchDirection.Forward;
            appointmentReq.Duration = 60;
            appointmentReq.NumberOfResults = 10;
            appointmentReq.NumberOfResults = 1;
            appointmentReq.ServiceId = plumberServiceId;

            // The search window describes the time when the resouce can be scheduled.
            // It must be set.
            appointmentReq.SearchWindowStart = new CrmDateTime();
            appointmentReq.SearchWindowStart.Value = DateTime.Now.ToUniversalTime().ToString();
            appointmentReq.SearchWindowEnd = new CrmDateTime();
            appointmentReq.SearchWindowEnd.Value = DateTime.Now.AddDays(7).ToUniversalTime().ToString();
            appointmentReq.UserTimeZoneCode = 1;

            // Create the request object.
            SearchRequest search = new SearchRequest();

            // Set the properties of the request object.
            search.AppointmentRequest = appointmentReq;

            // Execute the request.
            SearchResponse searched = (SearchResponse)service.Execute(search);

            #region check success

            if (searched.SearchResults.Proposals.Length > 0)
            {
               success = true;
            }

            #endregion

            #region Remove Data Required for this Sample

            service.Delete(EntityName.service.ToString(), plumberServiceId);
            service.Delete(EntityName.equipment.ToString(), vanId);
               
            #endregion
         }
         catch (System.Web.Services.Protocols.SoapException ex)
         {
            // Add your error handling code here.
            Console.WriteLine(ex.Detail.InnerText);
            success = false;
         }

         return success;
      }
   }
}
[Visual Basic .NET]
Imports Microsoft.VisualBasic
Imports System
Imports CrmSdk
Imports Microsoft.Crm.Sdk.Utility

Namespace Microsoft.Crm.Sdk.HowTo
   ''' <summary>
   ''' This sample shows how to schedule a resource.
   ''' </summary>
    Public Class ServiceManagement
        Shared Sub Main(ByVal args() As String)
            ' TODO: Change the server URL and Organization to match your CRM Server and CRM Organization
            ServiceManagement.Run("http://localhost:5555", "CRM_Organization")
        End Sub

        Public Shared Function Run(ByVal crmServerUrl As String, ByVal orgName As String) As Boolean
            ' Set up the CRM Service.
            Dim service As CrmService = CrmServiceUtility.GetCrmService(crmServerUrl, orgName)

            '         #Region "Setup Data Required for this Sample"
            Dim success As Boolean = False

            '         #End Region

            Try
                ' Get the current user's information.
                Dim userRequest As New WhoAmIRequest()
                Dim user As WhoAmIResponse = CType(service.Execute(userRequest), WhoAmIResponse)

                ' Create the van resource.
                Dim van As New equipment()
                van.name = "Van 1"
                van.timezonecode = New CrmNumber()
                van.timezonecode.Value = 1
                van.businessunitid = New Lookup()
                van.businessunitid.type = EntityName.businessunit.ToString()
                van.businessunitid.Value = user.BusinessUnitId

                ' Create the van object.
                Dim vanId As Guid = service.Create(van)

                ' Create the plumber resource group.
                Dim group As New constraintbasedgroup()
                group.businessunitid = New Lookup()
                group.businessunitid.type = EntityName.businessunit.ToString()
                group.businessunitid.Value = user.BusinessUnitId
                group.name = "Plumber with Van 1"
                Dim builder As New System.Text.StringBuilder("<Constraints>")
                builder.Append("<Constraint>")
                builder.Append("<Expression>")
                builder.Append("<Body>resource[""Id""] == ")
                builder.Append(user.UserId.ToString("B"))
                builder.Append(" || resource[""Id""] == ")
                builder.Append(vanId.ToString("B"))
                builder.Append("</Body>")
                builder.Append("<Parameters>")
                builder.Append("<Parameter name=""resource"" />")
                builder.Append("</Parameters>")
                builder.Append("</Expression>")
                builder.Append("</Constraint>")
                builder.Append("</Constraints>")
                group.constraints = builder.ToString()
                group.grouptypecode = New Picklist()
                group.grouptypecode.Value = 0

                Dim groupId As Guid = service.Create(group)

                ' Create the resource specification.
                Dim spec As New resourcespec()
                spec.businessunitid = New Lookup()
                spec.businessunitid.type = EntityName.businessunit.ToString()
                spec.businessunitid.Value = user.BusinessUnitId
                spec.objectiveexpression = "" & ControlChars.CrLf & "<Expression>" & ControlChars.CrLf & "<Body>udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)</Body>" & ControlChars.CrLf & "<Parameters>" & ControlChars.CrLf & "<Parameter name=""factory"" />" & ControlChars.CrLf & "<Parameter name=""resource"" />" & ControlChars.CrLf & "<Parameter name=""appointment"" />" & ControlChars.CrLf & "<Parameter name=""request"" />" & ControlChars.CrLf & "<Parameter name=""leftoffset"" />" & ControlChars.CrLf & "<Parameter name=""rightoffset"" />" & ControlChars.CrLf & "</Parameters>" & ControlChars.CrLf & "<Properties EvaluationInterval=""P0D"" evaluationcost=""0"" />" & ControlChars.CrLf & "</Expression>"
                spec.requiredcount = New CrmNumber()
                spec.requiredcount.Value = 1
                spec.name = "Test Spec"
                spec.groupobjectid = New UniqueIdentifier()
                spec.groupobjectid.Value = groupId

                Dim specId As Guid = service.Create(spec)

                ' Create the plumber required resource object.
                Dim plumberReq As New RequiredResource()
                plumberReq.ResourceId = user.UserId ' assume current user is the plumber
                plumberReq.ResourceSpecId = specId

                ' Create the van required resource object.
                Dim vanReq As New RequiredResource()
                vanReq.ResourceId = vanId
                vanReq.ResourceSpecId = specId

                ' Create the service.
                Dim plumberService As New service()
                plumberService.name = "Plumber1"
                plumberService.duration = New CrmNumber()
                plumberService.duration.Value = 60
                plumberService.initialstatuscode = New Status()
                plumberService.initialstatuscode.Value = 1
                plumberService.granularity = "FREQ=MINUTELY;INTERVAL=15;"
                plumberService.resourcespecid = New Lookup()
                plumberService.resourcespecid.type = EntityName.resourcespec.ToString()
                plumberService.resourcespecid.Value = specId
                plumberService.strategyid = New Lookup()
                ' This is a known GUID for the default strategy.
                plumberService.strategyid.Value = New Guid("07F7DC72-1671-452D-812C-7172D3CA881F")

                Dim plumberServiceId As Guid = service.Create(plumberService)

                ' Create the appointment request.
                Dim appointmentReq As New AppointmentRequest()
                appointmentReq.RequiredResources = New RequiredResource() {vanReq}
                appointmentReq.Direction = SearchDirection.Forward
                appointmentReq.Duration = 60
                appointmentReq.NumberOfResults = 10
                appointmentReq.NumberOfResults = 1
                appointmentReq.ServiceId = plumberServiceId

                ' The search window describes the time when the resouce can be scheduled.
                ' It must be set.
                appointmentReq.SearchWindowStart = New CrmDateTime()
                appointmentReq.SearchWindowStart.Value = DateTime.Now.ToUniversalTime().ToString()
                appointmentReq.SearchWindowEnd = New CrmDateTime()
                appointmentReq.SearchWindowEnd.Value = DateTime.Now.AddDays(7).ToUniversalTime().ToString()
                appointmentReq.UserTimeZoneCode = 1

                ' Create the request object.
                Dim search As New SearchRequest()

                ' Set the properties of the request object.
                search.AppointmentRequest = appointmentReq

                ' Execute the request.
                Dim searched As SearchResponse = CType(service.Execute(search), SearchResponse)

                '            #Region "check success"

                If searched.SearchResults.Proposals.Length > 0 Then
                    success = True
                End If

                '            #End Region

                '            #Region "Remove Data Required for this Sample"

                service.Delete(EntityName.service.ToString(), plumberServiceId)
                service.Delete(EntityName.equipment.ToString(), vanId)

                '            #End Region
            Catch ex As System.Web.Services.Protocols.SoapException
                ' Add your error handling code here.
                Console.WriteLine(ex.Detail.InnerText)
                success = False
            End Try

            Return success
        End Function
    End Class
End Namespace

See Also

Reference


© 2010 Microsoft Corporation. All rights reserved.


Show: