-
Notifications
You must be signed in to change notification settings - Fork 439
/
closeanincident.cs
256 lines (221 loc) · 9.92 KB
/
closeanincident.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// <snippetcloseanincident>
using System;
using System.ServiceModel;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Microsoft.Crm.Sdk.Samples
{
public class CloseAnIncident
{
#region Class Level Members
private OrganizationServiceProxy _serviceProxy;
private Guid _incidentId;
private Guid _appointmentId;
private Guid _accountId;
#endregion
#region How To Sample Code
public void Run(ServerConnection.Configuration serverConfig,
bool promptforDelete)
{
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early bound type support.
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
RunIncidentManipulation();
DeleteRecords(promptforDelete);
}
}
private void RunIncidentManipulation()
{
Console.WriteLine("=== Creating and Closing an Incident (Case) ===");
// Create an incident.
var incident = new Incident
{
CustomerId = new EntityReference(Account.EntityLogicalName, _accountId),
Title = "Sample Incident"
};
_incidentId = _serviceProxy.Create(incident);
NotifyEntityCreated(Incident.EntityLogicalName, _incidentId);
// Create a 30-minute appointment regarding the incident.
var appointment = new Appointment
{
ScheduledStart = DateTime.Now,
ScheduledEnd = DateTime.Now.Add(new TimeSpan(0, 30, 0)),
Subject = "Sample 30-minute Appointment",
RegardingObjectId = new EntityReference(Incident.EntityLogicalName,
_incidentId)
};
_appointmentId = _serviceProxy.Create(appointment);
NotifyEntityCreated(Appointment.EntityLogicalName, _appointmentId);
// Show the time spent on the incident before closing the appointment.
NotifyTimeSpentOnIncident();
// Check the validity of the state transition to closed on the incident.
NotifyValidityOfIncidentSolvedStateChange();
// Close the appointment.
var setAppointmentStateReq = new SetStateRequest
{
EntityMoniker = new EntityReference(Appointment.EntityLogicalName,
_appointmentId),
State = new OptionSetValue((int)AppointmentState.Completed),
Status = new OptionSetValue((int)appointment_statuscode.Completed)
};
_serviceProxy.Execute(setAppointmentStateReq);
Console.WriteLine(" Appointment state set to completed.");
// Show the time spent on the incident after closing the appointment.
NotifyTimeSpentOnIncident();
// Check the validity of the state transition to closed again.
NotifyValidityOfIncidentSolvedStateChange();
// Create the incident's resolution.
var incidentResolution = new IncidentResolution
{
Subject = "Resolved Sample Incident",
IncidentId = new EntityReference(Incident.EntityLogicalName, _incidentId)
};
// Close the incident with the resolution.
var closeIncidentRequest = new CloseIncidentRequest
{
IncidentResolution = incidentResolution,
Status = new OptionSetValue((int)incident_statuscode.ProblemSolved)
};
_serviceProxy.Execute(closeIncidentRequest);
Console.WriteLine(" Incident closed.");
}
private void NotifyValidityOfIncidentSolvedStateChange()
{
// Validate the state transition.
var isValidRequest = new IsValidStateTransitionRequest
{
Entity = new EntityReference(Incident.EntityLogicalName, _incidentId),
NewState = IncidentState.Resolved.ToString(),
NewStatus = (int)incident_statuscode.ProblemSolved
};
var response =
(IsValidStateTransitionResponse)_serviceProxy.Execute(isValidRequest);
var isValidString = response.IsValid ? "is valid" : "is not valid";
Console.WriteLine(" The transition to a completed status reason {0}.",
isValidString);
}
private void NotifyTimeSpentOnIncident()
{
// Calculate the total number of minutes spent on an incident.
var calculateRequestTime = new CalculateTotalTimeIncidentRequest
{
IncidentId = _incidentId
};
var response =
(CalculateTotalTimeIncidentResponse)_serviceProxy.Execute(calculateRequestTime);
Console.WriteLine(" {0} minutes have been spent on the incident.",
response.TotalTime);
}
private void NotifyEntityCreated(String entityName, Guid entityId)
{
Console.WriteLine(" {0} created with GUID {{{1}}}",
entityName, entityId);
}
private void CreateRequiredRecords()
{
// Create an account to act as a customer for the incident.
var account = new Account
{
Name = "Litware, Inc.",
Address1_StateOrProvince = "Colorado"
};
_accountId = (_serviceProxy.Create(account));
}
private void DeleteRecords(bool prompt)
{
bool toBeDeleted = true;
if (prompt)
{
// Ask the user if the created entities should be deleted.
Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
String answer = Console.ReadLine();
if (answer.StartsWith("y") ||
answer.StartsWith("Y") ||
answer == String.Empty)
{
toBeDeleted = true;
}
else
{
toBeDeleted = false;
}
}
if (toBeDeleted)
{
// The account is all that needs to be deleted. Everything else will be
// deleted with it.
_serviceProxy.Delete(Account.EntityLogicalName, _accountId);
}
}
#endregion How To Sample Code
#region Main method
/// <summary>
/// Standard Main() method used by most SDK samples.
/// </summary>
/// <param name="args"></param>
static public void Main(string[] args)
{
try
{
// Obtain the target organization's web address and client logon
// credentials from the user.
ServerConnection serverConnect = new ServerConnection();
ServerConnection.Configuration config = serverConnect.GetServerConfiguration();
var app = new CloseAnIncident();
app.Run(config, true);
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
Console.WriteLine("Message: {0}", ex.Detail.Message);
Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
Console.WriteLine("Inner Fault: {0}",
null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
}
catch (System.TimeoutException ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine("Message: {0}", ex.Message);
Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
Console.WriteLine("Inner Fault: {0}",
null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
}
catch (System.Exception ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine(ex.Message);
// Display the details of the inner exception.
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>;
if (fe != null)
{
Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
Console.WriteLine("Message: {0}", fe.Detail.Message);
Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
Console.WriteLine("Inner Fault: {0}",
null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
}
}
}
// Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
// SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.
finally
{
Console.WriteLine("Press <Enter> to exit.");
Console.ReadLine();
}
}
#endregion Main method
}
}
// </snippetcloseanincident>