void OnChildServiceRequested(int stepNumber, int attemptNumber)
        {
            // Get the step configuration elements
            ExecutionStepElement          stepConfig   = this.Configuration.ExecutionSteps[stepNumber];
            AccountServiceSettingsElement stepSettings =
                this.Configuration.StepSettings != null ?
                this.Configuration.StepSettings[stepConfig] :
                null;

            // Generate a child instance
            ServiceInstance child = Service.CreateInstance(
                stepSettings != null ?
                (EnabledConfigurationElement)stepSettings :
                (EnabledConfigurationElement)stepConfig,
                this,
                this.AccountID);

            child.StateChanged    += _childStateHandler;
            child.OutcomeReported += _childOutcomeHandler;
            _childServices.Add(child, stepNumber);

            if (ChildServiceRequested != null)
            {
                ChildServiceRequested(this, new ServiceRequestedEventArgs(child, attemptNumber));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        StepInfo GetStepFromHistory(ExecutionStepElement stepConfig)
        {
            foreach (StepInfo s in _stepHistory)
            {
                // Check whether the next step hasn't been added already
                if (s.StepConfig == stepConfig)
                {
                    return(s);
                }
            }

            return(null);
        }
        public AccountServiceSettingsElement this[ExecutionStepElement step]
        {
            get
            {
                foreach (AccountServiceSettingsElement elem in this)
                {
                    if (elem.Step.Element == step)
                    {
                        return(elem);
                    }
                }

                return(null);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="nextStepConfig"></param>
        /// <returns></returns>
        bool IsInStepHistory(ExecutionStepElement nextStepConfig)
        {
            bool alreadyAdded = false;

            foreach (StepInfo s in _stepHistory)
            {
                // Check whether the next step hasn't been added already
                if (s.StepConfig == nextStepConfig)
                {
                    alreadyAdded = true;
                    break;
                }
            }

            return(alreadyAdded);
        }
        public void Previous(int sessionID, StepCollectRequest request)
        {
            //ExecutionStepElement currentInstacnceElement = parentInstance.Configuration.ExecutionSteps[currentInstance.Configuration.Name];

            //int currentStepIndex = parentInstance.Configuration.ExecutionSteps.IndexOf(currentInstacnceElement);
            ServiceInstance previousStep;
            ServiceInstance currentStep;

            if (request.StepName != StepInstances[sessionID].Configuration.Name)
            {
                throw new Exception("Step name is not matching current step!");
            }
            currentStep = StepInstances[sessionID];
            ExecutionStepElement currentStepElement = currentStep.ParentInstance.Configuration.ExecutionSteps[currentStep.Configuration.Name];

            int currentStepIndex = currentStep.ParentInstance.Configuration.ExecutionSteps.IndexOf(currentStepElement);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the next step that is enabled and is not a failure handler. If there is none returns null.
        /// </summary>
        ExecutionStepElement GetNextStep(ExecutionStepElement stepConfig)
        {
            int indexOfCurrent = stepConfig == null ? 0 : Instance.Configuration.ExecutionSteps.IndexOf(stepConfig) + 1;

            // Find the next non-failure handler step
            ExecutionStepElement next = null;

            for (int i = indexOfCurrent; i < Instance.Configuration.ExecutionSteps.Count; i++)
            {
                ExecutionStepElement step = Instance.Configuration.ExecutionSteps[i];
                if (
                    step.IsEnabled &&
                    !step.IsFailureHandler &&
                    IsStepConditionValid(step.ConditionOptions, step.Condition)
                    )
                {
                    next = Instance.Configuration.ExecutionSteps[i];
                    break;
                }
            }

            return(next);
        }
Ejemplo n.º 7
0
 /// <summary>
 ///
 /// </summary>
 public StepInfo(ExecutionStepElement stepConfig)
 {
     StepConfig = stepConfig;
     Config     = new ActiveExecutionStepElement(StepConfig);
 }
Ejemplo n.º 8
0
        /*=========================*/
        #endregion

        #region Constructors
        /*=========================*/

        /// <summary>
        ///
        /// </summary>
        public StepInfo(AccountServiceSettingsElement accountStepConfig)
        {
            StepConfig        = accountStepConfig.Step.Element;
            AccountStepConfig = accountStepConfig;
            Config            = new ActiveExecutionStepElement(AccountStepConfig);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        protected virtual ServiceOutcome DoWork()
        {
            if (Outcome != ServiceOutcome.Unspecified || State != ServiceState.Running)
            {
                throw new InvalidOperationException("DoWork() cannot be called because the service has ended.");
            }

            // Simulate processing execution time
            if (Instance.Configuration.DebugDelay > 0)
            {
                Thread.Sleep(Instance.Configuration.DebugDelay);
            }

            // Service with no steps means instant success!
            if (Instance.Configuration.ExecutionSteps.Count < 1)
            {
                return(ServiceOutcome.Success);
            }

            // Add the first step of the history as null - indicator for starting
            if (_stepHistory.Count < 1)
            {
                _stepHistory.Add(null);
            }

            // The return result
            bool stepsInProgress = false;

            ServiceOutcome outcome = ServiceOutcome.Unspecified;

            // Loop over each step in the history
            foreach (StepInfo step in _stepHistory.ToArray())
            {
                bool moveToNextStep = true;

                if (step != null)
                {
                    stepsInProgress = stepsInProgress || step.ServiceState != ServiceState.Ended;

                    // As long as a blocking process is running, halt all processing
                    if (stepsInProgress && step.Config.IsBlocking)
                    {
                        break;
                    }

                    // Indicates whether to process next step
                    moveToNextStep = step.ServiceOutcome == ServiceOutcome.Success;

                    if (!step.FailureWasHandled && (step.ServiceOutcome == ServiceOutcome.Failure || step.ServiceOutcome == ServiceOutcome.CouldNotBeScheduled || step.ServiceOutcome == ServiceOutcome.Aborted))
                    {
                        if (step.FailureRepetitions < step.Config.FailureRepeat - 1 && step.ServiceOutcome != ServiceOutcome.Aborted)
                        {
                            step.ServiceState = ServiceState.Uninitialized;
                            step.FailureRepetitions++;
                        }
                        else
                        {
                            if (step.Config.FailureOutcome == FailureOutcome.Continue)
                            {
                                // Process same as Success
                                moveToNextStep = true;
                            }

                            // This here is due to base[] getter bug
                            else if
                            (
                                !step.Config.IsFailureHandler &&
                                step.Config.FailureHandler.Element != null &&
                                step.Config.FailureHandler.Element.ServiceToUse.Element.Name != null &&
                                !IsInStepHistory(step.Config.FailureHandler.Element) &&
                                IsStepConditionValid(step.Config.FailureHandler.Element.ConditionOptions, step.Config.FailureHandler.Element.Condition)
                            )
                            {
                                // Get the correct step element
                                AccountServiceSettingsElement stepSettings = Instance.Configuration.StepSettings != null ? Instance.Configuration.StepSettings[step.Config.FailureHandler.Element] : null;

                                // Add a new step, the failure handler
                                if (stepSettings != null)
                                {
                                    _stepHistory.Add(new StepInfo(stepSettings));
                                }
                                else
                                {
                                    _stepHistory.Add(new StepInfo(step.Config.FailureHandler.Element));
                                }

                                // Done handling this step's failure
                                step.FailureWasHandled = true;
                            }
                            else
                            {
                                // Terminate because there is no failure handling - abort and stop processing
                                outcome = ServiceOutcome.Failure;
                                break;
                            }
                        }
                    }
                }

                if (moveToNextStep)
                {
                    // Get rid of the first null used to jump start the processing loop
                    if (step == null)
                    {
                        _stepHistory.Remove(step);
                    }

                    // Get the next step of a failure handler
                    ExecutionStepElement nextStepConfig = GetNextStep(step == null ? null : step.StepConfig);

                    if (nextStepConfig == null)
                    {
                        // No steps left to process
                        if (_stepHistory.TrueForAll(new Predicate <StepInfo>(delegate(StepInfo s) { return(s.ServiceState == ServiceState.Ended); })))
                        {
                            // All steps ended - outcome successful
                            outcome = ServiceOutcome.Success;
                            break;
                        }
                        else
                        {
                            // There are still steps being run so wait for them to complete before reporting that we are done
                            continue;
                        }
                    }
                    else if (nextStepConfig.WaitForPrevious && stepsInProgress)
                    {
                        // The next step needs to wait for all previous steps to end - stop processing
                        break;
                    }
                    else
                    {
                        bool adding = true;
                        while (adding)
                        {
                            if (!IsInStepHistory(nextStepConfig))
                            {
                                // Get the correct step element
                                AccountServiceSettingsElement stepSettings = Instance.Configuration.StepSettings != null ? Instance.Configuration.StepSettings[nextStepConfig] : null;

                                // Schedule the next step as long as it hasn't been added already
                                if (stepSettings != null)
                                {
                                    _stepHistory.Add(new StepInfo(stepSettings));
                                }
                                else
                                {
                                    _stepHistory.Add(new StepInfo(nextStepConfig));
                                }
                            }

                            // If the step is blocking or if it's a failure handler, stop adding steps, otherwise add the next
                            if (nextStepConfig.IsBlocking || nextStepConfig == Instance.Configuration.ExecutionSteps[Instance.Configuration.ExecutionSteps.Count - 1])
                            {
                                adding = false;
                            }
                            else
                            {
                                nextStepConfig = GetNextStep(nextStepConfig);

                                // Only add the next if it doesn't require previous steps to end first
                                if (nextStepConfig == null || nextStepConfig.WaitForPrevious)
                                {
                                    adding = false;
                                }
                            }
                        }
                    }
                }
            }

            if (outcome == ServiceOutcome.Unspecified)
            {
                // Request any pending child steps to be run
                foreach (StepInfo step in _stepHistory)
                {
                    if (step.ServiceState == ServiceState.Uninitialized)
                    {
                        RequestChildService(Instance.Configuration.ExecutionSteps.IndexOf(step.StepConfig), step.FailureRepetitions + 1);
                    }
                }
            }

            return(outcome);
        }
        public WizardSession Start(string WizardName)
        {
            //Debugger.Launch();

            //load the service from configuration file
            //CHANGED 1 (Service is taken from app.config- what to do if service not found?)
            int            wizardID;
            ServiceElement requestedWizardConfiguration = ServicesConfiguration.Services[WizardName];

            if (requestedWizardConfiguration == null)
            {
                throw new Exception("Wizard cannot be found");
            }



            //Get service data
            wizardID = int.Parse(requestedWizardConfiguration.Options["WizardID"]); //to insert in database it's int future
            //first step name
            ExecutionStepElement FirstStepCollector = GetFirstCollectorStep(requestedWizardConfiguration.ExecutionSteps);

            if (FirstStepCollector == null)
            {
                throw new Exception("No step collector found");
            }



            ActiveServiceElement configurationToRun = new ActiveServiceElement(requestedWizardConfiguration);


            //Initalize the main wizard service (account service...etc)

            ServiceInstance instance = Service.CreateInstance(configurationToRun);


            instance.ChildServiceRequested += new EventHandler <ServiceRequestedEventArgs>(instance_ChildServiceRequested);
            instance.ProgressReported      += new EventHandler(instance_ProgressReported);
            instance.StateChanged          += new EventHandler <ServiceStateChangedEventArgs>(instance_StateChanged);
            instance.OutcomeReported       += new EventHandler(instance_OutcomeReported);


            instance.Initialize();
            object sessionID = null;

            //Open new session by insert values in to the wizards_sessions_data table
            using (DataManager.Current.OpenConnection())
            {
                using (SqlCommand sqlCommand = DataManager.CreateCommand(@"INSERT INTO Wizards_Sessions_Data 
																		    (WizardID,CurrentStepName,ServiceInstanceID,WizardStatus)
																			Values (@WizardID:Int,@CurrentStepName:NvarChar,@ServiceInstanceID:BigInt,@WizardStatus:Int);SELECT @@IDENTITY"                                                                            ))
                {
                    sqlCommand.Parameters["@WizardID"].Value          = wizardID;
                    sqlCommand.Parameters["@CurrentStepName"].Value   = FirstStepCollector.Name;
                    sqlCommand.Parameters["@ServiceInstanceID"].Value = instance.InstanceID;
                    sqlCommand.Parameters["@WizardStatus"].Value      = WizardStatus.Collect;

                    sessionID = sqlCommand.ExecuteScalar();
                    if (sessionID == null)
                    {
                        throw new Exception("Error: Session not created");
                    }
                }
            }

            instance.Configuration.Options["SessionID"] = sessionID.ToString();

            //Create WizardSession object to return

            WizardSession wizardSession = new WizardSession();

            wizardSession.SessionID   = System.Convert.ToInt32(sessionID); //@@IDENTITY IS DECIMAL
            wizardSession.WizardID    = wizardID;
            wizardSession.CurrentStep = new StepConfiguration()
            {
                StepName = FirstStepCollector.Name
            };


            return(wizardSession);
        }
        public StepCollectResponse Collect(int sessionID, StepCollectRequest request)
        {
            StepCollectResponse response = null;
            StepCollectResponse tempResponse;

            try
            {
                // make sure request.StepName matches StepInstances[sessionID].Configuration.Name(client is in the right step)
                if (request.StepName != StepInstances[sessionID].Configuration.Name)
                {
                    throw new Exception("Step name is not matching current step!");
                }
                //connect to the  collector
                using (ServiceClient <IStepCollector> client = new ServiceClient <IStepCollector>("Test", String.Format("net.tcp://*****:*****@"UPDATE Wizards_Sessions_Data 
																			SET 
																			CurrentStepName=@CurrentStepName:NvarChar,
																			WizardStatus=@WizardStatus:Int
																			WHERE SessionID=@SessionID:Int 
																			AND ServiceInstanceID=@ServiceInstanceID:BigInt"                                                                            ))
                                {
                                    sqlCommand.Parameters["@CurrentStepName"].Value   = nextStep.Name;
                                    sqlCommand.Parameters["@SessionID"].Value         = sessionID;
                                    sqlCommand.Parameters["@WizardStatus"].Value      = WizardStatus.Collect;
                                    sqlCommand.Parameters["@ServiceInstanceID"].Value = parentInstance.ParentInstance.InstanceID;
                                    sqlCommand.ExecuteNonQuery();
                                }
                            }
                            //create succesful response with the collected details
                            response = new StepCollectResponse()
                            {
                                Errors = null, Result = StepResult.Next, NextStep = new StepConfiguration()
                                {
                                    StepName = nextStep.Name
                                }
                            };
                        }
                        else //the last step of the collectors
                        {
                            //Change Status and current Step
                            using (DataManager.Current.OpenConnection())
                            {
                                using (SqlCommand sqlCommand = DataManager.CreateCommand(@"UPDATE Wizards_Sessions_Data 
																			SET 
																			CurrentStepName=@CurrentStepName:NvarChar,
																			WizardStatus=@WizardStatus:Int
																			WHERE SessionID=@SessionID:Int 
																			AND ServiceInstanceID=@ServiceInstanceID:BigInt"                                                                            ))
                                {
                                    sqlCommand.Parameters["@CurrentStepName"].Value   = string.Empty;
                                    sqlCommand.Parameters["@SessionID"].Value         = sessionID;
                                    sqlCommand.Parameters["@WizardStatus"].Value      = WizardStatus.Execute;
                                    sqlCommand.Parameters["@ServiceInstanceID"].Value = parentInstance.ParentInstance.InstanceID;
                                    sqlCommand.ExecuteNonQuery();
                                }
                            }
                            response = new StepCollectResponse()
                            {
                                Errors = null, Result = StepResult.Done
                            };
                        }
                    }
                    else //error
                    {
                        response = new StepCollectResponse()
                        {
                            Result = StepResult.HasErrors, Errors = tempResponse.Errors
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write("Service not Started yet: ", ex);
                throw new WebFaultException <string>("Service not Started yet: " + ex.Message, HttpStatusCode.ServiceUnavailable);
            }
            return(response);
        }