Esempio n. 1
0
        private static WorkflowServiceHost CreateServiceHostCustomPersistence(
            String xamlxName, IItemSupport extension)
        {
            WorkflowService     wfService = LoadService(xamlxName);
            WorkflowServiceHost host      = new WorkflowServiceHost(wfService);

            InstanceStore store = new FileSystemInstanceStore();

            host.DurableInstancingOptions.InstanceStore = store;

            WorkflowIdleBehavior idleBehavior = new WorkflowIdleBehavior()
            {
                TimeToUnload = TimeSpan.FromSeconds(0)
            };

            host.Description.Behaviors.Add(idleBehavior);

            //host.Faulted += new EventHandler(host_Faulted);

            if (extension != null)
            {
                host.WorkflowExtensions.Add(extension);
            }

            _hosts.Add(host);

            return(host);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            Sequence            workflow;
            WorkflowServiceHost host = null;

            try
            {
                workflow = CreateWorkflow();
                host     = new WorkflowServiceHost(workflow, new Uri("net.pipe://localhost"));
                ResumeBookmarkEndpoint endpoint = new ResumeBookmarkEndpoint(new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), new EndpointAddress("net.pipe://localhost/workflowCreationEndpoint"));
                host.AddServiceEndpoint(endpoint);
                host.Open();
                IWorkflowCreation client = new ChannelFactory <IWorkflowCreation>(endpoint.Binding, endpoint.Address).CreateChannel();
                //create an instance
                Guid id = client.Create(null);
                Console.WriteLine("Workflow instance {0} created", id);
                //resume bookmark
                client.ResumeBookmark(id, "hello", "Hello World!");
                Console.WriteLine("Press return to exit ...");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (host != null)
                {
                    host.Close();
                }
            }
        }
Esempio n. 3
0
        public void TestOpenHostWithWrongStoreThrows()
        {
            // Create service host.
            WorkflowServiceHost host = new WorkflowServiceHost(new Microsoft.Samples.BuiltInConfiguration.CountingWorkflow(), new Uri(hostBaseAddress));


            // Add service endpoint.
            host.AddServiceEndpoint("ICountingWorkflow", new NetTcpBinding(), "");

            SqlWorkflowInstanceStoreBehavior instanceStoreBehavior = new SqlWorkflowInstanceStoreBehavior("Server =localhost; Initial Catalog = WFXXX; Integrated Security = SSPI")
            {
                HostLockRenewalPeriod            = new TimeSpan(0, 0, 5),
                RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 2),
                InstanceCompletionAction         = InstanceCompletionAction.DeleteAll,
                InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry,
                InstanceEncodingOption           = InstanceEncodingOption.GZip,
            };

            host.Description.Behaviors.Add(instanceStoreBehavior);


            var ex = Assert.Throws <CommunicationException>(()
                                                            => host.Open());

            Assert.NotNull(ex.InnerException);
            Assert.Equal(typeof(System.Runtime.DurableInstancing.InstancePersistenceCommandException), ex.InnerException.GetType());
            Assert.Equal(CommunicationState.Faulted, host.State);//so can't be disposed.
        }
Esempio n. 4
0
//<Snippet1>
        static void Main(string[] args)
        {
            // Create service host.
            WorkflowServiceHost host = new WorkflowServiceHost(CountingWorkflow(), new Uri(hostBaseAddress));

            // Add service endpoint.
            host.AddServiceEndpoint("ICountingWorkflow", new BasicHttpBinding(), "");

            // Define SqlWorkflowInstanceStore and assign it to host.
            SqlWorkflowInstanceStoreBehavior store = new SqlWorkflowInstanceStoreBehavior(connectionString);
            List <XName> variantProperties         = new List <XName>()
            {
                xNS.GetName("Count")
            };

            store.Promote("CountStatus", variantProperties, null);

            host.Description.Behaviors.Add(store);

            host.WorkflowExtensions.Add <CounterStatus>(() => new CounterStatus());
            host.Open(); // This sample needs to be run with Admin privileges.
                         // Otherwise the channel listener is not allowed to open ports.
                         // See sample documentation for details.

            // Create a client that sends a message to create an instance of the workflow.
            ICountingWorkflow client = ChannelFactory <ICountingWorkflow> .CreateChannel(new BasicHttpBinding(), new EndpointAddress(hostBaseAddress));

            client.start();

            Console.WriteLine("(Press [Enter] at any time to terminate host)");
            Console.ReadLine();
            host.Close();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            var host = new WorkflowServiceHost(
                new Leaveflow.LeaveWorkflow(),
                new Uri("http://localhost:8080/LWS"));
            host.AddDefaultEndpoints();

            host.Description.Behaviors.Add(
                new ServiceMetadataBehavior() { HttpGetEnabled = true });

            host.Description.Behaviors.Add(
                new WorkflowIdleBehavior() {
                    TimeToPersist = new TimeSpan(0, 0, 0),
                    TimeToUnload = new TimeSpan(0, 0, 0)
                });

            host.AddServiceEndpoint(
                "IMetadataExchange",
                MetadataExchangeBindings.CreateMexHttpBinding(),
                "mex");

            var store = new SqlWorkflowInstanceStore(
                "server=(local)\\sqlexpress;database=wftest;uid=sa;pwd=123456;");

            host.DurableInstancingOptions.InstanceStore = store;
            host.UnknownMessageReceived += (o, e) => {
                Console.WriteLine("\n" + e.Message + "\n");
            };
            host.Open();
            Console.WriteLine("> Server is ready.");
            Console.Read();
        }
Esempio n. 6
0
        private static WorkflowServiceHost CreateServiceHost(String xamlxName)
        {
            WorkflowService     wfService = LoadService(xamlxName);
            WorkflowServiceHost host      = new WorkflowServiceHost(wfService);

            //host.UnknownMessageReceived += (sender, e) =>
            //{
            //    Console.WriteLine("Service1 UnknownMessageReceived");
            //    Console.WriteLine(((UnknownMessageReceivedEventArgs)e).Message);
            //};
            //host.Faulted += (sender, e) =>
            //{
            //    Console.WriteLine("Service1 Faulted");
            //};

            //
            //add the extension
            //

            //host.WorkflowExtensions.Add<ServiceLibrary.OrderUtilityExtension>(
            //    () => new ServiceLibrary.OrderUtilityExtension());
            host.WorkflowExtensions.Add(new ServiceLibrary.OrderUtilityExtension());

            _hosts.Add(host);

            return(host);
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            // <Snippet03>
            Console.WriteLine("Starting up...");
            WorkflowService     service = CreateService();
            Uri                 address = new Uri(Constants.ServiceBaseAddress);
            WorkflowServiceHost host    = new WorkflowServiceHost(service, address);

            try
            {
                Console.WriteLine("Opening service...");
                host.Open();

                Console.WriteLine("Service is listening on {0}...", address);
                Console.WriteLine("To terminate press ENTER");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Service terminated with exception {0}", ex.ToString());
            }
            finally
            {
                host.Close();
            }
            // </Snippet03>
        }
        public virtual void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost workflowServiceHost = serviceHostBase as WorkflowServiceHost;

            if (null != workflowServiceHost)
            {
                string workflowDisplayName = workflowServiceHost.Activity.DisplayName;
                string hostReference       = string.Empty;

                if (AspNetEnvironment.Enabled)
                {
                    VirtualPathExtension virtualPathExtension = serviceHostBase.Extensions.Find <VirtualPathExtension>();
                    if (virtualPathExtension != null && virtualPathExtension.VirtualPath != null)
                    {
                        //Format Website name\Application Virtual Path|\relative service virtual path|serviceName
                        string name        = serviceDescription != null ? serviceDescription.Name : string.Empty;
                        string application = virtualPathExtension.ApplicationVirtualPath;

                        //If the application is the root, do not include it in servicePath
                        string servicePath = virtualPathExtension.VirtualPath.Replace("~", application + "|");
                        hostReference = string.Format(CultureInfo.InvariantCulture, "{0}{1}|{2}", virtualPathExtension.SiteName, servicePath, name);
                    }
                }

                TrackingProfile trackingProfile = this.GetProfile(this.ProfileName, workflowDisplayName);
                workflowServiceHost.WorkflowExtensions.Add(
                    () => new EtwTrackingParticipant
                {
                    ApplicationReference = hostReference,
                    TrackingProfile      = trackingProfile
                });
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            string queueName = @".\private$\ReceiveTx";

            if (!MessageQueue.Exists(queueName))
            {
                MessageQueue.Create(queueName, true);
                Console.WriteLine("Message Queue {0} created", queueName);
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
                return;
            }

            WorkflowServiceHost host = WorkflowHost.CreateWorkflowServiceHost();

            host.Open();

            Console.WriteLine("The Workflow service is ready");
            Console.WriteLine("Press <ENTER> to close the service \n");

            WorkflowTestClient.Run(1);

            Console.ReadLine();

            host.Close();
        }
Esempio n. 10
0
        static void Main()
        {
            // Same workflow as Dataflow sample
            Activity            workflow = LoadProgram("Dataflow.xaml");
            WorkflowServiceHost host     = new WorkflowServiceHost(workflow,
                                                                   new Uri("http://localhost/Dataflow.xaml"));

            WorkflowControlEndpoint controlEndpoint = new WorkflowControlEndpoint(
                new BasicHttpBinding(),
                new EndpointAddress(new Uri("http://localhost/DataflowControl.xaml")));

            CreationEndpoint creationEndpoint = new CreationEndpoint(
                new BasicHttpBinding(),
                new EndpointAddress(new Uri("http://localhost/DataflowControl.xaml/Creation")));

            host.AddServiceEndpoint(controlEndpoint);
            host.AddServiceEndpoint(creationEndpoint);

            host.Open();

            Console.WriteLine("Host open...");

            IWorkflowCreation creationClient = new ChannelFactory <IWorkflowCreation>(creationEndpoint.Binding, creationEndpoint.Address).CreateChannel();

            // Start a new instance of the workflow
            Guid instanceId = creationClient.CreateSuspended(null);
            WorkflowControlClient controlClient = new WorkflowControlClient(controlEndpoint);

            controlClient.Unsuspend(instanceId);

            Console.WriteLine("Hit any key to exit Host...");
            Console.ReadLine();
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:8081/StopWatchService";

            try
            {
                using (WorkflowServiceHost host = new WorkflowServiceHost(new StopWatchWorkflow(), new Uri(baseAddress)))
                {
                    host.Description.Behaviors.Add(new ServiceMetadataBehavior()
                    {
                        HttpGetEnabled = true
                    });

                    Console.WriteLine("Opening StopWatchService...");
                    host.Open();

                    Console.WriteLine("StopWatchService waiting at: " + baseAddress);
                    Console.WriteLine("Press [ENTER] to exit");
                    Console.ReadLine();
                    host.Close();
                }
            }
            catch (AddressAlreadyInUseException)
            {
                Console.WriteLine("Error - An error occurred while opening the service. Please ensure that there are no other instances of this service running.");
                Console.WriteLine("Press [ENTER] to exit");
                Console.ReadLine();
            }
            catch (CommunicationObjectFaultedException)
            {
                Console.WriteLine("Error - An error occurred while opening the service. Please ensure that there are no other instances of this service running.");
                Console.WriteLine("Press [ENTER] to exit");
                Console.ReadLine();
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting up...");
            WorkflowService service = CreateService();

            WorkflowServiceHost host = new WorkflowServiceHost(service, new Uri("http://localhost:8000/DiscoveryPrintService"));

            try
            {
                // ServiceDiscoveryBehavior and UdpDiscoveryEndpoint are being added through config
                Console.WriteLine("Opening service...");
                host.Open();

                Console.WriteLine("To terminate press ENTER");
                Console.ReadLine();

                host.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);
            }

            if (host.State != CommunicationState.Closed)
            {
                Console.WriteLine("Aborting service...");
                host.Abort();
            }
        }
Esempio n. 13
0
        private static void HostContentCorrelation()
        {
            Activity wf = GetCCWorkflowWithInitializeCorrelationActivity(); // GetCCWorkflow();

            string baseAddress = "http://localhost:8080/OrderService";

            using (WorkflowServiceHost host = new WorkflowServiceHost(wf, new Uri(baseAddress)))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                ServiceDebugBehavior sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>();
                sdb.IncludeExceptionDetailInFaults = true;

                // Unneeded using ZeroConfig
                //host.AddServiceEndpoint(OrderContractName, Binding2, Service1Address);

                host.Open();
                Console.WriteLine("Service waiting at: " + baseAddress);
                Console.WriteLine("Press [ENTER] to exit");
                Console.ReadLine();
                host.Close();
            }
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            string baseAddr            = "http://localhost:8080/OpScope";
            XName  serviceContractName = XName.Get("IBankService", "http://bank.org");

            WorkflowService svc = new WorkflowService
            {
                Name = serviceContractName,
                Body = new BankService()
            };

            using (WorkflowServiceHost host = new WorkflowServiceHost(svc, new Uri(baseAddr)))
            {
                host.AddServiceEndpoint(serviceContractName, new BasicHttpContextBinding(), "");
                host.Description.Behaviors.Add(new ServiceMetadataBehavior()
                {
                    HttpGetEnabled = true
                });
                Console.WriteLine("Starting ...");
                host.Open();

                Console.WriteLine("Service is waiting at: " + baseAddr);
                Console.WriteLine("Press [Enter] to exit");
                Console.ReadLine();
                host.Close();
            }
        }
        protected override WorkflowServiceHost CreateWorkflowServiceHost(Activity activity, Uri[] baseAddresses)
        {
            var serviceHost = new WorkflowServiceHost(activity, baseAddresses);

            serviceHost.MakeAnnouncingService();
            return(serviceHost);
        }
Esempio n. 16
0
        public void TestOpenHost()
        {
            // Create service host.
            using (WorkflowServiceHost host = new WorkflowServiceHost(new Microsoft.Samples.BuiltInConfiguration.CountingWorkflow(), new Uri(hostBaseAddress)))
            {
                // Add service endpoint.
                host.AddServiceEndpoint("ICountingWorkflow", new NetTcpBinding(), "");

                SqlWorkflowInstanceStoreBehavior instanceStoreBehavior = new SqlWorkflowInstanceStoreBehavior(connectionString)
                {
                    HostLockRenewalPeriod            = new TimeSpan(0, 0, 5),
                    RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 2),
                    InstanceCompletionAction         = InstanceCompletionAction.DeleteAll,
                    InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry,
                    InstanceEncodingOption           = InstanceEncodingOption.GZip,
                };
                host.Description.Behaviors.Add(instanceStoreBehavior);

                host.Open();
                Assert.Equal(CommunicationState.Opened, host.State);


                // Create a client that sends a message to create an instance of the workflow.
                ICountingWorkflow client = ChannelFactory <ICountingWorkflow> .CreateChannel(new NetTcpBinding(), new EndpointAddress(hostBaseAddress));

                client.start();
                Debug.WriteLine("client.start() done.");
                System.Threading.Thread.Sleep(10000);
                Debug.WriteLine("sleep finished");
                host.Close();
            }
        }
Esempio n. 17
0
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            ICorrelationDataSource property = endpoint.Binding.GetProperty <ICorrelationDataSource>(new BindingParameterCollection());

            if (property != null)
            {
                this.ConfigureBindingDataNames(property);
                this.ConfigureBindingDefaultQueries(endpoint, property, true);
            }
            System.ServiceModel.Description.ServiceDescription description = endpointDispatcher.ChannelDispatcher.Host.Description;
            WorkflowServiceHost host = endpointDispatcher.ChannelDispatcher.Host as WorkflowServiceHost;

            if (host == null)
            {
                this.ScopeName = XNamespace.Get(description.Namespace).GetName(description.Name);
            }
            else
            {
                this.ScopeName = host.DurableInstancingOptions.ScopeName;
            }
            endpointDispatcher.ChannelDispatcher.ChannelInitializers.Add(this);
            if (this.shouldPreserveMessage)
            {
                endpointDispatcher.DispatchRuntime.PreserveMessage = true;
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            const string connectionString =
                "Server=.\\SQLEXPRESS;Initial Catalog=Persistence;Integrated Security=SSPI";
            // The Throw class derives from the Activity class, needed to construct a WorkflowServiceHost.
            Throw throwError = new Throw();

            WorkflowServiceHost host = new WorkflowServiceHost(throwError,
                                                               new Uri(@"http://microsoft/services/"));

            //<snippet1>
            // Code to create a WorkFlowServiceHost is not shown here.
            // Note that SqlWorkflowInstanceStore is in the System.Activities.DurableInstancing.dll
            host.DurableInstancingOptions.InstanceStore = new SqlWorkflowInstanceStore(connectionString);
            WorkflowIdleBehavior alteredBehavior = new WorkflowIdleBehavior();

            // Alter the time to persist and unload.
            alteredBehavior.TimeToPersist = new TimeSpan(0, 4, 0);
            alteredBehavior.TimeToUnload  = new TimeSpan(0, 5, 0);
            //Remove the existing behavior and replace it with the new one.
            host.Description.Behaviors.Remove <WorkflowIdleBehavior>();
            host.Description.Behaviors.Add(alteredBehavior);
            //</snippet1>
            Console.WriteLine(alteredBehavior.TimeToUnload.Minutes.ToString());
            //wfsh.Open();
            Console.WriteLine("closed");
            Console.ReadLine();
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:8080/PropertyService";

            using (WorkflowServiceHost host = new WorkflowServiceHost(GetPropertyWorkflow(), new Uri(baseAddress)))
            {
                host.UnknownMessageReceived += new EventHandler <UnknownMessageReceivedEventArgs>(OnUnknownMessage);
                host.AddServiceEndpoint(XName.Get("IProperty", ns), new BasicHttpBinding(), baseAddress);

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(smb);

                try
                {
                    host.Open();

                    Console.WriteLine("Service host is open for business. Press [Enter] to close the host...");
                    Console.ReadLine();
                }
                finally
                {
                    host.Close();
                }
            }
        }
        public virtual void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost host = serviceHostBase as WorkflowServiceHost;

            if (host != null)
            {
                string displayName   = host.Activity.DisplayName;
                string hostReference = string.Empty;
                if (AspNetEnvironment.Enabled)
                {
                    VirtualPathExtension extension = serviceHostBase.Extensions.Find <VirtualPathExtension>();
                    if ((extension != null) && (extension.VirtualPath != null))
                    {
                        string str2 = (serviceDescription != null) ? serviceDescription.Name : string.Empty;
                        string applicationVirtualPath = extension.ApplicationVirtualPath;
                        string str4 = extension.VirtualPath.Replace("~", applicationVirtualPath + "|");
                        hostReference = string.Format(CultureInfo.InvariantCulture, "{0}{1}|{2}", new object[] { extension.SiteName, str4, str2 });
                    }
                }
                TrackingProfile trackingProfile = this.GetProfile(this.ProfileName, displayName);
                host.WorkflowExtensions.Add <EtwTrackingParticipant>(() => new EtwTrackingParticipant {
                    ApplicationReference = hostReference, TrackingProfile = trackingProfile
                });
            }
        }
Esempio n. 21
0
        public override void Start()
        {
            if (IsRunning)
            {
                return;
            }

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(Xaml)))
            {
                workflowServiceHost = new WorkflowServiceHost(XamlServices.Load(stream) as WorkflowService);
            }

            workflowServiceHost.WorkflowExtensions.Add(OutputWriter);

            workflowServiceHost.Opened  += WorkflowServiceHostOnOpened;
            workflowServiceHost.Opening += WorkflowServiceHostOnOpening;
            workflowServiceHost.Closed  += WorkflowServiceHostOnClosed;
            workflowServiceHost.Closing += WorkflowServiceHostOnClosing;
            workflowServiceHost.Faulted += WorkflowServiceHostOnFaulted;
            workflowServiceHost.UnknownMessageReceived += WorkflowServiceHostOnUnknownMessageReceived;

            try
            {
                OnExecutingStateChanged(new WorkflowExecutingStateEventArgs(true));
                workflowServiceHost.Open();
            }
            catch (Exception e)
            {
                OutputWriter.WriteLine(e.StackTrace);
                OnExecutingStateChanged(new WorkflowExecutingStateEventArgs(false));
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            // Create service host.
            WorkflowServiceHost host = new WorkflowServiceHost(new CountingWorkflow(), new Uri(hostBaseAddress));

            // Add service endpoint.
            host.AddServiceEndpoint("ICountingWorkflow", new BasicHttpBinding(), "");

            // Define SqlWorkflowInstanceStoreBehavior:
            //   Set interval to renew instance lock to 5 seconds.
            //   Set interval to check for runnable instances to 2 seconds.
            //   Instance Store does not keep instances after it is completed.
            //   Select exponential back-off algorithm when retrying to load a locked instance.
            //   Instance state information is compressed using the GZip compressing algorithm.
            SqlWorkflowInstanceStoreBehavior instanceStoreBehavior = new SqlWorkflowInstanceStoreBehavior(connectionString);

            instanceStoreBehavior.HostLockRenewalPeriod            = new TimeSpan(0, 0, 5);
            instanceStoreBehavior.RunnableInstancesDetectionPeriod = new TimeSpan(0, 0, 2);
            instanceStoreBehavior.InstanceCompletionAction         = InstanceCompletionAction.DeleteAll;
            instanceStoreBehavior.InstanceLockedExceptionAction    = InstanceLockedExceptionAction.AggressiveRetry;
            instanceStoreBehavior.InstanceEncodingOption           = InstanceEncodingOption.GZip;
            host.Description.Behaviors.Add(instanceStoreBehavior);

            // Open service host.
            host.Open();

            // Create a client that sends a message to create an instance of the workflow.
            ICountingWorkflow client = ChannelFactory <ICountingWorkflow> .CreateChannel(new BasicHttpBinding(), new EndpointAddress(hostBaseAddress));

            client.start();

            Console.WriteLine("(Press [Enter] at any time to terminate host)");
            Console.ReadLine();
            host.Close();
        }
        static void Main(string[] args)
        {
            using (Session session = new Session()) {
                session.ConnectionString = DevExpressConnectionString;
                session.UpdateSchema(typeof(XpoWorkflowInstance), typeof(XpoInstanceKey));
                session.CreateObjectTypeRecords(typeof(XpoWorkflowInstance), typeof(XpoInstanceKey));
            }

            // Create service host.
            WorkflowServiceHost host = new WorkflowServiceHost(new CountingWorkflow(), new Uri(hostBaseAddress));

            // Add service endpoint.
            host.AddServiceEndpoint("ICountingWorkflow", new BasicHttpBinding(), "");

            // Open service host.
            host.Open();

            // Create a client that sends a message to create an instance of the workflow.
            ICountingWorkflow client = ChannelFactory <ICountingWorkflow> .CreateChannel(new BasicHttpBinding(), new EndpointAddress(hostBaseAddress));

            client.start();

            Console.WriteLine("(Press [Enter] at any time to terminate host)");
            Console.ReadLine();
            host.Close();
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            Sequence            workflow;
            WorkflowServiceHost host = null;

            try
            {
                workflow = CreateWorkflow();
                host     = new WorkflowServiceHost(workflow, new Uri("net.pipe://localhost"));
                CreationEndpoint creationEp = new CreationEndpoint(new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), new EndpointAddress("net.pipe://localhost/workflowCreationEndpoint"));
                host.AddServiceEndpoint(creationEp);
                host.Open();
                //client using NetNamedPipeBinding
                IWorkflowCreation client = new ChannelFactory <IWorkflowCreation>(creationEp.Binding, creationEp.Address).CreateChannel();
                //client using BasicHttpBinding
                IWorkflowCreation client2 = new ChannelFactory <IWorkflowCreation>(new BasicHttpBinding(), new EndpointAddress("http://localhost/workflowCreationEndpoint")).CreateChannel();
                //create instance
                Console.WriteLine("Workflow Instance created using CreationEndpoint added in code. Instance Id: {0}", client.Create(null));
                //create another instance
                Console.WriteLine("Workflow Instance created using CreationEndpoint added in config. Instance Id: {0}", client2.Create(null));
                Console.WriteLine("Press return to exit ...");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (host != null)
                {
                    host.Close();
                }
            }
        }
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            ICorrelationDataSource source = endpoint.Binding.GetProperty <ICorrelationDataSource>(new BindingParameterCollection());

            if (source != null)
            {
                this.ConfigureBindingDataNames(source);
                this.ConfigureBindingDefaultQueries(endpoint, source, true);
            }

            ServiceDescription  description = endpointDispatcher.ChannelDispatcher.Host.Description;
            WorkflowServiceHost host        = endpointDispatcher.ChannelDispatcher.Host as WorkflowServiceHost;

            if (host == null)
            {
                // setup the scope name to be the Namespace + Name of the ServiceDescription. This will be
                // either have been explicitly set by WorkflowService.Name or defaulted through the infrastructure
                this.ScopeName = XNamespace.Get(description.Namespace).GetName(description.Name);
            }
            else
            {
                this.ScopeName = host.DurableInstancingOptions.ScopeName;
            }

            endpointDispatcher.ChannelDispatcher.ChannelInitializers.Add(this);
            if (this.shouldPreserveMessage)
            {
                // there could be a query that might be read from the message body
                // let us buffer the message at the dispatcher
                endpointDispatcher.DispatchRuntime.PreserveMessage = true;
            }
        }
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost workflowServiceHost = serviceHostBase as WorkflowServiceHost;

            if (workflowServiceHost != null)
            {
                workflowServiceHost.UnhandledExceptionAction = this.Action;
            }
        }
        public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost host = serviceHostBase as WorkflowServiceHost;

            if (host != null)
            {
                host.UnhandledExceptionAction = this.Action;
            }
        }
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost workflowServiceHost = serviceHostBase as WorkflowServiceHost;

            if (workflowServiceHost != null)
            {
                workflowServiceHost.WorkflowExtensions.Add(new SendMessageChannelCache(this.FactorySettings, this.ChannelSettings, this.AllowUnsafeCaching));
            }
        }
Esempio n. 29
0
        public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost host = serviceHostBase as WorkflowServiceHost;

            if (host != null)
            {
                host.IdleTimeToPersist = this.TimeToPersist;
                host.IdleTimeToUnload  = this.TimeToUnload;
            }
        }
Esempio n. 30
0
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost workflowServiceHost = serviceHostBase as WorkflowServiceHost;

            if (workflowServiceHost != null)
            {
                workflowServiceHost.IdleTimeToPersist = this.TimeToPersist;
                workflowServiceHost.IdleTimeToUnload  = this.TimeToUnload;
            }
        }
        protected virtual WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses)
        {
            WorkflowServiceHost workflowServiceHost = new WorkflowServiceHost(service, baseAddresses);

            if (service.DefinitionIdentity != null)
            {
                AddSupportedVersions(workflowServiceHost, service);
            }
            return(workflowServiceHost);
        }
Esempio n. 32
0
        public static WorkflowServiceHost CreateWorkflowServiceHost()
        {
            // add the workflow implementation and application endpoint to the host
            WorkflowService service = new WorkflowService()
            {
                Body = PurchaseOrderWorkflow.CreateBody(),

                Endpoints =
                {
                    // adds an application endpoint
                    new System.ServiceModel.Endpoint
                    {
                        Binding = new System.ServiceModel.NetMsmqBinding("NetMsmqBindingTx"),
                        AddressUri = new Uri("net.msmq://localhost/private/ReceiveTx"),
                        ServiceContractName = XName.Get(PurchaseOrderWorkflow.poContractDescription.Name)
                    }
                }
            };
            WorkflowServiceHost workflowServiceHost = new WorkflowServiceHost(service);

            // add the workflow management behaviors
            IServiceBehavior idleBehavior = new WorkflowIdleBehavior { TimeToUnload = TimeSpan.Zero };
            workflowServiceHost.Description.Behaviors.Add(idleBehavior);

            IServiceBehavior workflowUnhandledExceptionBehavior = new WorkflowUnhandledExceptionBehavior()
            {
                Action = WorkflowUnhandledExceptionAction.AbandonAndSuspend // this is also the default
            };
            workflowServiceHost.Description.Behaviors.Add(workflowUnhandledExceptionBehavior);

            // add the instance store
            SqlWorkflowInstanceStoreBehavior instanceStoreBehavior = new SqlWorkflowInstanceStoreBehavior()
            {
                ConnectionString = "Server=localhost\\SQLEXPRESS;Integrated Security=true;Initial Catalog=DefaultSampleStore;"
            };
            workflowServiceHost.Description.Behaviors.Add(instanceStoreBehavior);

            // add a workflow management endpoint
            ServiceEndpoint workflowControlEndpoint = new WorkflowControlEndpoint()
            {
                Binding = new System.ServiceModel.NetNamedPipeBinding(System.ServiceModel.NetNamedPipeSecurityMode.None),
                Address = new System.ServiceModel.EndpointAddress("net.pipe://workflowInstanceControl")
            };
            workflowServiceHost.AddServiceEndpoint(workflowControlEndpoint);

            // add the tracking participant
            workflowServiceHost.WorkflowExtensions.Add(new TrackingListenerConsole());

            foreach (ServiceEndpoint ep in workflowServiceHost.Description.Endpoints)
            {
                Console.WriteLine(ep.Address);
            }

            return workflowServiceHost;
        }
        internal PersistenceProviderDirectory(InstanceStore store, InstanceOwner owner, IDictionary<XName, InstanceValue> instanceMetadataChanges, WorkflowDefinitionProvider workflowDefinitionProvider, WorkflowServiceHost serviceHost,
            DurableConsistencyScope consistencyScope, int maxInstances)
            : this(workflowDefinitionProvider, serviceHost, consistencyScope, maxInstances)
        {
            Fx.Assert(store != null, "InstanceStore must be specified on PPD.");
            Fx.Assert(owner != null, "InstanceOwner must be specified on PPD.");

            this.store = store;
            this.owner = owner;
            this.InstanceMetadataChanges = instanceMetadataChanges;
        }
Esempio n. 34
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting the service.");

            using (WorkflowServiceHost wsh = new WorkflowServiceHost(new ServiceWorkflow(), new Uri("net.tcp://localhost:8001/SuppressSample")))
            {
                wsh.Open();
                Console.WriteLine("Service is now running. Press [ENTER] to close.");
                Console.ReadLine();
            }
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting the service.");
            ManualResetEvent serverResetEvent = new ManualResetEvent(false);

            using (WorkflowServiceHost host = new WorkflowServiceHost(new ServiceWorkflow()))
            {
                host.Open();

                Console.WriteLine("Service is running, press enter to close.");
                Console.ReadLine();
            };
        }
Esempio n. 36
0
        static void Main(string[] args)
        {
            Console.Title = "Service";
            Console.WriteLine("Starting up");

            System.ServiceModel.Activities.WorkflowServiceHost host = new WorkflowServiceHost(GetService(), new Uri("http://localhost:8000/"));
            host.Open();

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

            host.Close();
        }
        public ControlOperationInvoker(OperationDescription description, ServiceEndpoint endpoint,
            CorrelationKeyCalculator correlationKeyCalculator, IOperationInvoker innerInvoker, ServiceHostBase host)
        {
            Fx.Assert(host is WorkflowServiceHost, "ControlOperationInvoker must be used with a WorkflowServiceHost");

            this.host = (WorkflowServiceHost)host;
            this.instanceManager = this.host.DurableInstanceManager;
            this.operationName = description.Name;
            this.isOneWay = description.IsOneWay;
            this.endpoint = endpoint;
            this.innerInvoker = innerInvoker;
            this.keyCalculator = correlationKeyCalculator;
            this.persistTimeout = this.host.PersistTimeout;

            if (description.DeclaringContract == WorkflowControlEndpoint.WorkflowControlServiceContract ||
                description.DeclaringContract == WorkflowControlEndpoint.WorkflowControlServiceBaseContract)
            {
                //Mode1: This invoker belongs to IWorkflowInstanceManagement operation.
                this.isControlOperation = true;
                switch (this.operationName)
                {
                    case XD2.WorkflowInstanceManagementService.Cancel:
                    case XD2.WorkflowInstanceManagementService.TransactedCancel:
                    case XD2.WorkflowInstanceManagementService.Run:
                    case XD2.WorkflowInstanceManagementService.TransactedRun:
                    case XD2.WorkflowInstanceManagementService.Unsuspend:
                    case XD2.WorkflowInstanceManagementService.TransactedUnsuspend:
                        this.inputParameterCount = 1;
                        break;
                    case XD2.WorkflowInstanceManagementService.Abandon:
                    case XD2.WorkflowInstanceManagementService.Suspend:
                    case XD2.WorkflowInstanceManagementService.TransactedSuspend:
                    case XD2.WorkflowInstanceManagementService.Terminate:
                    case XD2.WorkflowInstanceManagementService.TransactedTerminate:
                    case XD2.WorkflowInstanceManagementService.Update:
                    case XD2.WorkflowInstanceManagementService.TransactedUpdate:
                        this.inputParameterCount = 2;
                        break;
                    default:
                        throw Fx.AssertAndThrow("Unreachable code");
                }
            }
            else if (endpoint is WorkflowHostingEndpoint)
            {
                this.CanCreateInstance = true;
            }
            else
            {
                this.bufferedReceiveManager = this.host.Extensions.Find<BufferedReceiveManager>();
            }
        }
        internal DurableInstanceManager(WorkflowServiceHost host)
        {
            DurableInstancingOptions = new DurableInstancingOptions(this);
            this.instanceOwnerMetadata = new Dictionary<XName, InstanceValue>();
            this.instanceMetadataChanges = new Dictionary<XName, InstanceValue>();
            this.thisLock = new object();

            // This is for collision detection.  Will replace with the real service name prior to executing.
            InstanceValue sentinel = new InstanceValue(XNamespace.Get("http://tempuri.org").GetName("Sentinel"));
            this.instanceOwnerMetadata.Add(WorkflowNamespace.WorkflowHostType, sentinel);
            this.instanceMetadataChanges.Add(WorkflowNamespace.WorkflowHostType, sentinel);
            this.instanceMetadataChanges.Add(PersistenceMetadataNamespace.InstanceType, new InstanceValue(WorkflowNamespace.WorkflowHostType, InstanceValueOptions.WriteOnly));

            this.Host = host;
        }
Esempio n. 39
0
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:8080/CalculatorService";

            using (WorkflowServiceHost host = new WorkflowServiceHost(new Calculator(), new Uri(baseAddress)))
            {
                host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });

                // no application endpoints are defined explicitly
                // the Config Simplification feature adds a default endpoint with BasicHttpBinding at baseAddress + Receive.ServiceContractName.LocalName

                host.Open();
                Console.WriteLine("CalculatorService waiting at: {0}", baseAddress);
                Console.WriteLine("Press [ENTER] to exit");
                Console.ReadLine();
                host.Close();
            }
        }
        PersistenceProviderDirectory(WorkflowDefinitionProvider workflowDefinitionProvider, WorkflowServiceHost serviceHost, DurableConsistencyScope consistencyScope, int maxInstances)
        {
            Fx.Assert(workflowDefinitionProvider != null, "definition provider must be specified on PPD.");
            Fx.Assert(serviceHost != null, "WorkflowServiceHost must be specified on PPD.");
            Fx.AssertAndThrow(maxInstances > 0, "MaxInstance must be greater than zero on PPD.");

            this.workflowDefinitionProvider = workflowDefinitionProvider;
            this.serviceHost = serviceHost;

            ConsistencyScope = consistencyScope;
            MaxInstances = maxInstances;

            this.throttle = new InstanceThrottle(MaxInstances, serviceHost);
            this.pipelinesInUse = new HashSet<PersistencePipeline>();

            this.keyMap = new Dictionary<Guid, PersistenceContext>();
            this.instanceCache = new Dictionary<Guid, PersistenceContext>();
            this.loadsInProgress = new Dictionary<InstanceKey, AsyncWaitHandle>();            
        }
Esempio n. 41
0
        static void Main()
        {
            Console.WriteLine("Building the server.");
            using (WorkflowServiceHost host = new WorkflowServiceHost(new DeclarativeServiceWorkflow(), new Uri("net.tcp://localhost:8000/TransactedReceiveService/Declarative")))
            {
                host.WorkflowExtensions.Add(new EventTrackingParticipant(Program.syncEvent));

                //Start the server
                host.Open();
                Console.WriteLine("Service started.");
                syncEvent.WaitOne();

                //Shutdown
                host.Close();

            };

            Console.WriteLine();
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }
        protected override void LoadAndExecute()
        {
            MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));
            WorkflowService workflowToRun = XamlServices.Load(ms) as WorkflowService;

            this.workflowServiceHost = new WorkflowServiceHost(workflowToRun);
            this.workflowServiceHost.WorkflowExtensions.Add(this.output);
            this.workflowServiceHost.WorkflowExtensions.Add(this.InitialiseVisualTrackingParticipant(workflowToRun.GetWorkflowRoot()));
            this.AddHandlers();

            try
            {
                this.running = true;
                this.workflowServiceHost.Open();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionInDebugStatus, this.workflowName);
            }
        }
        public void Run()
        {
            this.workflowDesigner.Flush();
            MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));

            WorkflowService workflowToRun = XamlServices.Load(ms) as WorkflowService;

            this.workflowServiceHost = new WorkflowServiceHost(workflowToRun);

            this.workflowServiceHost.WorkflowExtensions.Add(this.output);
            try
            {
                this.AddHandlers();
                this.running = true;
                this.workflowServiceHost.Open();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionServiceHostStatus, this.workflowName);
                this.running = false;
            }
        }
Esempio n. 44
0
 /// <summary>
 /// Attaches a StateTracker to a WorkflowServiceHost
 /// </summary>
 /// <param name="workflowServiceHost">
 /// The host 
 /// </param>
 /// <param name="maxHistory">
 /// The maximum history 
 /// </param>
 /// <returns>
 /// The Microsoft.Activities.Extensions.Tracking.StateTracker. 
 /// </returns>
 public static StateTracker Attach(
     WorkflowServiceHost workflowServiceHost, int maxHistory = StateMachineInfo.DefaultMaxHistory)
 {
     return Attach(workflowServiceHost, null, maxHistory);
 }
        void CreateWorkflowManagementEndpoint(WorkflowServiceHost workflowServiceHost)
        {
            Binding controlEndpointBinding; 
            if (workflowServiceHost.InternalBaseAddresses.Contains(Uri.UriSchemeNetPipe))
            {
                controlEndpointBinding = NamedPipeControlEndpointBinding;
            }
            else if (workflowServiceHost.InternalBaseAddresses.Contains(Uri.UriSchemeHttp))
            {
                controlEndpointBinding = HttpControlEndpointBinding;
            }
            else
            {
                return;
            }

            Uri controlEndpointAddress = ServiceHost.GetVia(controlEndpointBinding.Scheme, new Uri(ControlEndpointAddress, UriKind.Relative), workflowServiceHost.InternalBaseAddresses);            
            XmlQualifiedName contractName = new XmlQualifiedName(XD2.WorkflowInstanceManagementService.ContractName, XD2.WorkflowServices.Namespace);
            //Create the Endpoint Dispatcher
            EndpointAddress address = new EndpointAddress(controlEndpointAddress.AbsoluteUri);
            EndpointDispatcher endpointDispatcher = new EndpointDispatcher(address,
                XD2.WorkflowInstanceManagementService.ContractName,
                XD2.WorkflowServices.Namespace, true)
            {
                ContractFilter = new ActionMessageFilter(
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Abandon, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Cancel, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Run, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Suspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Terminate, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedCancel, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedRun, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedSuspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedTerminate, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedUnsuspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.TransactedUpdate, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Unsuspend, null, false),
                    NamingHelper.GetMessageAction(contractName, XD2.WorkflowInstanceManagementService.Update, null, false)),
            };

            //Create Listener
            ServiceEndpoint endpoint = new ServiceEndpoint(WorkflowControlEndpoint.WorkflowControlServiceContract, controlEndpointBinding, address);
            BindingParameterCollection parameters = workflowServiceHost.GetBindingParameters(endpoint);

            IChannelListener listener;
            if (controlEndpointBinding.CanBuildChannelListener<IDuplexSessionChannel>(controlEndpointAddress, parameters))
            {
                listener = controlEndpointBinding.BuildChannelListener<IDuplexSessionChannel>(controlEndpointAddress, parameters);
            }
            else if (controlEndpointBinding.CanBuildChannelListener<IReplySessionChannel>(controlEndpointAddress, parameters))
            {
                listener = controlEndpointBinding.BuildChannelListener<IReplySessionChannel>(controlEndpointAddress, parameters);
            }
            else
            {
                listener = controlEndpointBinding.BuildChannelListener<IReplyChannel>(controlEndpointAddress, parameters);
            }

            //Add the operations
            bool formatRequest;
            bool formatReply;
            foreach (OperationDescription operation in WorkflowControlEndpoint.WorkflowControlServiceContract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = new DataContractSerializerOperationBehavior(operation);

                DispatchOperation operationDispatcher = new DispatchOperation(endpointDispatcher.DispatchRuntime, operation.Name,
                    NamingHelper.GetMessageAction(operation, false), NamingHelper.GetMessageAction(operation, true))
                {
                    Formatter = (IDispatchMessageFormatter)dataContractSerializerOperationBehavior.GetFormatter(operation, out formatRequest, out formatReply, false),
                    Invoker = new ControlOperationInvoker(
                        operation,
                        new WorkflowControlEndpoint(controlEndpointBinding, address),
                        null,
                        workflowServiceHost),
                };
                endpointDispatcher.DispatchRuntime.Operations.Add(operationDispatcher);

                OperationBehaviorAttribute operationAttribute = operation.Behaviors.Find<OperationBehaviorAttribute>();
                ((IOperationBehavior)operationAttribute).ApplyDispatchBehavior(operation, operationDispatcher);
            }

            DispatchRuntime dispatchRuntime = endpointDispatcher.DispatchRuntime;
            dispatchRuntime.ConcurrencyMode = ConcurrencyMode.Multiple;
            dispatchRuntime.InstanceContextProvider = new DurableInstanceContextProvider(workflowServiceHost);
            dispatchRuntime.InstanceProvider = new DurableInstanceProvider(workflowServiceHost);
            dispatchRuntime.ServiceAuthorizationManager = new WindowsAuthorizationManager(this.WindowsGroup);

            //Create the Channel Dispatcher
            ServiceDebugBehavior serviceDebugBehavior = workflowServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
            ServiceBehaviorAttribute serviceBehaviorAttribute = workflowServiceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();

            bool includeDebugInfo = false;
            if (serviceDebugBehavior != null)
            {
                includeDebugInfo |= serviceDebugBehavior.IncludeExceptionDetailInFaults;
            }
            if (serviceBehaviorAttribute != null)
            {
                includeDebugInfo |= serviceBehaviorAttribute.IncludeExceptionDetailInFaults;
            }

            ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener, controlEndpointBinding.Name, controlEndpointBinding)
            {
                MessageVersion = controlEndpointBinding.MessageVersion,
                Endpoints = { endpointDispatcher },
                ServiceThrottle = workflowServiceHost.ServiceThrottle
            };
            workflowServiceHost.ChannelDispatchers.Add(channelDispatcher);
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            WorkflowDefinitionContext workflowDefinitionContext = null;

            Stream workflowDefinitionStream = null;
            Stream ruleDefinitionStream = null;

            if (string.IsNullOrEmpty(constructorString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.WorkflowServiceHostFactoryConstructorStringNotProvided)));
            }

            if (!HostingEnvironment.IsHosted)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.ProcessNotExecutingUnderHostedContext)));
            }

            Type workflowType = this.GetTypeFromString(constructorString, baseAddresses);

            if (workflowType != null)
            {
                workflowDefinitionContext = new CompiledWorkflowDefinitionContext(workflowType);
            }
            else
            {
                try
                {
                    IDisposable impersonationContext = null;
                    try
                    {
                        try
                        {

                        }
                        finally
                        {
                            //Ensure thread.Abort doesnt interfere b/w impersonate & assignment.
                            impersonationContext = HostingEnvironment.Impersonate();
                        }

                        string xomlVirtualPath = Path.Combine(AspNetEnvironment.Current.CurrentVirtualPath, constructorString);

                        if (HostingEnvironment.VirtualPathProvider.FileExists(xomlVirtualPath))
                        {
                            workflowDefinitionStream = HostingEnvironment.VirtualPathProvider.GetFile(xomlVirtualPath).Open();
                            string ruleFilePath = Path.ChangeExtension(xomlVirtualPath, WorkflowServiceBuildProvider.ruleFileExtension);

                            if (HostingEnvironment.VirtualPathProvider.FileExists(ruleFilePath))
                            {
                                ruleDefinitionStream = HostingEnvironment.VirtualPathProvider.GetFile(ruleFilePath).Open();
                                workflowDefinitionContext = new StreamedWorkflowDefinitionContext(workflowDefinitionStream, ruleDefinitionStream, this.typeProvider);
                            }
                            else
                            {
                                workflowDefinitionContext = new StreamedWorkflowDefinitionContext(workflowDefinitionStream, null, this.typeProvider);
                            }
                        }
                    }
                    finally
                    {
                        if (impersonationContext != null)
                        {
                            impersonationContext.Dispose();
                        }
                    }
                }
                catch
                {
                    throw; //Prevent impersonation leak through Exception Filters.
                }
                finally
                {
                    if (workflowDefinitionStream != null)
                    {
                        workflowDefinitionStream.Close();
                    }

                    if (ruleDefinitionStream != null)
                    {
                        ruleDefinitionStream.Close();
                    }
                }
            }

            if (workflowDefinitionContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CannotResolveConstructorStringToWorkflowType, constructorString)));
            }

            WorkflowServiceHost serviceHost = new WorkflowServiceHost(workflowDefinitionContext, baseAddresses);

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WorkflowServiceHostCreated, SR.GetString(SR.TraceCodeWorkflowServiceHostCreated), this);
            }
            return serviceHost;
        }
Esempio n. 47
0
        /// <summary>
        /// Attaches a StateTracker to a WorkflowServiceHost
        /// </summary>
        /// <param name="workflowServiceHost">
        /// The host 
        /// </param>
        /// <param name="sqlWorkflowInstanceStore">
        /// The instance store 
        /// </param>
        /// <param name="maxHistory">
        /// The maximum history 
        /// </param>
        /// <returns>
        /// The Microsoft.Activities.Extensions.Tracking.StateTracker. 
        /// </returns>
        public static StateTracker Attach(
            WorkflowServiceHost workflowServiceHost, 
            SqlWorkflowInstanceStore sqlWorkflowInstanceStore, 
            int maxHistory = StateMachineInfo.DefaultMaxHistory)
        {
            Contract.Requires(workflowServiceHost != null);
            if (workflowServiceHost == null)
            {
                throw new ArgumentNullException("workflowServiceHost");
            }

            var stateTracker = new StateTracker(maxHistory);
            workflowServiceHost.WorkflowExtensions.Add(stateTracker);

            if (sqlWorkflowInstanceStore != null)
            {
                if (sqlWorkflowInstanceStore.IsReadOnly())
                {
                    throw new InvalidOperationException("Instance store is read only - cannot promote properties");
                }

                StateTrackerPersistence.Promote(sqlWorkflowInstanceStore);
                var persistence = new StateTrackerPersistence(stateTracker);
                workflowServiceHost.WorkflowExtensions.Add(persistence);
            }

            return stateTracker;
        }
 internal PersistenceProviderDirectory(WorkflowDefinitionProvider workflowDefinitionProvider, WorkflowServiceHost serviceHost, int maxInstances)
     : this(workflowDefinitionProvider, serviceHost, DurableConsistencyScope.Local, maxInstances)
 {
 }
 public InstanceThrottle(int maxCount, WorkflowServiceHost serviceHost)
 {
     this.throttle = new ThreadNeutralSemaphore(maxCount);
     this.maxCount = maxCount;
     this.warningRestoreLimit = (int)Math.Floor(0.7 * (double)maxCount);
     this.serviceHost = serviceHost;
 }
 // create a dummy instance to configure extensions and determine if a load-time transaction is required
 public static bool IsLoadTransactionRequired(WorkflowServiceHost host)
 {
     WorkflowServiceInstance instance = new WorkflowServiceInstance(host);
     instance.RegisterExtensionManager(host.WorkflowExtensions);
     return instance.GetExtensions<IPersistencePipelineModule>().Any(module => module.IsLoadTransactionRequired);
 }
 // dummy ctor only used to calculate IsLoadTransactionRequired
 WorkflowServiceInstance(WorkflowServiceHost serviceHost)
     : base(serviceHost.Activity)
 {
 }
        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();
        }
        void AddSupportedVersions(WorkflowServiceHost workflowServiceHost, WorkflowService baseService)
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            IList<Tuple<string, Stream>> streams = null;
            string xamlFileName = Path.GetFileNameWithoutExtension(VirtualPathUtility.GetFileName(this.xamlVirtualFile));
            GetSupportedVersionStreams(xamlFileName, out streams);
           
            if (streams != null)
            {
                try
                {
                    foreach (Tuple<string, Stream> stream in streams)
                    {
                        try
                        {
                            WorkflowService service = CreatetWorkflowServiceAndSetCompiledExpressionRoot(stream.Item1, stream.Item2, baseService.Name);
                            if (service != null)
                            {
                                workflowServiceHost.SupportedVersions.Add(service);
                            }
                        }
                        catch (Exception e)
                        {
                            Exception newException;
                            if (Fx.IsFatal(e) || !TryWrapSupportedVersionException(stream.Item1, e, out newException))
                            {
                                throw;
                            }

                            throw FxTrace.Exception.AsError(newException);
                        }
                    }
                }
                finally
                {
                    foreach (Tuple<string, Stream> stream in streams)
                    {
                        stream.Item2.Dispose();
                    }
                }
            }
        }
        public void WorkflowServiceHostReturnsExtensionsCollection()
        {
            var traceTrackingParticipant = new TraceTrackingParticipant();
            var listTrackingParticipant = new ListTrackingParticipant();

            var service = new WorkflowService() { Body = new Sequence() };
            var host = new WorkflowServiceHost(service);

            // Add a couple of singleton extensions
            host.WorkflowExtensions.Add(traceTrackingParticipant);
            host.WorkflowExtensions.Add(listTrackingParticipant);

            // Now I can get the Singleton Extensions as a collection
            var extensions = host.WorkflowExtensions.GetSingletonExtensions();
            Assert.IsNotNull(extensions);
            Assert.AreEqual(2, extensions.Count);

            Assert.IsTrue(extensions.Contains(traceTrackingParticipant));
            Assert.IsTrue(extensions.Contains(listTrackingParticipant));
        }
Esempio n. 55
0
	    protected virtual void ConfigureServiceHost(WorkflowServiceHost serviceHost)
	    {
	    }
Esempio n. 56
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting up...");
            CreateService();
            Uri address = new Uri(Common.Constants.ServiceBaseAddress);
            WorkflowServiceHost host = new WorkflowServiceHost(service, address);

            // A host level channel cache is not necessary for this example as our server workflow
            // does not have a Send activity. However, the following can be used to add a host level
            // channel cache that the Send activities in the service workflow could use.

            //Func<object> hostLevelChannelCacheProvider = () =>
            //    {
            //        return new SendMessageChannelCache
            //        {
            //            FactorySettings = new ChannelCacheSettings
            //            {
            //                MaxItemsInCache = 10,
            //                IdleTimeout = TimeSpan.FromSeconds(10),
            //                LeaseTimeout = TimeSpan.FromSeconds(5)
            //            },
            //            ChannelSettings = new ChannelCacheSettings
            //            {
            //                MaxItemsInCache = 10,
            //                IdleTimeout = TimeSpan.FromSeconds(10),
            //                LeaseTimeout = TimeSpan.FromSeconds(5)
            //            }
            //        };
            //    };

            //host.WorkflowExtensions.Add(hostLevelChannelCacheProvider);

            try
            {

                Console.WriteLine("Opening service...");
                host.Open();

                Console.WriteLine("Service is listening on {0}...", address);
                Console.WriteLine("To terminate press ENTER");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Service terminated with exception {0}", ex.ToString());
            }
            finally
            {
                host.Close();
            }
        }
        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;
        }
 protected virtual WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses)
 {
     WorkflowServiceHost workflowServiceHost = new WorkflowServiceHost(service, baseAddresses);
     if (service.DefinitionIdentity != null)
     {
         AddSupportedVersions(workflowServiceHost, service);
     }
     return workflowServiceHost;
 }
Esempio n. 59
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting up...");
            CreateService();
            Uri address = new Uri(Constants.ServiceBaseAddress);
            WorkflowServiceHost host = new WorkflowServiceHost(service, address);

            try
            {
                Console.WriteLine("Opening service...");
                host.Open();

                Console.WriteLine("Service is listening on {0}...", address);
                Console.WriteLine("To terminate press ENTER");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Service terminated with exception {0}", ex.ToString());
            }
            finally
            {
                host.Close();
            }
        }