public WorkflowInstance(IWorkflowHost host, Activity workflowDefinition, WorkflowIdentity definitionIdentity)
            : base(workflowDefinition, definitionIdentity)
        {
            this.host = host;

            SynchronizationContext = new SynchronizationContext();
        }
 protected virtual IDictionary <string, object> ExecuteWorkflow(WorkflowIdentity identity,
                                                                IDictionary <string, object> inputs, TimeSpan?timeout)
 {
     return(timeout.HasValue
         ? _workflowService.Run(identity, inputs, timeout.Value)
         : _workflowService.Run(identity, inputs));
 }
Example #3
0
        public void QueueState_should_be_error_when_content_wf_exception()
        {
            var contentWfName         = "I_THROW_EXCEPTION";
            var sessionShareExtention = new SessionShareExtention();
            var customActivity        = new CustomActivity(Error);
            var wfIdentity            = new WorkflowIdentity(contentWfName, new Version(WfVersion), WfPackageName);
            var wfAppFactory          = GetWfFactory(wfIdentity, customActivity);

            using (var childContainer = _container.CreateChildContainer())
            {
                childContainer.RegisterInstance <IWorkflowApplicationFactory>(wfAppFactory);
                childContainer.RegisterInstance(sessionShareExtention);

                using (var session = _sessionFactory.OpenSession())
                    using (var transaction = session.BeginTransaction())
                    {
                        sessionShareExtention.SharedSession = session;

                        var queueIn = CreateQueueIn(session);
                        session.Save(queueIn);

                        var inputs = new Dictionary <string, object>
                        {
                            { "ContentWorkflowIdentity", GetWfFullName(contentWfName) },
                            { "MandantCode", queueIn.Mandant.PartnerCode },
                            { "QueueMessageTypeCode", queueIn.QueueMessageType.Code }
                        };
                        var service = childContainer.Resolve <TestWorkflowService>();

                        service.Run(_mainDoWhileWfIdentity, inputs);
                        queueIn.QueueMessageState.Should().Be(QueueMessageStates.Error);
                        transaction.Rollback();
                    }
            }
        }
 public Activity this[WorkflowIdentity definitionIdentity]
 {
     get
     {
         return(ActivityPersistenceHelper.LoadActivity(InstanceDefinitions[definitionIdentity]));
     }
 }
        static WorkflowVersionMap()
        {
            map = new Dictionary<WorkflowIdentity, Activity>();

            // Add the current workflow version identities.
            StateMachineNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "StateMachineNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };

            FlowchartNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "FlowchartNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };

            SequentialNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "SequentialNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };

            map.Add(StateMachineNumberGuessIdentity, new StateMachineNumberGuessWorkflow());
            map.Add(FlowchartNumberGuessIdentity, new FlowchartNumberGuessWorkflow());
            map.Add(SequentialNumberGuessIdentity, new SequentialNumberGuessWorkflow());
        }
Example #6
0
        static WorkflowVersionMap()
        {
            map = new Dictionary <WorkflowIdentity, Activity>();

            // Add the current workflow version identities.
            StateMachineNumberGuessIdentity = new WorkflowIdentity
            {
                Name    = "StateMachineNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };

            FlowchartNumberGuessIdentity = new WorkflowIdentity
            {
                Name    = "FlowchartNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };

            SequentialNumberGuessIdentity = new WorkflowIdentity
            {
                Name    = "SequentialNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };

            //map.Add(StateMachineNumberGuessIdentity, new StateMachineNumberGuessWorkflow());
            map.Add(FlowchartNumberGuessIdentity, new FlowchartNumberGuessWorkflow());
            map.Add(SequentialNumberGuessIdentity, new SequentialNumberGuessWorkflow());
        }
Example #7
0
 private WorkflowDefinition(String name, String definition)
 {
     Name       = name;
     Definition = definition;
     Type       = WorkflowType.Definition;
     Identity   = new WorkflowIdentity(Name, new Version(Version, 0), null);
 }
Example #8
0
        private static WorkflowApplicationInstance GetADummyWorkflowApplicationInstance()
        {
            WorkflowIdentity wfIdentity   = new WorkflowIdentity("GetAWorkflowApplicationInstanceParameter", new Version(1, 0), null);
            TestSequence     wfDefinition = new TestSequence()
            {
                Activities =
                {
                    new TestWriteLine("testWriteLine1",    "In TestWriteLine1"),
                    new TestReadLine <string>("ReadLine1", "testReadLine1"),
                    new TestWriteLine("testWriteLine2",    "In TestWriteLine2")
                },
            };

            WorkflowApplicationInstance waInstance;

            JsonFileInstanceStore.FileInstanceStore jsonStore = new JsonFileInstanceStore.FileInstanceStore(".\\~");

            using (TestWorkflowRuntime workflowRuntime = TestRuntime.CreateTestWorkflowRuntime(wfDefinition, null, jsonStore, PersistableIdleAction.Unload))
            {
                //PersistenceProviderHelper pphelper = new PersistenceProviderHelper(workflowRuntime.PersistenceProviderFactoryType);
                //InstanceStore store = pphelper.CreateWorkflowInstanceStore();

                workflowRuntime.ExecuteWorkflow();
                workflowRuntime.WaitForIdle();
                workflowRuntime.UnloadWorkflow();
                workflowRuntime.WaitForUnloaded();

                Guid worklfowInstanceId = workflowRuntime.CurrentWorkflowInstanceId;
                waInstance = WorkflowApplication.GetInstance(worklfowInstanceId, jsonStore);
                waInstance.Abandon();
            }

            return(waInstance);
        }
        public Activity this[WorkflowIdentity definitionIdentity]
        {
            get
            {
                Activity activity = null;
                var      found    = InstanceDefinitions.TryGetValue(definitionIdentity, out activity);
                if (found)
                {
                    return(activity);
                }

                var assemblyFullName = definitionIdentity.Package;
                var activityTypeName = definitionIdentity.Name;
                System.Diagnostics.Trace.Assert(assemblyFullName.Contains(definitionIdentity.Version.ToString()));
                var objectHandle = Activator.CreateInstance(assemblyFullName, activityTypeName);//tons of exceptions needed to be handled in production
                activity = objectHandle.Unwrap() as Activity;
                if (activity == null)
                {
                    throw new InvalidOperationException("You must have been crazy.");
                }

                InstanceDefinitions.TryAdd(definitionIdentity, activity);
                return(activity);
            }
        }
Example #10
0
 private WorkflowDefinition(String source)
 {
     // clr:A2.Workflows
     // file:fullName
     Source = source.Trim();
     if (Source.StartsWith("clr:"))
     {
         var(assembly, type) = ClrHelpers.ParseClrType(source);
         Name     = type;
         Assembly = assembly;
     }
     else if (Source.StartsWith("file:"))
     {
         Type = WorkflowType.File;
         Path = Source.Substring(5).Trim();
         Name = System.IO.Path.GetFileNameWithoutExtension(Path);
     }
     else if (Source.StartsWith("db:"))
     {
         Type = WorkflowType.Db;
         Path = Source.Substring(3).Trim();
         Name = System.IO.Path.GetFileNameWithoutExtension(Path);
     }
     else
     {
         throw new WorkflowException($"Invalid workflow source ('{Source}')");
     }
     Identity = new WorkflowIdentity(Name, new Version(Version, 0), null);
 }
Example #11
0
        public void Dont_do_anything_when_bad_input_parameters()
        {
            var contentWfName         = "I_DONT_MAKE_PROBLEMS";
            var sessionShareExtention = new SessionShareExtention();
            var customActivity        = new CustomActivity();
            var wfIdentity            = new WorkflowIdentity(contentWfName, new Version(WfVersion), WfPackageName);
            var wfAppFactory          = GetWfFactory(wfIdentity, customActivity);

            using (var childContainer = _container.CreateChildContainer())
            {
                childContainer.RegisterInstance <IWorkflowApplicationFactory>(wfAppFactory);
                childContainer.RegisterInstance(sessionShareExtention);

                using (var session = _sessionFactory.OpenSession())
                    using (var transaction = session.BeginTransaction())
                    {
                        sessionShareExtention.SharedSession = session;

                        var inputs = new Dictionary <string, object>
                        {
                            { "ContentWorkflowIdentity", GetWfFullName(contentWfName) },
                            { "MandantCode", "NotExistingMandantCode" },
                            { "QueueMessageTypeCode", "NotExistingQueueMessageTypeCode" }
                        };
                        var service = childContainer.Resolve <TestWorkflowService>();
                        service.Run(_mainDoWhileWfIdentity, inputs);
                        customActivity.IsExecuted.Should().BeFalse();
                        transaction.Rollback();
                    }
            }
        }
Example #12
0
        private static WorkflowApplication CreateWorkflow(InstanceStore store, WorkflowApps appType = WorkflowApps.App1)
        {
            var identity = new WorkflowIdentity {
                Name = appType.ToString(), Version = new Version(1, 0),
            };

            Activity activity = new WorkflowApp1();

            if (appType == WorkflowApps.App2)
            {
                activity = new WorkflowApp2();
            }

            var whoAmI = new PP(appType);

            var app = new WorkflowApplication(activity, identity)
            {
                InstanceStore = store
            };

            app.Extensions.Add(whoAmI);

            SetEvents(app);

            return(app);
        }
Example #13
0
        public void TestWaitForSignalOrDelayVersion2()
        {
            var a = new WaitForSignalOrAlarm()
            {
                AlarmTime    = DateTime.Now.AddSeconds(10),
                BookmarkName = "Wakeup",
            };

            var definitionIdentity = new WorkflowIdentity("WaitForSignalOrDelay", new Version(2, 0), null);


            AutoResetEvent syncEvent = new AutoResetEvent(false);

            bool completed1 = false;
            bool unloaded1  = false;
            var  app        = new WorkflowApplication(a, definitionIdentity)
            {
                InstanceStore   = WFDefinitionStore.Instance.Store,
                PersistableIdle = (eventArgs) =>
                {
                    return(PersistableIdleAction.Unload);
                },

                OnUnhandledException = (e) =>
                {
                    return(UnhandledExceptionAction.Abort);
                },

                Completed = delegate(WorkflowApplicationCompletedEventArgs e)
                {
                    completed1 = true;
                    syncEvent.Set();
                },


                Unloaded = (eventArgs) =>
                {
                    unloaded1 = true;
                    syncEvent.Set();
                },
            };

            var id = app.Id;

            app.Run();


            syncEvent.WaitOne();
            Assert.False(completed1);
            Assert.True(unloaded1);

            WFDefinitionIdentityStore.Instance.TryAdd(definitionIdentity, a);

            Thread.Sleep(5000); // from 1 seconds to 9 seconds, the total time of the test case is the same.

            var outputs = LoadAndCompleteLongRunning(id, definitionIdentity);

            Assert.False((bool)outputs["Result"]);
        }
Example #14
0
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     if (value is string valueString)
     {
         return(WorkflowIdentity.Parse(valueString));
     }
     return(base.ConvertFrom(context, culture, value));
 }
        public static void Trace(Guid workflowInstanceId, WorkflowIdentity workflowDefinitionIdentity, WorkflowInstanceState state)
        {
            WorkflowInstanceTrace trace = new WorkflowInstanceTrace(workflowInstanceId, workflowDefinitionIdentity, state);

            TraceSource ts = new TraceSource("CoreWf.Tracking", SourceLevels.Information);

            ts.TraceData(TraceEventType.Information, 1, trace);
        }
Example #16
0
        public WorkflowManager(Activity wfDefinition, Version vrsn)
        {
            SqlWorkflowInstanceStore wfInstanceStore = InitializeInstanceStore();

            WorkflowIdentity wfIdentity = InitializeIdentity(wfDefinition, vrsn);

            this.WFApplication = InitializeApplication(wfDefinition, wfIdentity, wfInstanceStore);
        }
 /// <summary>
 /// Creates the application instance with event handlers. Workflow must accept 'DataEventArgument' as a parameter of type DataEventArgs
 /// Relies on: PersistanceHelper.WorkflowHostTypePropertyName, PersistanceHelper.HostTypeName, PersistanceHelper.Store
 /// </summary>
 /// <param name="activity"></param>
 /// <param name="identity"></param>
 /// <param name="args"></param>
 /// <remarks>DO NOT get the ID of the workflow instance before it's used otherwise on unpersisted workflows they will not work.</remarks>
 /// <exception cref="InvalidOperationException"></exception>
 /// <exception cref="ArgumentNullException"></exception>
 public ApplicationHelper(Activity activity, WorkflowIdentity identity, DataEventArgs args = null)  :
     this(activity, identity,
          //Supply null arguments if they are passed in as null. Other wise default
          args == null ? null : new Dictionary <string, object> {
     { DataEventArgumentName, args }
 })
 {
 }
 public bool TryAdd <T>(WorkflowIdentity definitionIdentity, ActivityBuilder <T> ab)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         ActivityPersistenceHelper.SaveActivity(ab, stream);
         stream.Position = 0;
         return(InstanceDefinitions.TryAdd(definitionIdentity, stream.ToArray()));
     }
 }
Example #19
0
        private WorkflowIdentity InitializeIdentity(Activity wfDefinition, Version vrsn)
        {
            WorkflowIdentity identity = new WorkflowIdentity();

            identity.Name    = wfDefinition.DisplayName;
            identity.Version = vrsn;

            return(identity);
        }
Example #20
0
        internal static Activity GetWorkflow(WorkflowIdentity workflowIdentity)
        {
            if (_map.ContainsKey(workflowIdentity))
            {
                return(_map[workflowIdentity]);
            }

            throw new ArgumentException(workflowIdentity.Name);
        }
 internal WorkflowApplicationInstance(
     WorkflowApplication.PersistenceManagerBase persistenceManager, 
     IDictionary<XName, InstanceValue> values, 
     WorkflowIdentity definitionIdentity)
 {
     this.PersistenceManager = persistenceManager;
     this.Values = values;
     this.DefinitionIdentity = definitionIdentity;
     this.state = (int)State.Initialized;
 }
Example #22
0
        protected WorkflowInstance(Activity workflowDefinition, WorkflowIdentity definitionIdentity)
        {
            if (workflowDefinition == null)
            {
                throw FxTrace.Exception.ArgumentNull("workflowDefinition");
            }

            this.WorkflowDefinition = workflowDefinition;
            this.DefinitionIdentity = definitionIdentity;
        }
 public void Update(Guid instanceId, WorkflowIdentity updatedDefinitionIdentity)
 {
     if (this.IsTransactedInvoke)
     {
         base.Channel.TransactedUpdate(instanceId, updatedDefinitionIdentity);
     }
     else
     {
         base.Channel.Update(instanceId, updatedDefinitionIdentity);
     }
 }
Example #24
0
        private WorkflowApplicationFactory GetWfFactory(WorkflowIdentity wfIdentity, Activity wf, bool loadContentWf = true)
        {
            var mockWfStorage = new Mock <IWorkflowStorage>();

            mockWfStorage.Setup(i => i.Load(_mainDoWhileWfIdentity)).Returns(new INTEGRATION_IN_MAIN());
            if (loadContentWf)
            {
                mockWfStorage.Setup(i => i.Load(wfIdentity)).Returns(wf);
            }
            return(new WorkflowApplicationFactory(null as InstanceStore, mockWfStorage.Object));
        }
Example #25
0
        public Guid StartNewInstance(String modelName)
        {
            WorkflowIdentity workflowIdentity = new WorkflowIdentity("Process1", new Version(0, 1), "wf");
            var wf  = this.GetExtension <IWorkflowModelCatalog>()?.GetActiveModel("Process1");
            var app = new WorkflowApplication(wf);

            EnrichWorkflowApplication(app);
            app.Run();
            lastid = app.Id;
            Console.WriteLine(lastid);
            return(app.Id);
        }
        public void UpdateAsync(Guid instanceId, WorkflowIdentity updatedDefinitionIdentity, object userState)
        {
            if (this.onBeginUpdateDelegate == null)
            {
                this.onBeginUpdateDelegate    = new BeginOperationDelegate(OnBeginUpdate);
                this.onEndUpdateDelegate      = new EndOperationDelegate(OnEndUpdate);
                this.onUpdateCompleteDelegate = Fx.ThunkCallback(new SendOrPostCallback(OnUpdateCompleted));
            }

            base.InvokeAsync(this.onBeginUpdateDelegate, new object[] { instanceId, updatedDefinitionIdentity },
                             this.onEndUpdateDelegate, this.onUpdateCompleteDelegate, userState);
        }
 //Compare identities and returns true if they are equal otherwise false
 public static bool CompareIdentities(WorkflowIdentity baseIdentity, WorkflowIdentity identity)
 {
     if (baseIdentity == null && identity == null)
     {
         return(true);
     }
     else if (baseIdentity == null || identity == null) //Either one of them is null
     {
         return(false);
     }
     return(baseIdentity.Equals(identity) || object.Equals(baseIdentity, identity));
 }
        private void NewGame_Click(object sender, EventArgs e)
        {
            var inputs = new Dictionary <string, object>();

            inputs.Add("MaxNumber", Convert.ToInt32(NumberRange.SelectedItem));

            WorkflowIdentity identity = null;

            switch (WorkflowType.SelectedItem.ToString())
            {
            case "SequentialNumberGuessWorkflow":
                identity = WorkflowVersionMap.SequentialNumberGuessIdentity;
                break;

            case "StateMachineNumberGuessWorkflow":
                identity = WorkflowVersionMap.StateMachineNumberGuessIdentity;
                break;

            case "FlowchartNumberGuessWorkflow":
                identity = WorkflowVersionMap.FlowchartNumberGuessIdentity;
                break;

            case "SequentialNumberGuessWorkflow v1":
                identity = WorkflowVersionMap.SequentialNumberGuessIdentity_v1;
                break;

            case "StateMachineNumberGuessWorkflow v1":
                identity = WorkflowVersionMap.StateMachineNumberGuessIdentity_v1;
                break;

            case "FlowchartNumberGuessWorkflow v1":
                identity = WorkflowVersionMap.FlowchartNumberGuessIdentity_v1;
                break;
            }
            ;

            Activity wf = WorkflowVersionMap.GetWorkflowDefinition(identity);

            WorkflowApplication wfApp = new WorkflowApplication(wf, inputs, identity);

            // Add the workflow to the list and display the version information.
            WorkflowStarting         = true;
            InstanceId.SelectedIndex = InstanceId.Items.Add(wfApp.Id);
            WorkflowVersion.Text     = identity.ToString();
            WorkflowStarting         = false;

            // Configure the instance store, extensions, and
            // workflow lifecycle handlers.
            ConfigureWorkflowApplication(wfApp);

            // Start the workflow.
            wfApp.Run();
        }
Example #29
0
 public static void PersistAndUpdate(this TestWorkflowRuntime twRuntime, WorkflowIdentity updatedIdentity)
 {
     twRuntime.PersistWorkflow();
     twRuntime.UnloadWorkflow();
     if (null != updatedIdentity)
     {
         twRuntime.LoadAndUpdateWorkflow(updatedIdentity.ToString());
     }
     else
     {
         twRuntime.LoadWorkflow();
     }
     twRuntime.ResumeWorkflow();
 }
        private void NewGame_Click(object sender, EventArgs e)
        {
            var inputs = new Dictionary <string, object>
            {
                { "MaxNumber", Convert.ToInt32(NumberRange.SelectedItem) }
            };

            WorkflowIdentity identity = null;

            switch (WorkflowType.SelectedItem.ToString())
            {
            case "SequentialNumberGuessWorkflow":
                identity = WorkflowVersionMap.SequentialNumberGuessIdentity;
                break;

            case "StateMachineNumberGuessWorkflow":
                identity = WorkflowVersionMap.StateMachineNumberGuessIdentity;
                break;

            case "FlowchartNumberGuessWorkflow":
                identity = WorkflowVersionMap.FlowchartNumberGuessIdentity;
                break;

            case "SequentialNumberGuessWorkflow v1":
                identity = WorkflowVersionMap.SequentialNumberGuessIdentity_v1;
                break;

            case "StateMachineNumberGuessWorkflow v1":
                identity = WorkflowVersionMap.StateMachineNumberGuessIdentity_v1;
                break;

            case "FlowchartNumberGuessWorkflow v1":
                identity = WorkflowVersionMap.FlowchartNumberGuessIdentity_v1;
                break;
            }
            ;

            Activity wf = WorkflowVersionMap.GetWorkflowDefinition(identity);

            WorkflowApplication wfApp = new WorkflowApplication(wf, inputs, identity);

            WorkflowStarting         = true;
            InstanceId.SelectedIndex = InstanceId.Items.Add(wfApp.Id);
            WorkflowVersion.Text     = identity.ToString();
            WorkflowStarting         = false;

            ConfigureWorkflowApplication(wfApp);

            wfApp.Run();
        }
        /// <summary>
        /// Creates the application instance with event handlers. Not using the DataEventArgument will prevent transaction id's from propagating through log4net.
        /// Relies on: PersistanceHelper.WorkflowHostTypePropertyName, PersistanceHelper.HostTypeName, PersistanceHelper.Store
        /// </summary>
        /// <param name="activity"></param>
        /// <param name="identity"></param>
        /// <param name="extensibleArguments">Optional if reloading the workflow. Only required on inital trigger. KVP of argument name and value.</param>
        /// <remarks>DO NOT get the ID of the workflow instance before it's used otherwise on unpersisted workflows they will not work.</remarks>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public ApplicationHelper(Activity activity, WorkflowIdentity identity, Dictionary <string, object> extensibleArguments)
        {
            if (activity == null)
            {
                throw new ArgumentNullException(nameof(activity));
            }
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

            if (PersistanceHelper.Store == null)
            {
                throw new InvalidOperationException("PersistanceHelper.Store is not set. ");
            }

            if (extensibleArguments == null)
            {
                //This should only be used when the workflow is reconstitued.
                _application = new WorkflowApplication(activity, identity);
            }
            else
            {
                _application = new WorkflowApplication(
                    activity,
                    extensibleArguments,
                    identity);
            }


            //Owner of the workflow activity
            Dictionary <XName, object> wfScope = new Dictionary <XName, object>
            {
                {
                    PersistanceHelper.WorkflowHostTypePropertyName,
                    PersistanceHelper.HostTypeName
                }
            };

            _application.InstanceStore        = PersistanceHelper.Store;
            _application.OnUnhandledException = UnhandledExceptionEvent;
            _application.PersistableIdle      = AbleToPersistEvent;
            _application.Completed            = CompletedEvent;
            _application.Unloaded             = UnloadedEvent;
            _application.Aborted = AbortedEvent;
            _application.Idle    = IdleEvent;

            // Add the WorkflowHostType value to workflow application so that it stores this data in the instance store when persisted
            _application.AddInitialInstanceValues(wfScope);
        }
Example #32
0
        private void Start(Func <WorkflowIdentity, Activity> workflowMap,
                           WorkflowIdentity workflowIdentity, IDictionary <string, object> inputs)
        {
            // >>>> START A WORKFLOW <<<<

            Activity            workflow = workflowMap(workflowIdentity);
            WorkflowApplication wfApp    = new WorkflowApplication(workflow, inputs, workflowIdentity);

            // Configure the instance store, extensions, and
            // workflow lifecycle handlers.
            ConfigureWorkflowApplication(wfApp);

            // Start the workflow.
            wfApp.Run();
        }
 private static string GetMessage(WorkflowIdentity expectedVersion, WorkflowIdentity actualVersion)
 {
     if (actualVersion == null && expectedVersion != null)
     {
         return SR.WorkflowIdentityNullStateId(expectedVersion);
     }
     else if (actualVersion != null && expectedVersion == null)
     {
         return SR.WorkflowIdentityNullHostId(actualVersion);
     }
     else if (!object.Equals(expectedVersion, actualVersion))
     {
         return SR.WorkflowIdentityStateIdHostIdMismatch(actualVersion, expectedVersion);
     }
     else
     {
         return null;
     }
 }
        static WorkflowVersionMap()
        {
            map = new Dictionary<WorkflowIdentity, Activity>();

            // Add the current workflow version identities.
            StateMachineNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "StateMachineNumberGuessWorkflow",
                Version = new Version(2, 0, 0, 0)
            };
            FlowchartNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "FlowchartNumberGuessWorkflow",
                Version = new Version(2, 0, 0, 0)
            };
            SequentialNumberGuessIdentity = new WorkflowIdentity
            {
                Name = "SequentialNumberGuessWorkflow",
                Version = new Version(2, 0, 0, 0)
            };
            map.Add(StateMachineNumberGuessIdentity, new StateMachineNumberGuessWorkflow());
            map.Add(FlowchartNumberGuessIdentity, new FlowchartNumberGuessWorkflow());
            map.Add(SequentialNumberGuessIdentity, new SequentialNumberGuessWorkflow());

            // Initialize the previous workflow version identities.
            StateMachineNumberGuessIdentity_v1 = new WorkflowIdentity
            {
                Name = "StateMachineNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };
            FlowchartNumberGuessIdentity_v1 = new WorkflowIdentity
            {
                Name = "FlowchartNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };
            SequentialNumberGuessIdentity_v1 = new WorkflowIdentity
            {
                Name = "SequentialNumberGuessWorkflow",
                Version = new Version(1, 0, 0, 0)
            };
            // Add the previous version workflow identities to the dictionary along with
            // the corresponding workflow definitions loaded from the v1 assembly.
            // Assembly.LoadFile requires an absolute path so convert this relative path
            // to an absolute path.
            string v1AssemblyPath = @"..\..\..\PreviousVersions\NumberGuessWorkflowActivities_v1.dll";
            v1AssemblyPath = Path.GetFullPath(v1AssemblyPath);
            Assembly v1Assembly = Assembly.LoadFile(v1AssemblyPath);
            map.Add(StateMachineNumberGuessIdentity_v1, v1Assembly.CreateInstance("NumberGuessWorkflowActivities.StateMachineNumberGuessWorkflow") as Activity);
            map.Add(SequentialNumberGuessIdentity_v1, v1Assembly.CreateInstance("NumberGuessWorkflowActivities.SequentialNumberGuessWorkflow") as Activity);
            map.Add(FlowchartNumberGuessIdentity_v1, v1Assembly.CreateInstance("NumberGuessWorkflowActivities.FlowchartNumberGuessWorkflow") as Activity);

            // Initialize the dynamic update workflow identities.
            StateMachineNumberGuessIdentity_v15 = new WorkflowIdentity
            {
                Name = "StateMachineNumberGuessWorkflow",
                Version = new Version(1, 5, 0, 0)
            };
            FlowchartNumberGuessIdentity_v15 = new WorkflowIdentity
            {
                Name = "FlowchartNumberGuessWorkflow",
                Version = new Version(1, 5, 0, 0)
            };
            SequentialNumberGuessIdentity_v15 = new WorkflowIdentity
            {
                Name = "SequentialNumberGuessWorkflow",
                Version = new Version(1, 5, 0, 0)
            };
            // Add the dynamic update workflow identities to the dictionary along with
            // the corresponding workflow definitions loaded from the v15 assembly.
            // Assembly.LoadFile requires an absolute path so convert this relative path
            // to an absolute path.
            string v15AssemblyPath = @"..\..\..\PreviousVersions\NumberGuessWorkflowActivities_v15.dll";
            v15AssemblyPath = Path.GetFullPath(v15AssemblyPath);
            Assembly v15Assembly = Assembly.LoadFile(v15AssemblyPath);
            map.Add(StateMachineNumberGuessIdentity_v15, v15Assembly.CreateInstance("NumberGuessWorkflowActivities.StateMachineNumberGuessWorkflow") as Activity);
            map.Add(SequentialNumberGuessIdentity_v15, v15Assembly.CreateInstance("NumberGuessWorkflowActivities.SequentialNumberGuessWorkflow") as Activity);
            map.Add(FlowchartNumberGuessIdentity_v15, v15Assembly.CreateInstance("NumberGuessWorkflowActivities.FlowchartNumberGuessWorkflow") as Activity);
        }
 public WorkflowInstanceTerminatedRecord(Guid instanceId, long recordNumber, string activityDefinitionId, string reason, WorkflowIdentity workflowDefinitionIdentity)
     : this(instanceId, recordNumber, activityDefinitionId, reason)
 {
     this.WorkflowDefinitionIdentity = workflowDefinitionIdentity;
 }
 public WorkflowInstanceAbortedRecord(Guid instanceId, string activityDefinitionId, string reason, WorkflowIdentity workflowDefinitionIdentity)
     : this(instanceId, activityDefinitionId, reason)
 {
     this.WorkflowDefinitionIdentity = workflowDefinitionIdentity;
 }
 public static string GetIdentityDescription(WorkflowIdentity identity)
 {
     return identity.ToString();
 }
 public WorkflowInstanceReminderRecord(Guid instanceId, long recordNumber, string activityDefinitionId, string state, string reminderName, WorkflowIdentity workflowDefinitionIdentity)
     : this(instanceId, recordNumber, activityDefinitionId, state, reminderName)
 {
     WorkflowDefinitionIdentity = workflowDefinitionIdentity;
 }
 public WorkflowInstanceUnhandledExceptionRecord(Guid instanceId, long recordNumber, string activityDefinitionId, ActivityInfo faultSource, Exception exception, WorkflowIdentity workflowDefinitionIdentity)
     : this(instanceId, recordNumber, activityDefinitionId, faultSource, exception)
 {
     this.WorkflowDefinitionIdentity = workflowDefinitionIdentity;
 }
        public WorkflowServiceInstance InitializeInstance(Guid instanceId, PersistenceContext context, WorkflowIdentity definitionIdentity, WorkflowIdentityKey updatedIdentity, IDictionary<XName, InstanceValue> instance, WorkflowCreationContext creationContext)
        {
            Activity workflowDefinition = null;
            DynamicUpdateMap updateMap = null;
            if (updatedIdentity != null && !object.Equals(updatedIdentity.Identity, definitionIdentity))
            {
                if (!this.workflowDefinitionProvider.TryGetDefinitionAndMap(definitionIdentity, updatedIdentity.Identity, out workflowDefinition, out updateMap))
                {
                    if (this.workflowDefinitionProvider.TryGetDefinition(updatedIdentity.Identity, out workflowDefinition))
                    {
                        throw FxTrace.Exception.AsError(new FaultException(
                            OperationExecutionFault.CreateUpdateFailedFault(SR.UpdateMapNotFound(definitionIdentity, updatedIdentity.Identity))));
                    }
                    else
                    {
                        throw FxTrace.Exception.AsError(new FaultException(
                            OperationExecutionFault.CreateUpdateFailedFault(SR.UpdateDefinitionNotFound(updatedIdentity.Identity))));
                    }
                }
            }
            else if (!this.workflowDefinitionProvider.TryGetDefinition(definitionIdentity, out workflowDefinition))
            {
                throw FxTrace.Exception.AsError(new VersionMismatchException(SR.WorkflowServiceDefinitionIdentityNotMatched(definitionIdentity), null, definitionIdentity));
            }

            WorkflowIdentity definitionToLoad = updatedIdentity == null ? definitionIdentity : updatedIdentity.Identity;
            return WorkflowServiceInstance.InitializeInstance(context, instanceId, workflowDefinition, definitionToLoad, instance, creationContext,
                WorkflowSynchronizationContext.Instance, this.serviceHost, updateMap);
        }
        public static WorkflowServiceInstance InitializeInstance(PersistenceContext persistenceContext, Guid instanceId, Activity workflowDefinition, WorkflowIdentity definitionIdentity, IDictionary<XName, InstanceValue> loadedObject, WorkflowCreationContext creationContext,
            SynchronizationContext synchronizationContext, WorkflowServiceHost serviceHost, DynamicUpdateMap updateMap = null)
        {
            Fx.Assert(workflowDefinition != null, "workflowDefinition cannot be null.");
            Fx.Assert(serviceHost != null, "serviceHost cannot be null!");
            Fx.Assert(instanceId != Guid.Empty, "instanceId cannot be empty.");

            WorkflowServiceInstance workflowInstance = new WorkflowServiceInstance(workflowDefinition, definitionIdentity, instanceId, serviceHost, persistenceContext)
            {
                SynchronizationContext = synchronizationContext
            };

            // let us initalize the instance level extensions here
            workflowInstance.SetupExtensions(serviceHost.WorkflowExtensions);

            if (loadedObject != null)
            {
                InstanceValue stateValue;
                object deserializedRuntimeState;

                if (!loadedObject.TryGetValue(WorkflowNamespace.Workflow, out stateValue) || stateValue.Value == null)
                {
                    throw FxTrace.Exception.AsError(
                        new InstancePersistenceException(SR.WorkflowInstanceNotFoundInStore(instanceId)));
                }
                deserializedRuntimeState = stateValue.Value;

                if (loadedObject.TryGetValue(WorkflowServiceNamespace.CreationContext, out stateValue))
                {
                    workflowInstance.creationContext = (WorkflowCreationContext)stateValue.Value;
                }

                if (persistenceContext.IsSuspended)
                {
                    workflowInstance.state = State.Suspended;
                }
                try
                {
                    workflowInstance.Initialize(deserializedRuntimeState, updateMap);
                }
                catch (InstanceUpdateException)
                {
                    // Need to flush the tracking record for the update failure
                    workflowInstance.ScheduleAbortTracking(true);
                    throw;
                }

                if (updateMap != null)
                {
                    workflowInstance.HasBeenUpdated = true;
                }
            }
            else
            {
                IList<Handle> rootExecutionProperties = null;
                IDictionary<string, object> workflowArguments = null;
                // Provide default CorrelationScope if root activity is not CorrelationScope
                if (!(workflowDefinition is CorrelationScope))
                {
                    rootExecutionProperties = new List<Handle>(1)
                    {
                        new CorrelationHandle()
                    };
                }

                if (creationContext != null)
                {
                    workflowArguments = creationContext.RawWorkflowArguments;
                    workflowInstance.creationContext = creationContext;
                }
                workflowInstance.Initialize(workflowArguments, rootExecutionProperties);
            }

            return workflowInstance;
        }
        WorkflowServiceInstance(Activity workflowDefinition, WorkflowIdentity definitionIdentity, Guid instanceId, WorkflowServiceHost serviceHost, PersistenceContext persistenceContext)
            : base(workflowDefinition, definitionIdentity)
        {
            this.serviceHost = serviceHost;
            this.instanceId = instanceId;
            this.persistTimeout = serviceHost.PersistTimeout;
            this.trackTimeout = serviceHost.TrackTimeout;
            this.bufferedReceiveManager = serviceHost.Extensions.Find<BufferedReceiveManager>();

            if (persistenceContext != null)
            {
                this.persistenceContext = persistenceContext;
                this.persistenceContext.Closed += this.OnPersistenceContextClosed;
            }

            this.thisLock = new object();
            this.pendingRequests = new List<WorkflowOperationContext>();
            this.executorLock = new WorkflowExecutionLock(this);
            this.activeOperationsLock = new object();
            this.acquireReferenceSemaphore = new ThreadNeutralSemaphore(1);
            this.acquireLockTimeout = TimeSpan.MaxValue;

            // Two initial references are held:
            // The first referenceCount is owned by UnloadInstancePolicy (ReleaseInstance)
            this.referenceCount = 1;
            // The second referenceCount is owned by the loader / creator of the instance.
            this.TryAddReference();
        }
 static Guid GetIdentityHash(WorkflowIdentity id)
 {
     byte[] identityHashBuffer = Encoding.Unicode.GetBytes(id.ToString());
     return new Guid(HashHelper.ComputeHash(identityHashBuffer));
 }
 public WorkflowInstanceRecord(Guid instanceId, string activityDefinitionId, string state, WorkflowIdentity workflowDefinitionIdentity)
     : this(instanceId, activityDefinitionId, state)
 {
     this.WorkflowDefinitionIdentity = workflowDefinitionIdentity;
 }
 public VersionMismatchException(string message, WorkflowIdentity expectedVersion, WorkflowIdentity actualVersion, Exception innerException)
     : base(message, innerException)
 {
     this.ExpectedVersion = expectedVersion;
     this.ActualVersion = actualVersion;
 }
 public VersionMismatchException(WorkflowIdentity expectedVersion, WorkflowIdentity actualVersion)
     : base(GetMessage(expectedVersion, actualVersion))
 {
     this.ExpectedVersion = expectedVersion;
     this.ActualVersion = actualVersion;
 }
 public WorkflowInstanceUpdatedRecord(Guid instanceId, long recordNumber, string activityDefinitionId, WorkflowIdentity originalDefinitionIdentity, WorkflowIdentity updatedDefinitionIdentity)
     : base(instanceId, recordNumber, activityDefinitionId, WorkflowInstanceStates.Updated, updatedDefinitionIdentity)
 {
     this.OriginalDefinitionIdentity = originalDefinitionIdentity;
 }
 public WorkflowInstanceUpdatedRecord(Guid instanceId, long recordNumber, string activityDefinitionId, WorkflowIdentity originalDefinitionIdentity, WorkflowIdentity updatedDefinitionIdentity, IList<ActivityBlockingUpdate> blockingActivities)
     : base(instanceId, recordNumber, activityDefinitionId, WorkflowInstanceStates.UpdateFailed, updatedDefinitionIdentity)
 {
     this.OriginalDefinitionIdentity = originalDefinitionIdentity;
     this.BlockingActivities = new List<ActivityBlockingUpdate>(blockingActivities).AsReadOnly();
 }
        static Guid GetIdentityAnyRevisionFilterHash(WorkflowIdentity id)
        {
            if (id.Version != null)
            {
                Version version;
                if (id.Version.Build >= 0)
                {
                    version = new Version(id.Version.Major, id.Version.Minor, id.Version.Build);
                }
                else
                {
                    version = new Version(id.Version.Minor, id.Version.Minor);
                }

                return GetIdentityHash(new WorkflowIdentity(id.Name, version, id.Package));
            }
            else
            {
                return GetIdentityHash(id);
            }
        }
 public static Activity GetWorkflowDefinition(WorkflowIdentity identity)
 {
     return map[identity];
 }
 public WorkflowInstanceExceptionRecord(Guid instanceId, long recordNumber, string activityDefinitionId, Exception exception, WorkflowIdentity workflowDefinitionIdentity)
     : this(instanceId, recordNumber, activityDefinitionId, exception)
 {
     WorkflowDefinitionIdentity = workflowDefinitionIdentity;
 }