// Implements the SendSMS Workflow Activity.
namespace LucasDemoPlugins.TropoWorkflows
{
using System;
using System.Activities;
using System.ServiceModel;
using System.Globalization;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
using System.Net;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
public sealed class SendSMS : CodeActivity
{
[Input("Recipient phone number")]
public InArgument RecipientIn { get; set; }
[Input("Message")]
public InArgument MessageIn { get; set; }
private string _webAddress = "https://api.tropo.com/v1/sessions";
private string _tropoToken = "YOUR_TOKEN_HERE"; //voice or messaging token as appropriate
///
/// Executes the workflow activity.
///
/// The execution context.
protected override void Execute(CodeActivityContext executionContext)
{
// Create the tracing service
ITracingService tracingService = executionContext.GetExtension();
if (tracingService == null)
{
throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
}
tracingService.Trace("Entered SendSMS.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
executionContext.ActivityInstanceId,
executionContext.WorkflowInstanceId);
// Create the context
IWorkflowContext context = executionContext.GetExtension();
if (context == null)
{
throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
}
tracingService.Trace("SendSMS.Execute(), Correlation Id: {0}, Initiating User: {1}",
context.CorrelationId,
context.InitiatingUserId);
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
//create a new troporequest object
TropoRequest tropoReq = new TropoRequest
{
To = RecipientIn.Get(executionContext),
Message = MessageIn.Get(executionContext),
Token = _tropoToken
};
//serialize the troporequest to json
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(tropoReq.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, tropoReq);
string jsonMsg = Encoding.Default.GetString(ms.ToArray());
//create the json webrequest and execute it
System.Net.WebRequest req = System.Net.WebRequest.Create(_webAddress);
req.ContentType = "application/json";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsonMsg.ToString());
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
//get the response
System.Net.WebResponse resp = req.GetResponse();
//deserialize the response to a troporesponse object
TropoResponse tropoResponse = new TropoResponse();
System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(tropoResponse.GetType());
tropoResponse = deserializer.ReadObject(resp.GetResponseStream()) as TropoResponse;
//if the success value is false, throw an error - not strictly necessary as tropo returns an HTTP error code, but still good to have just in case
if (!tropoResponse.Success)
{
throw new Exception("SendSMS failure: " + tropoResponse.Reason);
}
}
catch (WebException exception)
{
string str = string.Empty;
if (exception.Response != null)
{
using (StreamReader reader =
new StreamReader(exception.Response.GetResponseStream()))
{
str = reader.ReadToEnd();
}
exception.Response.Close();
}
if (exception.Status == WebExceptionStatus.Timeout)
{
throw new InvalidPluginExecutionException(
"The timeout elapsed while attempting to issue the request.", exception);
}
throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
"A Web exception ocurred while attempting to issue the request. {0}: {1}",
exception.Message, str), exception);
}
catch (FaultException e)
{
tracingService.Trace("Exception: {0}", e.ToString());
// Handle the exception.
throw;
}
catch (Exception e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
tracingService.Trace("Exiting SendSMS.Execute(), Correlation Id: {0}", context.CorrelationId);
}
}
}