码迷,mamicode.com
首页 > 其他好文 > 详细

文档审批工作流

时间:2016-05-16 08:13:12      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:

技术分享技术分享技术分享技术分享技术分享技术分享技术分享技术分享技术分享

//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System;
using System.Activities;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Activities;
using System.ServiceModel.Activities.Description;

using Microsoft.Samples.DocumentApprovalProcess.ApprovalManagerActivityLibrary;

namespace Microsoft.Samples.DocumentApprovalProcess.ApprovalManager
{
    class Program
    {
        static string ApprovalProcessDBConnectionString = ConfigurationManager.ConnectionStrings["ApprovalProcessDB"].ConnectionString;

        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();
        }
    }


}

  

//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System.ServiceModel;

using Microsoft.Samples.DocumentApprovalProcess.ApprovalMessageContractLibrary;

namespace Microsoft.Samples.DocumentApprovalProcess.ApprovalManager
{
    // This service is how clients opt-in/out of the approval system
    [ServiceContract]
    interface ISubscriptionService
    {
        [OperationContract]
        User Subscribe(User newuser);
        [OperationContract]
        void Unsubscribe(User id);
    }

    class SubscriptionManager : ISubscriptionService
    {

        public User Subscribe(User newuser)
        {
            return UserManager.AddUser(newuser.Name, newuser.Type, newuser.AddressRequest, newuser.AddressResponse);
        }

        public void Unsubscribe(User id)
        {
            UserManager.RemoveUser(id);
        }
    }
}

  

//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Samples.DocumentApprovalProcess.ApprovalMessageContractLibrary;

namespace Microsoft.Samples.DocumentApprovalProcess.ApprovalManager
{
    // This contains all the SQL code to manage users participating in the approval system
    public static class UserManager
    {
        static String dbconnStr = ConfigurationManager.ConnectionStrings["ApprovalProcessDB"].ConnectionString;

        public static User AddUser(String uname, String utype, String endaddressrequest, String endaddressresponse)
        {
            User newUser = new User(uname, utype, endaddressrequest, endaddressresponse);
            using (SqlConnection sCon = new SqlConnection(dbconnStr))
            {
                SqlCommand sCom = new SqlCommand();
                sCom.Connection = sCon;
                sCom.CommandText = "insert into users (username,usertype,addressrequest,addressresponse,guid) values(‘" + uname + "‘, ‘" + utype + "‘, ‘" + endaddressrequest + "‘, ‘" + endaddressresponse + "‘, ‘" + newUser.Id + "‘)";
                sCon.Open();
                sCom.ExecuteNonQuery();
                sCon.Dispose();
            }
            return newUser;
        }

        public static void RemoveUser(User id)
        {
            using (SqlConnection sCon = new SqlConnection(dbconnStr))
            {
                using (SqlCommand sCom = new SqlCommand())
                {
                    sCom.Connection = sCon;
                    sCom.CommandText = "DELETE FROM users WHERE guid=‘" + id.Id + "‘";
                    sCon.Open();
                    sCom.ExecuteNonQuery();
                    sCon.Dispose();
                }
            }            
        }

        public static List<User> GetUsersByType(String utype)
        {
            String query = "SELECT * FROM users WHERE usertype=‘" + utype + "‘";
            List<User> filteredUsers = new List<User>();
            DataSet ds = new DataSet();

            using (SqlConnection sCon = new SqlConnection(dbconnStr))
            {
                using (SqlDataAdapter sAda = new SqlDataAdapter(query, sCon)){
                    sAda.Fill(ds);
                    if (ds.Tables["Table"] != null)
                    {
                        foreach (DataRow dr in ds.Tables["Table"].Rows)
                        {
                            filteredUsers.Add(new User((String)dr["username"], (String)dr["usertype"], (String)dr["address"], (String)dr["guid"]));
                        }
                    }
                }
                sCon.Dispose();
            }
            return filteredUsers;
        }

        public static void DeleteAllUsers()
        {
            using (SqlConnection sCon = new SqlConnection(dbconnStr))
            {
                using (SqlCommand sCom = new SqlCommand())
                {
                    sCom.Connection = sCon;
                    sCom.CommandText = "DELETE FROM users";
                    sCon.Open();
                    sCom.ExecuteNonQuery();
                    sCon.Dispose();
                }
            }
        }
    }
}

  

//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System.ServiceModel;

using Microsoft.Samples.DocumentApprovalProcess.ApprovalMessageContractLibrary;

namespace Microsoft.Samples.DocumentApprovalProcess.ApprovalClient
{
    [ServiceContract]
    interface IClientApproval
    {
        // Called by ApprovalManager seeking approval of a document
        [OperationContract(IsOneWay=true)]
        void RequestClientResponse(ApprovalRequest docApprovalRequest);

        // Called by ApprovalManager informing client that a approval request has been canceled
        [OperationContract(IsOneWay = true)]
        void CancelRequestClientResponse(ApprovalRequest docApprovalRequest);
    }

    class ApprovalRequestsService : IClientApproval
    {
        public void RequestClientResponse(ApprovalRequest docApprovalRequest)
        {
            ExternalToMainComm.NewApprovalRequest(docApprovalRequest);
        }

        public void CancelRequestClientResponse(ApprovalRequest docApprovalRequest)
        {
            ExternalToMainComm.CancelApprovalRequest(docApprovalRequest);
        }
    }
}
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System;
using System.Activities;
using System.Activities.Statements;
using System.ServiceModel;
using System.ServiceModel.Activities;
using System.ServiceModel.Dispatcher;
using Microsoft.Samples.DocumentApprovalProcess.ApprovalMessageContractLibrary;

namespace Microsoft.Samples.DocumentApprovalProcess.ApprovalClient
{
    public sealed class ClientRequestApprovalWorkflow : Activity
    {
        public ClientRequestApprovalWorkflow()
        {
            Variable<CorrelationHandle> corr = new Variable<CorrelationHandle>();
            Variable<ApprovalResponse> response = new Variable<ApprovalResponse>();
            Variable<ApprovalRequest> cancelRequest = new Variable<ApprovalRequest> { Name = "CancelRequest" };
            Variable<StartApprovalParams> startParams = new Variable<StartApprovalParams>();
            Variable<CorrelationHandle> requestReplyHandle = new Variable<CorrelationHandle> { Name = "RequestReplyHandle" };

            // For correlating between approval requests and responses
            MessageQuerySet approvalMQS = new MessageQuerySet
            {
                {
                    "ApprovalProcessId",
                    new XPathMessageQuery("local-name()=‘Id‘", new XPathMessageContext())
                }
            };
 
            this.Implementation = () => 
                new Sequence
                {
                    Variables = { corr, response, startParams, requestReplyHandle, cancelRequest },
                    Activities =
                    {
                        // Called by a local client proxy to trigger the creation of a new approval request
                        new Receive
                        {
                            OperationName = "StartGetApproval",
                            ServiceContractName = "IApprovalResults",
                            Content = new ReceiveMessageContent(new OutArgument<StartApprovalParams>(startParams)),
                            CanCreateInstance = true,
                        },
                        // Ask the approval manager to start the approval process
                        new Send
                        {
                            OperationName = "RequestApprovalOf",
                            ServiceContractName = "IApprovalProcess",
                            EndpointAddress = new InArgument<Uri>(env => startParams.Get(env).ServiceAddress),
                            Endpoint = new Endpoint
                            {
                                 Binding = new BasicHttpBinding(),
                            },
                            Content = new SendMessageContent(new InArgument<ApprovalRequest>(env => startParams.Get(env).Request)),
                            CorrelationInitializers = 
                            {
                                new QueryCorrelationInitializer
                                {
                                    CorrelationHandle = corr,
                                    MessageQuerySet = approvalMQS,
                                },
                            }
                        },
                        // Get a response from the approval manager or a request to cancel the approval
                        //  from the local client proxy (user presses the cancel request button on the ui)
                        new Pick
                        {
                            Branches =
                            {
                                new PickBranch
                                {
                                    Trigger = new Receive
                                    {
                                        OperationName = "ApprovalProcessResults",
                                        ServiceContractName = "IApprovalResults",
                                        CorrelatesWith = corr,
                                        CorrelatesOn = approvalMQS,
                                        Content = new ReceiveMessageContent(new OutArgument<ApprovalResponse>(response)),
                                    },
                                },
                                new PickBranch
                                {
                                    Trigger = new Receive
                                    {
                                        OperationName = "CancelApprovalRequest",
                                        ServiceContractName = "IApprovalResults",
                                        CorrelatesWith = corr,
                                        CorrelatesOn = approvalMQS,
                                        Content = new ReceiveMessageContent(new OutArgument<ApprovalRequest>(cancelRequest)),
                                    },
                                    // Send cancelation to the approval manager to pass on to clients approving document
                                    Action = new Sequence
                                    {
                                        Activities = 
                                        {
                                            new Send
                                            {
                                                OperationName = "CancelApprovalRequest",
                                                ServiceContractName = "IApprovalProcess",
                                                EndpointAddress = new InArgument<Uri>(env => startParams.Get(env).ServiceAddress),
                                                Endpoint = new Endpoint
                                                {
                                                    Binding = new BasicHttpBinding(),
                                                },
                                                Content = new SendMessageContent(new InArgument<ApprovalRequest>(env => startParams.Get(env).Request)),
                                            },
                                            new TerminateWorkflow
                                            {
                                                Reason = "Approval Request Canceled",
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        new InvokeMethod
                        {
                            TargetType = typeof(ExternalToMainComm),
                            MethodName = "WriteStatusLine",
                            Parameters = 
                            {
                                new InArgument<String>("Got an approval response..."),
                            },
                        },
                        // update ui with new response
                        new InvokeMethod
                        {
                            TargetType = typeof(ExternalToMainComm),
                            MethodName = "ApprovalRequestResponse",
                            Parameters =
                            {
                                new InArgument<ApprovalResponse>(response),
                            }
                        },
                    }
                };
        }
    }
}

  

//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System;
using System.IO;

using Microsoft.Samples.DocumentApprovalProcess.ApprovalMessageContractLibrary;

namespace Microsoft.Samples.DocumentApprovalProcess.ApprovalClient
{
    // This class is used to communicate with the Main WPF window from external sources
    // that don‘t have a reference to the UI (ex, for WCF services and WorkflowServiceHost)
    public static class ExternalToMainComm
    {
        public static Main Context { get; set; }

        // Called if ApprovalRequestsService got new approval request
        public static void NewApprovalRequest(ApprovalRequest request)
        {
            if (Context != null)
                Context.AddApprovalItem(request);
        }

        // Called if ApprovalRequestsService was told to cancel an existing request
        public static void CancelApprovalRequest(ApprovalRequest request)
        {
            if (Context != null)
                Context.RemoveApprovalItem(request);
        }

        // Called if the ApprovalRequestsService gets a response to a approval request generated locally
        public static void ApprovalRequestResponse(ApprovalResponse response)
        {
            if (Context != null)
                Context.ProcessResponse(response);
        }

        // Returns a writer that writes to the WPF status window -- this is used for client side tracking
        public static TextWriter GetStatusWriter()
        {
            if (Context != null)
                return new WindowTextWriter(Context.GetStatusTextBox());
            else
                return null;
        }

        // Simpler but less flexable way to write to the WPF status window when compared 
        // to getting a writer using GetStatusWriter() -- this is used to output debug messages
        public static void WriteStatusLine(String status)
        {
            if (Context != null)
            {
                GetStatusWriter().WriteLine(status);
            }
        }
    }
}

 

文档审批工作流

标签:

原文地址:http://www.cnblogs.com/linhongquan/p/5496859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!