CRM tracing for plugin but not for custom workflow activity - dynamics-crm-2015

I use the the tracing service of CRM for plugins and custom workflow activities. The plugins run in sandbox mode, the custom workflow activities in non-sandbox mode.
One of my plugins starts a custom workflow. I see trace logs during the execution of the plugin, but no trace logs are written for my custom workflow activity.
I have restarted the CRM services also, still no logs
What can be wrong here ?
Here is some code:
public class MyPlugin : Plugin
{
protected override void Execute(RuntimeContext context)
{
var actionToExecute = new OrganizationRequest("MyActivity")
{
}
context.MyOrganizationService.Execute(actionToExecute);
}
}
public class MyActivity : CodeActivity
{
protected override void Execute(CodeActivityContext executionContext)
{
var context = new RuntimeContext(executionContext);
var tracingService = executionContext.GetExtension<ITracingService>();
tracingService.Trace("Hello world");
}
}

Related

Spring Boot Cucumber Java 8 Testing ApplicationOnReady Event

I have a reporting application that generates a report on ApplicationReadyEvent. I am trying to write cucumber tests for it but as the application event is fired even before my feature is executed , i am not sure what is the right way to test it. Can i control the event during testing ?
#EventListener(ApplicationReadyEvent.class)
private void generateAccuracyAnalysisReport() throws IOException
{
//some Logic
}
Cucumber Classes :
#SpringBootTest
#CucumberContextConfiguration
#ActiveProfiles("junit")
public class CucumberConfiguration
{
}
#RunWith(Cucumber.class)
#CucumberOptions(plugin = "pretty", features = "src/test/resources/cucumber/features")
public class CucumberFullIntegrationTest
{
}
Step Definition:
public class ReportStepDefs implements En {
public ReportStepDefs() {
When("^System sends an application event to generate report$", () -> {
});
Then("^Report should be generated successfully\\.$", () -> {
});
}
}
If your Cucumber tests involve Spring life-cycle you can not use cucumber-spring. Rather you have to use something like Springs ApplicationContextRunner to, configure, run and verify something about your application as part of each scenario.
// Given
ApplicationContextRunner contextRunner = new ApplicationContextRunner();
// When
contextRunner.withConfiguration(AutoConfigurations.of(...);
// Then
contextRunner.run(context -> assertThat(context).... /* something */ );
// Or assert something external to the application context.
Though it sounds like your application is doing something once and then exits. If so you should be using the CommandLineRunner instead of ApplicationReadyEvent in a web application. This is testable with cucumber-spring.
#RequiredArsConstructor
public class StepDefinitions {
final MyCommandLineRunner commandLineRunner;
#When(....)
public void something() {
commandLineRunner.run("input.txt", "input2.txt");
}
#Then(....)
public void assertSomething() {
// check if report was generated
}
}

BackgroundService with asp.net Core MVC 3.1

Here is what i've done:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHostedService<MyBatch>();
}
public class MyBatch : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stopToken)
{
while (!stopToken.IsCancellationRequested)
{
Console.Writeline("test");
await Task.Delay(TimeSpan.FromSeconds(10));
}
}
}
I have 2 problems:
First: The web application does not respond on 5000 port when i launch "dotnet run". If i remove my batch, the 5000 port works again. (test messages are displayed on console)
Second: I want to access to my database with Entity Framework. How can i access to my database context from this batch file ?
Thanks
I want to access to my database with Entity Framework. How can i access to my database context from this batch file ?
To consume a scoped service (such as DbContext etc) from singleton hosted service, you can create a scope then use it to resolve scoped service(s) you need from this scope, like below.
public class MyBatch : BackgroundService
{
public IServiceProvider Services { get; }
public MyBatch(IServiceProvider services)
{
Services = services;
}
protected override async Task ExecuteAsync(CancellationToken stopToken)
{
while (!stopToken.IsCancellationRequested)
{
Console.WriteLine("test");
await Task.Delay(TimeSpan.FromSeconds(10));
await DoWithDb(stopToken);
}
}
private async Task DoWithDb(CancellationToken stoppingToken)
{
//...
using (var scope = Services.CreateScope())
{
var _myDbContext =
scope.ServiceProvider
.GetRequiredService<MyDbContext>();
//code logic here
//...
}
}
}
You can also get detailed information about "consuming a scoped service in a background task" from here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio#consuming-a-scoped-service-in-a-background-task

How to unit test an action filter attribute for web api in asp.net core?

I have written an action filter for a web api. If a method in the api controller throws an unhandled exception, then the filter creates an internal error 500 response.
I need to know how to test the filter?
I have researched extensively but could not create a suitable test. I tried context mocking, a service locator implementation and even an integration test using a test server.
The web api controller looks like this:
namespace Plod.Api.ApiControllers
{
[TypeFilter(typeof(UnhandledErrorFilterAttribute))]
[Route("api/[controller]")]
public class GamesController : BaseApiController
{
public GamesController(IGameService repository,
ILogger<GamesController> logger,
IGameFactory gameFactory
) : base(
repository,
logger,
gameFactory
)
{ }
// ..... controller methods are here
}
}
The complete controller is found here.
The filter is this:
namespace Plod.Api.Filters
{
public class UnhandledErrorFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.ExceptionHandled = true;
}
}
}
}
I even welcome changes to the filter implementation as a possible work around. Any help or ideas would be much appreciated. Thanks.
You probably can't. However, what you can do is spin up a TestServer and then hit it with a HttpClient. This really is an integration test and not a unit test. However, it's the good kind of integration test because it can be run safely in pipelines.
This document explains how to do this:
https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1
The issue you are going to face is that you will need to mock the underlying services inside your app. If you don't do that, your whole server will spin up and attempt to hit the database etc. Here is an example. This is using Moq. Incidentally I am sharing the ConfigureServices method with unit tests so they use the same object mesh of mocked services. You can still use the full functionality of Moq or NSubstitute to test the back-end (or even front -end).
I can hit my attributes in the test with breakpoint.
private void ConfigureServices(IServiceCollection services)
{
var hostBuilder = new WebHostBuilder();
hostBuilder.UseStartup<TestStartup>();
hostBuilder.ConfigureServices(services =>
{
ConfigureServices(services);
});
_testServer = new TestServer(hostBuilder);
_httpClient = _testServer.CreateClient();
}
private void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(_storageManagerFactory.Object);
services.AddSingleton(_blobReferenceManagerMock.Object);
services.AddSingleton(_ipActivitiesLoggerMocker.Object);
services.AddSingleton(_loggerFactoryMock.Object);
services.AddSingleton(_hashingService);
services.AddSingleton(_settingsServiceMock.Object);
services.AddSingleton(_ipActivitiesManager.Object);
services.AddSingleton(_restClientMock.Object);
_serviceProvider = services.BuildServiceProvider();
}
public class TestStartup
{
public void Configure(
IApplicationBuilder app,
ISettingsService settingsService)
{
app.Configure(settingsService.GetSettings());
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var mvc = services.AddMvc(option => option.EnableEndpointRouting = false);
mvc.AddApplicationPart(typeof(BlobController).Assembly);
services.AddSingleton(new Mock<IHttpContextAccessor>().Object);
return services.BuildServiceProvider();
}
}

JBPM Task Event Lister Registration

I am using JBPM 6.2 core engine in our application.
I wanted to use my own Custom Task Event Listener to execute my own java code.
I didn't find any documentation so that I can use with JBPM core runtime engine. I found multiple places to use with console and define in deployment descriptor.
Please help!
We can register Task event Listener at RuntimeManager level or at TaskService level.
TaskService taskService = runtime.getTaskService();
((EventService<TaskLifeCycleEventListener>)taskService).registerTaskEventListener(new DefaultTaskEventListener() {
#Override
public void afterTaskAddedEvent(TaskEvent event) {
System.out.println("taskId = " + event.getTask().getId());
}
});
At RuntimeManager level:
RuntimeEnvironment environment =
RuntimeEnvironmentBuilder.getDefault()
.persistence(true)
.entityManagerFactory(emf)
.userGroupCallback(userGroupCallback)
.addAsset(ResourceFactory.newClassPathResource(process),
ResourceType.BPMN2)
.registerableItemsFactory(new DefaultRegisterableItemsFactory() {
#Override
public List getTaskListeners() {
List listeners = super.getTaskListeners();
listeners.add(new DefaultTaskEventListener() {
#Override
public void afterTaskAddedEvent(TaskEvent event) {
System.out.println("taskId = " + event.getTask().getId());
}
});
return listeners;
}
})
.get();
return RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment);

Autofac with MEF integration

I need help. I create Windows Service with Autofac container.
And I use MEF Integration service for create several alternative components for my service.
For example:
Module 1
[Export(typeof(IClass1))]
public class Class1 : IClass1
{
public void Show()
{
Console.WriteLine("Hallo from Class1");
}
}
Module 2
[Export(typeof(IClass2))]
public class Class2 : IClass2
{
public void Show()
{
Console.WriteLine("Hallo from Class2");
}
}
Basic class for modules integration - example
class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
// Create your builder.
var builder = new ContainerBuilder();
/** find all modules in selected folder */
var catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\modules", "*Module.dll");
/** register finded modules */
builder.RegisterComposablePartCatalog(catalog);
builder.RegisterType<MyClass>().As<IMyClass>().SingleInstance();
Container = builder.Build();
var cls = Container.Resolve<IMyClass>();
cls.Show();
Console.WriteLine("Class ready. Press Enter");
Console.ReadKey(true);
}
}
class MyClass: IMyClass
{
private readonly IClass1 _class1;
private readonly IClass1 _class3;
private readonly IClass2 _class2;
private readonly IClass2 _class4;
public MyClass(IClass1 class1, IClass2 class2)
{
_class1 = class1;
_class2 = class2;
_class3 = class1;
_class4 = class2;
}
public void Show()
{
_class1.Show();
Console.WriteLine("Class1 ready. Press Enter");
Console.ReadKey(true);
_class2.Show();
Console.WriteLine("Class1 ready. Press Enter");
Console.ReadKey(true);
}
}
internal interface IMyClass
{
void Show();
}
In this example all work fine.This principle I use in my service. For test start and debug my service I use Service.Helper from Nuget packages repository.
Everithyng work fine too.
But. If i create install package in Advance installer and install my service in system (Windows 8.1 x64) service do not start.
Logging exception from service write System.ArgumentNullException in system Event log. Exception most likely in this line
builder.RegisterComposablePartCatalog(catalog);
Service do not load any modules from start folder. Access denied from service to his subfolder. Help please. Thanks.
Try Assembly.GetEntryAssembly().Location insted of Assembly.GetExecutingAssembly().Location

Resources