Skip to contentSkip to navigationSkip to topbar
On this page

Dynamic Call Center with C# and ASP.NET MVC


In this tutorial we will show how to automate the routing of calls from customers to your support agents. In this example customers would select a product, then be connected to a specialist for that product. If no one is available our customer's number will be saved so that our agent can call them back.


This is what the application does at a high level

this-is-what-the-application-does-at-a-high-level page anchor
  • Configure a workspace using the Twilio TaskRouter REST API.
  • Listen for incoming calls and let the user select a product with the dial pad.
  • Create a Task with the selected product and let TaskRouter handle it.
  • Store missed calls so agents can return the call to customers.
  • Redirect users to a voice mail when no one answers the call.
  • Allow agents to change their status (Available/Offline) via SMS.

In order to instruct TaskRouter to handle the Tasks, we need to configure a Workspace. We can do this in the TaskRouter Console(link takes you to an external page) or programmatically using the TaskRouter REST API.

In this ASP.NET MVC application this step will be executed in the Application_Start event every time you run the app.

A Workspace is the container element for any TaskRouter application. The elements are:

  • Tasks - Represents a customer trying to contact an agent
  • Workers - The agents responsible for handling Tasks
  • Task Queues - Holds Tasks to be consumed by a set of Workers
  • Workflows - Responsible for placing Tasks into Task Queues
  • Activities - Possible states of a Worker. Eg: idle, offline, busy

We'll use a TaskRouterClient provided in the twilio-csharp(link takes you to an external page) helper library to create and configure the workspace.

Create, Setup and Configure the Workspace

create-setup-and-configure-the-workspace page anchor

TaskRouter.Web/App_Start/WorkspaceConfig.cs

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Web.Helpers;
5
using TaskRouter.Web.Infrastructure;
6
using Twilio;
7
using Twilio.Rest.Taskrouter.V1;
8
using Twilio.Rest.Taskrouter.V1.Workspace;
9
10
namespace TaskRouter.Web
11
{
12
public class WorkspaceConfig
13
{
14
private readonly Config _config;
15
16
private const string VoiceQueue = "VoiceQueue";
17
private const string SmsQueue = "SMSQueue";
18
private const string AllQueue = "AllQueue";
19
20
public static void RegisterWorkspace()
21
{
22
new WorkspaceConfig().Register();
23
}
24
25
public WorkspaceConfig():this(new Config())
26
{
27
}
28
29
public WorkspaceConfig(Config config)
30
{
31
TwilioClient.Init(config.AccountSID, config.AuthToken);
32
_config = config;
33
34
}
35
36
public WorkspaceConfig(Type workspaceResource):this()
37
{
38
}
39
40
public virtual ActivityResource GetActivityByFriendlyName(string workspaceSid, string friendlyName)
41
{
42
return ActivityResource.Read(workspaceSid, friendlyName).First();
43
}
44
45
public virtual ActivityResource CreateActivityWithFriendlyName(string workspaceSid, string friendlyName)
46
{
47
return ActivityResource.Create(workspaceSid, friendlyName);
48
}
49
50
public virtual WorkspaceResource GetWorkspaceByFriendlyName(string friendlyName)
51
{
52
return WorkspaceResource.Read(friendlyName).FirstOrDefault();
53
}
54
55
public virtual WorkspaceResource CreateWorkspace(string friendlyName, Uri eventCallbackUrl)
56
{
57
return WorkspaceResource.Create(friendlyName, eventCallbackUrl);
58
}
59
60
public virtual bool DeleteWorkspace(string workspaceSid)
61
{
62
return WorkspaceResource.Delete(workspaceSid);
63
}
64
65
public virtual WorkerResource CreateWorker(string workspaceSid, string bob, string activitySid, string attributes)
66
{
67
return WorkerResource.Create(workspaceSid, bob, activitySid, attributes);
68
}
69
70
public void Register()
71
{
72
var workspace = DeleteAndCreateWorkspace(
73
"Twilio Workspace", new Uri(new Uri(_config.HostUrl), "/callback/events").AbsoluteUri);
74
var workspaceSid = workspace.Sid;
75
76
var assignmentActivity = GetActivityByFriendlyName(workspaceSid, "Unavailable");
77
var idleActivity = GetActivityByFriendlyName(workspaceSid, "Available");
78
var reservationActivity = CreateActivityWithFriendlyName(workspaceSid, "Reserved");
79
var offlineActivity = GetActivityByFriendlyName(workspaceSid, "Offline");
80
81
var workers = CreateWorkers(workspaceSid, idleActivity);
82
var taskQueues = CreateTaskQueues(workspaceSid, assignmentActivity, reservationActivity);
83
var workflow = CreateWorkflow(workspaceSid, taskQueues);
84
85
Singleton.Instance.WorkspaceSid = workspaceSid;
86
Singleton.Instance.WorkflowSid = workflow.Sid;
87
Singleton.Instance.Workers = workers;
88
Singleton.Instance.PostWorkActivitySid = idleActivity.Sid;
89
Singleton.Instance.IdleActivitySid = idleActivity.Sid;
90
Singleton.Instance.OfflineActivitySid = offlineActivity.Sid;
91
}
92
93
public virtual WorkspaceResource DeleteAndCreateWorkspace(string friendlyName, string eventCallbackUrl) {
94
var workspace = GetWorkspaceByFriendlyName(friendlyName);
95
if (workspace != null)
96
{
97
DeleteWorkspace(workspace.Sid);
98
}
99
100
return CreateWorkspace(friendlyName, new Uri(eventCallbackUrl));
101
}
102
103
private IDictionary<string, string> CreateWorkers(string workspaceSid, ActivityResource activity)
104
{
105
var attributesForBob = new
106
{
107
products = new List<object>()
108
{
109
"ProgrammableSMS"
110
},
111
contact_uri = _config.AgentForProgrammableSMS
112
};
113
114
var bobWorker = CreateWorker(workspaceSid, "Bob", activity.Sid, Json.Encode(attributesForBob));
115
116
var attributesForAlice = new
117
{
118
products = new List<object>()
119
{
120
"ProgrammableVoice"
121
},
122
contact_uri = _config.AgentForProgrammableVoice
123
};
124
125
var alice = CreateWorker(workspaceSid, "Alice", activity.Sid, Json.Encode(attributesForAlice));
126
127
return new Dictionary<string, string>
128
{
129
{ _config.AgentForProgrammableSMS, bobWorker.Sid },
130
{ _config.AgentForProgrammableVoice, alice.Sid },
131
};
132
}
133
134
public virtual TaskQueueResource CreateTaskQueue(
135
string workspaceSid, string friendlyName,
136
string assignmentActivitySid, string reservationActivitySid, string targetWorkers)
137
{
138
var queue = TaskQueueResource.Create(
139
workspaceSid,
140
friendlyName: friendlyName,
141
assignmentActivitySid: assignmentActivitySid,
142
reservationActivitySid: reservationActivitySid
143
);
144
145
TaskQueueResource.Update(
146
workspaceSid,
147
queue.Sid,
148
friendlyName,
149
targetWorkers,
150
assignmentActivitySid,
151
reservationActivitySid,
152
1);
153
154
return queue;
155
}
156
157
private IDictionary<string, TaskQueueResource> CreateTaskQueues(
158
string workspaceSid, ActivityResource assignmentActivity, ActivityResource reservationActivity)
159
{
160
161
var voiceQueue = CreateTaskQueue(
162
workspaceSid, "Voice",
163
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableVoice'");
164
165
var smsQueue = CreateTaskQueue(
166
workspaceSid, "SMS",
167
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableSMS'");
168
169
var allQueue = CreateTaskQueue(
170
workspaceSid, "All",
171
assignmentActivity.Sid, reservationActivity.Sid, "1 == 1");
172
173
return new Dictionary<string, TaskQueueResource> {
174
{ VoiceQueue, voiceQueue },
175
{ SmsQueue, smsQueue },
176
{ AllQueue, allQueue }
177
};
178
}
179
180
public virtual WorkflowResource CreateWorkflow(string workspaceSid, IDictionary<string, TaskQueueResource> taskQueues)
181
{
182
var voiceQueue = taskQueues[VoiceQueue];
183
var smsQueue = taskQueues[SmsQueue];
184
var allQueue = taskQueues[AllQueue];
185
186
var voiceFilter = new {
187
friendlyName = "Voice",
188
expression = "selected_product==\"ProgrammableVoice\"",
189
targets = new List<object>() {
190
new { queue = voiceQueue.Sid, Priority = "5", Timeout = "30" },
191
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
192
}
193
};
194
195
var smsFilter = new {
196
friendlyName = "SMS",
197
expression = "selected_product==\"ProgrammableSMS\"",
198
targets = new List<object>() {
199
new { queue = smsQueue.Sid, Priority = "5", Timeout = "30" },
200
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
201
}
202
};
203
204
var workflowConfiguration = new
205
{
206
task_routing = new
207
{
208
filters = new List<object>()
209
{
210
voiceFilter,
211
smsFilter
212
},
213
default_filter = new
214
{
215
queue = allQueue.Sid,
216
expression = "1==1",
217
priority = "1",
218
timeout = "30"
219
}
220
}
221
};
222
223
// Call REST API
224
return WorkflowResource.Create(
225
workspaceSid,
226
"Tech Support",
227
Json.Encode(workflowConfiguration),
228
new Uri($"{_config.HostUrl}/callback/assignment"),
229
new Uri($"{_config.HostUrl}/callback/assignment"),
230
15);
231
}
232
}
233
}

Now let's look in more detail at all the steps, starting with the creation of the workspace itself.


Before creating a workspace, we need to delete any others with the same friendlyName as the one we are trying to create. In order to create a workspace we need to provide a friendlyName and a eventCallbackUrl where a requests will be made every time an event is triggered in our workspace.

TaskRouter.Web/App_Start/WorkspaceConfig.cs

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Web.Helpers;
5
using TaskRouter.Web.Infrastructure;
6
using Twilio;
7
using Twilio.Rest.Taskrouter.V1;
8
using Twilio.Rest.Taskrouter.V1.Workspace;
9
10
namespace TaskRouter.Web
11
{
12
public class WorkspaceConfig
13
{
14
private readonly Config _config;
15
16
private const string VoiceQueue = "VoiceQueue";
17
private const string SmsQueue = "SMSQueue";
18
private const string AllQueue = "AllQueue";
19
20
public static void RegisterWorkspace()
21
{
22
new WorkspaceConfig().Register();
23
}
24
25
public WorkspaceConfig():this(new Config())
26
{
27
}
28
29
public WorkspaceConfig(Config config)
30
{
31
TwilioClient.Init(config.AccountSID, config.AuthToken);
32
_config = config;
33
34
}
35
36
public WorkspaceConfig(Type workspaceResource):this()
37
{
38
}
39
40
public virtual ActivityResource GetActivityByFriendlyName(string workspaceSid, string friendlyName)
41
{
42
return ActivityResource.Read(workspaceSid, friendlyName).First();
43
}
44
45
public virtual ActivityResource CreateActivityWithFriendlyName(string workspaceSid, string friendlyName)
46
{
47
return ActivityResource.Create(workspaceSid, friendlyName);
48
}
49
50
public virtual WorkspaceResource GetWorkspaceByFriendlyName(string friendlyName)
51
{
52
return WorkspaceResource.Read(friendlyName).FirstOrDefault();
53
}
54
55
public virtual WorkspaceResource CreateWorkspace(string friendlyName, Uri eventCallbackUrl)
56
{
57
return WorkspaceResource.Create(friendlyName, eventCallbackUrl);
58
}
59
60
public virtual bool DeleteWorkspace(string workspaceSid)
61
{
62
return WorkspaceResource.Delete(workspaceSid);
63
}
64
65
public virtual WorkerResource CreateWorker(string workspaceSid, string bob, string activitySid, string attributes)
66
{
67
return WorkerResource.Create(workspaceSid, bob, activitySid, attributes);
68
}
69
70
public void Register()
71
{
72
var workspace = DeleteAndCreateWorkspace(
73
"Twilio Workspace", new Uri(new Uri(_config.HostUrl), "/callback/events").AbsoluteUri);
74
var workspaceSid = workspace.Sid;
75
76
var assignmentActivity = GetActivityByFriendlyName(workspaceSid, "Unavailable");
77
var idleActivity = GetActivityByFriendlyName(workspaceSid, "Available");
78
var reservationActivity = CreateActivityWithFriendlyName(workspaceSid, "Reserved");
79
var offlineActivity = GetActivityByFriendlyName(workspaceSid, "Offline");
80
81
var workers = CreateWorkers(workspaceSid, idleActivity);
82
var taskQueues = CreateTaskQueues(workspaceSid, assignmentActivity, reservationActivity);
83
var workflow = CreateWorkflow(workspaceSid, taskQueues);
84
85
Singleton.Instance.WorkspaceSid = workspaceSid;
86
Singleton.Instance.WorkflowSid = workflow.Sid;
87
Singleton.Instance.Workers = workers;
88
Singleton.Instance.PostWorkActivitySid = idleActivity.Sid;
89
Singleton.Instance.IdleActivitySid = idleActivity.Sid;
90
Singleton.Instance.OfflineActivitySid = offlineActivity.Sid;
91
}
92
93
public virtual WorkspaceResource DeleteAndCreateWorkspace(string friendlyName, string eventCallbackUrl) {
94
var workspace = GetWorkspaceByFriendlyName(friendlyName);
95
if (workspace != null)
96
{
97
DeleteWorkspace(workspace.Sid);
98
}
99
100
return CreateWorkspace(friendlyName, new Uri(eventCallbackUrl));
101
}
102
103
private IDictionary<string, string> CreateWorkers(string workspaceSid, ActivityResource activity)
104
{
105
var attributesForBob = new
106
{
107
products = new List<object>()
108
{
109
"ProgrammableSMS"
110
},
111
contact_uri = _config.AgentForProgrammableSMS
112
};
113
114
var bobWorker = CreateWorker(workspaceSid, "Bob", activity.Sid, Json.Encode(attributesForBob));
115
116
var attributesForAlice = new
117
{
118
products = new List<object>()
119
{
120
"ProgrammableVoice"
121
},
122
contact_uri = _config.AgentForProgrammableVoice
123
};
124
125
var alice = CreateWorker(workspaceSid, "Alice", activity.Sid, Json.Encode(attributesForAlice));
126
127
return new Dictionary<string, string>
128
{
129
{ _config.AgentForProgrammableSMS, bobWorker.Sid },
130
{ _config.AgentForProgrammableVoice, alice.Sid },
131
};
132
}
133
134
public virtual TaskQueueResource CreateTaskQueue(
135
string workspaceSid, string friendlyName,
136
string assignmentActivitySid, string reservationActivitySid, string targetWorkers)
137
{
138
var queue = TaskQueueResource.Create(
139
workspaceSid,
140
friendlyName: friendlyName,
141
assignmentActivitySid: assignmentActivitySid,
142
reservationActivitySid: reservationActivitySid
143
);
144
145
TaskQueueResource.Update(
146
workspaceSid,
147
queue.Sid,
148
friendlyName,
149
targetWorkers,
150
assignmentActivitySid,
151
reservationActivitySid,
152
1);
153
154
return queue;
155
}
156
157
private IDictionary<string, TaskQueueResource> CreateTaskQueues(
158
string workspaceSid, ActivityResource assignmentActivity, ActivityResource reservationActivity)
159
{
160
161
var voiceQueue = CreateTaskQueue(
162
workspaceSid, "Voice",
163
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableVoice'");
164
165
var smsQueue = CreateTaskQueue(
166
workspaceSid, "SMS",
167
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableSMS'");
168
169
var allQueue = CreateTaskQueue(
170
workspaceSid, "All",
171
assignmentActivity.Sid, reservationActivity.Sid, "1 == 1");
172
173
return new Dictionary<string, TaskQueueResource> {
174
{ VoiceQueue, voiceQueue },
175
{ SmsQueue, smsQueue },
176
{ AllQueue, allQueue }
177
};
178
}
179
180
public virtual WorkflowResource CreateWorkflow(string workspaceSid, IDictionary<string, TaskQueueResource> taskQueues)
181
{
182
var voiceQueue = taskQueues[VoiceQueue];
183
var smsQueue = taskQueues[SmsQueue];
184
var allQueue = taskQueues[AllQueue];
185
186
var voiceFilter = new {
187
friendlyName = "Voice",
188
expression = "selected_product==\"ProgrammableVoice\"",
189
targets = new List<object>() {
190
new { queue = voiceQueue.Sid, Priority = "5", Timeout = "30" },
191
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
192
}
193
};
194
195
var smsFilter = new {
196
friendlyName = "SMS",
197
expression = "selected_product==\"ProgrammableSMS\"",
198
targets = new List<object>() {
199
new { queue = smsQueue.Sid, Priority = "5", Timeout = "30" },
200
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
201
}
202
};
203
204
var workflowConfiguration = new
205
{
206
task_routing = new
207
{
208
filters = new List<object>()
209
{
210
voiceFilter,
211
smsFilter
212
},
213
default_filter = new
214
{
215
queue = allQueue.Sid,
216
expression = "1==1",
217
priority = "1",
218
timeout = "30"
219
}
220
}
221
};
222
223
// Call REST API
224
return WorkflowResource.Create(
225
workspaceSid,
226
"Tech Support",
227
Json.Encode(workflowConfiguration),
228
new Uri($"{_config.HostUrl}/callback/assignment"),
229
new Uri($"{_config.HostUrl}/callback/assignment"),
230
15);
231
}
232
}
233
}

We have a brand new workspace, now we need workers. Let's create them on the next step.


We'll create two workers: Bob and Alice. They each have two attributes: contact_uri a phone number and products, a list of products each worker is specialized in. We also need to specify an activity.Sid and a name for each worker. The selected activity will define the status of the worker.

A set of default activities is created with your workspace. We use the Idle activity to make a worker available for incoming calls.

TaskRouter.Web/App_Start/WorkspaceConfig.cs

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Web.Helpers;
5
using TaskRouter.Web.Infrastructure;
6
using Twilio;
7
using Twilio.Rest.Taskrouter.V1;
8
using Twilio.Rest.Taskrouter.V1.Workspace;
9
10
namespace TaskRouter.Web
11
{
12
public class WorkspaceConfig
13
{
14
private readonly Config _config;
15
16
private const string VoiceQueue = "VoiceQueue";
17
private const string SmsQueue = "SMSQueue";
18
private const string AllQueue = "AllQueue";
19
20
public static void RegisterWorkspace()
21
{
22
new WorkspaceConfig().Register();
23
}
24
25
public WorkspaceConfig():this(new Config())
26
{
27
}
28
29
public WorkspaceConfig(Config config)
30
{
31
TwilioClient.Init(config.AccountSID, config.AuthToken);
32
_config = config;
33
34
}
35
36
public WorkspaceConfig(Type workspaceResource):this()
37
{
38
}
39
40
public virtual ActivityResource GetActivityByFriendlyName(string workspaceSid, string friendlyName)
41
{
42
return ActivityResource.Read(workspaceSid, friendlyName).First();
43
}
44
45
public virtual ActivityResource CreateActivityWithFriendlyName(string workspaceSid, string friendlyName)
46
{
47
return ActivityResource.Create(workspaceSid, friendlyName);
48
}
49
50
public virtual WorkspaceResource GetWorkspaceByFriendlyName(string friendlyName)
51
{
52
return WorkspaceResource.Read(friendlyName).FirstOrDefault();
53
}
54
55
public virtual WorkspaceResource CreateWorkspace(string friendlyName, Uri eventCallbackUrl)
56
{
57
return WorkspaceResource.Create(friendlyName, eventCallbackUrl);
58
}
59
60
public virtual bool DeleteWorkspace(string workspaceSid)
61
{
62
return WorkspaceResource.Delete(workspaceSid);
63
}
64
65
public virtual WorkerResource CreateWorker(string workspaceSid, string bob, string activitySid, string attributes)
66
{
67
return WorkerResource.Create(workspaceSid, bob, activitySid, attributes);
68
}
69
70
public void Register()
71
{
72
var workspace = DeleteAndCreateWorkspace(
73
"Twilio Workspace", new Uri(new Uri(_config.HostUrl), "/callback/events").AbsoluteUri);
74
var workspaceSid = workspace.Sid;
75
76
var assignmentActivity = GetActivityByFriendlyName(workspaceSid, "Unavailable");
77
var idleActivity = GetActivityByFriendlyName(workspaceSid, "Available");
78
var reservationActivity = CreateActivityWithFriendlyName(workspaceSid, "Reserved");
79
var offlineActivity = GetActivityByFriendlyName(workspaceSid, "Offline");
80
81
var workers = CreateWorkers(workspaceSid, idleActivity);
82
var taskQueues = CreateTaskQueues(workspaceSid, assignmentActivity, reservationActivity);
83
var workflow = CreateWorkflow(workspaceSid, taskQueues);
84
85
Singleton.Instance.WorkspaceSid = workspaceSid;
86
Singleton.Instance.WorkflowSid = workflow.Sid;
87
Singleton.Instance.Workers = workers;
88
Singleton.Instance.PostWorkActivitySid = idleActivity.Sid;
89
Singleton.Instance.IdleActivitySid = idleActivity.Sid;
90
Singleton.Instance.OfflineActivitySid = offlineActivity.Sid;
91
}
92
93
public virtual WorkspaceResource DeleteAndCreateWorkspace(string friendlyName, string eventCallbackUrl) {
94
var workspace = GetWorkspaceByFriendlyName(friendlyName);
95
if (workspace != null)
96
{
97
DeleteWorkspace(workspace.Sid);
98
}
99
100
return CreateWorkspace(friendlyName, new Uri(eventCallbackUrl));
101
}
102
103
private IDictionary<string, string> CreateWorkers(string workspaceSid, ActivityResource activity)
104
{
105
var attributesForBob = new
106
{
107
products = new List<object>()
108
{
109
"ProgrammableSMS"
110
},
111
contact_uri = _config.AgentForProgrammableSMS
112
};
113
114
var bobWorker = CreateWorker(workspaceSid, "Bob", activity.Sid, Json.Encode(attributesForBob));
115
116
var attributesForAlice = new
117
{
118
products = new List<object>()
119
{
120
"ProgrammableVoice"
121
},
122
contact_uri = _config.AgentForProgrammableVoice
123
};
124
125
var alice = CreateWorker(workspaceSid, "Alice", activity.Sid, Json.Encode(attributesForAlice));
126
127
return new Dictionary<string, string>
128
{
129
{ _config.AgentForProgrammableSMS, bobWorker.Sid },
130
{ _config.AgentForProgrammableVoice, alice.Sid },
131
};
132
}
133
134
public virtual TaskQueueResource CreateTaskQueue(
135
string workspaceSid, string friendlyName,
136
string assignmentActivitySid, string reservationActivitySid, string targetWorkers)
137
{
138
var queue = TaskQueueResource.Create(
139
workspaceSid,
140
friendlyName: friendlyName,
141
assignmentActivitySid: assignmentActivitySid,
142
reservationActivitySid: reservationActivitySid
143
);
144
145
TaskQueueResource.Update(
146
workspaceSid,
147
queue.Sid,
148
friendlyName,
149
targetWorkers,
150
assignmentActivitySid,
151
reservationActivitySid,
152
1);
153
154
return queue;
155
}
156
157
private IDictionary<string, TaskQueueResource> CreateTaskQueues(
158
string workspaceSid, ActivityResource assignmentActivity, ActivityResource reservationActivity)
159
{
160
161
var voiceQueue = CreateTaskQueue(
162
workspaceSid, "Voice",
163
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableVoice'");
164
165
var smsQueue = CreateTaskQueue(
166
workspaceSid, "SMS",
167
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableSMS'");
168
169
var allQueue = CreateTaskQueue(
170
workspaceSid, "All",
171
assignmentActivity.Sid, reservationActivity.Sid, "1 == 1");
172
173
return new Dictionary<string, TaskQueueResource> {
174
{ VoiceQueue, voiceQueue },
175
{ SmsQueue, smsQueue },
176
{ AllQueue, allQueue }
177
};
178
}
179
180
public virtual WorkflowResource CreateWorkflow(string workspaceSid, IDictionary<string, TaskQueueResource> taskQueues)
181
{
182
var voiceQueue = taskQueues[VoiceQueue];
183
var smsQueue = taskQueues[SmsQueue];
184
var allQueue = taskQueues[AllQueue];
185
186
var voiceFilter = new {
187
friendlyName = "Voice",
188
expression = "selected_product==\"ProgrammableVoice\"",
189
targets = new List<object>() {
190
new { queue = voiceQueue.Sid, Priority = "5", Timeout = "30" },
191
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
192
}
193
};
194
195
var smsFilter = new {
196
friendlyName = "SMS",
197
expression = "selected_product==\"ProgrammableSMS\"",
198
targets = new List<object>() {
199
new { queue = smsQueue.Sid, Priority = "5", Timeout = "30" },
200
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
201
}
202
};
203
204
var workflowConfiguration = new
205
{
206
task_routing = new
207
{
208
filters = new List<object>()
209
{
210
voiceFilter,
211
smsFilter
212
},
213
default_filter = new
214
{
215
queue = allQueue.Sid,
216
expression = "1==1",
217
priority = "1",
218
timeout = "30"
219
}
220
}
221
};
222
223
// Call REST API
224
return WorkflowResource.Create(
225
workspaceSid,
226
"Tech Support",
227
Json.Encode(workflowConfiguration),
228
new Uri($"{_config.HostUrl}/callback/assignment"),
229
new Uri($"{_config.HostUrl}/callback/assignment"),
230
15);
231
}
232
}
233
}

After creating our workers, let's set up the Task Queues.


Next, we set up the Task Queues. Each with a friendlyName and a targetWorkers, which is an expression to match Workers. Our Task Queues are:

  1. SMS - Will target Workers specialized in Programmable SMS, such as Bob, using the expression "products HAS \"ProgrammableSMS\"".
  2. Voice - Will do the same for Programmable Voice Workers, such as Alice, using the expression "products HAS \"ProgrammableVoice\"".

TaskRouter.Web/App_Start/WorkspaceConfig.cs

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Web.Helpers;
5
using TaskRouter.Web.Infrastructure;
6
using Twilio;
7
using Twilio.Rest.Taskrouter.V1;
8
using Twilio.Rest.Taskrouter.V1.Workspace;
9
10
namespace TaskRouter.Web
11
{
12
public class WorkspaceConfig
13
{
14
private readonly Config _config;
15
16
private const string VoiceQueue = "VoiceQueue";
17
private const string SmsQueue = "SMSQueue";
18
private const string AllQueue = "AllQueue";
19
20
public static void RegisterWorkspace()
21
{
22
new WorkspaceConfig().Register();
23
}
24
25
public WorkspaceConfig():this(new Config())
26
{
27
}
28
29
public WorkspaceConfig(Config config)
30
{
31
TwilioClient.Init(config.AccountSID, config.AuthToken);
32
_config = config;
33
34
}
35
36
public WorkspaceConfig(Type workspaceResource):this()
37
{
38
}
39
40
public virtual ActivityResource GetActivityByFriendlyName(string workspaceSid, string friendlyName)
41
{
42
return ActivityResource.Read(workspaceSid, friendlyName).First();
43
}
44
45
public virtual ActivityResource CreateActivityWithFriendlyName(string workspaceSid, string friendlyName)
46
{
47
return ActivityResource.Create(workspaceSid, friendlyName);
48
}
49
50
public virtual WorkspaceResource GetWorkspaceByFriendlyName(string friendlyName)
51
{
52
return WorkspaceResource.Read(friendlyName).FirstOrDefault();
53
}
54
55
public virtual WorkspaceResource CreateWorkspace(string friendlyName, Uri eventCallbackUrl)
56
{
57
return WorkspaceResource.Create(friendlyName, eventCallbackUrl);
58
}
59
60
public virtual bool DeleteWorkspace(string workspaceSid)
61
{
62
return WorkspaceResource.Delete(workspaceSid);
63
}
64
65
public virtual WorkerResource CreateWorker(string workspaceSid, string bob, string activitySid, string attributes)
66
{
67
return WorkerResource.Create(workspaceSid, bob, activitySid, attributes);
68
}
69
70
public void Register()
71
{
72
var workspace = DeleteAndCreateWorkspace(
73
"Twilio Workspace", new Uri(new Uri(_config.HostUrl), "/callback/events").AbsoluteUri);
74
var workspaceSid = workspace.Sid;
75
76
var assignmentActivity = GetActivityByFriendlyName(workspaceSid, "Unavailable");
77
var idleActivity = GetActivityByFriendlyName(workspaceSid, "Available");
78
var reservationActivity = CreateActivityWithFriendlyName(workspaceSid, "Reserved");
79
var offlineActivity = GetActivityByFriendlyName(workspaceSid, "Offline");
80
81
var workers = CreateWorkers(workspaceSid, idleActivity);
82
var taskQueues = CreateTaskQueues(workspaceSid, assignmentActivity, reservationActivity);
83
var workflow = CreateWorkflow(workspaceSid, taskQueues);
84
85
Singleton.Instance.WorkspaceSid = workspaceSid;
86
Singleton.Instance.WorkflowSid = workflow.Sid;
87
Singleton.Instance.Workers = workers;
88
Singleton.Instance.PostWorkActivitySid = idleActivity.Sid;
89
Singleton.Instance.IdleActivitySid = idleActivity.Sid;
90
Singleton.Instance.OfflineActivitySid = offlineActivity.Sid;
91
}
92
93
public virtual WorkspaceResource DeleteAndCreateWorkspace(string friendlyName, string eventCallbackUrl) {
94
var workspace = GetWorkspaceByFriendlyName(friendlyName);
95
if (workspace != null)
96
{
97
DeleteWorkspace(workspace.Sid);
98
}
99
100
return CreateWorkspace(friendlyName, new Uri(eventCallbackUrl));
101
}
102
103
private IDictionary<string, string> CreateWorkers(string workspaceSid, ActivityResource activity)
104
{
105
var attributesForBob = new
106
{
107
products = new List<object>()
108
{
109
"ProgrammableSMS"
110
},
111
contact_uri = _config.AgentForProgrammableSMS
112
};
113
114
var bobWorker = CreateWorker(workspaceSid, "Bob", activity.Sid, Json.Encode(attributesForBob));
115
116
var attributesForAlice = new
117
{
118
products = new List<object>()
119
{
120
"ProgrammableVoice"
121
},
122
contact_uri = _config.AgentForProgrammableVoice
123
};
124
125
var alice = CreateWorker(workspaceSid, "Alice", activity.Sid, Json.Encode(attributesForAlice));
126
127
return new Dictionary<string, string>
128
{
129
{ _config.AgentForProgrammableSMS, bobWorker.Sid },
130
{ _config.AgentForProgrammableVoice, alice.Sid },
131
};
132
}
133
134
public virtual TaskQueueResource CreateTaskQueue(
135
string workspaceSid, string friendlyName,
136
string assignmentActivitySid, string reservationActivitySid, string targetWorkers)
137
{
138
var queue = TaskQueueResource.Create(
139
workspaceSid,
140
friendlyName: friendlyName,
141
assignmentActivitySid: assignmentActivitySid,
142
reservationActivitySid: reservationActivitySid
143
);
144
145
TaskQueueResource.Update(
146
workspaceSid,
147
queue.Sid,
148
friendlyName,
149
targetWorkers,
150
assignmentActivitySid,
151
reservationActivitySid,
152
1);
153
154
return queue;
155
}
156
157
private IDictionary<string, TaskQueueResource> CreateTaskQueues(
158
string workspaceSid, ActivityResource assignmentActivity, ActivityResource reservationActivity)
159
{
160
161
var voiceQueue = CreateTaskQueue(
162
workspaceSid, "Voice",
163
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableVoice'");
164
165
var smsQueue = CreateTaskQueue(
166
workspaceSid, "SMS",
167
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableSMS'");
168
169
var allQueue = CreateTaskQueue(
170
workspaceSid, "All",
171
assignmentActivity.Sid, reservationActivity.Sid, "1 == 1");
172
173
return new Dictionary<string, TaskQueueResource> {
174
{ VoiceQueue, voiceQueue },
175
{ SmsQueue, smsQueue },
176
{ AllQueue, allQueue }
177
};
178
}
179
180
public virtual WorkflowResource CreateWorkflow(string workspaceSid, IDictionary<string, TaskQueueResource> taskQueues)
181
{
182
var voiceQueue = taskQueues[VoiceQueue];
183
var smsQueue = taskQueues[SmsQueue];
184
var allQueue = taskQueues[AllQueue];
185
186
var voiceFilter = new {
187
friendlyName = "Voice",
188
expression = "selected_product==\"ProgrammableVoice\"",
189
targets = new List<object>() {
190
new { queue = voiceQueue.Sid, Priority = "5", Timeout = "30" },
191
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
192
}
193
};
194
195
var smsFilter = new {
196
friendlyName = "SMS",
197
expression = "selected_product==\"ProgrammableSMS\"",
198
targets = new List<object>() {
199
new { queue = smsQueue.Sid, Priority = "5", Timeout = "30" },
200
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
201
}
202
};
203
204
var workflowConfiguration = new
205
{
206
task_routing = new
207
{
208
filters = new List<object>()
209
{
210
voiceFilter,
211
smsFilter
212
},
213
default_filter = new
214
{
215
queue = allQueue.Sid,
216
expression = "1==1",
217
priority = "1",
218
timeout = "30"
219
}
220
}
221
};
222
223
// Call REST API
224
return WorkflowResource.Create(
225
workspaceSid,
226
"Tech Support",
227
Json.Encode(workflowConfiguration),
228
new Uri($"{_config.HostUrl}/callback/assignment"),
229
new Uri($"{_config.HostUrl}/callback/assignment"),
230
15);
231
}
232
}
233
}

We have a Workspace, Workers and Task Queues... what's left? A Workflow. Let's see how to create one next!


Finally, we create the Workflow using the following parameters:

  1. friendlyName as the name of a Workflow.

  2. assignmentCallbackUrl and fallbackAssignmentCallbackUrl as the public URL where a request will be made when this Workflow assigns a Task to a Worker. We will learn how to implement it on the next steps.

  3. Timeout as the maximum time we want to wait until a Worker is available for handling a Task.

  4. workflowConfiguration which is a set of rules for placing Tasks into Task Queues. The routing configuration will take a Task's attribute and match this with Task Queues. This application's Workflow rules are defined as:

    • "selected_product==\ "ProgrammableSMS\"" expression for SMS Task Queue. This expression will match any Task with ProgrammableSMS as the selected_product attribute.
    • "selected_product==\ "ProgrammableVoice\"" expression for Voice Task Queue.

TaskRouter.Web/App_Start/WorkspaceConfig.cs

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Web.Helpers;
5
using TaskRouter.Web.Infrastructure;
6
using Twilio;
7
using Twilio.Rest.Taskrouter.V1;
8
using Twilio.Rest.Taskrouter.V1.Workspace;
9
10
namespace TaskRouter.Web
11
{
12
public class WorkspaceConfig
13
{
14
private readonly Config _config;
15
16
private const string VoiceQueue = "VoiceQueue";
17
private const string SmsQueue = "SMSQueue";
18
private const string AllQueue = "AllQueue";
19
20
public static void RegisterWorkspace()
21
{
22
new WorkspaceConfig().Register();
23
}
24
25
public WorkspaceConfig():this(new Config())
26
{
27
}
28
29
public WorkspaceConfig(Config config)
30
{
31
TwilioClient.Init(config.AccountSID, config.AuthToken);
32
_config = config;
33
34
}
35
36
public WorkspaceConfig(Type workspaceResource):this()
37
{
38
}
39
40
public virtual ActivityResource GetActivityByFriendlyName(string workspaceSid, string friendlyName)
41
{
42
return ActivityResource.Read(workspaceSid, friendlyName).First();
43
}
44
45
public virtual ActivityResource CreateActivityWithFriendlyName(string workspaceSid, string friendlyName)
46
{
47
return ActivityResource.Create(workspaceSid, friendlyName);
48
}
49
50
public virtual WorkspaceResource GetWorkspaceByFriendlyName(string friendlyName)
51
{
52
return WorkspaceResource.Read(friendlyName).FirstOrDefault();
53
}
54
55
public virtual WorkspaceResource CreateWorkspace(string friendlyName, Uri eventCallbackUrl)
56
{
57
return WorkspaceResource.Create(friendlyName, eventCallbackUrl);
58
}
59
60
public virtual bool DeleteWorkspace(string workspaceSid)
61
{
62
return WorkspaceResource.Delete(workspaceSid);
63
}
64
65
public virtual WorkerResource CreateWorker(string workspaceSid, string bob, string activitySid, string attributes)
66
{
67
return WorkerResource.Create(workspaceSid, bob, activitySid, attributes);
68
}
69
70
public void Register()
71
{
72
var workspace = DeleteAndCreateWorkspace(
73
"Twilio Workspace", new Uri(new Uri(_config.HostUrl), "/callback/events").AbsoluteUri);
74
var workspaceSid = workspace.Sid;
75
76
var assignmentActivity = GetActivityByFriendlyName(workspaceSid, "Unavailable");
77
var idleActivity = GetActivityByFriendlyName(workspaceSid, "Available");
78
var reservationActivity = CreateActivityWithFriendlyName(workspaceSid, "Reserved");
79
var offlineActivity = GetActivityByFriendlyName(workspaceSid, "Offline");
80
81
var workers = CreateWorkers(workspaceSid, idleActivity);
82
var taskQueues = CreateTaskQueues(workspaceSid, assignmentActivity, reservationActivity);
83
var workflow = CreateWorkflow(workspaceSid, taskQueues);
84
85
Singleton.Instance.WorkspaceSid = workspaceSid;
86
Singleton.Instance.WorkflowSid = workflow.Sid;
87
Singleton.Instance.Workers = workers;
88
Singleton.Instance.PostWorkActivitySid = idleActivity.Sid;
89
Singleton.Instance.IdleActivitySid = idleActivity.Sid;
90
Singleton.Instance.OfflineActivitySid = offlineActivity.Sid;
91
}
92
93
public virtual WorkspaceResource DeleteAndCreateWorkspace(string friendlyName, string eventCallbackUrl) {
94
var workspace = GetWorkspaceByFriendlyName(friendlyName);
95
if (workspace != null)
96
{
97
DeleteWorkspace(workspace.Sid);
98
}
99
100
return CreateWorkspace(friendlyName, new Uri(eventCallbackUrl));
101
}
102
103
private IDictionary<string, string> CreateWorkers(string workspaceSid, ActivityResource activity)
104
{
105
var attributesForBob = new
106
{
107
products = new List<object>()
108
{
109
"ProgrammableSMS"
110
},
111
contact_uri = _config.AgentForProgrammableSMS
112
};
113
114
var bobWorker = CreateWorker(workspaceSid, "Bob", activity.Sid, Json.Encode(attributesForBob));
115
116
var attributesForAlice = new
117
{
118
products = new List<object>()
119
{
120
"ProgrammableVoice"
121
},
122
contact_uri = _config.AgentForProgrammableVoice
123
};
124
125
var alice = CreateWorker(workspaceSid, "Alice", activity.Sid, Json.Encode(attributesForAlice));
126
127
return new Dictionary<string, string>
128
{
129
{ _config.AgentForProgrammableSMS, bobWorker.Sid },
130
{ _config.AgentForProgrammableVoice, alice.Sid },
131
};
132
}
133
134
public virtual TaskQueueResource CreateTaskQueue(
135
string workspaceSid, string friendlyName,
136
string assignmentActivitySid, string reservationActivitySid, string targetWorkers)
137
{
138
var queue = TaskQueueResource.Create(
139
workspaceSid,
140
friendlyName: friendlyName,
141
assignmentActivitySid: assignmentActivitySid,
142
reservationActivitySid: reservationActivitySid
143
);
144
145
TaskQueueResource.Update(
146
workspaceSid,
147
queue.Sid,
148
friendlyName,
149
targetWorkers,
150
assignmentActivitySid,
151
reservationActivitySid,
152
1);
153
154
return queue;
155
}
156
157
private IDictionary<string, TaskQueueResource> CreateTaskQueues(
158
string workspaceSid, ActivityResource assignmentActivity, ActivityResource reservationActivity)
159
{
160
161
var voiceQueue = CreateTaskQueue(
162
workspaceSid, "Voice",
163
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableVoice'");
164
165
var smsQueue = CreateTaskQueue(
166
workspaceSid, "SMS",
167
assignmentActivity.Sid, reservationActivity.Sid, "products HAS 'ProgrammableSMS'");
168
169
var allQueue = CreateTaskQueue(
170
workspaceSid, "All",
171
assignmentActivity.Sid, reservationActivity.Sid, "1 == 1");
172
173
return new Dictionary<string, TaskQueueResource> {
174
{ VoiceQueue, voiceQueue },
175
{ SmsQueue, smsQueue },
176
{ AllQueue, allQueue }
177
};
178
}
179
180
public virtual WorkflowResource CreateWorkflow(string workspaceSid, IDictionary<string, TaskQueueResource> taskQueues)
181
{
182
var voiceQueue = taskQueues[VoiceQueue];
183
var smsQueue = taskQueues[SmsQueue];
184
var allQueue = taskQueues[AllQueue];
185
186
var voiceFilter = new {
187
friendlyName = "Voice",
188
expression = "selected_product==\"ProgrammableVoice\"",
189
targets = new List<object>() {
190
new { queue = voiceQueue.Sid, Priority = "5", Timeout = "30" },
191
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
192
}
193
};
194
195
var smsFilter = new {
196
friendlyName = "SMS",
197
expression = "selected_product==\"ProgrammableSMS\"",
198
targets = new List<object>() {
199
new { queue = smsQueue.Sid, Priority = "5", Timeout = "30" },
200
new { queue = allQueue.Sid, Expression = "1==1", Priority = "1", Timeout = "30" }
201
}
202
};
203
204
var workflowConfiguration = new
205
{
206
task_routing = new
207
{
208
filters = new List<object>()
209
{
210
voiceFilter,
211
smsFilter
212
},
213
default_filter = new
214
{
215
queue = allQueue.Sid,
216
expression = "1==1",
217
priority = "1",
218
timeout = "30"
219
}
220
}
221
};
222
223
// Call REST API
224
return WorkflowResource.Create(
225
workspaceSid,
226
"Tech Support",
227
Json.Encode(workflowConfiguration),
228
new Uri($"{_config.HostUrl}/callback/assignment"),
229
new Uri($"{_config.HostUrl}/callback/assignment"),
230
15);
231
}
232
}
233
}

Our workspace is completely setup. Now it's time to see how we use it to route calls.


Handle Twilio's Request

handle-twilios-request page anchor

Right after receiving a call, Twilio will send a request to the URL specified on the number's configuration.

The endpoint will then process the request and generate a TwiML response. We'll use the Say verb to give the user product alternatives, and a key they can press in order to select one. The Gather verb allows us to capture the user's key press.

Handling Twilio's Requests

handling-twilios-requests page anchor

TaskRouter.Web/Controllers/CallController.cs

1
using System.Web.Mvc;
2
using TaskRouter.Web.Infrastructure;
3
using TaskRouter.Web.Models;
4
using TaskRouter.Web.Services;
5
using Twilio.AspNet.Mvc;
6
using Twilio.TwiML;
7
8
namespace TaskRouter.Web.Controllers
9
{
10
public class CallController : TwilioController
11
{
12
private readonly IMissedCallsService _service;
13
14
public CallController()
15
{
16
_service = new MissedCallsService(new TaskRouterDbContext());
17
}
18
19
public CallController(IMissedCallsService service)
20
{
21
_service = service;
22
}
23
24
[HttpPost]
25
public ActionResult Incoming()
26
{
27
var response = new VoiceResponse();
28
var gather = new Gather(numDigits: 1, action: "/call/enqueue", method: "POST");
29
gather.Say("For Programmable SMS, press one. For Voice, press any other key.");
30
response.Gather(gather);
31
32
return TwiML(response);
33
}
34
35
[HttpPost]
36
public ActionResult Enqueue(string digits)
37
{
38
var selectedProduct = digits == "1" ? "ProgrammableSMS" : "ProgrammableVoice";
39
var response = new VoiceResponse();
40
41
response.Enqueue(
42
selectedProduct,
43
workflowSid: Singleton.Instance.WorkflowSid);
44
45
return TwiML(response);
46
}
47
48
49
}
50
}

We just asked the caller to choose a product, next we will use their choice to create the appropriate Task.


This is the endpoint set as the action URL on the Gather verb on the previous step. A request is made to this endpoint when the user presses a key during the call. This request has a Digits parameter that holds the pressed keys. A Task will be created based on the pressed digit with the selected_product as an attribute. The Workflow will take this Task's attributes and match them with the configured expressions in order to find a Task Queue for this Task, so an appropriate available Worker can be assigned to handle it.

We use the Enqueue verb with a WorkflowSid attribute to integrate with TaskRouter. Then the voice call will be put on hold while TaskRouter tries to find an available Worker to handle this Task.

TaskRouter.Web/Controllers/CallController.cs

1
using System.Web.Mvc;
2
using TaskRouter.Web.Infrastructure;
3
using TaskRouter.Web.Models;
4
using TaskRouter.Web.Services;
5
using Twilio.AspNet.Mvc;
6
using Twilio.TwiML;
7
8
namespace TaskRouter.Web.Controllers
9
{
10
public class CallController : TwilioController
11
{
12
private readonly IMissedCallsService _service;
13
14
public CallController()
15
{
16
_service = new MissedCallsService(new TaskRouterDbContext());
17
}
18
19
public CallController(IMissedCallsService service)
20
{
21
_service = service;
22
}
23
24
[HttpPost]
25
public ActionResult Incoming()
26
{
27
var response = new VoiceResponse();
28
var gather = new Gather(numDigits: 1, action: "/call/enqueue", method: "POST");
29
gather.Say("For Programmable SMS, press one. For Voice, press any other key.");
30
response.Gather(gather);
31
32
return TwiML(response);
33
}
34
35
[HttpPost]
36
public ActionResult Enqueue(string digits)
37
{
38
var selectedProduct = digits == "1" ? "ProgrammableSMS" : "ProgrammableVoice";
39
var response = new VoiceResponse();
40
41
response.Enqueue(
42
selectedProduct,
43
workflowSid: Singleton.Instance.WorkflowSid);
44
45
return TwiML(response);
46
}
47
48
49
}
50
}

After sending a Task to Twilio, let's see how we tell TaskRouter which Worker to use to execute that task.


When TaskRouter selects a Worker, it does the following:

  1. The Task's Assignment Status is set to 'reserved'.
  2. A Reservation instance is generated, linking the Task to the selected Worker.
  3. At the same time the Reservation is created, a POST request is made to the Workflow's AssignmentCallbackURL, which was configured using the WorkspaceConfig(link takes you to an external page) class when the application is initialized. This request includes the full details of the Task, the selected Worker, and the Reservation.

Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, email, push notifications or make a call.

Since we created this Task during a voice call with an Enqueue verb, let's instruct TaskRouter to dequeue the call and dial a Worker. If we do not specify a to parameter with a phone number, TaskRouter will pick the Worker's contact_uri attribute.

We also send a post_work_activity_sid which will tell TaskRouter which Activity to assign this worker after the call ends.

TaskRouter.Web/Controllers/CallbackController.cs

1
using Newtonsoft.Json;
2
using System;
3
using System.Linq;
4
using System.Threading.Tasks;
5
using System.Web.Mvc;
6
using TaskRouter.Web.Infrastructure;
7
using TaskRouter.Web.Models;
8
using TaskRouter.Web.Services;
9
using Twilio;
10
using Twilio.AspNet.Mvc;
11
using Twilio.Rest.Api.V2010.Account;
12
using Twilio.Types;
13
14
namespace TaskRouter.Web.Controllers
15
{
16
public class CallbackController : TwilioController
17
{
18
private readonly IMissedCallsService _service;
19
20
public CallbackController()
21
{
22
_service = new MissedCallsService(new TaskRouterDbContext());
23
24
if (Config.ENV != "test")
25
{
26
TwilioClient.Init(Config.AccountSID, Config.AuthToken);
27
}
28
}
29
30
public CallbackController(IMissedCallsService service)
31
{
32
_service = service;
33
}
34
35
[HttpPost]
36
public ActionResult Assignment()
37
{
38
var response = new
39
{
40
instruction = "dequeue",
41
post_work_activity_sid = Singleton.Instance.PostWorkActivitySid
42
};
43
44
return new JsonResult() { Data = response };
45
}
46
47
[HttpPost]
48
public async Task<ActionResult> Events(
49
string eventType, string taskAttributes, string workerSid, string workerActivityName, string workerAttributes)
50
{
51
if (IsEventTimeoutOrCanceled(eventType))
52
{
53
await CreateMissedCallAndRedirectToVoiceMail(taskAttributes);
54
}
55
56
if (HasWorkerChangedToOffline(eventType, workerActivityName))
57
{
58
SendMessageToWorker(workerSid, workerAttributes);
59
}
60
61
return new EmptyResult();
62
}
63
64
65
private bool IsEventTimeoutOrCanceled(string eventType)
66
{
67
var desiredEvents = new string[] { "workflow.timeout", "task.canceled" };
68
return desiredEvents.Any(e => e == eventType);
69
}
70
71
private bool HasWorkerChangedToOffline(string eventType, string workerActivityName)
72
{
73
return eventType == "worker.activity.update" && workerActivityName == "Offline";
74
}
75
76
private async Task CreateMissedCallAndRedirectToVoiceMail(string taskAttributes)
77
{
78
dynamic attributes = JsonConvert.DeserializeObject(taskAttributes);
79
var missedCall = new MissedCall
80
{
81
PhoneNumber = attributes.from,
82
Product = attributes.selected_product,
83
CreatedAt = DateTime.Now
84
};
85
86
await _service.CreateAsync(missedCall);
87
string voiceSid = attributes.call_sid;
88
VoiceMail(voiceSid);
89
}
90
91
private void SendMessageToWorker(string workerSid, string workerAttributes)
92
{
93
const string message = "You went offline. To make yourself available reply with \"on\"";
94
95
dynamic attributes = JsonConvert.DeserializeObject(workerAttributes);
96
string workerPhoneNumber = attributes.contact_uri;
97
98
MessageResource.Create(
99
to: new PhoneNumber(Config.TwilioNumber),
100
from: new PhoneNumber(workerPhoneNumber),
101
body: message
102
);
103
}
104
105
private void VoiceMail(string callSid)
106
{
107
var msg = "Sorry, All agents are busy. Please leave a message. We will call you as soon as possible";
108
var routeUrl = "http://twimlets.com/voicemail?Email=" + Config.VoiceMail + "&Message=" + Url.Encode(msg);
109
CallResource.Update(callSid, url: new Uri(routeUrl));
110
}
111
}
112
}

Now that our Tasks are routed properly, let's deal with missed calls in the next step.


This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout event. This event is triggered when the Task waits more than the limit set on Workflow Configuration-- or rather when no worker is available.

Here we use TwilioRestClient to route this call to a Voicemail Twimlet(link takes you to an external page). Twimlets are tiny web applications for voice. This one will generate a TwiML response using Say verb and record a message using Record verb. The recorded message will then be transcribed and sent to the email address configured.

Note that we are also listening for task.canceled. This is triggered when the customer hangs up before being assigned to an agent, therefore canceling the task. Capturing this event allows us to collect the information from the customers that hang up before the Workflow times out.

TaskRouter.Web/Controllers/CallbackController.cs

1
using Newtonsoft.Json;
2
using System;
3
using System.Linq;
4
using System.Threading.Tasks;
5
using System.Web.Mvc;
6
using TaskRouter.Web.Infrastructure;
7
using TaskRouter.Web.Models;
8
using TaskRouter.Web.Services;
9
using Twilio;
10
using Twilio.AspNet.Mvc;
11
using Twilio.Rest.Api.V2010.Account;
12
using Twilio.Types;
13
14
namespace TaskRouter.Web.Controllers
15
{
16
public class CallbackController : TwilioController
17
{
18
private readonly IMissedCallsService _service;
19
20
public CallbackController()
21
{
22
_service = new MissedCallsService(new TaskRouterDbContext());
23
24
if (Config.ENV != "test")
25
{
26
TwilioClient.Init(Config.AccountSID, Config.AuthToken);
27
}
28
}
29
30
public CallbackController(IMissedCallsService service)
31
{
32
_service = service;
33
}
34
35
[HttpPost]
36
public ActionResult Assignment()
37
{
38
var response = new
39
{
40
instruction = "dequeue",
41
post_work_activity_sid = Singleton.Instance.PostWorkActivitySid
42
};
43
44
return new JsonResult() { Data = response };
45
}
46
47
[HttpPost]
48
public async Task<ActionResult> Events(
49
string eventType, string taskAttributes, string workerSid, string workerActivityName, string workerAttributes)
50
{
51
if (IsEventTimeoutOrCanceled(eventType))
52
{
53
await CreateMissedCallAndRedirectToVoiceMail(taskAttributes);
54
}
55
56
if (HasWorkerChangedToOffline(eventType, workerActivityName))
57
{
58
SendMessageToWorker(workerSid, workerAttributes);
59
}
60
61
return new EmptyResult();
62
}
63
64
65
private bool IsEventTimeoutOrCanceled(string eventType)
66
{
67
var desiredEvents = new string[] { "workflow.timeout", "task.canceled" };
68
return desiredEvents.Any(e => e == eventType);
69
}
70
71
private bool HasWorkerChangedToOffline(string eventType, string workerActivityName)
72
{
73
return eventType == "worker.activity.update" && workerActivityName == "Offline";
74
}
75
76
private async Task CreateMissedCallAndRedirectToVoiceMail(string taskAttributes)
77
{
78
dynamic attributes = JsonConvert.DeserializeObject(taskAttributes);
79
var missedCall = new MissedCall
80
{
81
PhoneNumber = attributes.from,
82
Product = attributes.selected_product,
83
CreatedAt = DateTime.Now
84
};
85
86
await _service.CreateAsync(missedCall);
87
string voiceSid = attributes.call_sid;
88
VoiceMail(voiceSid);
89
}
90
91
private void SendMessageToWorker(string workerSid, string workerAttributes)
92
{
93
const string message = "You went offline. To make yourself available reply with \"on\"";
94
95
dynamic attributes = JsonConvert.DeserializeObject(workerAttributes);
96
string workerPhoneNumber = attributes.contact_uri;
97
98
MessageResource.Create(
99
to: new PhoneNumber(Config.TwilioNumber),
100
from: new PhoneNumber(workerPhoneNumber),
101
body: message
102
);
103
}
104
105
private void VoiceMail(string callSid)
106
{
107
var msg = "Sorry, All agents are busy. Please leave a message. We will call you as soon as possible";
108
var routeUrl = "http://twimlets.com/voicemail?Email=" + Config.VoiceMail + "&Message=" + Url.Encode(msg);
109
CallResource.Update(callSid, url: new Uri(routeUrl));
110
}
111
}
112
}

Most of the features of our application are implemented. The last piece is allowing the Workers to change their availability status. Let's see how to do that next.


Change a Worker's Activity

change-a-workers-activity page anchor

We have created this endpoint, so a worker can send an SMS message to the support line with the command "On" or "Off" to change their availability status.

This is important as a worker's activity will change to Offline when they miss a call. When this happens, they receive an SMS letting them know that their activity has changed, and that they can reply with the On command to make themselves available for incoming calls again.

Changing a Worker's Activity

changing-a-workers-activity page anchor

TaskRouter.Web/Controllers/MessageController.cs

1
using System;
2
using System.Web.Mvc;
3
using TaskRouter.Web.Infrastructure;
4
using Twilio;
5
using Twilio.AspNet.Mvc;
6
using Twilio.Rest.Taskrouter.V1.Workspace;
7
using Twilio.TwiML;
8
9
namespace TaskRouter.Web.Controllers
10
{
11
public class MessageController : TwilioController
12
{
13
private const string On = "on";
14
private const string Off = "off";
15
16
public MessageController()
17
{
18
if (Config.ENV != "test")
19
{
20
TwilioClient.Init(Config.AccountSID, Config.AuthToken);
21
}
22
}
23
24
public virtual WorkerResource FetchWorker(string workspaceSid, string workerSid)
25
{
26
return WorkerResource.Fetch(workspaceSid, workerSid);
27
}
28
29
public virtual WorkerResource UpdateWorker(string pathWorkspaceSid, string pathSid, string activitySid = null,
30
string attributes = null, string friendlyName = null)
31
{
32
return WorkerResource.Update(pathWorkspaceSid, pathSid, activitySid, attributes, friendlyName);
33
}
34
35
[HttpPost]
36
public ActionResult Incoming(string from, string body)
37
{
38
var workspaceSid = Singleton.Instance.WorkspaceSid;
39
var workerSid = Singleton.Instance.Workers[from];
40
var idleActivitySid = Singleton.Instance.IdleActivitySid;
41
var offlineActivitySid = Singleton.Instance.OfflineActivitySid;
42
var message = "Unrecognized command, reply with \"on\" to activate your worker or \"off\" otherwise";
43
44
var worker = FetchWorker(workspaceSid, workerSid);
45
46
if (body.Equals(On, StringComparison.InvariantCultureIgnoreCase))
47
{
48
UpdateWorker(workspaceSid, workerSid, idleActivitySid, worker.Attributes, worker.FriendlyName);
49
message = "Your worker is online";
50
}
51
52
if (body.Equals(Off, StringComparison.InvariantCultureIgnoreCase))
53
{
54
UpdateWorker(workspaceSid, workerSid, offlineActivitySid, worker.Attributes, worker.FriendlyName);
55
message = "Your worker is offline";
56
}
57
58
return TwiML(new MessagingResponse().Message(message));
59
}
60
}
61
}

Congratulations! You finished this tutorial. As you can see, using Twilio's TaskRouter is quite simple.


If you're a .NET developer working with Twilio, you might also enjoy these tutorials:

Voice JavaScript SDK Quickstart

Learn how to use Twilio Voice SDK to make browser-to-phone and browser-to-browser calls with ease.

ETA-Notifications(link takes you to an external page)

Learn how to implement ETA Notifications using ASP.NET MVC and Twilio.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.