Example #1
0
        static void Main(string[] args)
        {
            Activity element = new ApprovalRouteAndExecute();

            WorkflowService shservice = new WorkflowService
            {
                Name = "ApprovalManager",
                ConfigurationName = "Microsoft.Samples.DocumentApprovalProcess.ApprovalManager.ApprovalManager",
                Body = element
            };

            // Cleanup old table of users from previous run
            UserManager.DeleteAllUsers();

            ServiceHost sh = new ServiceHost(typeof(Microsoft.Samples.DocumentApprovalProcess.ApprovalManager.SubscriptionManager), new Uri("http://localhost:8732/Design_Time_Addresses/service/SubscriptionManager/"));
            sh.Open();

            System.ServiceModel.Activities.WorkflowServiceHost wsh = new System.ServiceModel.Activities.WorkflowServiceHost(shservice, new Uri("http://localhost:8732/Design_TimeAddress/service/ApprovalManager"));

            // Setup persistence
            wsh.Description.Behaviors.Add(new SqlWorkflowInstanceStoreBehavior(ApprovalProcessDBConnectionString));
            WorkflowIdleBehavior wib = new WorkflowIdleBehavior();
            wib.TimeToUnload = new TimeSpan(0, 0, 2);
            wsh.Description.Behaviors.Add(wib);

            wsh.Open();

            Console.WriteLine("All services ready, press any key to close the services and exit.");

            Console.ReadLine();
            wsh.Close();
            sh.Close();
        }
Example #2
0
        private static void CreateService()
        {
            Variable<Expense> expense = new Variable<Expense> { Name = "expense" };
            Variable<VendorRequest> vendor = new Variable<VendorRequest> { Name = "vendor" };
            Variable<PurchaseOrder> po = new Variable<PurchaseOrder> { Name = "po" };
            Variable<bool> reply = new Variable<bool> { Name = "reply" };
            Variable<bool> replyPO = new Variable<bool> { Name = "reply" };
            Variable<VendorResponse> replyVendor = new Variable<VendorResponse> { Name = "reply" };

            Parallel workflow = new Parallel
            {
                Branches =
                {
                    GetApproveExpense(expense, reply),
                    GetApprovePO(po, replyPO),
                    GetApprovedVendor(vendor, replyVendor),
                }
            };
            service = new WorkflowService
            {
                Name = "FinanceService",
                Body = workflow,

                Endpoints =
                    {
                        new Endpoint
                        {
                            ServiceContractName="FinanceService",
                            AddressUri = new Uri(Constants.EchoServiceAddress),
                            Binding = new BasicHttpBinding(),
                        }
                    }
            };
        }
	    protected override WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses)
        {
            var container = new UnityContainer();
            ConfigureContainer(container);

            var host = base.CreateWorkflowServiceHost(service, baseAddresses);

            var injectionType = ConfigureInjectionType();

            if (injectionType == InjectionTypes.Push)
            {
                container.AddNewExtension<WorkflowExtension>();

                var rootActivity = host.Activity;
                container.BuildUp(rootActivity.GetType(), rootActivity);
            }
            else
            {
                var diExtension = new DependencyInjectionExtension(container);
                host.WorkflowExtensions.Add(diExtension);
            }

		    ConfigureServiceHost(host);
            return host;
        }
Example #4
0
        private static void CreateService()
        {
            Variable<string> message = new Variable<string> { Name = "message" };
            Variable<string> echo = new Variable<string> { Name = "echo" };

            Receive receiveString = new Receive
            {
                OperationName = "Echo",
                ServiceContractName = "Echo",
                CanCreateInstance = true,
                //parameters for receive
                Content = new ReceiveParametersContent
                {
                    Parameters =
                    {
                        {"message", new OutArgument<string>(message)}
                    }
                }
            };
            Sequence workflow = new Sequence()
            {
                Variables = { message, echo },
                Activities =
                    {
                        receiveString,
                        new WriteLine
                        {
                            Text = new InArgument<string>(env =>("Message received: " + message.Get(env)))
                        },
                        new Assign<string>
                        {
                            Value = new InArgument<string>(env =>("<echo> " + message.Get(env))),
                            To = new OutArgument<string>(echo)
                        },
                        //parameters for reply
                        new SendReply
                        {
                            Request = receiveString,
                            Content = new SendParametersContent
                            {
                                Parameters =
                                {
                                    { "echo", new InArgument<string>(echo) }
                                },
                            }
                        },
                        new WriteLine
                        {
                            Text = new InArgument<string>(env =>("Message sent: " + echo.Get(env)))
                        },
                    },
            };

            service = new WorkflowService
            {
                Name = "Echo",
                Body = workflow
            };
        }
Example #5
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;
        }
        static void Main(string[] args)
        {
            // Open the config file and get the name for this branch
            // and its network address
            Configuration config = ConfigurationManager
            .OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection app =
            (AppSettingsSection)config.GetSection("appSettings");
            string adr = app.Settings["Address"].Value;
            Console.WriteLine(app.Settings["Branch Name"].Value);
            // Create a service to handle incoming requests
            WorkflowService service = new WorkflowService
            {
                Name = "LibraryReservation",
                Body = new ProcessRequest(),
                Endpoints =
                        {
                                new Endpoint
                                {
                                ServiceContractName="ILibraryReservation",
                                AddressUri = new Uri("http://localhost:" + adr +"/LibraryReservation"),
                                Binding = new BasicHttpBinding(),
                                }
                        }
            };

            // Create a WorkflowServiceHost that listens for incoming messages
            System.ServiceModel.Activities.WorkflowServiceHost wsh = new System.ServiceModel.Activities.WorkflowServiceHost(service);
            wsh.Open();


            Console.WriteLine("Waiting for requests, press ENTER to send a request.");
            Console.ReadLine();
            // Create dictionary with input arguments for the workflow
            IDictionary<string, object> input = new Dictionary<string, object>
                                            {
                                                { "Title" , "Gone with the Wind" },
                                                { "Author", "Margaret Mitchell" },
                                                { "ISBN", "9781416548898" }
                                            };
            // Invoke the SendRequest workflow
            IDictionary<string, object> output = WorkflowInvoker.Invoke(new SendRequest(), input);
            ReservationResponse resp = (ReservationResponse)output["Response"];
            // Display the response
            Console.WriteLine("Response received from the {0} branch",resp.Provider.BranchName);
            Console.WriteLine();
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
            // Close the WorkflowSe



        }
Example #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Setting up queue");

            try
            {
                // Setup the queue
                CreateMessageQueue();
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("MSMQ is not installed or is not configured properly to run the sample. See readme for more info.");

                return;
            }

            Console.WriteLine("\nStarting client to queue messages");

            // Run the client to enqueue some messages for the service to process later
            WorkflowInvoker.Invoke(Client.Create());

            Console.WriteLine("Client finished");

            // Create the service and host it to start processing messages
            WorkflowService service = new WorkflowService
            {
                Name = "RewardsPointsWorkflowService",
                Body = Service.Create()
            };

            using (WorkflowServiceHost host = new WorkflowServiceHost(service))
            {
                // Specify the Contract, Binding and Address to service
                host.AddServiceEndpoint(Shared.Contract, Shared.Binding, Shared.Address);

                Console.WriteLine("\nStarting service to process messages");

                // Start service and begin processing messages
                host.Open();

                Console.WriteLine("Hit enter to quit...");

                Console.ReadLine();
            }

            // Cleanup queue
            DeleteMessageQueue();
        }
Example #8
0
        static WorkflowService GetService()
        {
            Variable<string> incomingMessage = new Variable<string> { Name = "inmessage" };
            Variable<int> outgoingMessage = new Variable<int> { Name = "outmessage" };
            Receive receiveSecureData = new Receive
            {
                OperationName = "AskQuestion",
                ServiceContractName = "ISecuredService",
                CanCreateInstance = true,
                Content = ReceiveContent.Create(new OutArgument<string>(incomingMessage))
            };
            Sequence SecuredWorkFlow = new Sequence()
            {
                Variables = { incomingMessage, outgoingMessage },
                Activities =
                {
                    receiveSecureData,
                    new WriteLine
                    {
                        Text = new InArgument<string>(env =>("Message received: " + incomingMessage.Get(env)))
                    },
                    new SendReply
                    {
                        Request = receiveSecureData,
                        Content = SendContent.Create(new InArgument<int>(4))
                    }
                }
            };

            WorkflowService service = new WorkflowService
            {
                Name = "SecuredService",
                Body = SecuredWorkFlow,
                ConfigurationName = "SecuredService"
            };
            return service;
        }
Example #9
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();
            }
        }
Example #10
0
        WorkflowServiceHost wsh; // Host for workflow -- receives responses to requests made by this client

        #endregion Fields

        #region Constructors

        public Main()
        {
            InitializeComponent();

            statusWriter = new WindowTextWriter(statusConsole);
            WriterParticipant.Writer = statusWriter;

            addrListenForApprovalResponses = "http://localhost:" + Convert.ToString(GenerateRandomPort()) + "/ClientService";
            addrListenForApprovalRequests = "http://localhost:" + Convert.ToString(GenerateRandomPort()) + "/ApprovalService";

            // Set static variable in another class so WCF service can find the user interface instance
            ExternalToMainComm.Context = this;

            // Service Host for approving requests from other clients
            sh = new ServiceHost(typeof(Microsoft.Samples.DocumentApprovalProcess.ApprovalClient.ApprovalRequestsService), new Uri(addrListenForApprovalRequests));

            // Create the workflow and service to be hosted by the Workflow ServiceHost
            Activity element = new ClientRequestApprovalWorkflow();
            WorkflowService wshservice = new WorkflowService
            {
                Name = "ApprovalMonitor",
                ConfigurationName = "Microsoft.Samples.DocumentApprovalProcess.ApprovalClient.ApprovalMonitor",
                Body = element
            };

            wsh = new WorkflowServiceHost(wshservice, new Uri(addrListenForApprovalResponses));

            subscriptionDC = new DiscoveryClient(new UdpDiscoveryEndpoint());
            approvalDC = new DiscoveryClient(new UdpDiscoveryEndpoint());

            sh.Open();
            wsh.Open();

            statusWriter.WriteLine(addrListenForApprovalResponses);
            statusWriter.WriteLine(addrListenForApprovalRequests);
        }
Example #11
0
        static WorkflowService GetService()
        {
            Variable<Customer> customer = new Variable<Customer>();
            Variable<Order> order = new Variable<Order>();
            Variable<string> drug = new Variable<string>();
            Variable<double> adjustedCost = new Variable<double>();
            Variable<int> percentagePaidByInsurance = new Variable<int>();
            Variable<CorrelationHandle> customerHandle = new Variable<CorrelationHandle>();
            Variable<CorrelationHandle> orderHandle = new Variable<CorrelationHandle>();

            XPathMessageContext pathContext = new XPathMessageContext();
            pathContext.AddNamespace("psns", Constants.PharmacyServiceNamespace);

            MessageQuerySet GetOrderQuerySet = new MessageQuerySet
            {
                {
                    "OrderID",
                    new XPathMessageQuery("//psns:Order/psns:OrderID",pathContext)
                }
            };

            MessageQuerySet GetOrderIDQuerySet = new MessageQuerySet
            {
                {
                    "OrderID",
                    new XPathMessageQuery("//ser:guid",pathContext)
                }
            };

            MessageQuerySet customerQuerySet = new MessageQuerySet
            {
                {
                    "CustomerID",
                    new XPathMessageQuery("//psns:GetBaseCost/psns:Customer/psns:CustomerID",pathContext)
                }
            };

            MessageQuerySet customerIDQuerySet = new MessageQuerySet
            {
                {
                    "CustomerID",
                    new XPathMessageQuery("//ser:guid",pathContext)
                }
            };

            // This will use implicit correlation within the workflow using the WorkflowServiceHost's default CorrelationHandle
            Receive prescriptionRequest = new Receive
            {
                DisplayName = "Request Perscription",
                OperationName = "GetBaseCost",
                ServiceContractName = Constants.PharmacyServiceContractName,
                CanCreateInstance = true,
                //CorrelatesWith = customerHandle,  -- add this line for explicit correlation
                CorrelatesOn = customerQuerySet,
                Content = new ReceiveParametersContent
                {
                    Parameters =
                    {
                        {"Customer",new OutArgument<Customer>(customer)},
                        {"Drug",new OutArgument<string>(drug)},
                    }
                }
            };

            // This will use implicit correlation within the workflow using the WorkflowServiceHost's default CorrelationHandle
            Receive GetInsurancePaymentPercentageRequest = new Receive
            {
                DisplayName = "Get Insurance Coverage",
                ServiceContractName = Constants.PharmacyServiceContractName,
                OperationName = "GetInsurancePaymentPercentage",
                CanCreateInstance = true,
                //CorrelatesWith = customerHandle,  -- add this line for explicit correlation
                CorrelatesOn = customerIDQuerySet,
                Content = ReceiveContent.Create(new OutArgument<Guid>())
            };

            // This will explicitly correlate with the SendReply action after the prescriptionRequest using the OrderID (stored in the orderHandle)
            Receive GetAdjustedCostRequest = new Receive
            {
                DisplayName = "Get Adjusted Cost",
                OperationName = "GetAdjustedCost",
                ServiceContractName = Constants.PharmacyServiceContractName,
                CanCreateInstance = true,
                CorrelatesOn = GetOrderIDQuerySet,
                CorrelatesWith = orderHandle,
                Content = ReceiveContent.Create(new OutArgument<Guid>())
            };

            Activity PrescriptonWorkflow = new Sequence()
            {
                Variables = { customer, order, drug, percentagePaidByInsurance, adjustedCost, customerHandle, orderHandle },
                Activities =
                {
                    new WriteLine
                    {
                        Text = "Beginning Workflow"
                    },

                    new Parallel
                    {
                        Branches =
                        {
                            new Sequence
                            {
                                Activities =
                                {
                                    GetInsurancePaymentPercentageRequest,
                                    new Assign<int>
                                    {
                                        To = new OutArgument<int>( (e) => percentagePaidByInsurance.Get(e) ),
                                        Value = new InArgument<int>( (e) => new Random().Next(0,100))
                                    },
                                    new SendReply
                                    {
                                        DisplayName = "Return Percentage",
                                        Request = GetInsurancePaymentPercentageRequest,
                                        Content = SendContent.Create(new InArgument<int>((e) => percentagePaidByInsurance.Get(e)))
                                    }

                                }
                            },

                            new Sequence
                            {
                                Activities =
                                {
                                    prescriptionRequest,
                                    new WriteLine
                                    {
                                        Text = new InArgument<string>(env => (string.Format("{0}, {1}\t{2}", customer.Get(env).LastName ,customer.Get(env).FirstName,customer.Get(env).CustomerID.ToString())))
                                    },
                                    new Assign<Order>
                                    {
                                        To = new OutArgument<Order>(order),
                                        Value = new InArgument<Order>( (e) => new Order() { CustomerID = customer.Get(e).CustomerID, Drug = drug.Get(e), OrderID = Guid.NewGuid() } )
                                    },
                                    new WriteLine
                                    {
                                        Text = new InArgument<string>(env => (string.Format("OrderID: {0}", order.Get(env).OrderID.ToString())))
                                    },
                                    new Assign<int>
                                    {
                                        To = new OutArgument<int>( (e) => order.Get(e).Cost ),
                                        Value = new InArgument<int>( (e) => new Random().Next(20,50))
                                    },
                                    new SendReply
                                    {
                                        DisplayName = "Send Adjusted Cost",
                                        Request = prescriptionRequest,
                                        // Initialize the orderHandle using the MessageQuerySet to correlate with the final GetAdjustedCost request
                                        CorrelationInitializers =
                                        {
                                            new QueryCorrelationInitializer
                                            {
                                                CorrelationHandle = orderHandle,
                                                MessageQuerySet = GetOrderQuerySet
                                            }
                                        },
                                        Content = SendContent.Create(new InArgument<Order>((e) => order.Get(e)))
                                    }
                                }
                            }
                        }
                    },

                    new Assign<double>
                    {
                        To = new OutArgument<double>( (e) => adjustedCost.Get(e) ),
                        Value = new InArgument<double>( (e) => order.Get(e).Cost *  (100-percentagePaidByInsurance.Get(e)) *.01)
                    },
                    new WriteLine
                    {
                        Text = new InArgument<string>(env => (string.Format("Base Cost: ${0}", order.Get(env).Cost.ToString())))
                    },
                    new WriteLine
                    {
                        Text = new InArgument<string>(env => (string.Format("Insurance Coverage: {0}%", percentagePaidByInsurance.Get(env).ToString())))
                    },
                    new WriteLine
                    {
                        Text = new InArgument<string>(env => (string.Format("Adjusted Cost: ${0}", decimal.Round(Convert.ToDecimal(adjustedCost.Get(env)),2))))
                    },
                    GetAdjustedCostRequest,
                    new SendReply
                    {
                        Request = GetAdjustedCostRequest,
                        Content = SendContent.Create(new InArgument<double>((e) => adjustedCost.Get(e)))
                    },
                    new WriteLine
                    {
                        Text = "Workflow Completed"
                    }

                }
            };

            WorkflowService service = new WorkflowService
            {
                Name = "PharmacyService",
                Body = PrescriptonWorkflow,
                ConfigurationName = "PharmacyService"
            };

            return service;
        }
 /// <summary>
 /// Opens the host
 /// </summary>
 /// <param name="workflowService">
 /// The workflow service. 
 /// </param>
 /// <param name="serviceUri">
 /// The service URI. 
 /// </param>
 /// <param name="behaviors">
 /// The behaviors. 
 /// </param>
 /// <returns>
 /// The workflow service host 
 /// </returns>
 public static WorkflowServiceTestHost Open(
     WorkflowService workflowService, Uri serviceUri, params IServiceBehavior[] behaviors)
 {
     return Open(workflowService, serviceUri, null, behaviors);
 }
        /// <summary>
        /// Opens the host
        /// </summary>
        /// <param name="workflowService">
        /// The workflow service. 
        /// </param>
        /// <param name="serviceUri">
        /// The service URI. 
        /// </param>
        /// <param name="instanceStore">
        /// The instance Store. 
        /// </param>
        /// <param name="behaviors">
        /// The behaviors. 
        /// </param>
        /// <returns>
        /// The workflow service host 
        /// </returns>
        public static WorkflowServiceTestHost Open(
            WorkflowService workflowService, 
            Uri serviceUri, 
            InstanceStore instanceStore, 
            params IServiceBehavior[] behaviors)
        {
            Contract.Requires(workflowService != null);
            Contract.Requires(serviceUri != null);

            if (workflowService == null)
            {
                throw new ArgumentNullException("workflowService");
            }

            if (serviceUri == null)
            {
                throw new ArgumentNullException("serviceUri");
            }

            var workflowServiceTestHost = new WorkflowServiceTestHost(workflowService, serviceUri);

            if (instanceStore != null)
            {
                workflowServiceTestHost.InstanceStore = instanceStore;
            }

            if (behaviors != null)
            {
                Debug.Assert(workflowServiceTestHost.Host != null, "workflowServiceTestHost.Host != null");
                Debug.Assert(
                    workflowServiceTestHost.Host.Description != null, "workflowServiceTestHost.Host.Description != null");
                Debug.Assert(
                    workflowServiceTestHost.Host.Description.Behaviors != null,
                    "workflowServiceTestHost.Host.Description.Behaviors != null");
                foreach (var serviceBehavior in behaviors)
                {
                    workflowServiceTestHost.Host.Description.Behaviors.Add(serviceBehavior);
                }
            }

            workflowServiceTestHost.Open();
            return workflowServiceTestHost;
        }
        /// <summary>
        /// Opens the host
        /// </summary>
        /// <param name="workflowService">
        /// The workflow service. 
        /// </param>
        /// <param name="serviceEndpoint">
        /// The service endpoint. 
        /// </param>
        /// <param name="instanceStore">
        /// The instance Store. 
        /// </param>
        /// <param name="behaviors">
        /// The behaviors. 
        /// </param>
        /// <returns>
        /// The workflow service host 
        /// </returns>
        public static WorkflowServiceTestHost Open(
            WorkflowService workflowService, 
            EndpointAddress serviceEndpoint, 
            InstanceStore instanceStore, 
            params IServiceBehavior[] behaviors)
        {
            Contract.Requires(workflowService != null);
            if (workflowService == null)
            {
                throw new ArgumentNullException("workflowService");
            }

            Contract.Requires(serviceEndpoint != null);
            if (serviceEndpoint == null)
            {
                throw new ArgumentNullException("serviceEndpoint");
            }

            return Open(workflowService, serviceEndpoint.Uri, instanceStore, behaviors);
        }
 protected override WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses) {
     WorkflowServiceHost workflowServiceHost = base.CreateWorkflowServiceHost(service, baseAddresses);
     AddBehaviorsAndEndpoints(workflowServiceHost);
     return workflowServiceHost;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowServiceTestHost"/> class.
        /// </summary>
        /// <param name="workflowService">
        /// The workflow service. 
        /// </param>
        /// <param name="serviceUri">
        /// The service URI. 
        /// </param>
        public WorkflowServiceTestHost(WorkflowService workflowService, Uri serviceUri)
        {
            Contract.Requires(workflowService != null);
            Contract.Requires(serviceUri != null);

            if (workflowService == null)
            {
                throw new ArgumentNullException("workflowService");
            }

            if (serviceUri == null)
            {
                throw new ArgumentNullException("serviceUri");
            }

            this.WorkflowService = workflowService;
            this.ServiceUri = serviceUri;

            // Fix for Issue 7835
            // Create the host in the ctor
            this.CreateWorkflowServiceHost();
        }
        /// <summary>
        /// Creates and Opens a WorkflowServiceTestHost
        /// </summary>
        /// <param name="workflowService">
        /// The workflow service. 
        /// </param>
        /// <param name="serviceEndpoint">
        /// The service endpoint. 
        /// </param>
        /// <returns>
        /// The WorkflowServiceTestHost 
        /// </returns>
        public static WorkflowServiceTestHost Open(WorkflowService workflowService, EndpointAddress serviceEndpoint)
        {
            Contract.Requires(workflowService != null);
            if (workflowService == null)
            {
                throw new ArgumentNullException("workflowService");
            }

            Contract.Requires(serviceEndpoint != null);
            if (serviceEndpoint == null)
            {
                throw new ArgumentNullException("serviceEndpoint");
            }

            return Open(workflowService, serviceEndpoint.Uri);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WorkflowServiceTestHost"/> class.
 /// </summary>
 /// <param name="workflowService">
 /// The workflow service. 
 /// </param>
 /// <param name="serviceEndpoint">
 /// The service endpoint. 
 /// </param>
 public WorkflowServiceTestHost(WorkflowService workflowService, EndpointAddress serviceEndpoint)
     : this(workflowService, serviceEndpoint != null ? serviceEndpoint.Uri : null)
 {
 }
        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));
        }
 protected virtual WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses)
 {
     return new WorkflowServiceHost(service, baseAddresses);
 }
 public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
 {
     WorkflowServiceHost host = null;
     Stream stream;
     string str2;
     if (string.IsNullOrEmpty(constructorString))
     {
         throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.WorkflowServiceHostFactoryConstructorStringNotProvided));
     }
     if (baseAddresses == null)
     {
         throw System.ServiceModel.Activation.FxTrace.Exception.ArgumentNull("baseAddresses");
     }
     if (baseAddresses.Length == 0)
     {
         throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.BaseAddressesNotProvided));
     }
     if (!HostingEnvironment.IsHosted)
     {
         throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.Hosting_ProcessNotExecutingUnderHostedContext("WorkflowServiceHostFactory.CreateServiceHost")));
     }
     string virtualPath = VirtualPathUtility.Combine(AspNetEnvironment.Current.XamlFileBaseLocation, constructorString);
     if (this.GetServiceFileStreamOrCompiledCustomString(virtualPath, baseAddresses, out stream, out str2))
     {
         object obj2;
         using (stream)
         {
             BuildManager.GetReferencedAssemblies();
             XamlXmlReaderSettings settings = new XamlXmlReaderSettings {
                 ProvideLineInfo = true
             };
             XamlReader xamlReader = ActivityXamlServices.CreateReader(new XamlXmlReader(XmlReader.Create(stream), settings));
             if (System.ServiceModel.Activation.TD.XamlServicesLoadStartIsEnabled())
             {
                 System.ServiceModel.Activation.TD.XamlServicesLoadStart();
             }
             obj2 = XamlServices.Load(xamlReader);
             if (System.ServiceModel.Activation.TD.XamlServicesLoadStopIsEnabled())
             {
                 System.ServiceModel.Activation.TD.XamlServicesLoadStop();
             }
         }
         WorkflowService service = null;
         if (obj2 is Activity)
         {
             service = new WorkflowService {
                 Body = (Activity) obj2
             };
         }
         else if (obj2 is WorkflowService)
         {
             service = (WorkflowService) obj2;
         }
         if (service != null)
         {
             if (service.Name == null)
             {
                 string fileName = VirtualPathUtility.GetFileName(virtualPath);
                 string namespaceName = string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) });
                 service.Name = XName.Get(XmlConvert.EncodeLocalName(fileName), namespaceName);
                 if ((service.ConfigurationName == null) && (service.Body != null))
                 {
                     service.ConfigurationName = XmlConvert.EncodeLocalName(service.Body.DisplayName);
                 }
             }
             host = this.CreateWorkflowServiceHost(service, baseAddresses);
         }
     }
     else
     {
         Type typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
         if (null == typeFromAssembliesInCurrentDomain)
         {
             typeFromAssembliesInCurrentDomain = this.GetTypeFromCompileCustomString(str2, constructorString);
         }
         if (null == typeFromAssembliesInCurrentDomain)
         {
             BuildManager.GetReferencedAssemblies();
             typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString);
         }
         if (null != typeFromAssembliesInCurrentDomain)
         {
             if (!TypeHelper.AreTypesCompatible(typeFromAssembliesInCurrentDomain, typeof(Activity)))
             {
                 throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.TypeNotActivity(typeFromAssembliesInCurrentDomain.FullName)));
             }
             Activity activity = (Activity) Activator.CreateInstance(typeFromAssembliesInCurrentDomain);
             host = this.CreateWorkflowServiceHost(activity, baseAddresses);
         }
     }
     if (host == null)
     {
         throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.CannotResolveConstructorStringToWorkflowType(constructorString)));
     }
     ((IDurableInstancingOptions) host.DurableInstancingOptions).SetScopeName(XName.Get(XmlConvert.EncodeLocalName(VirtualPathUtility.GetFileName(ServiceHostingEnvironment.FullVirtualPath)), string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) })));
     return host;
 }
 public ValidationRoot(WorkflowService workflowService)
 {
     Fx.Assert(workflowService != null, "workflowService != null");
     this.workflowService = workflowService;
 }
        private void SetupHost()
        {
            WorkflowService service = new WorkflowService
            {
                Name = "LeadResponse",
                Body = new WorkAssignment(),
                Endpoints =
                {
                    new Endpoint
                    {
                        ServiceContractName="CreateAssignment",
                        AddressUri = new Uri("http://localhost/CreateAssignment"),
                        Binding = new BasicHttpBinding(),
                    }
                }
            };

            // Create a WorkflowServiceHost that listens for incoming messages
            _wsh = new System.ServiceModel.Activities.WorkflowServiceHost(service);

            SqlWorkflowInstanceStoreBehavior instanceStoreBehavior
                = new SqlWorkflowInstanceStoreBehavior(_connectionString);
            instanceStoreBehavior.InstanceCompletionAction
                = InstanceCompletionAction.DeleteAll;
            instanceStoreBehavior.InstanceLockedExceptionAction
                = InstanceLockedExceptionAction.AggressiveRetry;
            _wsh.Description.Behaviors.Add(instanceStoreBehavior);

            WorkflowIdleBehavior wib = new WorkflowIdleBehavior();
            wib.TimeToUnload = TimeSpan.FromMilliseconds(100);
            _wsh.Description.Behaviors.Add(wib);

            _wsh.Description.Behaviors.Add
                (new DBExtensionBehavior(_connectionString));
            _wsh.Description.Behaviors.Add
                (new PersistAssignmentBehavior(_connectionString));

            // Open the service so it will listen for messages
            _wsh.Open();
        }
Example #24
0
        /// <summary>
        /// Gets a workflow service after injection
        /// </summary>
        /// <returns>
        /// The workflow service with test doubles
        /// </returns>
        public WorkflowService GetWorkflowService()
        {
            if (this.injectedService != null)
            {
                return this.injectedService;
            }

            this.GenerateUniqueTestFilename("xamlx");
            this.InjectXaml();
            return this.injectedService = (WorkflowService)XamlServices.Load(this.testXamlFile);
        }