Is there any way to pass Output of one workflow to another without using outarguments? - workflow-foundation-4

I have recently started working with Workflows.I am able to pass output of one activity as input to another through making use of OutArgument .Is it possible without using OutArgument.
If Possible please suggest me how?
Thanks all

You can use a workflow extension to act as a repository of variables in the scope of the whole workflow.
Create a workflow extension that contains properties.
Add the extension to the workflow application.
Set or Get the value of the properties from within Activities.
See https://msdn.microsoft.com/en-us/library/ff460215(v=vs.110).aspx
In response to your comment below.
You are wrong in your assumption. The extension "holds" the output from activity 1 which is then available to activity 2.
For example:
Create a class to hold properties:
public class PropertyStoreExtension
{
int _myProperty
public int MyProperty
{
get
{
return this._myProperty;
}
set
{
this._myProperty = value;
}
}
}
Add this as an extension to your workflow:
PropertyStoreExtension propertyStoreExtension = new PropertyStoreExtension
WorkflowInvoker myWorkflowInstence = new
WorkflowInvoker(myWorkflowDefinition());
myWorkflowInstence.Extensions.Add(propertyStoreExtension);
myWorkflowInstence.Invoke()
Your workflow contains 2 activities:
The first takes its "output" and stores it in the extension.
public class Activity1_SetProperty: CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
PropertyStoreExtension pse =context.GetExtension<PropertyStoreExtension>();
if (pse != null)
{
pse.MyProperty=outputValue;
}
}
}
The second gets the value out of the extension.
public class Activity2_GetProperty: CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
PropertyStoreExtension pse =context.GetExtension<PropertyStoreExtension>();
if (pse != null)
{
int intputValue; = pse.MyProperty
}
}
}

Related

After creating a custom projinvoice can't find created design

I need some help here. I created a custom report invoice design for PSAProjInvoice.
I did duplicate PSAProjInvoice and worked on a already made design.
Created a Controller and PrintMgmtDocTypeHandler class.
Created outputitem extension and redirected it to my ProjInvoiceController
In axapta in ProjFormletterParameters form parameters it shows me name of my custom report but when I go to project invoices and try to make a look at the invoice I just get a error: Unable to find the report design PSAProjInvoiceSZM.ReportPL.
class PSAProjInvoiceSZM
{
[PostHandlerFor(classStr(PSAProjAndContractInvoiceController),
staticMethodStr(PSAProjAndContractInvoiceController, construct))]
public static void ReportNamePostHandler(XppPrePostArgs arguments)
{
PSAProjAndContractInvoiceController controller = arguments.getReturnValue();
controller.parmReportName(ssrsreportstr(PSAprojinvoiceSZM, Report));
}
}
I think that it's a problem with my controller class because I actually have no idea how it should look like. Tried to make one based on salesinvoice tutorial found on microsoft docs but it didn't help me at all.
Tried to make it based on this article:
https://blogs.msdn.microsoft.com/dynamicsaxbi/2017/01/01/how-to-custom-designs-for-business-docs/
My Controller:
class ProjInvoiceControllerSZM extends PSAProjAndContractInvoiceController
{
public static ProjInvoiceControllerSZM construct()
{
return new ProjInvoiceControllerSZM();
}
public static void main(Args _args)
{
SrsReportRunController formLetterController =
ProjInvoiceControllerSZM::construct();
ProjInvoiceControllerSZM controller = formLetterController;
controller.initArgs(_args);
Controller.parmReportName(ssrsReportStr(PSAProjInvoiceSZM, Report));
/* if (classIdGet(_args.caller()) ==
classNum(PurchPurchOrderJournalPrint))
{
formLetterController.renderingCompleted +=
eventhandler(PurchPurchOrderJournalPrint::renderingCompleted);
}*/
formLetterController.startOperation();
}
protected void outputReport()
{
SRSCatalogItemName reportDesign;
reportDesign = ssrsReportStr(PSAProjInvoiceSZM,Report);
this.parmReportName(reportDesign);
this.parmReportContract().parmReportName(reportDesign);
formletterReport.parmReportRun().settingDetail().parmReportFormatName(reportDesign);
super();
}
}

Resolve named registration dependency in Unity with runtime parameter

I have a following problem. I register my components and initialize them in Unity like this (example is for a Console application):
public class SharePointBootstrapper : UnityBootstrapper
{
...
public object Initialize(Type type, object parameter) =>
Container.Resolve(type,
new DependencyOverride<IClientContext>(Container.Resolve<IClientContext>(parameter.ToString())),
new DependencyOverride<ITenantRepository>(Container.Resolve<ITenantRepository>(parameter.ToString())));
public void RegisterComponents()
{
Container
.RegisterType<IClientContext, SharePointOnlineClientContext>(SharePointClientContext.Online.ToString())
.RegisterType<IClientContext, SharePointOnPremiseClientContext>(SharePointClientContext.OnPremise.ToString())
.RegisterType<ITenantRepository, DocumentDbTenantRepository>(SharePointClientContext.Online.ToString())
.RegisterType<ITenantRepository, JsonTenantRepository>(SharePointClientContext.OnPremise.ToString());
}
}
public enum SharePointClientContext
{
Online,
OnPremise
}
class Program
{
static void Main(string[] args)
{
...
bootstrap.RegisterComponents();
var bla = bootstrap.Initialize(typeof(ISharePointManager), SharePointClientContext.Online);
}
}
So, I register my components in MVC, WCF, Console etc. once with RegisterComponents() and initialize them with Initialize().
My question is, if I want to initialize specific named registration at runtime, from e.g. user input, can it be done otherwise as the code presented (with InjectionFactory or similar)?
This code works fine, but I'm not happy with its implementation. I have a feeling that it could be written in RegisterComponents() instead of Initialize() so that it accepts a parameter of some type, but I don't know how to do it.
Or, is maybe my whole concept wrong? If so, what would you suggest? I need to resolve named registration from a parameter that is only known at runtime, regardless of the technology (MVC, WCF, Console, ...).
Thanks!
Instead of doing different registrations, I would do different resolves.
Let's say that you need to inject IClientContext, but you want different implementations depending on a runtime parameter.
I wrote a similiar answer here. Instead of injecting IClientContext, you could inject IClientContextFactory, which would be responsible for returning the correct IClientContext. It's called Strategy Pattern.
public interface IClientContextFactory
{
string Context { get; } // Add context to the interface.
}
public class SharePointOnlineClientContext : IClientContextFactory
{
public string Context
{
get
{
return SharePointClientContext.Online.ToString();
}
}
}
// Factory for resolving IClientContext.
public class ClientContextFactory : IClientContextFactory
{
public IEnumerable<IClientContext> _clientContexts;
public Factory(IClientContext[] clientContexts)
{
_clientContexts = clientContexts;
}
public IClientContext GetClientContext(string parameter)
{
IClientContext clientContext = _clientContexts.FirstOrDefault(x => x.Context == parameter);
return clientContext;
}
}
Register them all, just as you did. But instead of injecting IClientContext you inject IClientContextFactor.
There also another solution where you use a Func-factory. Look at option 3, in this answer. One may argue that this is a wrapper for the service locator-pattern, but I'll leave that discussion for another time.
public class ClientContextFactory : IClientContextFactory
{
private readonly Func<string, IClientContext> _createFunc;
public Factory(Func<string, IClientContext> createFunc)
{
_createFunc = createFunc;
}
public IClientContext CreateClientContext(string writesTo)
{
return _createFunc(writesTo);
}
}
And use named registrations:
container.RegisterType<IClientContext, SharePointOnlineClientContext>(SharePointClientContext.Online.ToString());
container.RegisterType<IClientContext, SharePointOnPremiseClientContext>(SharePointClientContext.OnPremise.ToString());
container.RegisterType<IFactory, Factory>(
new ContainerControlledLifetimeManager(), // Or any other lifetimemanager.
new InjectionConstructor(
new Func<string, IClientContext>(
context => container.Resolve<IClientContext>(context));
Usage:
public class MyService
{
public MyService(IClientContextFactory clientContextFactory)
{
_clientContextFactory = clientContextFactory;
}
public void DoStuff();
{
var myContext = SharePointClientContext.Online.ToString();
IClientContextclientContext = _clientContextFactory.CreateClientContext(myContext);
}
}

what is wrong with my code first migration?

This is my migration and seeding code:
internal sealed class Configuration : DbMigrationsConfiguration<AuthDb>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "Service.DAL.AuthDb";
}
}
public class CreateOrRunMigrations: CreateDatabaseIfNotExists<AuthDb>
{
public override void InitializeDatabase(AuthDb context)
{
base.InitializeDatabase(context);
var migrator = new DbMigrator(new Migrations.Configuration());
migrator.Update();
}
protected override void Seed(AuthDb context)
{
base.Seed(context);
// add Default product and company
}
}
The context is constructed this way
public class AuthDb : DbContext
{
public AuthDb() : base("name=xxx")
{
Database.SetInitializer(new CreateOrRunMigrations());
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
Configuration.AutoDetectChangesEnabled = true;
}
}
What I want is:
When the database is created first time, the seeding data is added.
When I make a change in the model, the migration code will apply the changes to the database automatically.
When I make a change (e.g. Company), and use update_database to add a migration in the console, the migration file was created. But when the code is run, I got an error complaining that my model and database doesn't match any more.
Of course it doesn't match as I just made a change and I was hoping that the migration will apply the change. However, it didn't. What I did wrong?
Your initializer derives from CreateDatabaseIfNotExists so it's only going to run when the database does not exist. Try making it derive from MigrateDatabaseToLatestVersion:
public class CreateOrRunMigrations: MigrateDatabaseToLatestVersion<AuthDb>
{
// no need for InitializeDatabase override since that's what this initializer does...
protected override void Seed(AuthDb context)
{
base.Seed(context);
// add Default product and company
}
}

Set up an actitivity that will blocked until a new element insert into my database

I'm new in workflows C #, I want to set up an activity that will be blocked until a new element insert into my database , after I pass to another activity.
From your question I believe you are asking for a way to stop the workflow proceeding until you get a database entry and if you do to continue the workflow.
And if you do not get the entry to not continue the workflow.
This answer uses the Flowchart model of workflows.
A way to do this is to write an Code Activity (also called Custom Activity) that reads your database and determines if the entry has arrived and then sets a bool Out Argument of the activity. This bool should set a Variable in the workflow.
Then after that you add a FlowDecision activity to read the bool Variable.
If true you continue the workflow
If false you add a loop back to your database reading activity.
This solution leaves the workflow running in memory.
There are more sophisticated solutions but as you are new to workflows I have given the most simple.
public sealed class Controller: CodeActivity
{
public OutArgument<String> Item { get; set; }
CodeActivityContext con;
public SqlTableDependency<VacationRequest> _dependency;
private void _dependency_OnChanged(object sender, TableDependency.EventArgs.RecordChangedEventArgs<VacationRequest> even)
{
if (even.ChangeType != ChangeType.None)
{
switch (even.ChangeType)
{
case ChangeType.Update:
try
{
Item.Set(con, "yeééés");// ****Exception
Console.WriteLine("iiiiiiiiiiiiiiii");
//_dependency.Stop();
break;
}
catch (Exception)
{
con.SetValue(Item, "tttt");
break;
}
}
}
}
protected override void Execute(CodeActivityContext context)
{
con = context;
_dependency = new SqlTableDependency<VacationRequest>(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString, "VacationRequests");
_dependency.OnChanged += _dependency_OnChanged;
_dependency.Start();
//context.SetValue(Item, "test");
}
}

How can I make AutoMoqCustomization use Strict MockBehavior?

Using AutoFixture with the AutoFixture.AutoMoq package, I sometimes find tests that weren't configured to correctly test the thing they meant to test, but the problem was never discovered because of the default (Loose) Mock behavior:
public interface IService
{
bool IsSomethingTrue(int id);
}
void Main()
{
var fixture = new Fixture()
.Customize(new AutoMoqCustomization());
var service = fixture.Freeze<Mock<IService>>();
Console.WriteLine(service.Object.IsSomethingTrue(1)); // false
}
I'd like to make Mocks get created with Strict behavior, so we're forced to call Setup() for the methods we expect to be called. I can do this for each individual mock like this:
fixture.Customize<Mock<IService>>(c => c.FromFactory(() => new Mock<IService>(MockBehavior.Strict)));
But after combing through source code for AutoMoqCustomization() and the various ISpecimenBuilder and other implementations, I'm pretty lost as to the best way to just make all Mocks get initialized with strict behavior. The framework appears to be very flexible and extensible, so I'm sure there's a simple way to do this--I just can't figure out how.
There's no simple built-in feature that will enable you to do something like that, but it shouldn't be that hard to do.
Essentially, you'd need to change MockConstructorQuery so that it invokes the constructor that takes a MockBehavior value, and pass in MockBehavior.Strict.
Now, you can't change that behaviour in MockConstructorQuery, but that class is only some 9-10 lines of code, so you should be able to create a new class that implements IMethodQuery by using MockConstructorQuery as a starting point.
Likewise, you'll also need to create a custom ICustomization that does almost exactly the same as AutoMoqCustomization, with the only exception that it uses your custom IMethodQuery with strict mock configuration instead of MockConstructorQuery. That's another 7 lines of code you'll need to write.
All that said, in my experience, using strict mocks is a bad idea. It'll make your tests brittle, and you'll waste a lot of time mending 'broken' tests. I can only recommend that you don't do this, but now I've warned you; it's your foot.
For those interested, down below you can find #MarkSeemann's reply translated into code. I am pretty sure it does not cover all use cases and it was not heavily tested. But it should be a good starting point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Kernel;
namespace ConsoleApplication1
{
public class StrictAutoMoqCustomization : ICustomization
{
public StrictAutoMoqCustomization() : this(new MockRelay()) { }
public StrictAutoMoqCustomization(ISpecimenBuilder relay)
{
// TODO Null check params
Relay = relay;
}
public ISpecimenBuilder Relay { get; }
public void Customize(IFixture fixture)
{
// TODO Null check params
fixture.Customizations.Add(new MockPostprocessor(new MethodInvoker(new StrictMockConstructorQuery())));
fixture.ResidueCollectors.Add(Relay);
}
}
public class StrictMockConstructorMethod : IMethod
{
private readonly ConstructorInfo ctor;
private readonly ParameterInfo[] paramInfos;
public StrictMockConstructorMethod(ConstructorInfo ctor, ParameterInfo[] paramInfos)
{
// TODO Null check params
this.ctor = ctor;
this.paramInfos = paramInfos;
}
public IEnumerable<ParameterInfo> Parameters => paramInfos;
public object Invoke(IEnumerable<object> parameters) => ctor.Invoke(parameters?.ToArray() ?? new object[] { });
}
public class StrictMockConstructorQuery : IMethodQuery
{
public IEnumerable<IMethod> SelectMethods(Type type)
{
if (!IsMock(type))
{
return Enumerable.Empty<IMethod>();
}
if (!GetMockedType(type).IsInterface && !IsDelegate(type))
{
return Enumerable.Empty<IMethod>();
}
var ctor = type.GetConstructor(new[] { typeof(MockBehavior) });
return new IMethod[]
{
new StrictMockConstructorMethod(ctor, ctor.GetParameters())
};
}
private static bool IsMock(Type type)
{
return type != null && type.IsGenericType && typeof(Mock<>).IsAssignableFrom(type.GetGenericTypeDefinition()) && !GetMockedType(type).IsGenericParameter;
}
private static Type GetMockedType(Type type)
{
return type.GetGenericArguments().Single();
}
internal static bool IsDelegate(Type type)
{
return typeof(MulticastDelegate).IsAssignableFrom(type.BaseType);
}
}
}
Usage
var fixture = new Fixture().Customize(new StrictAutoMoqCustomization());

Resources