Esempio n. 1
0
        public void TransitionContext_SetVariable_ReplacesExistingVariableValue()
        {
            // Arrange
            Switcher switcher = new Switcher
            {
                Type = OnOffWorkflow.TYPE
            };
            var context  = new TransitionContext(switcher);
            var variable = new SwitcherWorkflowVariable(true);

            context.SetVariable <SwitcherWorkflowVariable>(
                SwitcherWorkflowVariable.KEY,
                variable);

            Assert.IsTrue(context
                          .GetVariable <SwitcherWorkflowVariable>(SwitcherWorkflowVariable.KEY)
                          .CanSwitch);

            variable.CanSwitch = false;

            // Act
            context.SetVariable <SwitcherWorkflowVariable>(
                SwitcherWorkflowVariable.KEY,
                variable);

            // Assert
            Assert.IsNotNull(context);
            Assert.IsTrue(context.HasVariables);
            Assert.IsTrue(context.ContainsKey(SwitcherWorkflowVariable.KEY));
            Assert.IsFalse(context
                           .GetVariable <SwitcherWorkflowVariable>(SwitcherWorkflowVariable.KEY)
                           .CanSwitch);
        }
Esempio n. 2
0
        private bool IsCreator(TransitionContext context)
        {
            var stepper = context.GetInstance <Stepper>();

            return(stepper.Assignee == stepper.Creator &&
                   stepper.Assignee != UserContextService.SYSTEM_USER);
        }
Esempio n. 3
0
        public void TriggerResult_NewInstanceWithVariables_CreatesANewInstance()
        {
            // Arrange
            var      trigger  = "SwitchOn";
            Switcher switcher = new Switcher
            {
                Type = OnOffWorkflow.TYPE
            };
            var transitionContext = new TransitionContext(switcher);
            var variable          = new SwitcherWorkflowVariable(true);

            transitionContext.SetVariable <SwitcherWorkflowVariable>(
                SwitcherWorkflowVariable.KEY,
                variable);
            var canTrigger = true;

            // Act
            var result = new TriggerResult(trigger, transitionContext, canTrigger);

            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.CanTrigger);
            Assert.IsFalse(result.IsAborted);
            Assert.AreSame(result.TriggerName, trigger);
            Assert.IsFalse(result.HasErrors);
            Assert.AreSame(result.CurrentState, switcher.State);

            var v = result.GetVariable <SwitcherWorkflowVariable>(SwitcherWorkflowVariable.KEY);

            Assert.IsNotNull(v);
            Assert.IsTrue(v.CanSwitch);
        }
                /************************************************************************************************************************/

                /// <summary>
                /// Draws the root `property` GUI and calls
                /// <see cref="Editor.TransitionDrawer.DoPropertyGUI"/> for each of its children.
                /// </summary>
                public override void OnGUI(Rect area, SerializedProperty property, GUIContent label)
                {
                    var originalProperty = property.Copy();

                    base.OnGUI(area, property, label);

                    if (!originalProperty.isExpanded)
                    {
                        return;
                    }

                    using (TransitionContext.Get(this, property))
                    {
                        if (Context.Transition == null)
                        {
                            return;
                        }

                        var states = GatherDetails(originalProperty);

                        var indentLevel = EditorGUI.indentLevel;

                        area.yMin = area.yMax - states.GetHeight();

                        EditorGUI.indentLevel++;
                        area = EditorGUI.IndentedRect(area);

                        EditorGUI.indentLevel = 0;
                        states.DoList(area);

                        EditorGUI.indentLevel = indentLevel;

                        TryCollapseArrays();
                    }
                }
Esempio n. 5
0
        private bool BossIsApproving(TransitionContext context)
        {
            var holiday = context.GetInstance <Holiday>();

            this._logger.LogInformation($"Holiday entity in BossIsApproving: {holiday.Superior}");

            return(holiday.Superior == this._userContextService.UserName);
        }
Esempio n. 6
0
        private void ThankBossForApproving(TransitionContext context)
        {
            var holiday = context.GetInstance <Holiday>();

            this._logger.LogInformation($"Thank you very much: {holiday.Superior}!");

            holiday.Assignee = holiday.Requester;
        }
Esempio n. 7
0
 /// <summary>
 /// Returns the workflow variable from the TransitionContext.
 /// </summary>
 /// <typeparam name="TVariable"></typeparam>
 /// <param name="transitionContext"></param>
 /// <returns></returns>
 public static TVariable ReturnVariable <TVariable>(
     this TransitionContext transitionContext
     ) where TVariable : WorkflowVariableBase
 {
     return(transitionContext.GetVariable <TVariable>(
                KeyBuilder.ToKey(typeof(TVariable))
                ));
 }
Esempio n. 8
0
 private AutoTrigger GoToStep3(TransitionContext context)
 {
     return(new AutoTrigger
     {
         Trigger = GOTO3_TRIGGER,
         DueDate = SystemTime.Now().AddMinutes(2)
     });
 }
Esempio n. 9
0
        private void AssignToCreator(TransitionContext context)
        {
            var issue = context.GetInstance <Issue>();

            issue.Assignee = issue.Creator;

            this._logger.LogInformation($"Assignee: {issue.Assignee}");
        }
Esempio n. 10
0
        private void AssignToAdmin(TransitionContext context)
        {
            // because admin is the dev ;-)...
            var issue = context.GetInstance <Issue>();

            issue.Assignee = "admin";

            this._logger.LogInformation($"Assignee: {issue.Assignee}");
        }
        public override string Execute(
            TransitionContext context)
        {
            string retEvent	= ActionUtil.EVENT_ERROR;
            ReadOnlyCollection<MembershipAttribute> result = null;
            try {
            // TODO: should not be hard-coded to "users" -- has to match RequestItemName on GetUser action
                SearchResult<Account> acctResults = (SearchResult<Account>)context.Request.Items["users"];

            // TODO: what if > 1 account in list??
                if ((acctResults == null) || (acctResults.Items.Count == 0)) {
                    throw new ApplicationException("No account found in Request.Items.");
                }

                Account account = acctResults.Items[0];

                if (account == null) {
                    throw new ApplicationException("No account found in SearchResult.");
                }

                        //  get the attribute type (name) and value from the request
                string attrType = AttributeTypeName ?? context.Request[MembershipConstants.PARAM_ATTRIBUTE_TYPE];

                //  determine if the attribute specified in the request already exists in the account
                //int index = account.IndexOfAttribute(attrType, attrValue);

                //  if the attribute alread exists, delete it, else add it
                if (account.GetAttribute(attrType) != null)
                {
                    result = account.GetAttribute(attrType);
                } else {
                }

                context.Request.Items[RequestItemName] = result;
                switch (result.Count)
                {
                    case 0:
                        retEvent = ActionUtil.EVENT_FOUND_ZERO;
                        break;
                    case 1:
                        retEvent = ActionUtil.EVENT_FOUND_ONE;
                        break;
                    default:
                        retEvent = ActionUtil.EVENT_FOUND_MULTIPLE;
                        break;
                }
                //retEvent = ActionUtil.EVENT_PASS;
            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAttributeAction.Execute: ", e);
            }

            if (this.Formatter != null) {
                context.Request.Items[this.requestItemName] = this.Formatter.Format(result);
            }

            return retEvent;
        }
Esempio n. 12
0
        private void AfterTransition(TransitionContext context)
        {
            if (context.HasVariable <LightSwitcherWorkflowVariable>())
            {
                var variable = context.ReturnVariable <LightSwitcherWorkflowVariable>();

                variable.CanSwitch = !variable.CanSwitch;
            }
        }
 /// <summary>
 /// Constructs a <b>PublishException</b> for the given TransitionContext 
 /// and PublishRecord, with the specified message.
 /// </summary>
 /// <param name="context">The <b>TransitionContext</b> in which the exception occurred.</param>
 /// <param name="publishRecord">The <b>PublishRecord</b> in use at the time 
 ///			the exception occurred.</param>
 /// <param name="message">The error message to return.</param>
 public PublishException(
     TransitionContext context,
     PublishRecord publishRecord,
     string message)
     : base(message)
 {
     this.context = context;
     this.publishRecord = publishRecord;
 }
Esempio n. 14
0
        private async Task <TriggerResult> TriggerForPersistingInstance(TriggerParam param)
        {
            TriggerResult result;

            using (var transaction = this.repository.Database.BeginTransaction())
            {
                try
                {
                    Workflow workflow  = null;
                    var      execution = this.GetExecution(param.Instance.Type);
                    var      entity    = param.Instance as IWorkflowInstanceEntity;

                    await this.repository.ApplyChangesAsync(); // so entity id gets resolved!

                    workflow = await this.FindOrCreate(
                        entity.Id,
                        param.Instance.Type,
                        param.Instance.State
                        );

                    this.EnsureWorkflowVariables(workflow, param);

                    result = execution.Trigger(param);
                    if (!result.IsAborted)
                    {
                        await this.PersistWorkflow(workflow, param, result);

                        await this.repository.ApplyChangesAsync();

                        transaction.Commit();
                    }
                }
                catch (Exception ex)
                {
                    transaction.Rollback();

                    this.logger.LogError(
                        "Trigger with TriggerParameter: {TriggerParameter} failed! {Exception}",
                        LogHelper.SerializeObject(param),
                        ex
                        );

                    var transitionContext = new TransitionContext(param.Instance);
                    transitionContext.AddError(ex.ToString());

                    result = new TriggerResult(
                        param.TriggerName,
                        transitionContext,
                        false
                        );
                }
            }

            return(result);
        }
Esempio n. 15
0
        private bool CanSwitch(TransitionContext context)
        {
            if (context.HasVariable <LightSwitcherWorkflowVariable>())
            {
                var variable = context.ReturnVariable <LightSwitcherWorkflowVariable>();

                return(variable.CanSwitch);
            }

            return(true);
        }
Esempio n. 16
0
        private void GoTo5(TransitionContext context)
        {
            this.AssignToSystem(context);

            var stepper = context.GetInstance <Stepper>();

            _messageBus.PublishAsync(WorkItemMessage.Create(
                                         GOTO5_TRIGGER,
                                         stepper.Id,
                                         stepper.Type
                                         ));
        }
Esempio n. 17
0
        public void TransitionContext_GetVariable_VariableNotPresent()
        {
            // Arrange
            Switcher switcher = new Switcher
            {
                Type = OnOffWorkflow.TYPE
            };
            var context = new TransitionContext(switcher);

            // Act
            Assert.Throws <Exception>(
                () => context.GetVariable <SwitcherWorkflowVariable>(SwitcherWorkflowVariable.KEY));
        }
Esempio n. 18
0
        private void AddAprovalMessage(TransitionContext context)
        {
            var holiday = context.GetInstance <Holiday>();

            if (context.HasVariable <ApproveHolidayViewModel>())
            {
                var model = context.ReturnVariable <ApproveHolidayViewModel>();
                if (!string.IsNullOrWhiteSpace(model.Message))
                {
                    holiday.AddMessage(this._userContextService.UserName, model.Message);
                }
            }
        }
Esempio n. 19
0
        public override Transition CreateTransition(TransitionContext context)
        {
            PopularControl oldPage = context.OldContent as PopularControl;
            PopularControl newPage = context.CurrentContent as PopularControl;

            if (oldPage.DisplayPage > newPage.DisplayPage)
            {
                return(this.BackTransition.CreateTransition(context));
            }
            else
            {
                return(this.ForwardTransition.CreateTransition(context));
            }
        }
		public override Transition CreateTransition(TransitionContext context)
		{
			PopularControl oldPage = context.OldContent as PopularControl;
			PopularControl newPage = context.CurrentContent as PopularControl;

			if (oldPage.DisplayPage > newPage.DisplayPage)
			{
				return this.BackTransition.CreateTransition(context);
			}
			else
			{
				return this.ForwardTransition.CreateTransition(context);
			}
		}
Esempio n. 21
0
        private bool CanSwitch(TransitionContext context)
        {
            var switcher = context.GetInstance <Switcher>();

            if (context.ContainsKey(SwitcherWorkflowVariable.KEY))
            {
                var variable = context
                               .GetVariable <SwitcherWorkflowVariable>(SwitcherWorkflowVariable.KEY);

                return(variable.CanSwitch);
            }

            return(true);
        }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try
            {

                if ((context.Request.Items[_requestparamname] != null) &&
                   (context.Request.Items[_requestparamname] is SearchResult<Account>))
                {
                    SearchResult<Account> account = (SearchResult<Account>)context.Request.Items[_requestparamname];

                    if (account.Items.Count == 1)
                    {
                        try
                        {
                            _emailaddress = account.Items[0].GetContact(_emailcontacttype)[0].Value;
                            context.Request["email"] = _emailaddress;
                            retEvent = EVENT_SUCCESS;
                        }
                        catch (Exception excep)
                        {
                            AddErrorToRequest(context, 40004);
                            return "error";
                        }

                    }
                    else
                    {
                        AddErrorToRequest(context, 40006);
                        return "error";
                    }

                }
                else
                {
                    AddErrorToRequest(context, 40006);
                    return "error";
                }

            }
            catch (Exception e)
            {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("RetrieveUserPasswordAction", e);
            }

            return retEvent;
        }
Esempio n. 23
0
        public void LogsHandlingExitActionException()
        {
            const string StateMachineName            = "test machine";
            const States CurrentStateId              = States.A;
            var          stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var          stateMock = this.CreateState(CurrentStateId);
            var          context   = new TransitionContext <States, Events>(stateMock, new Missable <Events>(), null, null);
            var          exception = new Exception("test exception");

            this.testee.HandlingExitActionException(stateMachineInformationMock, stateMock, context, ref exception);

            this.log4Net.LogContains(
                Level.Error,
                "Exception in exit action of state A of state machine test machine: System.Exception: test exception");
        }
Esempio n. 24
0
        public void HandlingGuardException()
        {
            const string StateMachineName            = "test machine";
            const States CurrentStateId              = States.A;
            var          stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var          transitionMock              = new Mock <ITransition <States, Events> >();
            var          stateMock         = this.CreateStateMock(CurrentStateId);
            var          transitionContext = new TransitionContext <States, Events>(stateMock.Object, Events.B, null, null);
            var          exception         = new Exception("test exception");

            this.testee.HandlingGuardException(stateMachineInformationMock.Object, transitionMock.Object, transitionContext, ref exception);

            this.log4Net.LogMatch(
                Level.Error,
                "Exception in guard of transition .* of state machine test machine: System.Exception: test exception");
        }
Esempio n. 25
0
        public void LogsHandlingTransitionException()
        {
            const string StateMachineName            = "test machine";
            const States CurrentStateId              = States.A;
            var          stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var          transitionMock              = A.Fake <ITransition <States, Events> >();
            var          stateMock         = this.CreateState(CurrentStateId);
            var          transitionContext = new TransitionContext <States, Events>(stateMock, new Missable <Events>(Events.B), null, null);
            var          exception         = new Exception("test exception");

            this.testee.HandlingTransitionException(stateMachineInformationMock, transitionMock, transitionContext, ref exception);

            this.log4Net.LogMatch(
                Level.Error,
                "Exception in action of transition .* of state machine test machine: System.Exception: test exception");
        }
Esempio n. 26
0
        public void TransitionContext_GetInstance_InstanceReturned()
        {
            // Arrange
            Switcher switcher = new Switcher
            {
                Type = OnOffWorkflow.TYPE
            };
            var context = new TransitionContext(switcher);

            // Act
            var worflow = context.GetInstance <Switcher>();

            // Assert
            Assert.IsNotNull(worflow);
            Assert.AreEqual(worflow, switcher);
            Assert.AreEqual(worflow.State, switcher.State);
        }
Esempio n. 27
0
        private static bool IsCalledByRoutine(TransitionContext context, StackFrame callerStackFrame)
        {
            var callerMethodInfo = callerStackFrame.GetMethod();

            bool isCalledByRoutine;

            if (context.RoutineStateMachine != null)
            {
                isCalledByRoutine = ReferenceEquals(context.RoutineStateMachine.GetType(), callerMethodInfo.DeclaringType);
            }
            else
            {
                isCalledByRoutine = ReferenceEquals(context.RoutineMethod, callerMethodInfo);
            }

            return(isCalledByRoutine);
        }
Esempio n. 28
0
        /************************************************************************************************************************/

        /// <summary>
        /// Draws the root `property` GUI and calls <see cref="DoPropertyGUI"/> for each of its children.
        /// </summary>
        public override void OnGUI(Rect area, SerializedProperty property, GUIContent label)
        {
            InitialiseMode(property);

            using (TransitionContext.Get(this, property))
            {
                var isPreviewing = TransitionPreviewWindow.IsPreviewingCurrentProperty();
                if (isPreviewing)
                {
                    EditorGUI.DrawRect(area, new Color(0.35f, 0.5f, 1, 0.2f));
                }

                float headerHeight;
                DoHeaderGUI(area, property, label, isPreviewing, out headerHeight);
                DoChildPropertiesGUI(area, headerHeight, property);
            }
        }
Esempio n. 29
0
        private void ReAssignToRequestor(TransitionContext context)
        {
            var holiday = context.GetInstance <Holiday>();

            this._logger.LogInformation($"Reassign Holiday entity to requestor: {holiday.Requester}");

            holiday.Assignee = holiday.Requester;

            if (context.HasVariable <ApproveHolidayViewModel>())
            {
                var model = context.ReturnVariable <ApproveHolidayViewModel>();
                if (!string.IsNullOrWhiteSpace(model.Message))
                {
                    holiday.AddMessage(this._userContextService.UserName, model.Message);
                }
            }
        }
Esempio n. 30
0
        public void TransitionContext_NewInstance_CreatesANewInstance()
        {
            // Arrange
            Switcher switcher = new Switcher
            {
                Type = OnOffWorkflow.TYPE
            };

            // Act
            var context = new TransitionContext(switcher);

            // Assert
            Assert.IsNotNull(context);
            Assert.AreEqual(context.Instance, switcher);
            Assert.IsFalse(context.TransitionAborted);
            Assert.IsFalse(context.HasVariables);
            Assert.IsFalse(context.HasErrors);
        }
Esempio n. 31
0
        public override Transition CreateTransition(TransitionContext context)
        {
            WizzardPage oldPage = context.OldContent as WizzardPage;
            WizzardPage newPage = context.CurrentContent as WizzardPage;

            if (oldPage == null || newPage == null)
            {
                return(null);
            }
            else if (newPage.PageIndex > oldPage.PageIndex)
            {
                return(this.ForwardTransition.CreateTransition(context));
            }
            else
            {
                return(this.BackTransition.CreateTransition(context));
            }
        }
Esempio n. 32
0
        public ActionResult Index()
        {
            using (var session = OpenReadSession())
            {
                WorkflowContext model = new WorkflowContext
                {
                    Page       = TransitionContext.GetPage(session),
                    Transition = TransitionContext.GetTransition(session),
                    CurrentPublishingTarget = TransitionContext.GetCurrentPublishingTarget(session),
                    CurrentUser             = TransitionContext.GetCurrentUser(session),
                    ServerUrl       = _Common.ServerUrl,
                    AppBaseUrl      = TransitionContext.BaseUrl,
                    AppAssetBaseUrl = TransitionContext.AssetBaseUrl
                };

                return(View(model));
            }
        }
Esempio n. 33
0
        public void TransitionContext_AddError_TransitionHasErrors()
        {
            // Arrange
            Switcher switcher = new Switcher
            {
                Type = OnOffWorkflow.TYPE
            };
            var context = new TransitionContext(switcher);
            var error   = "Some error";

            // Act
            context.AddError(error);

            // Assert
            Assert.IsNotNull(context);
            Assert.IsFalse(context.HasVariables);
            Assert.IsTrue(context.HasErrors);
        }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try
            {

                if ((context.Request.Items[_requestparamname] != null) &&
                   (context.Request.Items[_requestparamname] is SearchResult<Account>))
                {
                    SearchResult<Account> account = (SearchResult<Account>)context.Request.Items[_requestparamname];

                    if (account.Items.Count == 1)
                    {

                            _password = account.Items[0].Password;

                            string decryptPwd = web.util.crypto.CryptoUtil.DecryptString(
                            _password,
                            MembershipConstants.ENCRYPTION_KEY,
                            MembershipConstants.INIT_VECTOR,
                            web.util.crypto.EncryptionAlgorithm.TripleDes);

                            _password = decryptPwd;

                            //context.Request.Items[_requestitemname] = _password;
                            context.Request[_requestitemname] = _password;

                            retEvent = EVENT_SUCCESS;

                    }

                }

            }
            catch (Exception e)
            {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("RetrieveUserPasswordAction", e);
            }

            return retEvent;
        }
Esempio n. 35
0
        private void AssignBoss(TransitionContext context)
        {
            var holiday = context.GetInstance <Holiday>();

            if (context.HasVariable <ApplyHolidayViewModel>())
            {
                var model = context.ReturnVariable <ApplyHolidayViewModel>();
                holiday.Assignee = holiday.Superior;
                holiday.From     = model.From;
                holiday.To       = model.To;

                if (!string.IsNullOrWhiteSpace(model.Message))
                {
                    holiday.AddMessage(this._userContextService.UserName, model.Message);
                }
            }

            this._logger.LogInformation($"Assignee: {holiday.Assignee}");
        }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try
            {
                // TODO: this should come from DAOFactory!!
                //            AccountDAO dao = AccountDAOFactory.GetAccountDAO();

                //  get the filter from the DAO
                RoleFilter filter = new RoleFilter();

                //  populate the filter from the request
                //filter.Fill(context.Request);

                //  get the account for the given username
                Dictionary<string, Role> result = RoleManager.GetInstance().GetRoles(filter);

                context.Request.Items[RequestItemName] = result;

                //  determine which event to return based on the number of
                //  accounts found
                switch (result.Count)
                {
                    case 0:
                        retEvent = EVENT_FOUND_0;
                        break;
                    case 1:
                        retEvent = EVENT_FOUND_1;
                        break;
                    default:
                        retEvent = EVENT_FOUND_MULTIPLE;
                        break;
                }
            }
            catch (Exception e)
            {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("GetUserAction", e);
            }

            return retEvent;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try
            {

                SearchResult<Account> acctResults = (SearchResult<Account>)context.Request.Items[requestUserName];

                int contactId = int.Parse(context.Request["contactvalues"]);

                if ((acctResults == null) || (acctResults.Items.Count == 0))
                {
                    throw new ApplicationException("No account found in Request.Items.");
                }

                Account account = acctResults.Items[0];

                if (account == null)
                {
                    throw new ApplicationException("No account found in SearchResult.");
                }

                try
                {

                    AccountDAO dao = AccountDAOFactory.GetAccountDAO();
                    dao.DeleteContact(account.Id, contactId);

                    retEvent = EVENT_SUCCESS;

                }
                catch (Exception) { }

            }
            catch (Exception e)
            {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("DeleteMemberContactAction:Execute", e);
            }

            return retEvent;
        }
Esempio n. 38
0
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try {

            AccountDAO dao = AccountDAOFactory.GetAccountDAO();

                    //  get the filter from the DAO
            AccountFilter filter = dao.GetFilter();

                    //  populate the filter from the request
            filter.Fill(context.Request);

            if (exactMatch)
                filter.ExactMatch = true;

                    //  get the account for the given username
            SearchResult<Account> result = dao.FindAccounts(filter);

            context.Request.Items[RequestItemName] = result;

                    //  determine which event to return based on the number of
                    //  accounts found
            switch (result.NumReturned) {
                case 0:
                    retEvent = EVENT_FOUND_0;
                    break;
                case 1:
                    retEvent = EVENT_FOUND_1;
                    break;
                default:
                    retEvent = EVENT_FOUND_MULTIPLE;
                    break;
            }
            } catch (Exception e) {
            Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("GetUserAction", e);
            }

            return retEvent;
        }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_INVALID;

            try {

                    //  make sure we got exactly 1 matching account
            if (System.Web.HttpContext.Current.Session[MembershipConstants.SESSION_USER_ACCOUNT] != null )
            {
                Account acct = (Account)System.Web.HttpContext.Current.Session[MembershipConstants.SESSION_USER_ACCOUNT];
                // update logout time

                // TODO: this should not access HttpContext directly!
                System.Web.HttpContext.Current.Session[MembershipConstants.SESSION_USER_ACCOUNT] = null;
                System.Web.HttpContext.Current.User = null;

                retEvent = EVENT_OK;
            }

            } catch (Exception e) {

                ErrorList errors = new ErrorList();
                ///TODO : fix this :
                //ErrorList errors = new ErrorList(FPErrorDictionary.GetDictionary(context.Site));
                //	create the error
                //Error error = FPErrorDictionary.GetDictionary(context.Site).getError(long.Parse(this.errorId));
                Error error = new Error();
                error.Id = long.Parse(this.errorId);
                error.Message = e.Message;
                error.Type = Error.ErrorType.FATAL;
                error.FormField = "";
                errors.Add(error);

                //  add the errors to the request to propagate back to the page
                context.Request.Items["errors"] = errors;
            }

            return retEvent;
        }
Esempio n. 40
0
        public override string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try {
            if ( context.Request[RequestItemName] != "" ){
                // redirect the currrent request
                // this isa hack but it is required.
                context.Request.Redirect(context.Request[RequestItemName]);
            }
            else {
                web.error.ErrorList eList = new web.error.ErrorList();
                eList.Add(new Error(1,"none","unable to redirect to origional request",Error.ErrorType.WARNING));
                retEvent = EVENT_ERROR;
            }
            } catch (Exception e) {
            Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("IsLoggedInAction", e);
            }

            return retEvent;
        }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try {
                    Guid accountId = Guid.NewGuid();
                    string username = context.Request[MembershipConstants.PARAM_USERNAME];
                    string reqPassword = context.Request[MembershipConstants.PARAM_PASSWORD];

                    string encryptPwd = CryptoUtil.EncryptString(
                                reqPassword,
                                MembershipConstants.ENCRYPTION_KEY,
                                MembershipConstants.INIT_VECTOR,
                                EncryptionAlgorithm.TripleDes);
                    string statusCode = accountStatus;
                    if ( context.Request[MembershipConstants.PARAM_STATUSCODE] != null ) {
                        statusCode = context.Request[MembershipConstants.PARAM_STATUSCODE];
                    }

                    Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Status("SaveUserAction: encryped password: "******"SaveUserAction:Execute:AccountDAO", e);
                    }
                    context.Request["uid"] = accountId.ToString();

            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAction:Execute", e);
            }

            return retEvent;
        }
Esempio n. 42
0
        /// <summary>
        /// Builds the <c>Action</c> associated with the state and executes it.
        /// </summary>
        /// <param name="context">The <c>TransitionContext</c> the state is being
        ///			executed in.</param>
        /// <returns>The event resulting from the execution of the associated <c>Action</c>.</returns>
        public override string Execute(
            TransitionContext context)
        {
            string result = null;
            IAction action = ActionFactory.Make(this.Action);

            //  make sure the action was created
            if (action != null) {
                //  if we need a formatter, create it
                if ((action is FormatableAction) && (this.Formatter != null)) {
                    ((FormatableAction)action).Formatter = FormatterFactory.Make(this.Formatter, context.Request);
                }

                //  copy any attributes from the state to the action
                if (Attributes != null) {
                    ReflectionUtilities.Deserialize(action, Attributes);
                }

                //  execute the action
                result = action.Execute(context);
            }

            return result;
        }
        /// <summary>
        /// Performs a transition from the given state to the start indicated by
        /// the transition defined by the state map matching the given event.
        /// </summary>
        /// <param name="startState">The state being transitioned from.</param>
        /// <param name="eventName">The event causing the transition.</param>
        /// <param name="transContext">The context of the request the transition is being
        ///			performed for.</param>
        /// <returns>A <c>string</c> containing the name of the target of the transition.
        ///			This may be a page name if the resulting state is a <c>PageState</c>,
        ///			or an action name if the resulting state is a <c>ActionState</c></returns>
        public IState DoTransition(
            IState startState,
            string eventName,
            TransitionContext transContext)
        {
            IState targetState = null;
            StateManager sm = StateManager.GetInstance();
            string evnt = eventName;

                //  get the settings from config file
            StatesConfigHandler.StatesConfig statesConfig =
            (StatesConfigHandler.StatesConfig)ConfigurationManager.GetSection(TritonConfigurationSection.SectionName + "/" + SECTION_NAME);

            do {
            try {
                if (statesConfig.ManagerTrace) {
                    TransitionSessionManager.AddEvent(transContext.Request.IP, startState.Id, evnt);
                }

                        //  get the transition for the given state and event
                Transition trans = startState.GetTransition(evnt);

                        //  if we didn't find a transition for the real event and there is
                        //  a default event defined, try for a transition for the default event
                if ((trans == null) && (statesConfig.DefaultEventName != null)) {
                    LogManager.GetCurrentClassLogger().Info(msg => msg(string.Format(
                            "No transition found for '{0}' on state {1}.  Attempting default ['{2}'].", evnt, startState.Id, statesConfig.DefaultEventName)));
                    trans = startState.GetTransition(statesConfig.DefaultEventName);
                }

                        //  make sure we found a transition matching the given event
                if (trans == null) {
                    // TODO: this should be a custom Exception type
                    throw new ApplicationException(string.Format(
                           	"No transition found: state= {0} event= {1} [{2}]",
                           	startState.Id, evnt, TransitionSessionManager.GetTrace(transContext)));
                }

                        //  get the State that is the destination of the tranistion
                targetState = sm.GetState(trans.ToState);

                if (targetState == null) {
                    // TODO: this should be a custom Exception type
                    throw new ApplicationException(string.Format(
                           	"State not found: state= {0} [{1}]",
                           	trans.ToState, TransitionSessionManager.GetTrace(transContext)));
                }

                        //  log the transition if logging is on
                if (statesConfig.LogTrace) {
                    LogManager.GetCurrentClassLogger().Debug(
                        traceMessage => traceMessage("Transition: {0} {1} -> {2} -> {3} {4}",
                                 startState.Id,
                                 string.IsNullOrEmpty(startState.Name) ? "" : "[" + startState.Name + "]",
                                 evnt,
                                 targetState.Id,
                                 string.IsNullOrEmpty(targetState.Name) ? "" : "[" + targetState.Name + "]"));
                }

                        //  set the current state that is being processed
                transContext.SetCurrentState(targetState);

                        //  handle the state
                try {
                            //  if there is a prerequisite on the state, recursively call DoTransition
                            //  for the prerequisite
                    if (targetState.HasPrerequisite) {
                        for (int p = 0; p < targetState.Prerequisite.Length; p++) {
                            LogManager.GetCurrentClassLogger().Debug(traceMessage => traceMessage(
                                    "Begin prerequisite {0}", targetState.Prerequisite[p].Name));
                            DoTransition(sm.GetState(targetState.Prerequisite[p].StartStateId), targetState.Prerequisite[p].StartEvent, transContext);
                            LogManager.GetCurrentClassLogger().Debug(traceMessage => traceMessage(
                                    "End prerequisite {0}", targetState.Prerequisite[p].Name));
                        }

                                //  need to reset the current state here since it will be the end state of the prerequisite otherwise
                        transContext.SetCurrentState(targetState);
                        // ?? what if ended on page state
                    }

                    evnt = targetState.Execute(transContext);
                } catch (Exception ex) {
                    throw new ApplicationException(string.Format("Error executing state {0}.",
                            targetState.Id), ex);
                }

                        //  the destination state becomes the start state for the next iteration
                startState = targetState;
            } catch (Exception e) {
                        //  to exit the loop if something goes wrong
                evnt = null;
                LogManager.GetCurrentClassLogger().Error(errorMessage => errorMessage(e.Message), e);

                throw;
            }

                //  if we got an event back from the execution of the state, it
                //  means continue processing states
            } while (evnt != null);

            return targetState;
        }
 public abstract string Execute(TransitionContext context);
        /// <summary>
        /// Determines if the content fulfilling the given context's request should be published.
        /// </summary>
        /// <param name="context">The context of the request the content is for.</param>
        /// <returns><b>True</b> if the content should be published, <b>false</b> if not.</returns>
        public virtual bool ShouldBePublished(
            TransitionContext context)
        {
            PublishConfigSection config = ConfigurationManager.GetSection(
                TritonConfigurationSection.SectionName + "/publishing") as PublishConfigSection;

                //  is the EndState a PublishableState and is publish set to true
            return (config.Publish && (context.EndState is PublishableState) && ((PublishableState)context.EndState).Publish);
        }
Esempio n. 46
0
 /// <summary>
 /// Carries out the actions to be performed by the state.
 /// </summary>
 /// <param name="context">The <c>TransitionContext</c> the state is being
 ///			executed in.</param>
 /// <returns>The event resulting from the execution of the state.</returns>
 public virtual string Execute(
     TransitionContext context)
 {
     return null;
 }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try {
                // TODO: should not be hard-coded to "users" -- has to match RequestItemName on GetUser action
                SearchResult<Account> acctResults = (SearchResult<Account>)context.Request.Items[requestUserName];

                // TODO: what if > 1 account in list??

                if ((acctResults == null) || (acctResults.Items.Count == 0))
                {
                    throw new ApplicationException("No account found in Request.Items.");
                }

                Account account = acctResults.Items[0];

                if (account == null)
                {
                    throw new ApplicationException("No account found in SearchResult.");
                }
                // get the address type from the request..
                // if it is not defined then use the first one available from the singleton
                string addressType = context.Request[MembershipConstants.PARAM_ADDRESS_TYPE] != null ? context.Request[MembershipConstants.PARAM_ADDRESS_TYPE] : SingletonBase<AddressType>.GetInstance().ToList()[0].Code;
                AccountDAO dao = AccountDAOFactory.GetAccountDAO(this.ConnectionType);
                AddressFilter filter = dao.GetAddressFilter();

                //determine if the address already exists
                filter.Fill(context.Request);
                SearchResult<Address> sr = dao.FindAddress(filter);
                Address addr = new Address(int.MinValue,"","","","","","","");
                if (sr.Items.Count == 1 )
                    addr = sr.Items[sr.Items.Count-1];

                if ( filter.AddressCity != "" ) {
                    addr.City = filter.AddressCity;
                }
                if ( filter.AddressPostalCode != "" ) {
                    addr.PostalCode = filter.AddressPostalCode;
                }
                if ( filter.AddressLine1 != "" ) {
                    addr.Line1 = filter.AddressLine1;
                }
                if (filter.AddressLine2 != "")
                {
                    addr.Line2 = filter.AddressLine2;
                }
                if (filter.AddressLine3 != "")
                {
                    addr.Line3 = filter.AddressLine3;
                }
                if( filter.AddressCountry != "" ) {
                    addr.Country = filter.AddressCountry;
                }
                if ( filter.AddressState != "" ) {
                    addr.State = filter.AddressState;
                }
                if (addr.Id > 0 ) {
                    // found an address we need to update
                    // TODO implement the update
                    dao.UpdateAddress(account, addressType, addr);
                }
                else {
                    // we have a new one.
                    dao.InsertAddress(account.Id, addressType, addr);
                }
                retEvent = EVENT_SUCCESS;
            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserContactAction:Execute", e);
            }

            //  TODO: GET THIS OUT OF HERE!!
            //  This is REALLY ugly -- used to get the last event fired back to the client
            //  for ajax requests
            try {
                if (context.Request is web.controller.request.WebXmlRequest) {
                    web.controller.format.Formatter formatter = web.controller.format.FormatterFactory.Make("PrimitiveValueFormatter", context.Request);

                    if (formatter != null) {
                        context.Request.Items["endevent"] = formatter.Format(retEvent);
                    }
                }
            } catch (Exception) {}

            return retEvent;
        }
Esempio n. 48
0
        public void LogsHandlingTransitionException()
        {
            const string StateMachineName = "test machine";
            const States CurrentStateId = States.A;
            var stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var transitionMock = A.Fake<ITransition<States, Events>>();
            var stateMock = this.CreateState(CurrentStateId);
            var transitionContext = new TransitionContext<States, Events>(stateMock, new Missable<Events>(Events.B), null, null);
            var exception = new Exception("test exception");

            this.testee.HandlingTransitionException(stateMachineInformationMock, transitionMock, transitionContext, ref exception);

            this.log4Net.LogMatch(
                Level.Error,
                "Exception in action of transition .* of state machine test machine: System.Exception: test exception");
        }
Esempio n. 49
0
        public void LogsHandlingExitActionException()
        {
            const string StateMachineName = "test machine";
            const States CurrentStateId = States.A;
            var stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var stateMock = this.CreateState(CurrentStateId);
            var context = new TransitionContext<States, Events>(stateMock, new Missable<Events>(), null, null);
            var exception = new Exception("test exception");

            this.testee.HandlingExitActionException(stateMachineInformationMock, stateMock, context, ref exception);

            this.log4Net.LogContains(
                Level.Error,
                "Exception in exit action of state A of state machine test machine: System.Exception: test exception");
        }
        /// <summary>
        /// Publishes the content contained in the publishParam.
        /// </summary>
        /// <param name="publishParam">Contains the content to be published.</param>
        /// <param name="context">The Context of the request the content is being published for.</param>
        /// <param name="publisher">The publisher </param>
        /// <returns></returns>
        public virtual string Publish(
            object publishParam,
            TransitionContext context,
            Publisher publisher)
        {
            string content = publishParam as string;
            string key = context.PublishKey;

            LogManager.GetCurrentClassLogger().Debug(
                traceMessage => traceMessage("PagePublisher.Publish page {0}: start page = {1}, event = {2}",
                        context.EndState.Id,
                        context.StartState.Id,
                        context.StartEvent));

            PublishRecord pubRec = publisher.GetPublishRecord(key, context, true);

            try {
                    //  make sure some other thread is not already publishing the page
            if (!pubRec.Publishing) {
                        //  flag the page as in the process of being published
                pubRec.Publishing = true;
                        //  get the key for the PublishRecord
                string filePrefix = pubRec.Key;
                        //  strip off the state ID
                        //  (should find a better way to do this so it's not so tightly coupled with
                        //  what MakeKey's implementation is
                filePrefix = filePrefix.Substring(filePrefix.IndexOf('_') + 1);

                        // replace special characters with their unicode representations.
                filePrefix = this.fileNameRegEx.Replace(filePrefix, this.fileNameEvaluator);

                        //  get the publish state -- the one we are publishing
                PublishableState publishState = (PublishableState)context.EndState;

            //				try {
            //					content = publishState.GetPublishContent(context);
            //				} catch (Exception e) {
            //					Logger.GetLogger(LOGGER).ReportInnerExceptions = true;
            //					Logger.GetLogger(LOGGER).Error("PagePublisher.Publish: ", e);
            //					throw e;
            //				}

                string fileName = publishState.BaseFileName;
                string section = publishState.Section;

                        //  build the path to the directory to publish to
                string targetPath = string.Format(@"{0}{1}/{2}", this.publishPath, publishState.Site, section);
                        //  make sure the directory exists
                IO.CreateDirectory(this.basePath + targetPath);

                        //	if the length of full path exceeds the maximum,
                        //	use hash code of filePrefix instead of filePrefix to construct tagetPath
                string tmpFullPath = string.Format(@"{0}{1}/{2}_{3}.html",
                        this.basePath, targetPath, filePrefix, fileName);
                if (tmpFullPath.Length > this.maxPathLen) {
                    filePrefix = filePrefix.GetHashCode().ToString();
                }
                        //  add the file name to the path
                targetPath = string.Format(@"{0}/{1}_{2}", targetPath, filePrefix, fileName);
                string path = this.basePath + targetPath;

                StreamWriter writer = null;
                try {
                    writer = new StreamWriter(path.ToLower(), false, Encoding.UTF8);

                            //  build comment content to append to published page
                    string append = PUBLISH_MARKER;
                            //  check config for setting to include published timestamp, and include timestamp if indicated
                    PublishConfigSection config = ConfigurationManager.GetSection(
                            TritonConfigurationSection.SectionName + "/publishing") as PublishConfigSection;
                    if (config.Settings[INCLUDE_TIMESTAMP_SETTING] != null) {
                        bool includeTimestamp;
                        if (bool.TryParse(config.Settings[INCLUDE_TIMESTAMP_SETTING].Value, out includeTimestamp) && includeTimestamp) {
                            append += " [" + DateTime.Now.ToString() + "]";
                        }
                    }

                            //  write the content received from Execute to the publish file
                    writer.Write(content + Environment.NewLine + "<!--" + append + "-->");

                } catch (Exception e) {
                    LogManager.GetCurrentClassLogger().Error(
                            errorMessage => errorMessage("PagePublisher.Publish write: "), e);
                    throw;
                } finally {
                    if (writer != null) {
                        writer.Close();
                    }
                }

                        //  make sure the relative URL starts with "/"
                if (!targetPath.StartsWith("/")) {
                    targetPath = "/" + targetPath;
                }

                pubRec.PublishedPath = targetPath;
                pubRec.LastPublished = DateTime.Now;

                LogManager.GetCurrentClassLogger().DebugFormat("Published {0} with key {1}", pubRec.PublishedPath, pubRec.Key);
            }
            } catch (Exception e) {
            LogManager.GetCurrentClassLogger().Error(
                    errorMessage => errorMessage("PagePublisher.Publish: "), e);
            content = null;
            } finally {
                    //  we never want to leave the page in a state of publishing
            pubRec.Publishing = false;
            }

            return content;
        }
Esempio n. 51
0
        /// <summary>
        /// Gets the <c>PublishRecord</c> for the target page of the given
        /// context.
        /// </summary>		
        /// <param name="key"></param>
        /// <param name="context">The <c>TransitionContext</c> to get the <c>PublishRecord</c> for.</param>
        /// <param name="publisher">The <c>ContentPublisher</c></param>
        /// <param name="addIfNotPresent">If <b>true</b> adds a new <b>PublishRecord</b> 
        ///		to the internal collection for the given context.</param>
        /// <returns>The <c>PublishRecord</c> for the target page of the given context.</returns>
        internal PublishRecord GetPublishRecord(
            string key,
            TransitionContext context,
            IContentPublisher publisher,
            bool addIfNotPresent)
        {
            PublishRecord pubRec = this.publishedPages[key];

            if ((pubRec == null) && addIfNotPresent) {
                pubRec = new PublishRecord(key,
                        context.StartState.Id,
                        context.StartEvent,
                        context.EndState.Id,
                        null,
                        null,
                        publisher.Name);
                this.publishedPages.Add(key, pubRec);
            }

            return pubRec;
        }
Esempio n. 52
0
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try {
                        //check if user is logged in, if logged in then an update, else create new user
                if (string.IsNullOrEmpty(context.Request[MembershipConstants.PARAM_UID])) {
                            //retrieve the data
                    Guid accountId = Guid.NewGuid();
                    string username = context.Request[MembershipConstants.PARAM_USERNAME];
                    string reqPassword = context.Request[MembershipConstants.PARAM_PASSWORD];

                    string encryptPwd = CryptoUtil.EncryptString(
                                reqPassword,
                                MembershipConstants.ENCRYPTION_KEY,
                                MembershipConstants.INIT_VECTOR,
                                EncryptionAlgorithm.TripleDes);

                    string statusCode = "active";

                    Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Status("SaveUserAction: encryped password: "******"uid"] = accountId.ToString();
                        retEvent = EVENT_SUCCESS;
                    } catch (Exception e) {
                        Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAction:Execute:AccountDAO", e);
                    }

                } else {
                    try {

                        Guid uid = new Guid(context.Request[MembershipConstants.PARAM_UID]);

                       string username = context.Request[MembershipConstants.PARAM_USERNAME];
                       string password = context.Request[MembershipConstants.PARAM_PASSWORD];
                       string encryptPwd = "";

                        if (password != "")
                       {
                           encryptPwd = CryptoUtil.EncryptString(
                                   password,
                                   MembershipConstants.ENCRYPTION_KEY,
                                   MembershipConstants.INIT_VECTOR,
                                   EncryptionAlgorithm.TripleDes);
                       }
                        AccountDAO dao = new MSAccountDAO(ConnectionType);
                        dao.UpdateAccount(uid, username, encryptPwd);
                        retEvent = EVENT_SUCCESS;
                    }
                    catch (Exception e) {
                        Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAction:Execute", e);
                    }

                }
            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAction:Execute", e);
            }

            #region Future Support
            /*	Guid accountId = null;

            //first find out if the account_id is in the session
            if (System.Web.HttpContext.Current.Session[Constants.SESSION_USER_ACCOUNT] != null) {
                accountId = (Guid)System.Web.HttpContext.Current.Session[Constants.SESSION_USER_ACCOUNT];
            }

            //if yes get the account and start the update of it
            //if no start creating new account

            try {
                // first check if the account already exists.
                MSAccountDAO dao = new MSAccountDAO(this.ConnectionType);
                Account oldAccount = dao.GetAccount(accountid);
                Account newAccount = MakeNewAccount(context.Request);

                if (oldAccount == null) {
                    // create the account with the dao.
                    dao.CreateAccount(newAccount.Id, newAccount.Password, newAccount.UserName, 0);
                    oldAccount = new Account(new Guid(), "", -1);
                } else {
                    // check the username and the password for
                    if (oldAccount.UserName != newAccount.UserName) {
                        // add a DAOAction to the dao to change the username

                    }
                    if (oldAccount.Password != newAccount.Password) {
                        // add a DAOAction to the dao to change the password

                    }
                }
                // process the account Attributes
                foreach (string sType in newAccount.GetAttributeTypes()) {
                    foreach (MembershipAttribute mAttr in newAccount.GetContact(sType)) {
                        // does this MembershipAttribute exist in the old account
                        foreach (MembershipAttribute oattr in oldAccount.GetContact(sType)) {
                            if (!oattr.Equals(mAttr)) {
                                // we need to create this. add the command to the DAO
                                dao.InsertAttribute(newAccount.Id, sType, mAttr.Value);
                            } else {
                                // we need to alter the existing Attribute;
                                dao.UpdateAttribute(newAccount.Id, sType, mAttr.Value);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAction", e);
            }
            */
            #endregion

            //  TODO: GET THIS OUT OF HERE!!
            //  This is REALLY ugly -- used to get the last event fired back to the client
            //  for ajax requests
            try {
                if (context.Request is web.controller.request.WebXmlRequest) {
                    web.controller.format.Formatter formatter = web.controller.format.FormatterFactory.Make("PrimitiveValueFormatter", context.Request);

                    if (formatter != null) {
                        context.Request.Items["endevent"] = formatter.Format(retEvent);
                    }
                }
            } catch (Exception) {}

            return retEvent;
        }
        /// <summary>
        /// Primary Action Method
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try
            {
                SearchResult<Account> srAccount = (SearchResult<Account>)context.Request.Items[userRequestItemName];

                Account account = (srAccount != null) ? srAccount.Items[srAccount.Items.Count - 1] : null;

                AccountStatus status = SingletonBase<AccountStatus>.GetInstance()[context.Request["status"]];

                account.Status = status;

                AccountDAO dao = AccountDAOFactory.GetAccountDAO(this.ConnectionType);

                dao.UpdateAccountStatus(account.Id, status);

                retEvent = EVENT_SUCCESS;
            }
            catch (Exception e) { }

            return retEvent;
        }
        /// <summary>
        /// Gets the publish key for the given context.
        /// </summary>
        /// <param name="context">The context to get the publish key for.</param>
        /// <returns>The publish key for the given context.</returns>
        public virtual string GetPublishKey(
            TransitionContext context)
        {
            StringBuilder keyParams = new StringBuilder();
            PublishableState state = context.StartState as PublishableState;

            //MvcTimer t = new MvcTimer();
            //t.Start();
            ArrayList parms = new ArrayList();
            parms.AddRange(context.Request.Params.AllKeys);

                //  build combined list of parameters to always exclude from the key
                //  + any defined in the state
            string excludeParams = (state.PublishExcludeParams == null)
                    ? PARAMS_TO_IGNORE
                    : PARAMS_TO_IGNORE + "," + state.PublishExcludeParams;
                //  make the list into an array, and remove them from the list to key parameters
            string[] excludes = excludeParams.Split(',');
            foreach (string p in excludes) {
            parms.Remove(p);
            }

                // sort the params in case different calls have different order
            parms.Sort();

            foreach (string parm in parms) {
            if (context.Request[parm] != null) {
                keyParams.Append(context.Request[parm] + "_");
            }
            }

                //  remove trailing "_"
            if (keyParams.Length > 1) {
            keyParams.Remove(keyParams.Length - 1, 1);
            }

            string key = string.Format("{0}_{1}_{2}", state.Id, context.StartEvent, keyParams);
            //  remove any invalid characters from the key
            //		fileNameRegEx.Replace(key, "");
            //t.Stop();
            //Logger.GetLogger(LOGGER).Config("MakeKey time: " + t.Time + " seconds");

            return key;
        }
        /// <summary>
        /// Carries out the actions required to execute the command.
        /// </summary>
        /// <param name="request">The <c>MvcRequest</c> request
        ///			that triggered the command to be executed.</param>
        public void Execute(
            MvcRequest request)
        {
            string startEvent = request[EVENT_PARAM_NAME].ToLower();

                //  get the starting start for the request
            IState startState = this.GetStartState(request);
            ContentProvider contentProvider = null;

            try {
            string content = null;
                    //  make the context for the request
            TransitionContext context = new TransitionContext(startState, startEvent, ((PageState)startState).Site, request);
                    //  make a ContentProvider for the request
            contentProvider = ContentProviderFactory.Make(context);
                    //  get a Publisher from the ContentProvider
            Publisher publisher = contentProvider.GetPublisher();

                    //  assume we need to perform the transition(s).  if published
                    //  content is sucessfully used, we'll set this to false.
            bool doTransitions = true;

                    //  make sure we got a publisher
            if (publisher != null) {
                        //  generate a publish key and remember it in the context
                context.PublishKey = publisher.MakeKey(context);

                        //  determine if we have publihsed content to fulfill this request
                        //  and if we should use it
                if (publisher.UsePublishedContent(context.PublishKey, context)) {
                            //  if so, get it
                    content = contentProvider.GetPublishedContent(context);

                            //  if there is no published content, do the transitions
                    if (content != null) {
                        doTransitions = false;
                    }
                }
            }

                    //  if we didn't use published content, we need to generate the content
                    //  by performing the transitions
            if (doTransitions) {
                //  put the TransitionContext into the request context so Page can get it
                request.Items["transitionContext"] = context;

                        //  perform the transition(s)
                StateTransitioner transitioner = new StateTransitioner();
                IState targetState = transitioner.DoTransition(startState, startEvent, context);
                        //  target state should be an EndState
                if (targetState is EndState) {
                    context.EndState = targetState;
                    request.Items["targetStateId"] = targetState.Id;
                    request.Items["targetState"] = targetState;
                } else {
            //  TODO: what if targgetState is not an EndState?
                    LogManager.GetCurrentClassLogger().Warn(
                        warn => warn("Target state {0}{1} is not an EndState.",
                                     targetState.Id,
                                     string.IsNullOrEmpty(targetState.Name) ? "" : " [" + targetState.Name + "]"));
                }

                //  save the ending state to the session and cookie
                try {
                    //HttpSessionState session = HttpContext.Current.Session;
                    if (SessionStateProvider.GetSessionState() != null) {
                        SessionStateProvider.GetSessionState()[CUR_STATE_NAME] = targetState.Id;
                    }
                }
                catch { }

                try {
                    //request.SetResponseCookie(new MvcCookie(CUR_STATE_NAME, targetState.Id.ToString()));
                }
                catch { }

                        //  determine if the content generated to fulfill the request should
                        //  be published for use by future requests
                if ((publisher != null) && publisher.ShouldBePublished(context)) {
                    content = contentProvider.RenderPublishContent(context);
            // TODO: what if "content" is not string??
            // should RenderPublishContent throw exception if no publish call wanted?
                    if (content != null) {
                        publisher.Publish(content, context);
                    }
                } else {
                    content = contentProvider.RenderContent(context);
                }
            }

            if (content != null) {
                request.WriteResponse(content, false);
            }
            } catch (ThreadAbortException) {
            //  ignore this one, since when a .aspx page is creating a new thread
            //  and killing the current thread thus throwing this exception
            } catch (Exception e) {
            LogManager.GetCurrentClassLogger().Error(
                errorMessage => errorMessage("Could not execute the command. "), e);
                    //since we cant do anything about this here, rethrow.
            throw;
            } finally {
            if (contentProvider != null) {
                contentProvider.Dispose();
            }
            }
        }
        public override string Execute(
            TransitionContext context)
        {
            string retEvent	= EVENT_FAILURE;

            try {
            // TODO: should not be hard-coded to "users" -- has to match RequestItemName on GetUser action
                SearchResult<Account> acctResults = (SearchResult<Account>)context.Request.Items[UserRequestItemName];

            // TODO: what if > 1 account in list??
                if ((acctResults == null) || (acctResults.Items.Count == 0)) {
                    throw new ApplicationException("No account found in Request.Items.");
                }

                Account account = acctResults.Items[0];

                if (account == null) {
                    throw new ApplicationException("No account found in SearchResult.");
                }

                        //  get the attribute type (name) and value from the request
                string[] attrType = context.Request[MembershipConstants.PARAM_ATTRIBUTE_TYPE].Split(',');
                string[] attrValue = context.Request[MembershipConstants.PARAM_ATTRIBUTE_VALUE].Split(',');

                if ( attrType.Length == attrValue.Length ) {
                    for ( int i = 0; i < attrType.Length; i++ ) {
                        //  determine if the attribute specified in the request already exists in the account
                        //int index = account.IndexOfAttribute(attrType[i], attrValue[i]);

                        bool allowMult = true;

                        try
                        {
                            AccountAttributeType attributeType = SingletonBase<AccountAttributeType>.GetInstance()[attrType[i]];
                            allowMult = attributeType.AllowMultiples;
                        }
                        catch (Exception exc) {
                            Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAttributeAction.Execute: ", exc);
                        }

                        // TODO: this should be obtained from the DaoFactory
                        // get the DAO
                        AccountDAO dao = AccountDAOFactory.GetAccountDAO(this.ConnectionType);

                        if (dao == null) {
                            throw new ApplicationException(string.Format("Unable to obtain DAO. [ConnectionType = '{0}']", ConnectionType));
                        }

                        if (allowMult)
                        {
                            int index = account.IndexOfAttribute(attrType[i], attrValue[i]);
                            //  if the attribute alread exists, delete it, else add it
                            if (index >= 0)
                            {
                                dao.DeleteAttribute(account.Id, attrType[i], attrValue[i]);
                            }
                            else
                            {
                                if (optionAllowInserts)
                                    dao.InsertAttribute(account.Id, attrType[i], attrValue[i]);
                            }
                        }
                        else {
                            int index = account.GetAttribute(attrType[i]).Count;
                            if (index >= 0)
                            {
                                if (optionAllowInserts)
                                {
                                    dao.DeleteMultipleAttribute(account.Id, attrType[i]);
                                    dao.InsertAttribute(account.Id, attrType[i], attrValue[i]);
                                }
                            }
                            else
                            {
                                if (optionAllowInserts)
                                    dao.InsertAttribute(account.Id, attrType[i], attrValue[i]);
                            }

                        }

                    }
                }

                retEvent = EVENT_SUCCESS;
            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAttributeAction.Execute: ", e);
            }

                    //  TODO: GET THIS OUT OF HERE!!
                    //  This is REALLY ugly -- used to get the last event fired back to the client
                    //  for ajax requests
            if (this.Formatter != null) {
                context.Request.Items[this.requestItemName] = this.Formatter.Format(retEvent);
            }

            return retEvent;
        }
Esempio n. 57
0
        /// <summary>
        /// Determines whether or not previously published content should be used
        /// to filfull the given request.
        /// </summary>
        /// <param name="key">The publish key of the request.</param>
        /// <param name="context">The <c>TransitionContext</c> to determine published
        ///		content use for.</param>
        /// <returns><c>True</c> if published content should be used, <c>false</c> if not.</returns>
        public bool UsePublishedContent(
            string key,
            TransitionContext context)
        {
            bool usePublished = IsPublished(key);

                //  if the IsPublished check passed and the contentPublisher has rules
                //  check to see if any of the rules prevent use of the published content
            if (usePublished && contentPublisher.HasRules) {
            usePublished = !contentPublisher.Rules.Any(rule => !rule.UsePublishedContent(context));
            }

            return usePublished;
        }
        public void HandlingGuardException()
        {
            const string StateMachineName = "test machine";
            const States CurrentStateId = States.A;
            var stateMachineInformationMock = this.CreateStateMachineInformation(StateMachineName, CurrentStateId);
            var transitionMock = new Mock<ITransition<States, Events>>();
            var stateMock = this.CreateStateMock(CurrentStateId);
            var transitionContext = new TransitionContext<States, Events>(stateMock.Object, Events.B, null, null);
            var exception = new Exception("test exception");

            this.testee.HandlingGuardException(stateMachineInformationMock.Object, transitionMock.Object, transitionContext, ref exception);

            this.log4Net.LogMatch(
                Level.Error,
                "Exception in guard of transition .* of state machine test machine: System.Exception: test exception");
        }
        public string Execute(
            TransitionContext context)
        {
            string retEvent = EVENT_ERROR;

            try {
                // TODO: should not be hard-coded to "users" -- has to match RequestItemName on GetUser action
                SearchResult<Account> acctResults = (SearchResult<Account>)context.Request.Items[userRequestItemName];

                // TODO: what if > 1 account in list??

                if ((acctResults == null) || (acctResults.Items.Count == 0))
                {
                    throw new ApplicationException("No account found in Request.Items.");
                }

                Account account = acctResults.Items[0];

                if (account == null)
                {
                    throw new ApplicationException("No account found in SearchResult.");
                }

                //  get the contact type (name) and value from the request
                string[] contactType = context.Request[MembershipConstants.PARAM_CONTACT_TYPE].Split(',');
                string[] contactValue = context.Request[MembershipConstants.PARAM_CONTACT_VALUE].Split(',');

                AccountDAO dao = AccountDAOFactory.GetAccountDAO(this.ConnectionType);
                //  determine if the attribute specified in the request already exists in the account

                if (contactType.Length == contactValue.Length)
                {
                    for (int i = 0; i < contactType.Length; i++)
                    {

                        if (account.GetContactTypes().Contains(contactType[i]))
                        { // we have this type of contact already
                            int index = account.GetContact(contactType[i]).IndexOf(new MembershipAttribute(contactType[i], contactValue[i]));
                            if (index == -1)
                            {
                                // create the new contact
                                dao.InsertContact(account.Id, contactType[i], contactValue[i], 1);
                            }
                            else
                            {
                                if (account.GetContact(contactType[i])[index].Value != contactValue[i])
                                {
                                    account.GetContact(contactType[i])[index].Value = contactValue[i];
                                    dao.UpdateContact(account.Id, contactType[i], contactValue[i], 1);
                                }
                            }

                        }
                        else
                        { // this contact type does not exists.
                            // consequently this contact cannot exist.
                            // so we create it.
                            account.AddContact(contactType[i], contactValue[i], 1);
                            dao.InsertContact(account.Id, contactType[i], contactValue[i], 1);
                        }

                    }
                    retEvent = EVENT_SUCCESS;
                }

                //else {
                //    // lets update the value if different
                //    int index = account.GetContact(contactType).IndexOf(new MembershipAttribute(contactType, contactValue));
                //    if ( index > 0 ) {
                //        if ( account.GetContact(contactType)[index].Value != contactValue ) {
                //            account.GetContact(contactType)[index].Value = contactValue;
                //            dao.UpdateContact(account.Id, contactType, contactValue, 1);
                //        }
                //    }
                //}

            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserContactAction:Execute", e);
            }

            #region Future Support
            /*	Guid accountId = null;

            //first find out if the account_id is in the session
            if (System.Web.HttpContext.Current.Session[Constants.SESSION_USER_ACCOUNT] != null) {
                accountId = (Guid)System.Web.HttpContext.Current.Session[Constants.SESSION_USER_ACCOUNT];
            }

            //if yes get the account and start the update of it
            //if no start creating new account

            try {
                // first check if the account already exists.
                MSAccountDAO dao = new MSAccountDAO(this.ConnectionType);
                Account oldAccount = dao.GetAccount(accountid);
                Account newAccount = MakeNewAccount(context.Request);

                if (oldAccount == null) {
                    // create the account with the dao.
                    dao.CreateAccount(newAccount.Id, newAccount.Password, newAccount.UserName, 0);
                    oldAccount = new Account(new Guid(), "", -1);
                } else {
                    // check the username and the password for
                    if (oldAccount.UserName != newAccount.UserName) {
                        // add a DAOAction to the dao to change the username

                    }
                    if (oldAccount.Password != newAccount.Password) {
                        // add a DAOAction to the dao to change the password

                    }
                }
                // process the account Attributes
                foreach (string sType in newAccount.GetAttributeTypes()) {
                    foreach (MembershipAttribute mAttr in newAccount.GetContact(sType)) {
                        // does this MembershipAttribute exist in the old account
                        foreach (MembershipAttribute oattr in oldAccount.GetContact(sType)) {
                            if (!oattr.Equals(mAttr)) {
                                // we need to create this. add the command to the DAO
                                dao.InsertAttribute(newAccount.Id, sType, mAttr.Value);
                            } else {
                                // we need to alter the existing Attribute;
                                dao.UpdateAttribute(newAccount.Id, sType, mAttr.Value);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Logger.GetLogger(MembershipConstants.ACTION_LOGGER).Error("SaveUserAction", e);
            }
            */
            #endregion

            //  TODO: GET THIS OUT OF HERE!!
            //  This is REALLY ugly -- used to get the last event fired back to the client
            //  for ajax requests
            try {
                if (context.Request is web.controller.request.WebXmlRequest) {
                    web.controller.format.Formatter formatter = web.controller.format.FormatterFactory.Make("PrimitiveValueFormatter", context.Request);

                    if (formatter != null) {
                        context.Request.Items["endevent"] = formatter.Format(retEvent);
                    }
                }
            } catch (Exception) {}

            return retEvent;
        }
Esempio n. 60
0
        /// <summary>
        /// Determines if the content fulfilling the given context's request should be published.
        /// </summary>
        /// <param name="context">The context of the request the content is for.</param>
        /// <returns><b>True</b> if the content should be published, <b>false</b> if not.</returns>
        public bool ShouldBePublished(
            TransitionContext context)
        {
            bool publish = contentPublisher.ShouldBePublished(context);

            if (publish && contentPublisher.HasRules) {
            publish = !contentPublisher.Rules.Any(rule => !rule.ShouldBePublished(context));
            }

            return publish;
        }