/// <summary> /// A plug-in that auto generates an account number when an /// account is created. /// </summary> /// <remarks>Register this plug-in on the Create message, account entity, /// and pre-operation stage. /// </remarks> //<snippetAccountNumberPlugin2> 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)); var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { tracing.Trace("Contains target"); // Obtain the target entity from the input parameters. Entity entity = (Entity)context.InputParameters["Target"]; //</snippetAccountNumberPlugin2> // Verify that the target entity represents an account. // If not, this plug-in was not registered correctly. if (entity.LogicalName == "account") { tracing.Trace("Is Account"); // An accountnumber attribute should not already exist because // it is system generated. if (entity.Attributes.Contains("accountnumber") == false) { // Create a new accountnumber attribute, set its value, and add // the attribute to the entity's attribute collection. Random rndgen = new Random(); entity.Attributes.Add("accountnumber", rndgen.Next().ToString()); } else { // Throw an error, because account numbers must be system generated. // Throwing an InvalidPluginExecutionException will cause the error message // to be displayed in a dialog of the Web application. throw new InvalidPluginExecutionException("The account number can only be set by the system."); } } } }
public void Execute(IServiceProvider serviceProvider) { Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // For impersonation // IOrganizationService service = serviceFactory.CreateOrganizationService(new Guid ("8240cddf-fb54-4d96-90db-0ff926be0c14")); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity entity = (Entity)context.InputParameters["Target"]; if (entity.LogicalName == "contact") { if (context.MessageName.ToLower() == "create" || context.MessageName.ToLower() == "update") { string city; string postCode; if (entity.Contains("address1_city") && entity.Contains("address1_postofficebox")) { city = entity.Attributes["address1_city"].ToString(); postCode = entity.Attributes["address1_postofficebox"].ToString(); EntityReference region = this.RetrieveRegionID(city, postCode, service); if (region != null) { if (entity.Contains("new_regionid")) { entity["new_regionid"] = region; } else { entity.Attributes.Add("new_regionid", region); } } } } } } }
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)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); var query = new QueryExpression("scnsoft_autonumberaz") { ColumnSet = new ColumnSet(true) }; var ConfigEntity = service.RetrieveMultiple(query).Entities.FirstOrDefault(); if (ConfigEntity == null) { ConfigEntity = CreateNewEntity(service); } // 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"]; ////</snippetAccountNumberPlugin2> //// Verify that the target entity represents an account. //// If not, this plug-in was not registered correctly. if (entity.LogicalName == entityName) { int uniqueNumber; entity[fieldName] = GetNameEntity(ConfigEntity, out uniqueNumber); SetUniqueNumber(ConfigEntity, uniqueNumber, service); } } }
/// <summary> /// A plug-in that auto generates a number for provided entity when a record /// is created. /// </summary> /// <remarks>Register this plug-in on the Create message, account entity, /// and pre-operation stage. /// </remarks> //<snippetAssignAutoNumberPlugin2> 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)); IOrganizationServiceFactory service = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); OrganizationService = service.CreateOrganizationService(context.UserId); // 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"]; //</snippetAssignAutoNumberPlugin2> if (entity.LogicalName == "dots_twitterpost") { // String x = entity.FormattedValues["dots_parent_twitterpublisherid"].ToString(); var lookup = entity.GetAttributeValue <EntityReference>("dots_parent_twitterpublisherid"); //var entityName = lookup.LogicalName; var entityId = lookup.Id; //var instanceName = lookup.Name; var message = entity.Attributes["dots_message"].ToString(); // var publisherId= entity.Attributes["dots_parent_twitterpublisherid"].ToString(); string result = PostMessage(message, "{" + entityId.ToString() + "}"); if (result != "Success") { throw new InvalidPluginExecutionException(result); } } } }
public void Execute(IServiceProvider serviceProvider) { Guid fsCurrentId = Guid.Empty; IOrganizationServiceFactory serviceFactory; IOrganizationService service; OrganizationServiceContext orgContext; try { // 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) { serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); service = serviceFactory.CreateOrganizationService(context.UserId); using (orgContext = new OrganizationServiceContext(service)) { Entity entity = (Entity)context.InputParameters["Target"]; entity = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(true)); if (entity.Contains("new_latitude") && entity.Contains("new_longitude")) { String lat = entity.GetAttributeValue <String>("new_latitude"); String lon = entity.GetAttributeValue <String>("new_longitude"); String fulladdress = getAddressfromGoogle(Convert.ToDouble(lat), Convert.ToDouble(lon)); Entity updatelocation = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(false)); updatelocation.Attributes["new_address"] = fulladdress; service.Update(updatelocation); } } } } catch (Exception ex) { throw new Exception("Error in retrieveing GetAddress" + ex.Message); } }
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)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService( typeof(IOrganizationServiceFactory)); //get service object from service factory IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // 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"]; //</snippetAccountNumberPlugin2> // Verify that the target entity represents an account. // If not, this plug-in was not registered correctly. /*Entity retrievedautoNumber = (Entity)service.Retrieve("bnu_autonumber", * new Guid("241563DF-3820-E711-80FD-5065F38A1B01"), new ColumnSet(new string[] { "bnu_initialnumber", "bnu_prefix", * "bnu_entityname", "bnu_conditionaloptionset", "bnu_optionsetvaluenumerical", "bnu_entityname", "bnu_recentnumber", * "bnu_updatefield" })); */ QueryExpression query = new QueryExpression { EntityName = "bnu_autonumber", ColumnSet = new ColumnSet("bnu_initialnumber", "bnu_prefix", "bnu_entityname", "bnu_conditionaloptionset", "bnu_optionsetvaluenumerical", "bnu_entityname", "bnu_recentnumber", "bnu_updatefield", "bnu_leadingzeros") }; EntityCollection entityCollection = service.RetrieveMultiple(query); Entity autoNumberupdate = new Entity("bnu_autonumber"); string relationValue = null; int conditionOptionsetvalue = 0; int initialNumber = 0; string prefix = null; string updatedField = null; Guid recordId = new Guid(); int leadingzeros = 0; int recentNumber = 0; foreach (Entity result in entityCollection.Entities) { relationValue = result.GetAttributeValue <string>("bnu_conditionaloptionset"); //customertypecode conditionOptionsetvalue = result.GetAttributeValue <int>("bnu_optionsetvaluenumerical"); //22 initialNumber = Int32.Parse(result.GetAttributeValue <string>("bnu_initialnumber")); //0001 prefix = result.GetAttributeValue <string>("bnu_prefix").ToString(); //PAR- updatedField = result.GetAttributeValue <string>("bnu_updatefield"); leadingzeros = result.GetAttributeValue <int>("bnu_leadingzeros"); recentNumber = Int32.Parse(result.GetAttributeValue <string>("bnu_recentnumber")); recordId = result.Id; bool customerTypeCodeFromEntity = entity.Contains(relationValue); if (customerTypeCodeFromEntity) { int conditionOptionsetValuefromEntity = ((OptionSetValue)entity[relationValue]).Value; if (conditionOptionsetValuefromEntity == conditionOptionsetvalue) { if (recentNumber != 0) { int incrementNumber = recentNumber + 1; string incrementedNumber = (recentNumber + 1).ToString(); string allocatedNumber = prefix + incrementedNumber.PadLeft(leadingzeros, '0'); entity.Attributes.Add(updatedField, allocatedNumber); Entity autoNumber = new Entity("bnu_autonumber"); autoNumber.Id = recordId; autoNumber["bnu_recentnumber"] = incrementedNumber; service.Update(autoNumber); break; } else { int incrementNumber = initialNumber + 1; string incrementedNumber = incrementNumber.ToString(); string allocatedNumber = prefix + incrementedNumber.PadLeft(leadingzeros, '0'); entity.Attributes.Add(updatedField, allocatedNumber); Entity autoNumber = new Entity("bnu_autonumber"); autoNumber.Id = recordId; autoNumber["bnu_recentnumber"] = incrementedNumber; service.Update(autoNumber); break; } } } } } }
/// <summary> /// A plugin that update sales order details when WCF Service returns some values /// /// </summary> /// <remarks>Register this plug-in on the Update message, salesorderdetail entity, /// and postoperation-event stage. /// </remarks> public void Execute(IServiceProvider serviceProvider) { //Extract the tracing service for use in debugging sandboxed plug-ins. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); // Obtaining the organization service reference. IOrganizationService orgService = null; IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); orgService = serviceFactory.CreateOrganizationService(context.UserId); // 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 parmameters. Entity entity = (Entity)context.InputParameters["Target"]; try { // Verify the target entity. switch (entity.LogicalName) { case "account": //Implementation of opportunity logic break; case "contact": //Implementation of opportunity logic break; case "opportunity": //Implementation of opportunity logic break; case "quote": //Implementation of quote logic break; case "quotedetail": //Implementation of quote detail logic break; case "salesorder": //Implementation of sales order logic break; case "salesorderdetail": //Implementation of sales order logic break; } } catch (FaultException <OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException("An error occurred in the UpdateSalesOrderDetails plug-in.", ex); } catch (Exception ex) { tracingService.Trace("UpdateSalesOrderDetailsPlugin: {0}", ex.ToString()); throw; } } }
public void Execute(IServiceProvider serviceProvider) { //Extract the tracing service for use in plug-in debugging. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); //make sure we have a target that is an entity if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { // Obtain the target entity from the input parameters. Entity entity = (Entity)context.InputParameters["Target"]; //set up the org service reference for our retrieve IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); //retrieve some results using the fetchxml supplied in the configuration EntityCollection results = service.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(string.Format(fetchXml, entity.Id.ToString()))); //we should have one and only one result if (results.Entities.Count != 1) { throw new Exception("query did not return a single result"); } Entity retrieved = results.Entities[0]; //set up our json writer StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonWriter jsonWriter = new JsonTextWriter(sw); jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; jsonWriter.WriteStartObject(); //loop through the retrieved attributes foreach (string attribute in retrieved.Attributes.Keys) { //generate different output for different attribute types switch (retrieved[attribute].GetType().ToString()) { //if we have a lookup, return the id and the name case "Microsoft.Xrm.Sdk.EntityReference": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(((EntityReference)retrieved[attribute]).Id); jsonWriter.WritePropertyName(attribute + "_name"); jsonWriter.WriteValue(((EntityReference)retrieved[attribute]).Name); break; //if we have an optionset value, return the value and the formatted value case "Microsoft.Xrm.Sdk.OptionSetValue": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(((OptionSetValue)retrieved[attribute]).Value); if (retrieved.FormattedValues.Contains(attribute)) { jsonWriter.WritePropertyName(attribute + "_formatted"); jsonWriter.WriteValue(retrieved.FormattedValues[attribute]); } break; //if we have money, return the value case "Microsoft.Xrm.Sdk.Money": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(((Money)retrieved[attribute]).Value); break; //if we have a datetime, return the value case "System.DateTime": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(retrieved[attribute]); break; //for everything else, return the value and a formatted value if it exists default: jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(retrieved[attribute]); if (retrieved.FormattedValues.Contains(attribute)) { jsonWriter.WritePropertyName(attribute + "_formatted"); jsonWriter.WriteValue(retrieved.FormattedValues[attribute]); } break; } } //always write out the message name (update, create, etc.), entity name and record id jsonWriter.WritePropertyName("operation"); jsonWriter.WriteValue(context.MessageName); jsonWriter.WritePropertyName("entity"); jsonWriter.WriteValue(retrieved.LogicalName); jsonWriter.WritePropertyName("id"); jsonWriter.WriteValue(retrieved.Id); jsonWriter.WriteEndObject(); //generate the json string string jsonMsg = sw.ToString(); jsonWriter.Close(); sw.Close(); try { //create the webrequest object and execute it (and post jsonmsg to it) //see http://www.alexanderdevelopment.net/post/2013/04/22/Postingprocessing-JSON-in-a-CRM-2011-custom-workflow-activity //for additional information on working with json from dynamics CRM System.Net.WebRequest req = System.Net.WebRequest.Create(webAddress); //must set the content type for json req.ContentType = "application/json"; //must set method to post req.Method = "POST"; //create a stream 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(); } 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 (Exception e) { tracingService.Trace("Exception: {0}", e.ToString()); throw; } } }
public Actions.AccountCountContactsResponse OnPostkipon_AccountCountContacts(Actions.IAccountCountContactsRequest request, ServiceAPI.IAccountService accountService, string Name, Microsoft.Xrm.Sdk.IPluginExecutionContext ctx) { if (string.IsNullOrEmpty(Name)) { return(new Actions.AccountCountContactsResponse { AMoney = new Money(0M), Count = 0 }); } else { return(new Actions.AccountCountContactsResponse { AMoney = new Money(10M), Count = Name.Length }); } }
/// <summary> /// A plug-in that auto generates a number for provided entity when a record /// is created. /// </summary> /// <remarks>Register this plug-in on the Create message, account entity, /// and pre-operation stage. /// </remarks> //<snippetAssignAutoNumberPlugin2> 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)); IOrganizationServiceFactory service = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); OrganizationService = service.CreateOrganizationService(context.UserId); // 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"]; //</snippetAssignAutoNumberPlugin2> string messageName = context.MessageName; if (entity.LogicalName == "dots_autonumber") { if (messageName == "Create") { //for check duplicate field //if (IsFieldExist(entity.LogicalName, entity.Attributes["new_targetattributelogicalname"].ToString())) // throw new InvalidPluginExecutionException(string.Format("Field {0} already exist in Entity {1}!", entity.Attributes["new_targetattributelogicalname"].ToString(), entity.LogicalName)); if (IsFieldExist2(entity.Attributes["new_targetentitylogicalname"].ToString(), entity.Attributes["new_targetattributelogicalname"].ToString())) { throw new InvalidPluginExecutionException(string.Format("Field {0} already exist in Entity {1}!", entity.Attributes["new_targetattributelogicalname"].ToString(), entity.Attributes["new_targetentitylogicalname"].ToString())); } // allow one fields for one entity if (IsEntityExist2(entity.LogicalName, entity.Attributes["new_targetentitylogicalname"].ToString())) { throw new InvalidPluginExecutionException(string.Format("Already created AutoNumber field for Entity {0}!", entity.Attributes["new_targetentitylogicalname"].ToString())); } SdkMessageProcessingStep step = new SdkMessageProcessingStep { AsyncAutoDelete = false, Mode = new OptionSetValue((int)CrmPluginStepMode.Synchronous), Name = _pluginTypeName + ": " + entity.Attributes["new_name"].ToString(), EventHandler = new EntityReference("plugintype", GetPluginTypeId()), Rank = 1, SdkMessageId = new EntityReference("sdkmessage", GetMessageId()), Stage = new OptionSetValue((int)CrmPluginStepStage.PreOperation), SupportedDeployment = new OptionSetValue((int)CrmPluginStepDeployment.ServerOnly), SdkMessageFilterId = new EntityReference("sdkmessagefilter", GetSdkMessageFilterId(entity.Attributes["new_targetentitylogicalname"].ToString())), Description = entity.Attributes["new_targetattributelogicalname"].ToString() }; var SdkMessageProcessingStepId = OrganizationService.Create(step); entity.Attributes.Add("new_sdkmessageprocessingstepid", SdkMessageProcessingStepId.ToString()); } } else { var entityDetail = GetEntityByName(entity.LogicalName); if (entity.Attributes.Contains(entityDetail.TargetAttributeLogicalName) == false) { var InitalValue = GetNewCode(entityDetail); var setValue = (InitalValue == null || InitalValue == "") ? "0" : InitalValue; string[] splitValues; if (setValue.Contains("#")) { splitValues = setValue.Split('#'); entity.Attributes.Add(entityDetail.TargetAttributeLogicalName, splitValues[0] + "" + splitValues[1]); int incrementValue = Convert.ToInt32(splitValues[1]); IncreaseCurrentNumber(entity.LogicalName, incrementValue); } else { entity.Attributes.Add(entityDetail.TargetAttributeLogicalName, setValue); int incrementValue = Convert.ToInt32(setValue); IncreaseCurrentNumber(entity.LogicalName, incrementValue); } } } } else if (context.InputParameters["Target"] is EntityReference) { if (context.PrimaryEntityName == "dots_autonumber") { if (context.MessageName == "Delete") { Guid id = ((EntityReference)context.InputParameters["Target"]).Id; DSAutoNumber entity2 = OrganizationService.Retrieve("dots_autonumber", ((EntityReference)context.InputParameters["Target"]).Id, new ColumnSet(true)).ToEntity <DSAutoNumber>(); OrganizationService.Delete("sdkmessageprocessingstep", new Guid(entity2.SdkMessageProcessingStepId.ToString())); } } } }
public PluginContext(IOrganizationServiceFactory serviceFactory, IOrganizationService service, ITracingService tracingService, Microsoft.Xrm.Sdk.IPluginExecutionContext context) { this.service = service; this.tracingService = tracingService; this.context = context; this.serviceFactory = serviceFactory; integrationUserService = changeToUser(ServiceFactory, Service, "System"); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePreContactCreate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)localContext.PluginExecutionContext; if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { //Organization Service IOrganizationService service = localContext.OrganizationService; //Tracing Service ITracingService trace = (ITracingService)localContext.TracingService; //Get the target entity Entity entity = (Entity)context.InputParameters["Target"]; try { //if (entity.Attributes.Contains("firstname")) //{ // entity.Attributes["jobtitle"] = "testing swsw"; //} if (entity.Attributes.Contains("mobilephone")) { string message = "New contact added in system for " + entity.Attributes["firstname"] + " " + entity.Attributes["lastname"]; SmsSender smsSender = new SmsSender(); string response = smsSender.SendSMS(entity.Attributes["mobilephone"].ToString(), "919460264151", "5b2a23d7", "59d9fa03", Uri.EscapeUriString(message)); // string fetchxmluser = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + // "<entity name='systemuser'>" + // "<attribute name='fullname' />" + // "<attribute name='businessunitid' />" + //"<attribute name='title' /> " + //"<attribute name='address1_telephone1'/>" + //"<attribute name='positionid' /> " + //"<attribute name='systemuserid' /> " + //"<attribute name='mobilephone' />" + //"<attribute name='parentsystemuserid' />" + //"<attribute name='firstname' />" + //"<order attribute='fullname' descending= 'false' />" + //"</entity>" + // "</fetch>"; //EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchxmluser)); //if (result.Entities.Count > 1) //{ // throw new InvalidPluginExecutionException(string.Format("Contract created by : {0} and total user {1}", entity.Attributes["createdby"], result.Entities.Count)); //} //if (entity.Attributes["mobilephone"].ToString() != "9999") //{ // throw new InvalidPluginExecutionException(string.Format("An error occured in PreContactCreate plugin: {0}", "invalid no")); //} } } catch (Exception ex) { throw new InvalidPluginExecutionException(string.Format("An error occured in PreContactCreate plugin: {0} {1} {2}", ex.ToString(), ex.InnerException, ex.StackTrace)); } } }
/// <summary> /// A plug-in that auto generates a number for provided entity when a record /// is created. /// </summary> /// <remarks>Register this plug-in on the Create message, account entity, /// and pre-operation stage. /// </remarks> //<snippetAssignAutoNumberPlugin2> 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)); IOrganizationServiceFactory service = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); OrganizationService = service.CreateOrganizationService(context.UserId); // 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"]; //</snippetAssignAutoNumberPlugin2> if (entity.LogicalName == "dots_autosms") { if (IsEntityExist(entity.LogicalName, entity.Attributes["dots_targetentitylogicalname"].ToString())) { throw new InvalidPluginExecutionException(string.Format("Already created SendSMS field for Entity {0}!", entity.Attributes["dots_targetentitylogicalname"].ToString())); } //for check duplicate field if (IsFieldExist(entity.LogicalName, entity.Attributes["dots_targetattributelogicalname"].ToString())) { throw new InvalidPluginExecutionException(string.Format("Field {0} already exist in Entity {1}!", entity.Attributes["dots_targetattributelogicalname"].ToString(), entity.LogicalName)); } SdkMessageProcessingStep step = new SdkMessageProcessingStep { AsyncAutoDelete = false, Mode = new OptionSetValue((int)CrmPluginStepMode.Synchronous), Name = _pluginTypeName + ": " + entity.Attributes["dots_name"].ToString(), EventHandler = new EntityReference("plugintype", GetPluginTypeId()), Rank = 1, SdkMessageId = new EntityReference("sdkmessage", GetMessageId()), Stage = new OptionSetValue((int)CrmPluginStepStage.PreOperation), SupportedDeployment = new OptionSetValue((int)CrmPluginStepDeployment.ServerOnly), SdkMessageFilterId = new EntityReference("sdkmessagefilter", GetSdkMessageFilterId(entity.Attributes["dots_targetentitylogicalname"].ToString())), Description = entity.Attributes["dots_targetattributelogicalname"].ToString() }; var SdkMessageProcessingStepId = OrganizationService.Create(step); entity.Attributes.Add("dots_sdkmessageprocessingstepid", SdkMessageProcessingStepId.ToString()); } else { var entityDetail = GetEntityByName(entity.LogicalName); if (entity.Attributes.Contains(entityDetail.TargetAttributeLogicalName) == true) { string contactNO = entity.Attributes[entityDetail.TargetAttributeLogicalName].ToString(); string i = SendSMS("CI00184183", "*****@*****.**", "xRldS3d7", contactNO, "hii You have created record for " + entity.LogicalName + " Thanks!"); if (i != "Success") { throw new InvalidPluginExecutionException(i); } //entity.Attributes.Add(entityDetail.TargetAttributeLogicalName, GetNewCode(entityDetail)); //IncreaseCurrentNumber(entity.LogicalName); } } } else if (context.InputParameters["Target"] is EntityReference) { if (context.PrimaryEntityName == "dots_autosms") { if (context.MessageName == "Delete") { Guid id = ((EntityReference)context.InputParameters["Target"]).Id; DSAutoSMS dots_autosms = OrganizationService.Retrieve("dots_autosms", ((EntityReference)context.InputParameters["Target"]).Id, new ColumnSet(true)).ToEntity <DSAutoSMS>(); OrganizationService.Delete("sdkmessageprocessingstep", new Guid(dots_autosms.SdkMessageProcessingStepId.ToString())); } } } }
public void Execute(IServiceProvider serviceProvider) { //Extract the tracing service for use in plug-in debugging. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); //make sure we have a target that is an entity if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { // Obtain the target entity from the input parameters. Entity entity = (Entity)context.InputParameters["Target"]; //set up the org service reference for our retrieve IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); //retrieve some results using the fetchxml supplied in the configuration EntityCollection results = service.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(string.Format(_fetchXml, entity.Id.ToString()))); //we should have one and only one result if (results.Entities.Count != 1) { throw new Exception("query did not return a single result"); } Entity retrieved = results.Entities[0]; //prepare the json message that will be sent to rabbitmq //set up our json writer StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonWriter jsonWriter = new JsonTextWriter(sw); jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; jsonWriter.WriteStartObject(); //loop through the retrieved attributes foreach (string attribute in retrieved.Attributes.Keys) { //generate different output for different attribute types switch (retrieved[attribute].GetType().ToString()) { //if we have a lookup, return the id and the name case "Microsoft.Xrm.Sdk.EntityReference": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(((EntityReference)retrieved[attribute]).Id); jsonWriter.WritePropertyName(attribute + "_name"); jsonWriter.WriteValue(((EntityReference)retrieved[attribute]).Name); break; //if we have an optionset value, return the value and the formatted value case "Microsoft.Xrm.Sdk.OptionSetValue": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(((OptionSetValue)retrieved[attribute]).Value); if (retrieved.FormattedValues.Contains(attribute)) { jsonWriter.WritePropertyName(attribute + "_formatted"); jsonWriter.WriteValue(retrieved.FormattedValues[attribute]); } break; //if we have money, return the value case "Microsoft.Xrm.Sdk.Money": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(((Money)retrieved[attribute]).Value); break; //if we have a datetime, return the value case "System.DateTime": jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(retrieved[attribute]); break; //for everything else, return the value and a formatted value if it exists default: jsonWriter.WritePropertyName(attribute); jsonWriter.WriteValue(retrieved[attribute]); if (retrieved.FormattedValues.Contains(attribute)) { jsonWriter.WritePropertyName(attribute + "_formatted"); jsonWriter.WriteValue(retrieved.FormattedValues[attribute]); } break; } } //always write out the message name (update, create, etc.), entity name and record id jsonWriter.WritePropertyName("operation"); jsonWriter.WriteValue(context.MessageName); jsonWriter.WritePropertyName("entity"); jsonWriter.WriteValue(retrieved.LogicalName); jsonWriter.WritePropertyName("id"); jsonWriter.WriteValue(retrieved.Id); jsonWriter.WriteEndObject(); //generate the json string string jsonMsg = sw.ToString(); jsonWriter.Close(); sw.Close(); try { //connect to rabbitmq var factory = new ConnectionFactory(); factory.UserName = _brokerUser; factory.Password = _brokerPassword; factory.VirtualHost = "/"; factory.Protocol = Protocols.DefaultProtocol; factory.HostName = _brokerEndpoint; factory.Port = AmqpTcpEndpoint.UseDefaultPort; IConnection conn = factory.CreateConnection(); using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { //tell rabbitmq to send confirmation when messages are successfully published channel.ConfirmSelect(); channel.WaitForConfirmsOrDie(); //prepare message to write to queue var body = Encoding.UTF8.GetBytes(jsonMsg); var properties = channel.CreateBasicProperties(); properties.SetPersistent(true); //publish the message to the exchange with the supplied routing key channel.BasicPublish(_exchange, _routingKey, properties, body); } } } catch (Exception e) { tracingService.Trace("Exception: {0}", e.ToString()); throw; } } }
public void Execute(IServiceProvider serviceProvider) { //Extract the tracing service for use in debugging sandboxed plug-ins. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); // Obtain the organization service reference. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); //Variable Declarations string webResourceName = string.Empty; Entity contactType = null; string content = string.Empty; // 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"]; //</snippetAccountNumberPlugin2> // Verify that the target entity represents an contact. // If not, this plug-in was not registered correctly. if (entity.LogicalName == "contact") { if (entity.Attributes.Contains("ims_contactgroups")) { tracingService.Trace("Contact Groups Found in Context"); EntityReference erfContactGroups = entity.GetAttributeValue <EntityReference>("ims_contactgroups"); if (erfContactGroups.Id != Guid.Empty) { //Get Web Resource Name from Contact type record contactType = service.Retrieve("ims_contacttype", erfContactGroups.Id, new ColumnSet("ims_webresourcename")); if (contactType != null && contactType.Attributes.Contains("ims_webresourcename")) { webResourceName = contactType.GetAttributeValue <string>("ims_webresourcename"); tracingService.Trace("Contact Groups Web Res Name Config:" + webResourceName); if (webResourceName != string.Empty) { //Get Web Resource content based on name var query = new QueryExpression("webresource"); query.TopCount = 1; query.ColumnSet.AddColumns("name", "content"); query.Criteria.AddCondition("name", ConditionOperator.Equal, webResourceName.Trim()); var webResource = service.RetrieveMultiple(query); if (webResource.Entities.Count > 0) { if (webResource.Entities[0].Attributes.Contains("content")) { tracingService.Trace("Web Res Content Found"); content = webResource.Entities[0].GetAttributeValue <string>("content"); Entity objContact = new Entity("contact"); objContact.Id = entity.Id; objContact["entityimage"] = Convert.FromBase64String(content); service.Update(objContact); } } } } } } } } }