Tuesday 20 January 2015

Self hosting workflow–working with InstanceStore and InstanceOwner

I’ve not been doing a great deal of Workflow recently but had to fix an issue at a customer today and as there’s such poor information about this on the Web I put fingers to keys to blog about it.

If you are self-hosting workflows using WorkflowApplication you’ll typically have some code such as the following to setup the workflow instance store…

    instanceStore = new SqlWorkflowInstanceStore
(@"Data Source=.\SQLEXPRESS;Initial Catalog=SampleInstanceStore;
Integrated Security=True;Asynchronous Processing=True");

InstanceHandle handle = instanceStore.CreateInstanceHandle();
InstanceView view = instanceStore.Execute(handle,
new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
handle.Free();

instanceStore.DefaultInstanceOwner = view.InstanceOwner;

The question is - where does this go? I’ll get on to that in a moment.


When you want to run a workflow you need to set it’s instance store – so you’ll typically do this…

    WorkflowApplication application = new WorkflowApplication(activity);
application.InstanceStore = instanceStore;

And then somewhere online you might have seen the DeleteWorkflowOwnerCommand as that’s the opposite of the CreateWorkflowOwnerCommand so has to be called somewhere, doesn’t it?


If all of this has you confused this is the article that will help you.


Instance Store: One Per Process


When creating the instance store you need no more than one per process. You can run multiple workflow instances in this process, and each will play nicely together – but all will use the same store. You don’t need loads, one will do per process.


I’m using AutoFac so have setup a dependency to be SingleInstance(), and each workflow wrapper that I run imports that single instance. The wrapper is shown below…

    public interface IWorkflowInstanceStore
{
InstanceStore Store { get; }
}

The implementation is also pretty trivial...

    public class WorkflowInstanceStore : IWorkflowInstanceStore, IDisposable
{
public WorkflowInstanceStore(string connectionString)
{
_instanceStore = new SqlWorkflowInstanceStore(connectionString);

InstanceHandle handle = _instanceStore.CreateInstanceHandle();
InstanceView view = _instanceStore.Execute(handle,
new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
handle.Free();

_instanceStore.DefaultInstanceOwner = view.InstanceOwner;
}

public InstanceStore Store
{
get { return _instanceStore; }
}

public void Dispose()
{
if (null != _instanceStore)
{
var deleteOwner = new DeleteWorkflowOwnerCommand();
InstanceHandle handle = _instanceStore.CreateInstanceHandle();
_instanceStore.Execute(handle, deleteOwner, TimeSpan.FromSeconds(10));
handle.Free();
}
}

private InstanceStore _instanceStore;
}

As you'll see here this is a disposable class and in the Dispose() method I call the DeleteWorkflowOwnerCommand. When running workflows, you'll get a row in the LockOwners for each instance store, and these are tidied up by the RecoverInstanceLocks stored procedure which runs periodically. This can be a source of poor performance, as if you use an instance store per workflow application (which is very common given the lack of guidance on this matter), then you'll end up with a large number of rows in this table and RecoverInstanceLocks will show up on your SQL traces as taking a long time to execute. The culprit isn't directly the stored procedure, it's the use of too many rows in the LockOwnersTable. Typically there should be just one row in there per process that runs workflows.


Workflow Runner: One per workflow application


Next up you’ll need a class that runs workflows – typically you’ll write a simple wrapper such as the one I’ve done below, this wraps running workflows and resuming bookmarks with Task based operations so that you can easily integrate Workflow into your code. Note – you might want to process other events and probably do some logging inside this class too, I’ve just provided a minimal implementation…

    public class WorkflowHoster
{
public WorkflowHoster(IWorkflowInstanceStore instanceStore,
params object[] services)
{
_instanceStore = instanceStore.Store;
_services = services.ToList();
}

public Task RunInstance(Activity root)
{
WorkflowApplication application = new WorkflowApplication(root);
foreach (var service in _services)
application.Extensions.Add(service);
var tcs = new TaskCompletionSource();

application.InstanceStore = _instanceStore;

application.PersistableIdle = (e) => PersistableIdleAction.Unload;
application.Unloaded = (e) => tcs.SetResult(e.InstanceId);
application.Aborted = (e) => tcs.SetException(e.Reason);
application.Run();

return tcs.Task;
}

public Task ResumeInstance(Activity root, Guid workflowInstanceId,
string bookmarkName, object bookmarkData = null)
{
WorkflowApplication application = new WorkflowApplication(root);
application.InstanceStore = _instanceStore;
var tcs = new TaskCompletionSource();

application.PersistableIdle = (e) => PersistableIdleAction.Unload;
application.Unloaded = (e) => tcs.SetResult(DateTime.UtcNow);
application.Aborted = (e) => tcs.SetException(e.Reason);
application.Load(workflowInstanceId);
application.ResumeBookmark(bookmarkName, bookmarkData);

return tcs.Task;
}

private InstanceStore _instanceStore;
private AutoResetEvent _instanceUnloaded = new AutoResetEvent(false);
private List<object> _services;
}

You may also want to pass parameters to the workflow instance etc. - as I mentioned the above is a minimal implementation just to show how this works.


Running a workflow


With that stuff defined you can run a workflow as follows…

    var store = GetThePerProcessStoreFromSomewhere();

var host = new WorkflowHoster(store);
Task wf = host.RunInstance(rootActivity);
// Now wait for the wf task to complete...

The task will complete when the workflow unloads (which obviously happens if the workflow completes entirely, or if it goes idle and persists due to a bookmark or delay).


Wrap Up


If you want to self-host workflow, then using your own persistence store requires a bit of knowledge which is hard to come by on the intertubes.


Create a single instance-store per process, and only call DeleteWorkflowOwnerCommand once when your process is shutting down. That should be all you need.

237 comments:

«Oldest   ‹Older   201 – 237 of 237
bretl460 said...

Need english research paper help ? AssignmentStudio.net offers best research paper writing help at affordable price.

Devin Smith said...

Good and informative post. I did not know there was so good Essay Help available. My assignments drastically improved a lot, thanks to expert essay. Now my results are improving beyond an idea. The portal has an easy to use service facility.

The Doy said...

There is no competition when it comes to VIN check on a car is case you are interested: http://vinpit.com/vin-check/title. There is a lot of use for this tool just go visit their website first.

Lauren Rose said...

Top Expert Dissertation Writer
Top Expert Dissertation Writer. Our dissertation writing service will help you write your PhD dissertation or Master's thesis within the shortest time frame.

James Ian said...

Hello, thank you for sharing with us this piece of content I’m entirely in debt for your help. CIPD has a great part in the evolution of L&D and HR; it has reached all around the globe and has numerous students around the world. But the fact that online students face various problems remains the same. Here you will learn more about our CIPD assignment help for level 3, level 5 and level 7. Read more on Get CIPD Assignment Writers

Aabira Zuhur said...

IATF 16949 Certification in Bahrain

ozpaperhelp said...

Hi
Thanku so much for providing wonderful information,Ozpaperhelp.com is the best platform where
you can get the best information about your assignment and Thesis

System Science Engineering Assignment Help Uk
System Science Engineering Assignment Help Uk
STATISTICAL MODELLING ASSIGNMENT
Programming
Performance Management For HR
Accounting Information Systems
HI6008 Assignment 1
Multisim Assignment Help
Mechanical Engineering Assignment Help
Civil Engineering Assignment Help
Environmental Engineering Assignment Help
Data Warehouse Assignment Help
Information Technology Assignment Help
Technology Assignment Help
Information Systems Business Assignment Help Uk
Networking Technologies Assignment Help
DATA COMMUNICATION AND NETWORK

ozpaperhelp said...

Hi
Thanku you for sharing excellent informations.Your site is very cool.I am impressed behalf of Ozpaperhelp.com, details that you have on this blog .
It reveals how nicely you perceive this subject.

Business Process Engineering Assignment Help Uk
Database Design Concept Assignment Help Uk
Networking Technologies Assignment Help
STRATEGIC INFORMATION SYSTEM
Data Analysis and Design
System Science Engineering Assignment Help Uk
Web Application Development Assignment Help UK
Geotechnical Engineering
Interior Design Assignment Help
HND Diploma in Web Design
HND Diploma in Digital Marketing
Technology Assignment Help Services
SIM 335 Managing Projects Assessment
Hnd Networking Technology Assignment
HND Computing And System Development
Mechanical Engineering Assignment Help
Environmental Engineering Assignment Help
Aeronautical Engineering Assignment Help
Engineering Assignment Help

vaibhav said...

I read this post your post so nice and very informative post thanks for sharing this post.If you are searching the best assignment help service then visit Ozpaperhelp.com. We have the best assignment experts who always ready to help students. For more information kindly check our links:

TCP/IP Networking Assignment Help
SAGE Assignment Help
MS Access Assignment Help
Linear Programming Assignment Help
Blockchain Assignment Help
Applied Communications Assignment Help
Cryptography Assignment Help
Cyber Security Assignment Help
Quantum Computing Assignment Help
VERILOG Assignment Help
Information Technology Assignment Help
Software Engineering Assignment Help
PHP Assignment Help
Java Assignment Help
Database Management Systems
Program Evaluation Implementation
System Science Engineering Assignment Help Uk
Law Contract Assignment Help Uk
Corporate Accounting Assignment Help Uk
Financial Analysis Assignment Help Uk
Human Happiness Cpm Hrm Assignment Help Uk
Managing Human Capital Assignment Help Uk
Integrated Capstone Project Assignment Help Uk

devin wood said...

Greetings for the day,

These are the most wonderful post which i have ever seen on any webpage. Ozpaperhelp.com is the fastest growing network on this planet for the assignment reports at an affordable cost.

Buy Dissertation Assignment Help
Dissertation Help Service London
Dissertation Help Online
Dissertation Proposal Help
Dissertation Assistance Service
Plagiarism Free Dissertation Help
Dissertation Writing
HND Diploma In Pre U Foundation Studies
Perfect Dissertation Layout
Impact of Globalization on McDonald’s Success
Reflection Of My Placement
HND Diploma in Digital Marketing
Social Networks In Business
Nursing Care Plan
Practical placement task
HND Diploma in Entrepreneurship
HND Diploma In Law
Academic Dissertation Help
HND Diploma in Creative Thinking


Regards,







Aabira Zuhur said...

ISO Training in Saudi Arabia

Business Leads World said...

Merchant Cash Advance Leads is your long-run strategic growth partner with expertise within the Best MCA Leads and various business loans.

ijcannonstart said...

Your blog is great. I read a lot of interesting things from it.
Hey, Get easy steps for canon Pixma wireless setup with a computer, laptop, mac & ios are available here. Set up your printer or with ij network device setup, and enjoy unparalleled image quality with our range of professional photo printers. This printer give sleek and stylish, our range of compact printers provides a perfect all-in-one home printing solution. To know more information, visit our ij.start.cannon site.

OZPAPERHELP said...

CheapAssignmentHelp.co.uk is the World’s Best Online Assignment help, Academic Homework Help and writing assistance web provider that prides itself in being the best online assignment help website for students around the world.
Help With Microeconomics Assignment
Research Paper Writing Service
Cheap Research Papers Assignment Help
Psychology Assignment Writing Help
Online Psychology Assignment Help Australia
Philosophy Assignment Help
Information System Assignment Help
UML Assignment Help
Unit 24 Destination Management Services
Unit 22 Airport Operations Management
Unit 21 Airline Operations Management
Unit 11 Corporate Travel Management
Unit 8 Visitor Attraction Management
Unit 7 Managing Conference and Events
Unit 38 Operations Management Support
International Trade Assignment Help
Burns Wound Management
Project Management Assignment Solutions
Business Management Assignment
Brand Management Assignments Help
Global Operations Management Assignment Help
LD6034 -Web Programming Assignment Help
Sole Parenting
Academic Integrity Statement Assignment Help

The Doy said...

Hi there. I have distribute this tool to many forums and blogs so you can have a try on how beneficial it is to your car's purchase. You can use this VIN decoder by head to VinPit and evaluate the value of any car easily, saving you both time and energy and of course money!

nilchavan said...

Share this honesty quotes with your kids, students and teens. This honesty quotes will make
them wise people. inspirational quotes for teens

Aabira Zuhur said...

IATF 16949 Certification in Qatar

Aabira Zuhur said...

ISO 45001 lead auditor training

Aabira Zuhur said...

IRCA ISO 22000 Lead Auditor Training in UAE

The Doy said...
This comment has been removed by the author.
The Doy said...

I might go easy for a lot of occasions in dealing with a car negotiation. There used to be a lot of tenses. Because I need to get the best deal out of it. But now I can use Chevy VIN decoder instead, click here to go on Chevy VIN decoder, which able to give me the upper hand in purchasing a car.

nilchavan said...

Best place where you can get quotes for entrepreneur, wise honesty quotes for men, thought for
the day for students, teachers, kids teens etc. good morning quotes for her

cryptocurrency said...

Cash App Refund ​| Cash app refund policy | Cash app refund process | Cash app refund online | Cash app refund merchant | Cash app refund request | Cash app refund number | Cash app protection refund | How to get money back from cash app | Cash app refund phone number | Refund on cash app | Refund cash app | Cash app request refund | Request refund cash app

APTRON said...

Learn about MCSA from the MCSA course in Noida and become one of the experts in MCSA and grow your career professionally. Course content by the best MCSA Training Institute in Noida is carefully crafted to match the industry requirements.

ravi sharma said...

Avail the best bluetooth earphones under 2000 of all brands offer only for limited period. Select from the best bluetooth earphones under 2000 in india with top notch quality you will surely love this. bluetooth earphones under 2000

Unknown said...

If it’s all about exploring Goa and its special combos, then nothing goes better than having the one and only and best fish thali in Calangute. Tasting with Seafood junction will never let you forget its taste and yummiest texture. Try the dishes from the most popular seafood restaurant in Goa to get the best ever taste for your lifetime.

Unknown said...

Interested in investing in a private pool villa in Goa? The luxury villas in Goa with private pools are worth considering as they are fully equipped and have inhouse staff. These private pool villas in Goa are high-priced for their superb location and string of amenities, besides service. Before you buy, you might like to take a luxury villa for rent in Goa.

Dissertation Help said...

Thank you for such a supportive thought on your site which help me in gaining informative knowledge.
We also provide service in Sop(Statement Of Purpose)writing services which is required for taking admission in college/university into another country.Student search for best sop written services by any professional writer but many of them not able to find such a writer who write clear and outstanding sop. TheStudentHelpline provide such a writer who write best and perfect sop for student visa for you while keeping you expectation into the mind and deliver you sop on time.

Gaurav said...

If you want to know your love compatibility by name, there is a Namank or name number chart that can help you figure out your name compatibility

Unknown said...
This comment has been removed by the author.
Jane Wilson said...

Great Post, Are you Looking for an online supply chain management assignment?, Here we provide the best help with supply chain management assignments online by an expert at a given deadline,24*7 support.

Namita Aggarwal said...

Are you looking for a place to stay in Mathura? Hotel Madhuvan in Mathura is a great option! Located centrally, our hotel offers comfortable rooms, a restaurant, and a rooftop terrace with views of the city. We're also close to all the major attractions, so you can easily visit them during your stay. Book your room today!

Palak Mittal said...

You are providing wonderful information. Our article "Do My Nursing Assignment" explores the benefits of hiring professional help and provides tips on finding reliable assistance. Get the grades you deserve with expert support.

Payday Cash said...

Need immediate cash? PaydayLoansUK is your answer. Trust Stantander for secure banking and explore Novuna Loans for tailored borrowing solutions. stantander login

aemma said...

its very informative website professional logo design services karachi

blogscoment7766 said...

Hiking gives your lovely dog a chance to get in tune with nature and also to reduce their stress and anxiety. It will also boost the overall bond between you two. If you have a trip in your mind, make sure you follow the above steps.check site k9nerds

Jackwilliams said...

If you're seeking academic assistance, consider the benefits of hiring a professional to take my online class. Entrusting an expert ensures quality performance, timely submissions, and alleviates academic stress. By engaging a knowledgeable individual, you gain an edge in understanding complex topics, ensuring better grades and a balanced academic life. Delegate coursework to proficient tutors or academic services that offer reliable support, enabling you to focus on other priorities. Remember, while seeking help, ensure ethical practices and transparency. Ultimately, opting for professional assistance can enhance your learning experience and provide valuable insights, fostering academic success without compromising integrity.

«Oldest ‹Older   201 – 237 of 237   Newer› Newest»