public override void Run() { var query = PluginExecutionContext.InputParameterOrDefault <QueryExpression>("Query"); var entities = DataService.GetEntities(query); PluginExecutionContext.OutputParameters["BusinessEntityCollection"] = entities; }
protected PluginExecutionContext CreatePluginExecutionContext(string messageName, int depth, string primaryEntityName, int pipelineStage, EntityReference targetEntityReference) { PluginExecutionContext pec = CreatePluginExecutionContext(messageName, depth, primaryEntityName, pipelineStage); pec.InputParameters[PlatformConstants.TargetEntityReferenceText] = targetEntityReference; return(pec); }
private PluginExecutionData CreateExecutionData(PluginConfigurationData configurationData) { if (configurationData == null) { throw new ArgumentNullException(nameof(configurationData)); } PluginExecutionContext executionContext = new PluginExecutionContext { ActivityExecutionId = new Guid("DB0F4D03-3C83-43FB-A169-327BAFE47B7D"), SessionId = "EQWX9L4M", UserName = "******", UserPassword = "******" }; return(new PluginExecutionData ( configurationData.GetMetadata(), configurationData.MetadataVersion, new AssetInfoCollection(new List <AssetInfo>()), new DocumentCollection(new List <Document>()), new ServerInfoCollection(new List <ServerInfo>()), new PrintQueueInfoCollection(new List <PrintQueueInfo>()), new PluginEnvironment(new SettingsDictionary(new Dictionary <string, string>()), GlobalSettings.Items[Setting.Domain], GlobalSettings.Items[Setting.DnsDomain]), executionContext, new PluginRetrySettingDictionary(new List <PluginRetrySetting>()) )); }
/// <summary> /// Trace information about the SdkMessage that triggered the plugin /// </summary> /// <param name="_"></param> /// <param name="config"></param> private static void TraceTrigger(PluginExecutionContext _, PluginConfiguration config) { bool blnTraceMessageStack; bool.TryParse(config.UnsecureDictionary["TraceMessageStack"], out blnTraceMessageStack); if (blnTraceMessageStack) { StringBuilder messageStack = new StringBuilder(); IPluginExecutionContext adam = _; do { messageStack.AppendLine(adam.ToTraceableMessage()); adam = adam.ParentContext; } while (adam.ParentContext != null); adam = null; _.Trace( "Plugin message stack: {0}{1}", Environment.NewLine, messageStack.ToString()); } else { _.Trace( "Plugin triggered by {0}", _.ToTraceableMessage()); } }
public void PostMessageUponCreate_ExceptionHandling_TargetEntityIsRequired() { #region ARRANGE // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT try { // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); } catch (InvalidPluginExecutionException ex) { ActualException = ex; } #endregion #region ASSERT Assert.IsNotNull(ActualException); Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.TargetEntityIsRequired, Plugin.GetType().Name), ActualException.Message); #endregion }
public void Execute(PluginExecutionContext context) { if (context.Stage == OperationStage.PreOperation) { Execute(context.MessageName, context.Target, context.EntityMetadata); } }
public override void ExecutePlugin(PluginExecutionContext _) { Entity target = _.GetTarget<Entity>(); _.Trace("Updating {0}. Modified fields: {1}.", target.ToEntityReference().ToTraceable(), string.Join(",", target.Attributes.Keys.ToList())); }
protected void SetupMockResponseForPluginExecutionContext(PluginExecutionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } Plugin.PluginExecutionContext.Stub(x => x.BusinessUnitId).Return(context.BusinessUnitId); Plugin.PluginExecutionContext.Stub(x => x.CorrelationId).Return(context.CorrelationId); Plugin.PluginExecutionContext.Stub(x => x.Depth).Return(context.Depth); Plugin.PluginExecutionContext.Stub(x => x.InitiatingUserId).Return(context.InitiatingUserId); Plugin.PluginExecutionContext.Stub(x => x.InputParameters).Return(context.InputParameters); Plugin.PluginExecutionContext.Stub(x => x.IsExecutingOffline).Return(context.IsExecutingOffline); Plugin.PluginExecutionContext.Stub(x => x.IsInTransaction).Return(context.IsInTransaction); Plugin.PluginExecutionContext.Stub(x => x.IsOfflinePlayback).Return(context.IsOfflinePlayback); Plugin.PluginExecutionContext.Stub(x => x.IsolationMode).Return(context.IsolationMode); Plugin.PluginExecutionContext.Stub(x => x.MessageName).Return(context.MessageName); Plugin.PluginExecutionContext.Stub(x => x.Mode).Return(context.Mode); Plugin.PluginExecutionContext.Stub(x => x.OperationCreatedOn).Return(context.OperationCreatedOn); Plugin.PluginExecutionContext.Stub(x => x.OperationId).Return(context.OperationId); Plugin.PluginExecutionContext.Stub(x => x.OrganizationId).Return(context.OrganizationId); Plugin.PluginExecutionContext.Stub(x => x.OrganizationName).Return(context.OrganizationName); Plugin.PluginExecutionContext.Stub(x => x.OutputParameters).Return(context.OutputParameters); Plugin.PluginExecutionContext.Stub(x => x.OwningExtension).Return(context.OwningExtension); Plugin.PluginExecutionContext.Stub(x => x.ParentContext).Return(context.ParentContext); Plugin.PluginExecutionContext.Stub(x => x.PostEntityImages).Return(context.PostEntityImages); Plugin.PluginExecutionContext.Stub(x => x.PreEntityImages).Return(context.PreEntityImages); Plugin.PluginExecutionContext.Stub(x => x.PrimaryEntityId).Return(context.PrimaryEntityId); Plugin.PluginExecutionContext.Stub(x => x.PrimaryEntityName).Return(context.PrimaryEntityName); Plugin.PluginExecutionContext.Stub(x => x.RequestId).Return(context.RequestId); Plugin.PluginExecutionContext.Stub(x => x.SecondaryEntityName).Return(context.SecondaryEntityName); Plugin.PluginExecutionContext.Stub(x => x.SharedVariables).Return(context.SharedVariables); Plugin.PluginExecutionContext.Stub(x => x.Stage).Return(context.Stage); Plugin.PluginExecutionContext.Stub(x => x.UserId).Return(context.UserId); }
PluginExecutionData IPluginFrameworkSimulator.CreateExecutionData(PluginConfigurationData configurationData) { if (configurationData == null) { throw new ArgumentNullException(nameof(configurationData)); } PluginExecutionContext executionContext = new PluginExecutionContext { ActivityExecutionId = SequentialGuid.NewGuid(), SessionId = SessionId, UserName = UserName, UserPassword = UserPassword }; // Retrieve all selected assets, then add any badge boxes associated with those assets var selectedAssets = PluginConfigurationTransformer.GetExecutionAssets(configurationData, _assetInventory); var badgeBoxes = _assetInventory.GetBadgeBoxes(selectedAssets); AssetInfoCollection executionAssets = new AssetInfoCollection(selectedAssets.Union(badgeBoxes).ToList()); return(new PluginExecutionData ( configurationData.GetMetadata(), configurationData.MetadataVersion, executionAssets, PluginConfigurationTransformer.GetExecutionDocuments(configurationData, _documentLibrary), PluginConfigurationTransformer.GetExecutionServers(configurationData, _assetInventory), PluginConfigurationTransformer.GetExecutionPrintQueues(configurationData, _assetInventory), (this as IPluginFrameworkSimulator).Environment, executionContext, new PluginRetrySettingDictionary(RetrySettings) )); }
protected PluginExecutionContext CreatePluginExecutionContext(EntityReference targetEntityReference) { PluginExecutionContext pec = CreatePluginExecutionContext(); pec.InputParameters[PlatformConstants.TargetEntityReferenceText] = targetEntityReference; return(pec); }
private static void GetPreImage(PluginExecutionContext _, out Entity preImage) { _.Trace("Getting PreEntityImage."); preImage = _.GetPreImage<Entity>(); if (preImage == null) { throw new InvalidPluginExecutionException("PreEntityImage is null. Register a single PreEntityImage on the message processing step, including all attributes that are to be compared."); } }
private static void TraceEntryPoint(PluginExecutionContext _, string pluginTypeName) { _.Trace("Entering {0}.Execute(), Depth: {1}, Request Id: {2}, Correlation Id: {3}, Running as: {4}.", pluginTypeName, _.Depth.ToString(), _.RequestId.ToString(), _.CorrelationId.ToString(), _.InitiatingUserId.ToString()); }
public String GetContextInfo() { return ("**** Context Info ****" + Environment.NewLine + "Plugin: " + PluginTypeName + Environment.NewLine + "* Registered Event *" + Environment.NewLine + Event.ToString(" ") + Environment.NewLine + PluginExecutionContext.ToStringDebug()); }
private static void GetTarget(PluginExecutionContext _, out Entity target) { _.Trace("Getting InputParameter['Target']."); target = _.GetTarget<Entity>(); if (target == null) { throw new InvalidPluginExecutionException("Target is null."); } }
protected void InitializeUnitTest(PluginExecutionContext context) { SetupMockObjects(); SetupMockResponseForServiceProvider(); SetupMockResponseForPluginExecutionContext(context); SetupMockResponseForOrganizationServiceFactory(); SetupMockResponseForOverriddenMethods(); }
public override void ExecutePlugin(PluginExecutionContext _) { Entity target = null; Entity preImage = null; OptimizedUpdate.ValidatePluginRegistration(_); OptimizedUpdate.GetTarget(_, out target); OptimizedUpdate.GetPreImage(_, out preImage); OptimizedUpdate.ReduceTargetToDelta(_, target, preImage); }
private void ExecutePluginWithTracesOnEntryAndExit(PluginExecutionContext _) { TraceEntryPoint(_, this.PluginTypeName); TraceTrigger(_, this.Configuration); TimeSpan duration = Metrics.TimeAction(() => { ExecutePlugin(_); }); TraceExitPointWithDuration(_, this.PluginTypeName, duration); }
protected PluginExecutionContext CreatePluginExecutionContext(string messageName, int depth, string primaryEntityName, int pipelineStage) { PluginExecutionContext pec = CreatePluginExecutionContext(); pec.Depth = depth; pec.MessageName = messageName; pec.PrimaryEntityName = primaryEntityName; pec.Stage = pipelineStage; return(pec); }
static void Main(string[] args) { // NOTES // 1. Start running in Debug mode in VS, I have set start up args (on project page) to be: // gitout.exe --plugin releasenotes --verbose --issuetracker "github" --accesstoken "sometoken" --reponame "myrepo" // you could also use: // gitout.exe --plugin semver // I have also set a post-build event on the ReleaseNotesPlugin project and the SemanticVersionPlugin project, // so that their assemblies are copied into the GitOut.exe directory, so that they can be discovered at runtime as a plugins. var parser = new CommandLine.Parser(with => with.IgnoreUnknownArguments = true); var appOptions = new Options(); if (parser.ParseArguments(args, appOptions)) { // parsing succeds // discover / load plugins var pluginManager = new PluginManager(); var plugin = pluginManager.GetPluginInstanceByName(appOptions.PluginName); if (plugin == null) { Console.WriteLine("Plugin not found for a command named: " + appOptions.PluginName); return; } try { // plugin execution context is context that we can pass to any plugin - and also could provide // the ability for plugins to access shared / central state. // it could contain commonly needed things like IssueTrackers, Loggers, or a service locator etc. var pluginExecutionContext = new PluginExecutionContext(); pluginExecutionContext.Args = args; // command line args defferred to the plugin. // Execute the plugin. plugin.Execute(pluginExecutionContext); } catch (Exception e) { HandlePluginExecutionError(e); return; } } else { // In addition to allowing particular plugins to be invoked on their own, // We could allow a workflow execution, based on a config file. // we could do that here by parsing a command that points to the yaml config // which would define which plugins were executed, with which settings, and in which order? Console.WriteLine("Failed to parse args, see usage."); } }
public void Execute(PluginExecutionContext context) { if (context.MessageName == OperationTypeEnum.Create && context.Stage == OperationStage.PreOperation) { var snr = _serialNumberRuleFinder.FindByEntityId(context.EntityMetadata.EntityId); if (snr != null && context.Target.GetStringValue(snr.AttributeName).IsEmpty()) { context.Target.SetAttributeValue(snr.AttributeName, _serialNumberGenerator.Generate(snr.SerialNumberRuleId)); } } }
PluginExecutionData IPluginFrameworkSimulator.CreateExecutionData(PluginConfigurationData configurationData) { if (configurationData == null) { throw new ArgumentNullException(nameof(configurationData)); } PluginExecutionContext executionContext = new PluginExecutionContext { ActivityExecutionId = SequentialGuid.NewGuid(), SessionId = SessionId, UserName = UserName, UserPassword = UserPassword }; // Retrieve all selected assets, then add any badge boxes associated with those assets var selectedAssets = PluginConfigurationTransformer.GetExecutionAssets(configurationData, _assetInventory); var badgeBoxes = _assetInventory.GetBadgeBoxes(selectedAssets); AssetInfoCollection executionAssets = new AssetInfoCollection(selectedAssets.Union(badgeBoxes).ToList()); // Set job media mode if (PaperlessMode != JobMediaMode.Unknown) { foreach (DeviceInfo deviceInfo in selectedAssets.Where(n => n.Attributes.HasFlag(AssetAttributes.Printer))) { using (var device = DeviceConstructor.Create(deviceInfo)) { try { DeviceSettingsManagerFactory.Create(device).SetJobMediaMode(PaperlessMode); } catch { //Did not set paperless mode. Ignore error. System.Diagnostics.Debug.WriteLine($"Error setting paperless mode. {executionAssets.ToString()}"); } } } } return(new PluginExecutionData ( configurationData.GetMetadata(), configurationData.MetadataVersion, executionAssets, PluginConfigurationTransformer.GetExecutionDocuments(configurationData, _documentLibrary), PluginConfigurationTransformer.GetExecutionServers(configurationData, _assetInventory), PluginConfigurationTransformer.GetExecutionPrintQueues(configurationData, _assetInventory), (this as IPluginFrameworkSimulator).Environment, executionContext, new PluginRetrySettingDictionary(RetrySettings), new ExternalCredentialInfoCollection(_assetInventory.GetExternalCredentials(executionContext.UserName)) )); }
public void MessageTests() { PluginExecutionContext.SetupGet(s => s.MessageName).Returns("Machin"); AssertException <InvalidPluginExecutionException>(() => { var message = LocalContext.MessageName; }); PluginExecutionContext.SetupGet(s => s.MessageName).Returns("Update"); var messageOk = LocalContext.MessageName; }
public void ModeTests() { PluginExecutionContext.SetupGet(s => s.Mode).Returns(45); AssertException <InvalidPluginExecutionException>(() => { var mode = LocalContext.Mode; }); PluginExecutionContext.SetupGet(s => s.Mode).Returns(0); var modeOk = LocalContext.Mode; }
protected PluginExecutionContext CreatePluginExecutionContext(string messageName, int depth, string primaryEntityName, int pipelineStage, EntityReference targetEntityReference, Entity preEntity, Entity postEntity) { PluginExecutionContext pec = CreatePluginExecutionContext(messageName, depth, primaryEntityName, pipelineStage, targetEntityReference); if (preEntity != null) { pec.PreEntityImages[PlatformConstants.PreBusinessEntityText] = preEntity; } if (postEntity != null) { pec.PostEntityImages[PlatformConstants.PostBusinessEntityText] = postEntity; } return(pec); }
protected PluginExecutionContext CreatePluginExecutionContext(EntityReference targetEntityReference, Entity preEntity, Entity postEntity) { PluginExecutionContext pec = CreatePluginExecutionContext(targetEntityReference); if (preEntity != null) { pec.PreEntityImages[PlatformConstants.PreBusinessEntityText] = preEntity; } if (postEntity != null) { pec.PostEntityImages[PlatformConstants.PostBusinessEntityText] = postEntity; } return(pec); }
public void Execute(PluginExecutionContext context) { if (context.Stage == OperationStage.PreOperation) { var hitRules = ExecuteCore(context.Target, context.EntityMetadata, context.AttributeMetadatas); if (hitRules != null && hitRules.Any()) { string error = string.Empty; foreach (var rule in hitRules) { error = " \n" + rule.Rule.Name + " \n" + rule.Rule.Description; } throw new XmsException(_loc["sdk_record_duplicated"] + ": " + error); } } }
protected PluginExecutionContext CreatePluginUnitTestContextEntityMoniker(EntityReference entityMoniker, Entity preEntity, Entity postEntity) { PluginExecutionContext pec = CreatePluginExecutionContext(); if (entityMoniker != null) { pec.InputParameters[PlatformConstants.EntityMonikerText] = entityMoniker; } if (preEntity != null) { pec.PreEntityImages[PlatformConstants.PreBusinessEntityText] = preEntity; } if (postEntity != null) { pec.PostEntityImages[PlatformConstants.PostBusinessEntityText] = postEntity; } return(pec); }
public void ManageEntityDeletionUponDelete_ExceptionHandling_MaxDepthViolation() { #region ARRANGE // Prepare the unit test mock target entity reference EntityReference targetEntityReference = new EntityReference(Account.EntityLogicalName, Guid.NewGuid()); // Prepare the unit test mock target entity Entity preEntity = CreateAccountEntity(); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(PlatformMessageHelper.Delete, CustomPlugin.MaximumAllowedExecutionDepth + 1, preEntity.LogicalName, (int)SdkMessageProcessingStepStage.PreOperation, targetEntityReference, preEntity, null); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT try { // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); } catch (InvalidPluginExecutionException ex) { ActualException = ex; } #endregion #region ASSERT Assert.IsNotNull(ActualException); Assert.AreEqual(ActualException.Message, string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.MaxDepthViolation, Plugin.GetType().Name, CustomPlugin.MaximumAllowedExecutionDepth, CustomPlugin.MaximumAllowedExecutionDepth + 1)); #endregion }
public void ManageEntityDeletionUponDelete_ExceptionHandling_WrongRegisteredEntity() { #region ARRANGE // Prepare the unit test mock target entity reference EntityReference targetEntityReference = new EntityReference(Account.EntityLogicalName, Guid.NewGuid()); // Prepare the unit test mock target entity Entity preEntity = new Entity { LogicalName = _dummyText }; // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(targetEntityReference, preEntity, null); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT try { // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); } catch (InvalidPluginExecutionException ex) { ActualException = ex; } #endregion #region ASSERT Assert.IsNotNull(ActualException); Assert.AreEqual(ActualException.Message, string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.WrongRegisteredEntity, Plugin.GetType().Name, _dummyText)); #endregion }
public void ForTypeTest() { var method = typeof(TestPlugin).GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)[0]; var account = new Entities.Account { AccountId = Guid.NewGuid() }; var unsecureConfig = "unsecure config"; var secureConfig = "secure config"; var context = PluginExecutionContext.ForMethodWithTarget(method, account); var serviceCache = new Kipon.Xrm.Reflection.ServiceCache(context, organizationServiceFactory, traceService, null, unsecureConfig, secureConfig); var methodCache = pluginMethodcache.ForPlugin(typeof(TestPlugin), 20, "Update", Entities.Account.EntityLogicalName, false); var p1 = serviceCache.Resolve(methodCache[0].Parameters[0]); Assert.AreEqual(p1, account); var p2 = serviceCache.Resolve(methodCache[0].Parameters[1]) as OrganizationService; Assert.IsInstanceOfType(p2, typeof(OrganizationService)); Assert.AreEqual(PluginExecutionContext.USERID, p2.UserId.Value); var p3 = serviceCache.Resolve(methodCache[0].Parameters[2]) as Kipon.Solid.Plugin.Entities.AdminCrmUnitOfWork; Assert.IsNotNull(p3); Assert.AreNotEqual(p2, p3.OrgService); var p4 = serviceCache.Resolve(methodCache[0].Parameters[3]) as Kipon.Solid.Plugin.Service.AccountService; Assert.IsNotNull(p4); Assert.AreEqual(p2, p4.OrgService); var p5 = serviceCache.Resolve(methodCache[0].Parameters[4]); Assert.AreEqual(account, p5); Assert.AreEqual(unsecureConfig, p4.UnsecureConfig); Assert.AreEqual(secureConfig, p4.SecureConfig); }
public void InitializeEntityUponCreate_InitializeEntityService_InitializeEntity_CurrentAccountNumberIsEmpty() { #region ARRANGE // Prepare the unit test mock target entity Account account = CreateAccount(string.Empty); Entity targetEntity = CreateAccountEntity(account); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(PlatformMessageHelper.Create, CustomPlugin.MaximumAllowedExecutionDepth, targetEntity.LogicalName, (int)SdkMessageProcessingStepStage.PreOperation, targetEntity); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); #endregion #region ASSERT // Load the modified plugin execution context IPluginExecutionContext pex = Plugin.PluginExecutionContext; Entity modifiedTargetEntity = (Entity)pex.InputParameters[PlatformConstants.TargetText]; Account modifiedTarget = modifiedTargetEntity.ToEntity <Account>(); // Assertions Assert.AreNotEqual(modifiedTarget.AccountNumber, string.Empty); Assert.AreEqual(modifiedTarget.AccountNumber, string.Format(CultureInfo.InvariantCulture, InitializeEntityService.TextFormat, modifiedTarget.CreatedOn.Value.ToString(InitializeEntityService.DateTimeFormat, CultureInfo.InvariantCulture))); #endregion }
void IPlugin.Execute(IServiceProvider serviceProvider) { PluginExecutionContext _ = new PluginExecutionContext(serviceProvider); try { this.ExecutePluginWithTracesOnEntryAndExit(_); } catch (InvalidPluginExecutionException) { throw; } catch (Exception ex) { _.Trace("!! Exception caught, plugin aborting."); throw new InvalidPluginExecutionException( string.Format( "Plugin '{0}' failed to execute, returning the error: {1}", PluginTypeName, ex.Message ), ex); } }
public void PostMessageUponCreate_ExceptionHandling_MaxDepthViolation() { #region ARRANGE // Prepare the unit test mock target entity Entity targetEntity = CreateExecutionContextEntity(); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(PlatformMessageHelper.Create, 8, targetEntity.LogicalName, (int)SdkMessageProcessingStepStage.PostOperation, targetEntity); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT try { // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); } catch (InvalidPluginExecutionException ex) { ActualException = ex; } #endregion #region ASSERT Assert.IsNotNull(ActualException); Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.MaxDepthViolation, Plugin.GetType().Name, CustomPlugin.MaximumAllowedExecutionDepth, CustomPlugin.MaximumAllowedExecutionDepth + 1), ActualException.Message); #endregion }
/// <summary> /// Initializes the plugin properties. /// </summary> /// <param name="plugin">The plugin.</param> private void InitializePluginProperties(IRegisteredEventsPlugin plugin) { Event = PluginExecutionContext.GetEvent(plugin.RegisteredEvents); if (Event == null) { var message = $"No RegisteredEvent found for the current context of Stage: {this.GetPipelineStage()}, Message: {MessageName}, Entity: {PrimaryEntityName}. Either Unregister the plugin for this event, or include this as a RegisteredEvent in the Plugin's RegisteredEvents."; try { TracingService.Trace(message); TracingService.Trace(this.GetContextInfo()); } finally { throw new InvalidPluginExecutionException(message); } } if (Event.Message == RegisteredEvent.Any) { Event = new RegisteredEvent(Event.Stage, PluginExecutionContext.GetMessageType(), Event.Execute); } PluginTypeName = plugin.GetType().FullName; }
public void InitializeEntityUponUpdate_InitializeEntityService_InitializeEntity_CurrentAccountNumberContainsData() { #region ARRANGE // Prepare the unit test mock target entity Account account = CreateAccount(_dummyString); Entity targetEntity = CreateAccountEntity(account); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(PlatformMessageHelper.Update, CustomPlugin.MaximumAllowedExecutionDepth, targetEntity.LogicalName, (int)SdkMessageProcessingStepStage.PreOperation, targetEntity, null, null); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); #endregion #region ASSERT // Load the modified plugin execution context IPluginExecutionContext pex = Plugin.PluginExecutionContext; Entity modifiedTargetEntity = (Entity)pex.InputParameters[PlatformConstants.TargetText]; Account modifiedTarget = modifiedTargetEntity.ToEntity <Account>(); // Assertions Assert.AreEqual(modifiedTarget.AccountNumber, _dummyString); #endregion }
public void PostMessageUponCreate_ExceptionHandling_IncorrectMessageName() { #region ARRANGE // Prepare the unit test mock target entity Entity targetEntity = CreateExecutionContextEntity(); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(_dummyText, _dummyNumber, targetEntity.LogicalName, _dummyNumber, targetEntity); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT try { // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); } catch (InvalidPluginExecutionException ex) { ActualException = ex; } #endregion #region ASSERT Assert.IsNotNull(ActualException); Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, TraceMessageHelper.IncorrectMessageName, Plugin.GetType().Name, PlatformMessageHelper.Create, _dummyText), ActualException.Message); #endregion }
public void StoreContextUponAnyEvent_ManageExecutionContext_StoreExecutionContext() { #region ARRANGE // Prepare the unit test mock target entity Account account = CreateAccount(_dummyText); Entity targetEntity = CreateAccountEntity(account); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(PlatformMessageHelper.Create, 7, targetEntity.LogicalName, (int)SdkMessageProcessingStepStage.PostOperation, targetEntity); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); #endregion #region ASSERT // Load the modified plugin execution context CrmServiceContext csc = Plugin.OrganizationServiceContext; ExecutionContext ec = csc.GetAttachedEntities().Single().ToEntity <ExecutionContext>(); // Assertions Assert.IsNotNull(ec); Assert.AreEqual(targetEntity.LogicalName, ec.EntityName); Assert.AreEqual(targetEntity.Id, new Guid(ec.EntityId)); #endregion }
public void PostMessageUponCreate_PostMessageService_PostMessage_Dosomething() { #region ARRANGE // Prepare the unit test mock target entity ExecutionContext account = CreateExecutionContext(_dummyText); Entity targetEntity = CreateExecutionContextEntity(account); // Setup the unit test mock context PluginExecutionContext context = CreatePluginExecutionContext(PlatformMessageHelper.Create, 7, targetEntity.LogicalName, (int)SdkMessageProcessingStepStage.PostOperation, targetEntity); // Initialize the unit test InitializeUnitTest(context); // Setup the plugin mock objects SetupMockObjectsForPlugin(); #endregion #region ACT // Execute the plugin step Plugin.Execute(Plugin.ServiceProvider); #endregion #region ASSERT // Load the modified plugin execution context IPluginExecutionContext pex = Plugin.PluginExecutionContext; Entity modifiedTargetEntity = (Entity)pex.InputParameters[PlatformConstants.TargetText]; ExecutionContext modifiedTarget = modifiedTargetEntity.ToEntity <ExecutionContext>(); // Assertions #endregion }
public abstract void ExecutePlugin(PluginExecutionContext _);
public override void ExecutePlugin(PluginExecutionContext _) { var target = _.GetTarget<Entity>(); _.Trace("Target: ", (target == null ? "(null)" : target.ToTraceable())); }
private static void ValidatePluginRegistration(PluginExecutionContext _) { if (string.Compare(_.MessageName, "Update", ignoreCase: true) != 0 || !(_.Stage == PluginStage.PreValidation || _.Stage == PluginStage.PreOperation)) { _.Trace("This plugin only supports the Update message in Pre-Validation or Pre-Operation stages."); throw new InvalidPluginExecutionException("Invalid SdkMessageStep registration."); } }
public override void ExecutePlugin(PluginExecutionContext _) { }
private static void TraceExitPointWithDuration(PluginExecutionContext _, string pluginTypeName, TimeSpan duration) { _.Trace("Exiting {0}.Execute(), Correlation Id: {1}, Duration: {2:N2}ms.", pluginTypeName, _.CorrelationId.ToString(), duration.TotalMilliseconds); }
private static void ReduceTargetToDelta(PluginExecutionContext _, Entity target, Entity preImage) { _.Trace("Reducing 'Target' Entity to delta, based on attribute values in the PreEntityImage."); IEnumerable<string> keysRemoved = target.ReduceToDelta(preImage); _.Trace("Removed attributes: {0}", string.Join(",", keysRemoved)); }