C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,344 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace LeadwayCIVUATPlugins
{
public class TurnquestAgentCreatorPlugin : IPlugin
{
private static string DateFormat = "yyyy-MM-dd";
private static string ValueForAttribute(string attributeName, Entity entity)
{
if (entity.Contains(attributeName))
{
if (attributeName == "new_typedecompte")
{
object value = entity.Attributes[attributeName];
if (value != null)
{
OptionSetValue osValue = (OptionSetValue)value;
switch (osValue.Value)
{
case 2: return "2";
case 3: return "3";
case 40: return "40";
}
}
}
if (attributeName == "new_bifurquer2")
{
object value = entity.Attributes[attributeName];
if (value != null)
{
OptionSetValue osValue = (OptionSetValue)value;
switch (osValue.Value)
{
case 284: return "MARCORY";
case 285: return "PLATEAU";
case 286: return "VALLON";
case 287: return "YOPOUGON";
case 288: return "CORPORATE OFFICE";
default: return "Unknown Option";
}
}
} // return entity.Attributes[attributeName].ToString();
if (entity.Attributes.Contains(attributeName) && entity.Attributes[attributeName] != null)
{
return entity.Attributes[attributeName].ToString();
}
else
{
return "Attribute value is null";
}
}
return null;
}
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Verify that the target entity represents an account or contact.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName == "new_intermdiaire" || entity.LogicalName == "new_franchise")
{
try
{
// Create the turnquest client model based on the entity attributes
DateTime now = DateTime.Now;
AgentPayload agent = new AgentPayload();
agent.accountTypeCode = int.Parse(ValueForAttribute("new_typedecompte", entity).ToString());
agent.branchCode = int.Parse(ValueForAttribute("new_bifurquer2", entity).ToString()); // get dob from entity.attributes
agent.emailAddress = ValueForAttribute("new_email", entity); // placeholder
agent.name = ValueForAttribute("new_name", entity);
agent.status = "ACTIVE";
agent.shortDescription = ValueForAttribute("new_crmid", entity); // crm id entity.Attributes["new_crmid"].ToString();//
agent.physicalAddress = ValueForAttribute("new_adresse", entity);
agent.postalAddress = ValueForAttribute("new_adresse", entity);
agent.code = null;
agent.webAddress = ValueForAttribute("new_siteweb", entity);
agent.telephone1 = ValueForAttribute("new_mobile", entity); // mobile phone
agent.contactPerson = ValueForAttribute("new_personnedecontact", entity); // last name
agent.contactTitle = "7914";
agent.pin = "0000";
agent.licenseNumber = ValueForAttribute("new_crmid", entity);
agent.statusEffectiveDate = now.ToString(DateFormat);
string json = new JavaScriptSerializer().Serialize(agent);
byte[] bytes = Encoding.UTF8.GetBytes(json);
// Send the create request to Turnquest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Configuration.RequestUrl);
//using (System.IO.MemoryStream serializeStream = new System.IO.MemoryStream())
//{
// DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(LagosReferrerObject));
// serializer.WriteObject(serializeStream, obj);
// postData = Encoding.Default.GetString(serializeStream.ToArray());
// /// return jsonString;
//}
request.ContentType = "application/json; encoding='utf-8'";
request.Accept = "application/json";
request.Headers.Add("Authorization", "46ea21639fb86ffb571a67fd348666f7067bf3c101924be1ea703dffcfb9c27ce3c4cfc88f29ee20bc23d8f7e5045dd0155acc87e19bc1dca41597b967e2a95f");//46ea21639fb86ffb571a67fd348666f7067bf3c101924be1ea703dffcfb9c27ce3c4cfc88f29ee20bc23d8f7e5045dd0155acc87e19bc1dca41597b967e2a95f
//46ea21639fb86ffb571a67fd348666f7067bf3c101924be1ea703dffcfb9c27ce3c4cfc88f29ee20bc23d8f7e5045dd0155acc87e19bc1dca41597b967e2a95f
request.ContentLength = bytes.Length;
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string jsonResponse = rd.ReadToEnd();
JavaScriptSerializer result = new JavaScriptSerializer();
AgentRootObject obj = new AgentRootObject();
obj = result.Deserialize<AgentRootObject>(jsonResponse);
;
//result.code
if (string.IsNullOrEmpty(obj.payload.code.ToString()))
{
throw new Exception(string.Format("No agent code was returned from Turnquest.\nJSON response: {0}", jsonResponse));
}
entity.Attributes.Add("new_tqid", obj.payload.code.ToString());
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string errorResponse = rd.ReadToEnd();
throw new InvalidPluginExecutionException(string.Format("The Turnquest request failed with the response:\n{0}", errorResponse + " | " + ex.Message), ex);
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(string.Format("A new CRM ID could not be generated: {0}\n{1}", ex.InnerException.Message, ex.StackTrace), ex);
}
}
}
}
private class Configuration
{
public static string RequestUrl = "http://172.20.90.139:9095/agents/v1/createUpdateAgent";//"http://172.20.90.131:9092/agents/v1/createUpdateAgent";
}
//
}
}