private DataTable CreateDataTableManifest(string info)
        {
            DataTable dt = new DataTable();

            if (string.IsNullOrEmpty(info))
            {
                return(dt);
            }

            try
            {
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(info);

                // Add columns
                DataColumn dtChannelName = dt.Columns.Add("Channel Name");
                DataColumn dcFlowID      = dt.Columns.Add("Flow ID");
                DataColumn dcGuid        = dt.Columns.Add("Guid");
                DataColumn dcKey         = dt.Columns.Add("Key");
                DataColumn dcValue       = dt.Columns.Add("Value");

                XmlNodeList xnlChannels = xd.SelectNodes("/statusInformation/channels/channel");
                foreach (XmlNode xnChannel in xnlChannels)
                {
                    if (xnChannel.SelectSingleNode("currentFlowManifest") == null)
                    {
                        break;
                    }

                    FlowManifest manifest = new FlowManifest(xnChannel.SelectSingleNode("currentFlowManifest").InnerText);
                    //
                    // Add key value
                    //
                    foreach (string key in manifest.InputParameters.Keys)
                    {
                        //
                        // New DataRow
                        //
                        DataRow dr = dt.NewRow();

                        //
                        // Add channel info
                        //
                        dr[dtChannelName] = xnChannel.Attributes["name"].InnerText;
                        dr[dcFlowID]      = manifest.FlowID;
                        dr[dcGuid]        = manifest.GUID.ToString();
                        dr[dcKey]         = key;
                        dr[dcValue]       = manifest.InputParameters[key];
                        //
                        // Add row to data table
                        //
                        dt.Rows.Add(dr);
                    }// for each
                }
            }
            catch (Exception)
            {
            }
            return(dt);
        }
        private DataTable CreateDataTableQueue(string info)
        {
            DataTable dt = new DataTable();

            if (string.IsNullOrEmpty(info))
            {
                return(dt);
            }

            try
            {
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(info);

                // Add columns
                DataColumn dtChannelName = dt.Columns.Add("Channel Name");
                DataColumn dtQueueCount  = dt.Columns.Add("Queue Count");
                DataColumn dcFlowID      = dt.Columns.Add("Flow ID");
                DataColumn dcGuid        = dt.Columns.Add("Guid");
                DataColumn dcKey         = dt.Columns.Add("Key");
                DataColumn dcValue       = dt.Columns.Add("Value");

                XmlNodeList xnlChannels = xd.SelectNodes("/statusInformation/channels/channel");
                foreach (XmlNode xnChannel in xnlChannels)
                {
                    XmlNodeList xnlQueueItems = xnChannel.SelectNodes("queue/item");
                    foreach (XmlNode xnQueueItem in xnlQueueItems)
                    {
                        FlowManifest manifest = new FlowManifest(xnQueueItem.InnerText);

                        foreach (string key in manifest.InputParameters.Keys)
                        {
                            //
                            // New DataRow
                            //
                            DataRow dr = dt.NewRow();
                            //
                            // Add channel info
                            //
                            dr[dtChannelName] = xnChannel.Attributes["name"].InnerText;
                            dr[dtQueueCount]  = xnChannel.Attributes["queueCount"].InnerText;

                            dr[dcFlowID] = manifest.FlowID;
                            dr[dcGuid]   = manifest.GUID.ToString();

                            dr[dcKey]   = key;
                            dr[dcValue] = manifest.InputParameters[key];

                            dt.Rows.Add(dr);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(dt);
        }
        public void HandleEvent(FlowManifest manifest, IExecutionEngine pIExecutionEngine)
        {
            StatusProgressItem spi0 = new StatusProgressItem {
                Description = "FlowStatus", Status = manifest.FlowStatus.ToString()
            };

            pIExecutionEngine.AddStatusInformation(spi0);

            StatusProgressItem spi = new StatusProgressItem {
                Description = "Testing .EndFlow", Status = "Running"
            };

            pIExecutionEngine.AddStatusInformation(spi);

            try
            {
                pIExecutionEngine.EndFlow = true;
                spi.Status = "SHOULD NOT WORK!";
            }
            catch (NotImplementedException)
            {
                spi.Status = "NotImplementedException";
            }

            StatusProgressItem spi2 = new StatusProgressItem {
                Description = "Testing .LogToEvents", Status = "Running"
            };

            pIExecutionEngine.AddStatusInformation(spi2);

            try
            {
                pIExecutionEngine.LogToEvents = true;
                spi2.Status = "SHOULD NOT WORK!";
            }
            catch (NotImplementedException)
            {
                spi2.Status = "NotImplementedException";
            }

            StatusProgressItem spi3 = new StatusProgressItem {
                Description = "Testing .ResponseInBrowser", Status = "Running"
            };

            pIExecutionEngine.AddStatusInformation(spi3);

            try
            {
                IResponseInBrowser i = pIExecutionEngine.ResponseInBrowser;
                spi3.Status = "SHOULD NOT WORK!";
            }
            catch (NotImplementedException)
            {
                spi3.Status = "NotImplementedException";
            }
        }
예제 #4
0
        /// <summary>
        /// Appends a flow manifest to the threads work queue.
        /// </summary>
        /// <param name="flowManifest"></param>
        public void Execute(FlowManifest flowManifest)
        {
            if (this.MarkedForTermination || this.Terminated)
            {
                return;
            }

            this.Queue.Enqueue(flowManifest);
            this.WaitHandle.Set( );
        }
 /// <summary>
 /// Executes a flow.
 /// </summary>
 /// <param name="flowManifest"></param>
 public void ExecuteFlow( FlowManifest flowManifest )
 {
     lock ( this ) {
         bool bExecuted = false;
         foreach ( string key in this.Channels.Keys ) {                    
             Channel<TSettings, TTransparentFlow, TRealFlow, THostRuntimeSettings> channel = this.Channels[key];
             if ( channel.IsInChannel( flowManifest.FlowID ) ) {
                 channel.Execute( flowManifest );
                 bExecuted = true;   
             }                   
         }
         if ( !bExecuted ) {
             string msg = string.Format( "No TransparentFlow to handle FlowID = '{0}'.", flowManifest.FlowID );
             ExceptionManager.PublishException(new CompuFlowException(msg), "Warning");
         }
     }
 }
예제 #6
0
        /// <summary>
        /// Executes a flow. Only executes if it is not marked for termination and/or is terminated.
        /// </summary>
        /// <param name="flowManifest"></param>
        public virtual void Execute(FlowManifest flowManifest)
        {
            if (this.MarkedForTermination || this.Terminated)
            {
                return;
            }

            if (!this.Initialized)
            {
                this.Initialize( );
            }

            //
            // Execute flow.
            //
            DateTime dtBefore = DateTime.Now;

            this.RealFlow.Execute(flowManifest.ToXmlDocument().OuterXml, Settings.ToHostRuntimeSettings());
            DateTime dtAfter = DateTime.Now;

            this.AddExecutionTime(dtAfter - dtBefore);
        }
예제 #7
0
        private void WorkerMethod()
        {
            //
            // Thread sleep for debugging purposes only. Se conditional attribute.
            //
            ThreadSleep(15000);

            try
            {
                //
                // Get/Load Settings
                //
                Settings settings = new Settings();

                //
                // Delete temporary flow files, temp files and folders
                //
                DeleteTemporaryFiles(settings);

                //
                // Create controller object.
                //
                Controller <Settings, TransparentRetrival, RealRetrival, HostRuntimeSettings> controller = new Controller <Settings, TransparentRetrival, RealRetrival, HostRuntimeSettings>(settings, false);

                //
                // Status Information Host
                //
                StatusInformationHost <Settings, TransparentRetrival, RealRetrival, HostRuntimeSettings> statusInformationHost = new StatusInformationHost <Settings, TransparentRetrival, RealRetrival, HostRuntimeSettings>(controller, "net.pipe://localhost/ItSoftware.CompuFlow.Retrival");

                //
                // Worker loop.
                //
                MessageQueue mq = new MessageQueue(settings.SourceMsmqPath);
                mq.Formatter = new BinaryMessageFormatter();
                System.Messaging.Message sourceMsg = null;
                do
                {
                    try
                    {
                        if (this.Paused)
                        {
                            Thread.Sleep(new TimeSpan(0, 0, 5));
                        }
                        else
                        {
                            try
                            {
                                sourceMsg = null;
                                sourceMsg = mq.Receive(new TimeSpan(0, 0, 5));
                            }
                            catch (MessageQueueException mqe)
                            {
                                if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                                {
                                    RetrivalException ge = new RetrivalException("MessageQueue.Receive threw an unexpected exception.", mqe);
                                    ExceptionManager.PublishException(ge, "Log Warning Policy");

                                    Thread.Sleep(new TimeSpan(0, 0, 5));
                                }
                            }
                            if (sourceMsg != null)
                            {
                                FlowManifest flowManifest = new FlowManifest(sourceMsg.Body as string);
                                controller.ExecuteFlow(flowManifest);
                            }
                        }
                    }
                    catch (OutOfMemoryException)
                    {
                        throw;
                    }
                    catch (StackOverflowException)
                    {
                        throw;
                    }
                    catch (ThreadAbortException)
                    {
                        controller.Stop();
                        throw;
                    }
                    catch (Exception x)
                    {
                        ExceptionManager.PublishException(x, "Error");
                    }
                } while (!this.Stopped);
                controller.Stop();
            }
            catch (ThreadAbortException tae)
            {
                if (!this.Stopped)
                {
                    ExceptionManager.PublishException(tae, "Error");
                    System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(base.ServiceName);
                    sc.Stop();
                }
            }
            catch (SettingsException se)
            {
                RetrivalException ge = new RetrivalException("Retrival could not continue execution.", se);
                ExceptionManager.PublishException(ge, "Error");

                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(base.ServiceName);
                sc.Stop();
            }
            catch (RetrivalException ge)
            {
                ExceptionManager.PublishException(ge, "Error");

                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(base.ServiceName);
                sc.Stop();
            }
            catch (RuntimeWrappedException rwe)
            {
                RetrivalException ge = new RetrivalException("An unhandled RuntimeWrappedException exception was thrown.\r\nRetrival could not continue execution.", rwe);
                ExceptionManager.PublishException(ge, "Error");

                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(base.ServiceName);
                sc.Stop();
            }
            catch (Exception x)
            {
                RetrivalException ge = new RetrivalException("An unhandled CLS complient exception was thrown.\r\nRetrival could not continue execution.", x);
                ExceptionManager.PublishException(ge, "Error");

                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(base.ServiceName);
                sc.Stop();
            }
        }
예제 #8
0
        /// <summary>
        /// Execute a flow.
        /// </summary>
        /// <param name="flowManifest"></param>
        /// <param name="hostRuntimeSettings"></param>
        public override void Execute(string flowManifest, HostRuntimeSettings settings)
        {
            // This base call sets up the this.CurrentExecutingFlowManifest.
            base.Execute(flowManifest, settings);

            //
            // First of all clear previous status information
            //
            this.m_statusInformation.Clear();


            FlowManifest manifest = this.CurrentExecutingFlowManifest; //= null;

            System.Globalization.CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            try
            {
                //XmlDocument xdManifest = new XmlDocument();
                //xdManifest.LoadXml(flowManifest);
                //manifest = new FlowManifest(xdManifest);
                if (this.BindingConfig == null)
                {
                    //
                    // Initialize the application cache.
                    //
                    this.ApplicationCache = new Hashtable();

                    //
                    // Set data directory
                    //
                    this.DataDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
                    if (!Directory.Exists(this.DataDirectory))
                    {
                        Directory.CreateDirectory(this.DataDirectory);
                    }

                    //
                    // Set config directory
                    //
                    this.ConfigDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
                    if (!Directory.Exists(this.ConfigDirectory))
                    {
                        //Directory.CreateDirectory(this.ConfigDirectory);
                        throw new HostRuntimeException("Missing Config directory in package file.");
                    }

                    //
                    // Load configuration data.
                    //
                    XmlDocument xdRetrival = new XmlDocument();
                    xdRetrival.Load(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config"), "Binding.xml"));
                    this.BindingConfig            = new RetrivalBindingConfig(xdRetrival);
                    this.ProgressItem.Description = this.BindingConfig.Description;
                }

                //
                // Reset progress item.
                //
                this.ProgressItem.ErrorInfo     = "";
                this.ProgressItem.ExecutionTime = TimeSpan.Zero;
                this.ProgressItem.StartTime     = DateTime.Now;
                this.ProgressItem.Status        = "Running";


                //
                // Create output directory and session object.
                //
                string outputDirectory = FileSystem.NormalizeDirectoryPath(Path.Combine(settings.OutputDirectory, manifest.GUID.ToString()));
                if (!Directory.Exists(outputDirectory))
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                manifest.GeneratorOutputDirectory = outputDirectory;

                //
                // Create temp directory.
                //
                string tempDirectory = FileSystem.NormalizeDirectoryPath(Path.Combine(settings.TempDirectory, manifest.GUID.ToString()));
                if (!Directory.Exists(tempDirectory))
                {
                    Directory.CreateDirectory(tempDirectory);
                }

                //
                // Execute generator.
                //
                DateTime dtBefore = DateTime.Now;
                this.BindingConfig.IGeneratorRef.Generate(manifest.InputParameters, this.ApplicationCache, tempDirectory, this.ConfigDirectory, this.DataDirectory, outputDirectory, manifest.RetrivalOutputDirectory, this);
                DateTime dtAfter = DateTime.Now;
                this.AddExecutionTime(dtAfter - dtBefore);

                this.ProgressItem.Status = "OK";

                //
                // Delete temp directory.
                //
                try
                {
                    FileSystem.DeleteDirectoryStructure(tempDirectory);
                }
                catch (Exception) { }

                //
                // Always perform a garbage collection after generation. Some generators, like powerpoint etc., hold
                // on to objects that make processes like powerpoint to keep running. We have to run the finalizers so
                // that they are released.
                //
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                //
                // If Retrival has ended the execution flow return now.
                //
                string msmqPath = null;
                if (this.EndFlow)
                {
                    //
                    // Send message to log.
                    //
                    if (settings.Log && this.LogToEvents)
                    {
                        manifest.FlowStatus = FlowStatus.CompletedGenerator;
                        msmqPath            = settings.EventsMsmqPath;
                        using (MessageQueue mqLog = new MessageQueue(settings.EventsMsmqPath))
                        {
                            mqLog.Formatter = new BinaryMessageFormatter();

                            System.Messaging.Message msgLog = new System.Messaging.Message();
                            msgLog.Formatter = new BinaryMessageFormatter();
                            msgLog.Body      = manifest.ToXmlDocument().OuterXml;
                            msgLog.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                            mqLog.Send(msgLog);
                        }
                    }

                    return;
                }


                //
                // Providers have executed. Pass message to destination and log.
                //
                msmqPath = settings.DestinationMsmqPath;
                try
                {
                    manifest.FlowStatus = FlowStatus.CompletedGenerator;

                    //
                    // Send to generator.
                    //
                    using (MessageQueue mqPublisher = new MessageQueue(settings.DestinationMsmqPath))
                    {
                        mqPublisher.Formatter = new BinaryMessageFormatter();

                        System.Messaging.Message msgPublisher = new System.Messaging.Message();
                        msgPublisher.Formatter = new BinaryMessageFormatter();
                        msgPublisher.Body      = manifest.ToXmlDocument().OuterXml;
                        msgPublisher.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                        mqPublisher.Send(msgPublisher);
                    }
                    //
                    // Send message to log.
                    //
                    if (settings.Log && this.LogToEvents)
                    {
                        msmqPath = settings.EventsMsmqPath;
                        using (MessageQueue mqLog = new MessageQueue(settings.EventsMsmqPath))
                        {
                            mqLog.Formatter = new BinaryMessageFormatter();

                            System.Messaging.Message msgLog = new System.Messaging.Message();
                            msgLog.Formatter = new BinaryMessageFormatter();
                            msgLog.Body      = manifest.ToXmlDocument().OuterXml;
                            msgLog.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                            mqLog.Send(msgLog);
                        }
                    }
                }
                catch (StackOverflowException)
                {
                    throw;
                }
                catch (OutOfMemoryException)
                {
                    throw;
                }
                catch (ThreadAbortException)
                {
                    throw;
                }
                catch (Exception x)
                {
                    string msg = string.Format("Failure to send message to MSMQ Path: {0}\r\nFlow: {0}.", msmqPath, manifest.GUID.ToString());
                    throw new HostRuntimeException(msg, x);
                }
            }
            catch (StackOverflowException)
            {
                throw;
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception x)
            {
                this.ProgressItem.Status    = "Failure";
                this.ProgressItem.ErrorInfo = string.Format("Type:\r\n{0}\r\n\r\nSource:\r\n{1}\r\n\r\nMessage:\r\n{2}\r\n\r\nStack Trace:\r\n{3}", x.GetType().FullName, (x.Source != null) ? x.Source : "<NULL>", x.Message, x.StackTrace);
                HostRuntimeException hre = new HostRuntimeException("Retrival.HostRuntime's RealRetrival.Execute method failed.", x);
                ExceptionManager.PublishException(hre, "Error");

                //
                // Uphold failure policy. Save packet to failure directory.
                //
                if (manifest != null)
                {
                    //
                    // Save FlowManifest to failure directory.
                    //
                    string failureDirectory = Path.Combine(settings.FailureDirectory, manifest.GUID.ToString());
                    try
                    {
                        if (Directory.Exists(failureDirectory))
                        {
                            FileSystem.DeleteDirectoryStructure(failureDirectory);
                        }
                        Directory.CreateDirectory(failureDirectory);
                        manifest.ToXmlDocument().Save(Path.Combine(failureDirectory, "FlowManifest.xml"));
                    }
                    catch (StackOverflowException)
                    {
                        throw;
                    }
                    catch (OutOfMemoryException)
                    {
                        throw;
                    }
                    catch (ThreadAbortException)
                    {
                        throw;
                    }
                    catch (Exception x2)
                    {
                        ExceptionManager.PublishException(new HostRuntimeException("Failed to uphold failure policy.", x2), "Error");
                    }
                    //
                    // If log, then log the failed execution.
                    //
                    if (settings.Log && this.LogToEvents)
                    {
                        try
                        {
                            manifest.FlowStatus = FlowStatus.ErrorRetrival;

                            using (MessageQueue mqLog = new MessageQueue(settings.EventsMsmqPath))
                            {
                                mqLog.Formatter = new BinaryMessageFormatter();

                                System.Messaging.Message msgLog = new System.Messaging.Message();
                                msgLog.Formatter = new BinaryMessageFormatter();
                                msgLog.Body      = manifest.ToXmlDocument().OuterXml;
                                msgLog.Label     = manifest.FlowID;

                                mqLog.Send(msgLog);
                            }
                        }
                        catch (StackOverflowException)
                        {
                            throw;
                        }
                        catch (OutOfMemoryException)
                        {
                            throw;
                        }
                        catch (ThreadAbortException)
                        {
                            throw;
                        }
                        catch (Exception x3)
                        {
                            ExceptionManager.PublishException(new HostRuntimeException("Failure logging error to log.", x3), "Error");
                        }
                    } // if ( settings.Log ...
                }     // if ( packet != null ...
            }         // catch ( Exception x ...
            finally
            {
                Thread.CurrentThread.CurrentCulture = cultureInfo;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string flowID = Request.QueryString["FlowID"];

            if (string.IsNullOrEmpty(flowID))
            {
                flowID = Request.Form["FlowID"];
                if (string.IsNullOrEmpty(flowID))
                {
                    Response.Write("Missing required parameter FlowID.");
                    return;
                }
            }

            NameValueCollection inputParameters = GenerateInputParameters(flowID);
            FlowManifest        manifest        = new FlowManifest();

            manifest.RequestInitiated = DateTime.Now;
            manifest.InputParameters  = inputParameters;
            manifest.FlowID           = flowID;
            manifest.GUID             = Guid.NewGuid();

            //foreach (string key in inputParameters.Keys)
            //{
            //    Response.Write("<br>" + key + "=" + inputParameters[key]);
            //}

            string msmqPath = ConfigurationManager.AppSettings["DestinationMsmqPath"];

            try
            {
                manifest.FlowStatus = FlowStatus.CompletedGateway;

                //
                // Send to Retrival.
                //
                using (MessageQueue mqPublisher = new MessageQueue(msmqPath))
                {
                    mqPublisher.Formatter = new BinaryMessageFormatter();

                    System.Messaging.Message msgPublisher = new System.Messaging.Message();
                    msgPublisher.Formatter = new BinaryMessageFormatter();
                    msgPublisher.Body      = manifest.ToXmlDocument().OuterXml;
                    msgPublisher.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                    mqPublisher.Send(msgPublisher);
                }
                //
                // Send message to log.
                //
                bool bLogToEvents = bool.Parse(ConfigurationManager.AppSettings["LogToEvents"]);
                if (bLogToEvents)
                {
                    msmqPath = ConfigurationManager.AppSettings["EventsMsmqPath"];
                    using (MessageQueue mqLog = new MessageQueue(msmqPath))
                    {
                        mqLog.Formatter = new BinaryMessageFormatter();

                        System.Messaging.Message msgLog = new System.Messaging.Message();
                        msgLog.Formatter = new BinaryMessageFormatter();
                        msgLog.Body      = manifest.ToXmlDocument().OuterXml;
                        msgLog.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                        mqLog.Send(msgLog);
                    }
                }
                //
                // If we have ResponseInBrowser = true then redirect to response in browser handler
                //
                bool   bRespInBrowser = false;
                string respInBrowser  = inputParameters["ResponseInBrowser"];
                if (!string.IsNullOrEmpty(respInBrowser) && !string.IsNullOrWhiteSpace(respInBrowser))
                {
                    try
                    {
                        bRespInBrowser = bool.Parse(respInBrowser);
                    }
                    catch (FormatException)
                    {
                    }
                }

                //
                // Do we have response in browser
                //
                if (bRespInBrowser)
                {
                    // Redirect to response in browser handler.
                    Response.Redirect("ResponseInBrowserHandler.ashx?guid=" + manifest.GUID.ToString(), true);
                }
            }
            catch (StackOverflowException)
            {
                throw;
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception x)
            {
                string msg = string.Format("Failure to send message to MSMQ Path: {0}\r\nFlow: {0}.", msmqPath, manifest.GUID.ToString());
                ExceptionManager.PublishException(new Exception(msg, x), "Error");
            }
        }
예제 #10
0
        /// <summary>
        /// Worker method.
        /// </summary>
        private void WorkerMethod( )
        {
            while (!this.MarkedForTermination)
            {
                try {
                    this.WaitHandle.WaitOne( );
                    //
                    // Terminate flow marked and remove references to them.
                    //
                    lock (this) {
                        List <TTransparentFlow> removeList = new List <TTransparentFlow>( );
                        foreach (TTransparentFlow transparentFlow in this.Flows)
                        {
                            if (transparentFlow.MarkedForTermination && !transparentFlow.Terminated)
                            {
                                try {
                                    transparentFlow.Terminate( );
                                    //
                                    // Add the flow to list of flows to be removed.
                                    //
                                    removeList.Add(transparentFlow);
                                }
                                catch (StackOverflowException) {
                                    throw;
                                }
                                catch (OutOfMemoryException) {
                                    throw;
                                }
                                catch (ThreadAbortException) {
                                    throw;
                                }
                                catch (Exception e) {
                                    ExceptionManager.PublishException(e, "Error");
                                }
                            }
                        }
                        //
                        // Remove the flows.
                        //
                        foreach (TTransparentFlow transparentFlow in removeList)
                        {
                            this.Flows.Remove(transparentFlow);
                        }
                    }// lock

                    //
                    // Execute flow.
                    //
                    while (this.Queue.Count > 0)
                    {
                        FlowManifest flowManifest = this.Queue.Dequeue( );
                        bool         bExecuted    = false;
                        foreach (TTransparentFlow transparentFlow in this.Flows)
                        {
                            if (transparentFlow.Flow.FlowID == flowManifest.FlowID && !transparentFlow.MarkedForTermination)
                            {
                                try {
                                    this.CurrentFlowManifest = flowManifest;
                                    transparentFlow.Execute(flowManifest);
                                }
                                catch (StackOverflowException) {
                                    throw;
                                }
                                catch (OutOfMemoryException) {
                                    throw;
                                }
                                catch (ThreadAbortException) {
                                    throw;
                                }
                                catch (Exception e) {
                                    string msg = string.Format("TransparentFlow threw an exception while executing flow with FlowID='{0}'.", flowManifest.FlowID);
                                    ExceptionManager.PublishException(e, "Error");
                                }
                                finally {
                                    bExecuted = true;
                                }
                            } // if
                        }     // foreach
                        if (!bExecuted)
                        {
                            string msg = string.Format("No TransparentFlow to handle FlowID = '{0}'.", flowManifest.FlowID);
                            ExceptionManager.PublishException(new CompuFlowException(msg), "Warning");
                        }
                    }
                }
                catch (StackOverflowException) {
                    throw;
                }
                catch (OutOfMemoryException) {
                    throw;
                }
                catch (ThreadAbortException tae) {
                    CompuFlowException rfe = new CompuFlowException("Could not continue execution.", tae);
                    ExceptionManager.PublishException(rfe, "Error");
                    this.Terminate( );

                    //System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController( "Psr3Engine" );
                    //sc.Stop( );
                }
                catch (Exception x) {
                    ExceptionManager.PublishException(x, "Error");
                }
            }// while

            //
            // Terminate all flows.
            //
            foreach (TTransparentFlow transparentFlow in this.Flows)
            {
                transparentFlow.Terminate( );
            }
            lock (this) {
                this.Flows.Clear( );
            }
            this.Terminated = true;
        }
        public void ExecuteFlow(string flowID, string[] keys, string[] values)
        {
            if (string.IsNullOrEmpty(flowID) || string.IsNullOrEmpty(flowID))
            {
                throw new Exception("Missing required parameter FlowID.");
            }

            NameValueCollection inputParameters = GenerateInputParameters(flowID, keys, values);
            FlowManifest        manifest        = new FlowManifest();

            manifest.RequestInitiated = DateTime.Now;
            manifest.InputParameters  = inputParameters;
            manifest.FlowID           = flowID;
            manifest.GUID             = Guid.NewGuid();

            string msmqPath = ConfigurationManager.AppSettings["DestinationMsmqPath"];

            try
            {
                manifest.FlowStatus = FlowStatus.CompletedGateway;

                //
                // Send to Retrival.
                //
                using (MessageQueue mqPublisher = new MessageQueue(msmqPath))
                {
                    mqPublisher.Formatter = new BinaryMessageFormatter();

                    System.Messaging.Message msgPublisher = new System.Messaging.Message();
                    msgPublisher.Formatter = new BinaryMessageFormatter();
                    msgPublisher.Body      = manifest.ToXmlDocument().OuterXml;
                    msgPublisher.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                    mqPublisher.Send(msgPublisher);
                }
                //
                // Send message to log.
                //
                bool bLogToEvents = bool.Parse(ConfigurationManager.AppSettings["LogToEvents"]);
                if (bLogToEvents)
                {
                    msmqPath = ConfigurationManager.AppSettings["EventsMsmqPath"];
                    using (MessageQueue mqLog = new MessageQueue(msmqPath))
                    {
                        mqLog.Formatter = new BinaryMessageFormatter();

                        System.Messaging.Message msgLog = new System.Messaging.Message();
                        msgLog.Formatter = new BinaryMessageFormatter();
                        msgLog.Body      = manifest.ToXmlDocument().OuterXml;
                        msgLog.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                        mqLog.Send(msgLog);
                    }
                }
            }
            catch (StackOverflowException)
            {
                throw;
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception x)
            {
                string msg = string.Format("Failure to send message to MSMQ Path: {0}\r\nFlow: {0}.", msmqPath, manifest.GUID.ToString());
                ExceptionManager.PublishException(new Exception(msg, x), "Error");
            }
        }
        private void ExecuteFlowWithReturnWorkerMethod(object param)
        {
            FlowParams flowParams = param as FlowParams;

            string flowID = flowParams.FlowID;

            string[] keys   = flowParams.Keys;
            string[] values = flowParams.Values;

            NameValueCollection inputParameters = GenerateInputParameters(flowID, keys, values);

            //
            // Force insertion of ResponseInBrowser = true
            //
            string respInBrowser = inputParameters["ResponseInBrowser"];

            if (respInBrowser != null)
            {
                inputParameters.Remove("ResponseInBrowser");
            }
            inputParameters["ResponseInBrowser"] = "True";

            FlowManifest manifest = new FlowManifest();

            manifest.RequestInitiated = DateTime.Now;
            manifest.InputParameters  = inputParameters;
            manifest.FlowID           = flowID;
            manifest.GUID             = Guid.NewGuid();

            byte[] returnValue = new byte[0];

            string msmqPath = ConfigurationManager.AppSettings["DestinationMsmqPath"];

            try
            {
                manifest.FlowStatus = FlowStatus.CompletedGateway;

                //
                // Send to Retrival.
                //
                using (MessageQueue mqPublisher = new MessageQueue(msmqPath))
                {
                    mqPublisher.Formatter = new BinaryMessageFormatter();

                    System.Messaging.Message msgPublisher = new System.Messaging.Message();
                    msgPublisher.Formatter = new BinaryMessageFormatter();
                    msgPublisher.Body      = manifest.ToXmlDocument().OuterXml;
                    msgPublisher.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                    mqPublisher.Send(msgPublisher);
                }
                //
                // Send message to log.
                //
                bool bLogToEvents = bool.Parse(ConfigurationManager.AppSettings["LogToEvents"]);
                if (bLogToEvents)
                {
                    msmqPath = ConfigurationManager.AppSettings["EventsMsmqPath"];
                    using (MessageQueue mqLog = new MessageQueue(msmqPath))
                    {
                        mqLog.Formatter = new BinaryMessageFormatter();

                        System.Messaging.Message msgLog = new System.Messaging.Message();
                        msgLog.Formatter = new BinaryMessageFormatter();
                        msgLog.Body      = manifest.ToXmlDocument().OuterXml;
                        msgLog.Label     = string.Format("{0} - {1}", manifest.FlowID, manifest.FlowStatus.ToString());

                        mqLog.Send(msgLog);
                    }
                }

                // Handle response and return.
                ResponseInBrowserHost host = new ResponseInBrowserHost(this.Context, "net.pipe://localhost/CompuFlow.Gateway." + manifest.GUID.ToString());
                host.NoHttpContextWrite = true;
                host.Start(manifest.GUID);
                returnValue = host.ResponseInBrowserData;
            }
            catch (StackOverflowException)
            {
                throw;
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception x)
            {
                string msg = string.Format("Failure to send message to MSMQ Path: {0}\r\nFlow: {0}.", msmqPath, manifest.GUID.ToString());
                ExceptionManager.PublishException(new Exception(msg, x), "Error");
            }

            flowParams.ReturnValue = returnValue;
            flowParams.ResetEvent.Set();
        }