Esempio n. 1
0
 public RootPage()
 {
     this.InitializeComponent();
     DataContext = RootPageViewModel.Instance;
     PageNavigationService.Instance.Register(new NavigationHandler81(ContentFrame));
     Loaded += async(s, e) => await LifeCycleManager.InitOnLoaded();
 }
Esempio n. 2
0
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await LifeCycleManager.SuspensionManagerSave();

            deferral.Complete();
        }
Esempio n. 3
0
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard XAML initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Language display initialization
            InitializeLanguage();

            // Show graphics profiling information while debugging.
            if (Debugger.IsAttached)
            {
                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Prevent the screen from turning off while under the debugger by disabling
                // the application's idle detection.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
            LifeCycleManager.Start();
            SetupMockIAP();
        }
Esempio n. 4
0
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
            LifeCycleManager.Start();
        }
Esempio n. 5
0
        //public DAViewModel FindDA(int? daID)
        //{
        //    DAViewModel dAViewModel = new DAViewModel();
        //    DAManager daManager = new DAManager();
        //    var da = daManager.FindDA(daID);
        //    dAViewModel.DAID = da.daid;
        //    dAViewModel.DAName = da.daName;
        //    dAViewModel.ModuleId = (int)da.ModuleId;
        //    return dAViewModel;
        //}

        public TransactionsViewModel FindTrans(int?Transq)
        {
            try
            {
                TransactionsViewModel transvm      = new TransactionsViewModel();
                TransactionsManager   transmanager = new TransactionsManager();

                var trans1 = transmanager.FindTransaction(Transq);
                var daId1  = trans1.daId;

                LifeCycleManager LCManager = new LifeCycleManager();
                transvm.lstLifeCycle     = LCManager.GetLifeCycles(daId1);
                transvm.TransactionSeq   = trans1.TransactionSeq;
                transvm.HighLevelTxnID   = trans1.HighLevelTxnID;
                transvm.HighLevelTxnDesc = trans1.HighLevelTxnDesc;
                transvm.ReqReference     = trans1.ReqReference;
                transvm.LifeCycleID      = trans1.LifeCycleID;
                transvm.LifeCycleDesc    = transvm.lstLifeCycle.Where(e => e.LifeCycleID.Equals(trans1.LifeCycleID)).First().LifeCycleDesc;
                transvm.daId             = trans1.daId;

                //transvm.lstTransactions = (IList<tbl_Transactions>)trans1;

                return(transvm);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void LifeCycleMangerConstructorLoadsAndComposesMefPartsOnFirstCall()
        {
            {
                var container = Mock.Create <CompositionContainer>();
                Mock.Arrange(() => container.ComposeParts())
                .IgnoreInstance()
                .CallOriginal()
                .MustBeCalled();

                var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
                var lifeCycleManagerWithPrivatAccess = new PrivateObject(lifeCycleManager);
                var stateMachine =
                    (StateMachine.StateMachine)lifeCycleManagerWithPrivatAccess.GetField(STATE_MACHINE_FIELD);

                Assert.IsNotNull(stateMachine);
                Assert.AreEqual(CUSTOM_STATE_MACHINE_CONFIG, stateMachine.GetStringRepresentation());
                Mock.Assert(container);
            }
            {
                var container = Mock.Create <CompositionContainer>();
                Mock.Arrange(() => container.ComposeParts())
                .IgnoreInstance()
                .CallOriginal()
                .OccursNever();

                var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
                var lifeCycleManagerWithPrivatAccess = new PrivateObject(lifeCycleManager);
                var stateMachine = (StateMachine.StateMachine)lifeCycleManagerWithPrivatAccess.GetField(STATE_MACHINE_FIELD);

                Assert.IsNotNull(stateMachine);
                Assert.AreEqual(CUSTOM_STATE_MACHINE_CONFIG, stateMachine.GetStringRepresentation());
                Mock.Assert(container);
            }
        }
Esempio n. 7
0
        private async void InitPimp()
        {
            await LifeCycleManager.Init();

            Initializer.Init();
            await LifeCycleManager.Start();
        }
Esempio n. 8
0
 public LifeCycles()
 {
     InitializeComponent();
     InitYears();
     numerologyObject = InitNumerologyObject();
     openFileDialog1.InitialDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CUSTOMER_FOLDER_NAME);
     manager = new LifeCycleManager();
     manager.Init();
 }
Esempio n. 9
0
        // PUT: api/Utilities.svc/LifeCycles(5)
        public async Task <IHttpActionResult> Put([FromODataUri] String key, LifeCycle lifeCycle)
        {
            var declaringType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            var fn            = String.Format("{0}:{1}",
                                              declaringType.Namespace,
                                              declaringType.Name);

            if (!ModelState.IsValid)
            {
                Debug.WriteLine("Entity to be changed by LifeCycleManager with id '{0}' has invalid ModelState.", key);
                return(BadRequest(ModelState));
            }

            if (key != lifeCycle.Id)
            {
                return(BadRequest());
            }

            try
            {
                Debug.WriteLine(fn);

                var identity = CurrentUserDataProvider.GetIdentity(TenantId);

                var permissionId = CreatePermissionId("CanUpdate");
                if (!identity.Permissions.Contains(permissionId))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }

                var entityUri        = new Uri(key);
                var entity           = LoadEntity(new DefaultAuthenticationProvider(), entityUri);
                var lifeCycleManager = new LifeCycleManager(new DefaultAuthenticationProvider(), ExtractTypeFromUriString(key));
                lifeCycleManager.RequestStateChange(entityUri, entity, lifeCycle.Condition, identity.Tid);

                return(Ok());
            }
            catch (UriFormatException e)
            {
                return(BadRequest("Invalid Id - Id has to be a valid URI"));
            }
            catch (HttpRequestException e)
            {
                return(BadRequest("Loading entity from passed Uri failed (Either not found or not authorized)"));
            }
            catch (InvalidOperationException e)
            {
                return(BadRequest(String.Format("Changing state with provided condition: '{0}' not possible", lifeCycle.Condition)));
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", e.Source, e.Message, e.StackTrace));
                throw;
            }
        }
Esempio n. 10
0
        protected virtual async Task OnNavigatedToAsync()
        {
            if (DataContext == null)
            {
                DataContext = AppModel;
            }
            await LifeCycleManager.Init();

            await LoadMusicItems();
            await PrepareSelectedPivot();
        }
        public void OnDeclineCallbackForPostCalloutRevertsActionSetsJobToCanceledAndUnlocksEntity()
        {
            Mock.Arrange(() => _entityController.LoadEntity(SAMPLE_ENTITY_URI))
            .IgnoreInstance()
            .Returns(UPDATED_ENTITY)
            .MustBeCalled();

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, SAMPLE_ENTITY))
            .IgnoreInstance()
            .OccursOnce();

            Job updatedJob = null;

            Mock.Arrange(() => _coreService.Jobs)
            .IgnoreInstance()
            .ReturnsCollection(new List <Job>(new List <Job> {
                CreateJob(SAMPLE_ENTITY_URI.ToString(), false)
            }))
            .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .DoInstead((Job j) => { updatedJob = j; })
            .OccursOnce();

            Mock.Arrange(() => _coreService.SaveChanges())
            .IgnoreInstance()
            .Occurs(2);

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);

            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                stateChangeLockToBeDeleted
            }))
            .InSequence()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
            .IgnoreInstance()
            .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            lifeCycleManager.OnDeclineCallback(CreateJob(SAMPLE_ENTITY_URI.ToString(), false));

            Assert.AreEqual(JobStateEnum.Canceled.ToString(), updatedJob.State);

            Mock.Assert(_coreService);
            Mock.Assert(_entityController);
        }
 // Start is called before the first frame update
 void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
         // DontDestroyOnLoad(this);
     }
     //else
     //{
     //    Destroy(this.gameObject);
     //}
 }
Esempio n. 13
0
 public IList <tbl_LifeCycle> GetLifeCycle(TransactionsViewModel TransVM)
 {
     try
     {
         LifeCycleManager lifeCycleManager = new LifeCycleManager();
         TransVM.lstLifeCycle = lifeCycleManager.GetLifeCycles(daId);
         return(TransVM.lstLifeCycle);
     }
     catch (Exception)
     {
         throw;
     }
 }
        public void LifeCycleManagerConstructorInitializesEntityController()
        {
            Mock.Arrange(() => _stateMachineConfigLoader.LoadConfiguration(ENTITY_TYPE))
            .IgnoreInstance()
            .Returns(CUSTOM_STATE_MACHINE_CONFIG)
            .MustBeCalled();

            var           lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            PrivateObject lifeCycleManagerWithPrivateAccess = new PrivateObject(lifeCycleManager);
            var           entityController = (EntityController)lifeCycleManagerWithPrivateAccess.GetField(ENTITY_CONTROLLER_FIELD);

            Assert.IsNotNull(entityController);
            Mock.Assert(_stateMachineConfigLoader);
        }
Esempio n. 15
0
        public LifeCyclesViewModel GetTransactionsLifecycle(int?designAccelaratorID)
        {
            try
            {
                LifeCyclesViewModel lifecyclesviewmodel = new LifeCyclesViewModel();
                LifeCycleManager    lifecycleManager    = new LifeCycleManager();
                lifecyclesviewmodel.lstLifeCycles = lifecycleManager.GetLifeCycles(designAccelaratorID);

                return(lifecyclesviewmodel);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void LifeCycleManagerConstructorInitializesStateMachineWithDefaultConfigurationIfNoConfigurationDefinedExplicit()
        {
            Mock.Arrange(() => _stateMachineConfigLoader.LoadConfiguration(ENTITY_TYPE))
            .IgnoreInstance()
            .Returns((String)null)
            .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            var lifeCycleManagerWithPrivateAccess = new PrivateObject(lifeCycleManager);
            var stateMachine = (StateMachine.StateMachine)lifeCycleManagerWithPrivateAccess.GetField(STATE_MACHINE_FIELD);

            Assert.IsNotNull(stateMachine);
            Assert.AreEqual(new StateMachine.StateMachine().GetStringRepresentation(), stateMachine.GetStringRepresentation());
            Mock.Assert(_stateMachineConfigLoader);
        }
        public void LifeCycleManagerConstructorInitializesStateMachineWithLoadedConfigurationIfAvailable()
        {
            Mock.Arrange(() => _stateMachineConfigLoader.LoadConfiguration(ENTITY_TYPE))
            .IgnoreInstance()
            .Returns(CUSTOM_STATE_MACHINE_CONFIG)
            .MustBeCalled();

            var           lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            PrivateObject lifecycleManagerWithPrivateAccess = new PrivateObject(lifeCycleManager);
            var           stateMachine = (StateMachine.StateMachine)lifecycleManagerWithPrivateAccess.GetField(STATE_MACHINE_FIELD);

            Assert.IsNotNull(stateMachine);
            Assert.AreEqual(CUSTOM_STATE_MACHINE_CONFIG, stateMachine.GetStringRepresentation());
            Mock.Assert(_stateMachineConfigLoader);
        }
        public void RequestStateChangeForLockedEntityThrowsInvalidOperationException()
        {
            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                CreateStateChangeLock(SAMPLE_ENTITY_URI)
            }))
            .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            ThrowsAssert.Throws <InvalidOperationException>(() => lifeCycleManager.
                                                            RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID));
            Mock.Assert(_coreService);
        }
Esempio n. 19
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
//#if DEBUG
//            // Show graphics profiling information while debugging.
//            if(System.Diagnostics.Debugger.IsAttached) {
//                // Display the current frame rate counters
//                this.DebugSettings.EnableFrameRateCounter = true;
//            }
//#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active

            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // defined in OldStyles.xaml
                rootFrame.Style = Resources["MediaElementRootFrameStyle"] as Style;
                //Associates the frame with a SuspensionManager key
                LifeCycleManager.SuspensionManagerRegister(rootFrame, "AppFrame");
                // Set the default language
                rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    await LifeCycleManager.SuspensionManagerRestore();
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(startPage, e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
Esempio n. 20
0
        public LifeCyclesViewModel FindLifeCycles(int?lifeCycleID)
        {
            try
            {
                LifeCyclesViewModel lifecyclevm      = new LifeCyclesViewModel();
                LifeCycleManager    lifecycleManager = new LifeCycleManager();
                var lifecycle = lifecycleManager.FindLifeCycles(lifeCycleID);
                lifecyclevm.daid          = lifecycle.daId;
                lifecyclevm.LifeCycleID   = lifecycle.LifeCycleID;
                lifecyclevm.LifeCycleDesc = lifecycle.LifeCycleDesc;

                return(lifecyclevm);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 21
0
        public void AddLifeCycle(LifeCyclesViewModel lifecyclesviewmodel)
        {
            try
            {
                tbl_LifeCycle tbllifecycle = new tbl_LifeCycle();

                tbllifecycle.LifeCycleDesc = lifecyclesviewmodel.LifeCycleDesc;
                tbllifecycle.daId          = lifecyclesviewmodel.daid;
                tbllifecycle.EntityState   = DA.DomainModel.EntityState.Added;

                LifeCycleManager lifecycleManager = new LifeCycleManager();
                lifecycleManager.AddLifeCycle(tbllifecycle);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 22
0
        public async Task <IHttpActionResult> Decline([FromODataUri] String token, ODataActionParameters parameters)
        {
            var declaringType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            var fn            = String.Format("{0}:{1}",
                                              declaringType.Namespace,
                                              declaringType.Name);

            try
            {
                Debug.WriteLine(fn);
                var identity = CurrentUserDataProvider.GetIdentity(TenantId);

                var permissionId = CreatePermissionId("CanDecline");
                if (!identity.Permissions.Contains(permissionId))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }

                var job = _coreService.Jobs.Where(j => token == j.Token &&
                                                  CALLOUT_JOB_TYPE == j.Type &&
                                                  j.State == JobStateEnum.Running.ToString())
                          .SingleOrDefault();

                if (null == job)
                {
                    return(StatusCode(HttpStatusCode.NotFound));
                }

                var calloutDefinition = JsonConvert.DeserializeObject <CalloutData>(job.Parameters);
                var lifeCycleManager  = new LifeCycleManager(new DefaultAuthenticationProvider(), calloutDefinition.EntityType);
                lifeCycleManager.OnDeclineCallback(job);

                return(Ok());
            }
            catch (InvalidOperationException e)
            {
                return(BadRequest(String.Format("Decline job with token: '{0} not possible", token)));
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", e.Source, e.Message, e.StackTrace));
                throw;
            }
        }
Esempio n. 23
0
        public async Task <IHttpActionResult> Cancel([FromODataUri] String key, ODataActionParameters parameters)
        {
            var declaringType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            var fn            = String.Format("{0}:{1}",
                                              declaringType.Namespace,
                                              declaringType.Name);

            try
            {
                Debug.WriteLine(fn);

                var identity = CurrentUserDataProvider.GetIdentity(TenantId);

                var permissionId = CreatePermissionId("CanCancel");
                if (!identity.Permissions.Contains(permissionId))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }

                var entityUri        = new Uri(key);
                var entity           = LoadEntity(new DefaultAuthenticationProvider(), entityUri);
                var lifeCycleManager = new LifeCycleManager(new DefaultAuthenticationProvider(), ExtractTypeFromUriString(key));
                lifeCycleManager.Cancel(entityUri, entity, identity.Tid);

                return(Ok());
            }
            catch (UriFormatException e)
            {
                return(BadRequest("Invalid id (Id should be a valid URI)"));
            }
            catch (HttpRequestException e)
            {
                return(BadRequest("Loading entity from passed Uri failed (Either not found or not authorized)"));
            }
            catch (InvalidOperationException e)
            {
                return(BadRequest("Changing state with 'Cancel' condition not possible"));
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", e.Source, e.Message, e.StackTrace));
                throw;
            }
        }
Esempio n. 24
0
        public TransactionsViewModel GetTransactions(int?daId)
        {
            try
            {
                TransactionsViewModel transviewmodel = new TransactionsViewModel();
                TransactionsManager   transmanager   = new TransactionsManager();
                LifeCycleManager      LCManager      = new LifeCycleManager();

                transviewmodel.lstLifeCycle = LCManager.GetLifeCycles(daId);

                transviewmodel.lstTransactions = transmanager.GetAllTransactions(daId);

                return(transviewmodel);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 25
0
        public bool DeleteLifeCycle(LifeCyclesViewModel lifecyclesviewmodel)
        {
            try
            {
                tbl_LifeCycle tbllifecycle = new tbl_LifeCycle();

                tbllifecycle.LifeCycleID = lifecyclesviewmodel.LifeCycleID;
                tbllifecycle.EntityState = DA.DomainModel.EntityState.Deleted;

                LifeCycleManager lifecycleManager = new LifeCycleManager();
                lifecycleManager.DeleteLifeCycle(tbllifecycle);

                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // defined in AppResDict.xaml
                rootFrame.Style = Resources["MediaElementRootFrameStyle"] as Style;
                LifeCycleManager.SuspensionManagerRegister(rootFrame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    await LifeCycleManager.SuspensionManagerRestore();
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(startPage, args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            if (args.Kind == ActivationKind.Launch)
            {
                InitSettingsCharm();
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
        public void OnAllowCallbackForPreCalloutRevertsTransactionAndThrowsInvalidOperationExceptionIfPostCalloutFails()
        {
            Job createdJob = null;
            Job updatedJob = null;

            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
            .Returns("Administrator")
            .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
            .IgnoreInstance()
            .ReturnsCollection(new List <Job>(new List <Job> {
                CreateJob(SAMPLE_ENTITY_URI.ToString())
            }))
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _entityController.LoadEntity(SAMPLE_ENTITY_URI))
            .IgnoreInstance()
            .Returns(SAMPLE_ENTITY)
            .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
            .Returns(_windowsIdentity)
            .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
            .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
            .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
            .IgnoreInstance()
            .ReturnsCollection(new List <CalloutDefinition>(new List <CalloutDefinition>
            {
                CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(),
                                        Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
            }))
            .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
            .IgnoreInstance()
            .Occurs(4);

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, UPDATED_ENTITY))
            .IgnoreInstance()
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .DoInstead((Job j) => { createdJob = j; })
            .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny <CalloutData>()))
            .Throws <HttpRequestException>()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
            .IgnoreInstance()
            .ReturnsCollection(new List <Job>(new List <Job> {
                CreateJob(SAMPLE_ENTITY_URI.ToString(), false)
            }))
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .DoInstead((Job j) => { updatedJob = j; })
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, SAMPLE_ENTITY))
            .IgnoreInstance()
            .OccursOnce();

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);

            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                stateChangeLockToBeDeleted
            }))
            .InSequence()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
            .IgnoreInstance()
            .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            lifeCycleManager._calloutExecutor = _calloutExecutor;
            ThrowsAssert.Throws <InvalidOperationException>(() => lifeCycleManager.OnAllowCallback(CreateJob(SAMPLE_ENTITY_URI.ToString())));

            Assert.AreEqual(JobStateEnum.Failed.ToString(), updatedJob.State);

            Assert.AreEqual(EXPECTED_POST_CALLOUT_DATA, createdJob.Parameters);
            Assert.AreEqual(SAMPLE_ENTITY_URI.ToString(), createdJob.ReferencedItemId);
            Assert.AreEqual(JobStateEnum.Running.ToString(), createdJob.State);
            Assert.AreEqual(CALLOUT_JOB_TYPE, createdJob.Type);
            Assert.AreEqual(TENANT_ID, createdJob.TenantId);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(_entityController);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
            Mock.Assert(() => HttpContext.Current.User.Identity);
            Mock.Assert(CredentialCache.DefaultCredentials);
            Mock.Assert(_windowsIdentity);
        }
        public void RequestStateChangeForNonLockedEntityRevertsTransactionAndThrowsInvalidOperationExceptionIfPreCalloutFails()
        {
            Job updatedJob = null;

            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
            .Returns("Administrator")
            .MustBeCalled();

            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                CreateStateChangeLock(SAMPLE_ENTITY_URI_2)
            }))
            .InSequence()
            .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
            .Returns(_windowsIdentity)
            .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
            .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
            .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
            .IgnoreInstance()
            .ReturnsCollection(new List <CalloutDefinition>(new List <CalloutDefinition>
            {
                CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(),
                                        Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString())
            }))
            .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToStateChangeLocks(Arg.IsAny <StateChangeLock>()))
            .IgnoreInstance()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
            .IgnoreInstance()
            .Occurs(4);

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny <CalloutData>()))
            .Throws <HttpRequestException>()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
            .IgnoreInstance()
            .ReturnsCollection(new List <Job>(new List <Job> {
                CreateJob(SAMPLE_ENTITY_URI.ToString())
            }))
            .MustBeCalled();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .DoInstead((Job j) => { updatedJob = j; })
            .MustBeCalled();

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);

            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                stateChangeLockToBeDeleted
            }))
            .InSequence()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
            .IgnoreInstance()
            .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            lifeCycleManager._calloutExecutor = _calloutExecutor;
            ThrowsAssert.Throws <InvalidOperationException>(() => lifeCycleManager.
                                                            RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID));

            Assert.AreEqual(JobStateEnum.Failed.ToString(), updatedJob.State);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
            Mock.Assert(() => HttpContext.Current.User.Identity);
            Mock.Assert(CredentialCache.DefaultCredentials);
            Mock.Assert(_windowsIdentity);
        }
        public void RequestStateChangeForNonLockedEntityWithoutPreCalloutDefinitionChangesStateAndExecutesPostCallout()
        {
            Job createdJob = null;

            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
            .Returns("Administrator")
            .MustBeCalled();

            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                CreateStateChangeLock(SAMPLE_ENTITY_URI_2)
            }))
            .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
            .Returns(_windowsIdentity)
            .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
            .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
            .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
            .IgnoreInstance()
            .ReturnsCollection(new List <CalloutDefinition>(new List <CalloutDefinition>
            {
                CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(),
                                        Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
            }))
            .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToStateChangeLocks(Arg.IsAny <StateChangeLock>()))
            .IgnoreInstance()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
            .IgnoreInstance()
            .MustBeCalled();

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, UPDATED_ENTITY))
            .IgnoreInstance()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .DoInstead((Job j) => { createdJob = j; })
            .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
            .IgnoreInstance()
            .ReturnsCollection(new List <Job>(new List <Job> {
                CreateJob(SAMPLE_ENTITY_URI.ToString())
            }))
            .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny <CalloutData>()))
            .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            lifeCycleManager._calloutExecutor = _calloutExecutor;
            lifeCycleManager.RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID);

            Assert.AreEqual(EXPECTED_POST_CALLOUT_DATA, createdJob.Parameters);
            Assert.AreEqual(SAMPLE_ENTITY_URI.ToString(), createdJob.ReferencedItemId);
            Assert.AreEqual(JobStateEnum.Running.ToString(), createdJob.State);
            Assert.AreEqual(CALLOUT_JOB_TYPE, createdJob.Type);
            Assert.AreEqual(TENANT_ID, createdJob.TenantId);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(_entityController);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
        }
        public void OnAllowCallbackForPreCalloutRevertsTransactionAndThrowsInvalidOperationExceptionIfChangingStateFails()
        {
            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job> { CreateJob(SAMPLE_ENTITY_URI.ToString()) }))
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _entityController.LoadEntity(SAMPLE_ENTITY_URI))
                .IgnoreInstance()
                .Returns(UPDATED_ENTITY)
                .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
                .IgnoreInstance()
                .ReturnsCollection(new List<CalloutDefinition>(new List<CalloutDefinition>
                {
                    CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(), 
                    Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
                }))
                .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
                .IgnoreInstance()
                .Occurs(3);

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, UPDATED_ENTITY))
                .IgnoreInstance()
                .Throws<HttpRequestException>()
                .OccursOnce();

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);
            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    stateChangeLockToBeDeleted
                }))
                .InSequence()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
                .IgnoreInstance()
                .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            lifeCycleManager._calloutExecutor = _calloutExecutor;
            ThrowsAssert.Throws<InvalidOperationException>(() => lifeCycleManager.OnAllowCallback(CreateJob(SAMPLE_ENTITY_URI.ToString())));

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(_entityController);
        }
        public void OnAllowCallbackForPreCalloutRevertsTransactionAndThrowsInvalidOperationExceptionIfPostCalloutFails()
        {
            Job createdJob = null;
            Job updatedJob = null;
            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
                .Returns("Administrator")
                .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job> { CreateJob(SAMPLE_ENTITY_URI.ToString()) }))
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _entityController.LoadEntity(SAMPLE_ENTITY_URI))
                .IgnoreInstance()
                .Returns(SAMPLE_ENTITY)
                .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
                .Returns(_windowsIdentity)
                .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
                .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
                .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
                .IgnoreInstance()
                .ReturnsCollection(new List<CalloutDefinition>(new List<CalloutDefinition>
                {
                    CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(), 
                    Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
                }))
                .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
                .IgnoreInstance()
                .Occurs(4);

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, UPDATED_ENTITY))
                .IgnoreInstance()
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .DoInstead((Job j) => { createdJob = j; })
                .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny<CalloutData>()))
                .Throws<HttpRequestException>()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job> { CreateJob(SAMPLE_ENTITY_URI.ToString(), false) }))
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .DoInstead((Job j) => { updatedJob = j; })
                .InSequence()
                .OccursOnce();

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, SAMPLE_ENTITY))
                .IgnoreInstance()
                .OccursOnce();

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);
            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    stateChangeLockToBeDeleted
                }))
                .InSequence()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
                .IgnoreInstance()
                .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            lifeCycleManager._calloutExecutor = _calloutExecutor;
            ThrowsAssert.Throws<InvalidOperationException>(() => lifeCycleManager.OnAllowCallback(CreateJob(SAMPLE_ENTITY_URI.ToString())));

            Assert.AreEqual(JobStateEnum.Failed.ToString(), updatedJob.State);

            Assert.AreEqual(EXPECTED_POST_CALLOUT_DATA, createdJob.Parameters);
            Assert.AreEqual(SAMPLE_ENTITY_URI.ToString(), createdJob.ReferencedItemId);
            Assert.AreEqual(JobStateEnum.Running.ToString(), createdJob.State);
            Assert.AreEqual(CALLOUT_JOB_TYPE, createdJob.Type);
            Assert.AreEqual(TENANT_ID, createdJob.TenantId);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(_entityController);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
            Mock.Assert(() => HttpContext.Current.User.Identity);
            Mock.Assert(CredentialCache.DefaultCredentials);
            Mock.Assert(_windowsIdentity);
        }
        public void RequestStateChangeForNonLockedEntityWithoutPreCalloutDefinitionChangesStateAndExecutesPostCallout()
        {
            Job createdJob = null;
            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
                .Returns("Administrator")
                .MustBeCalled();

            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    CreateStateChangeLock(SAMPLE_ENTITY_URI_2)
                }))
                .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
                .Returns(_windowsIdentity)
                .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
                .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
                .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
                .IgnoreInstance()
                .ReturnsCollection(new List<CalloutDefinition>(new List<CalloutDefinition>
                {
                    CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(), 
                    Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
                }))
                .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToStateChangeLocks(Arg.IsAny<StateChangeLock>()))
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, UPDATED_ENTITY))
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .DoInstead((Job j) => { createdJob = j; })
                .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job> { CreateJob(SAMPLE_ENTITY_URI.ToString()) }))
                .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny<CalloutData>()))
                .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            lifeCycleManager._calloutExecutor = _calloutExecutor;
            lifeCycleManager.RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID);

            Assert.AreEqual(EXPECTED_POST_CALLOUT_DATA, createdJob.Parameters);
            Assert.AreEqual(SAMPLE_ENTITY_URI.ToString(), createdJob.ReferencedItemId);
            Assert.AreEqual(JobStateEnum.Running.ToString(), createdJob.State);
            Assert.AreEqual(CALLOUT_JOB_TYPE, createdJob.Type);
            Assert.AreEqual(TENANT_ID, createdJob.TenantId);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(_entityController);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
        }
        public void OnDeclineCallbackForPostCalloutRevertsActionSetsJobToCanceledAndUnlocksEntity()
        {
            Mock.Arrange(() => _entityController.LoadEntity(SAMPLE_ENTITY_URI))
                .IgnoreInstance()
                .Returns(UPDATED_ENTITY)
                .MustBeCalled();

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, SAMPLE_ENTITY))
                .IgnoreInstance()
                .OccursOnce();

            Job updatedJob = null;
            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job> { CreateJob(SAMPLE_ENTITY_URI.ToString(), false) }))
                .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .DoInstead((Job j) => { updatedJob = j; })
                .OccursOnce();

            Mock.Arrange(() => _coreService.SaveChanges())
                .IgnoreInstance()
                .Occurs(2);

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);
            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    stateChangeLockToBeDeleted
                }))
                .InSequence()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
                .IgnoreInstance()
                .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            lifeCycleManager.OnDeclineCallback(CreateJob(SAMPLE_ENTITY_URI.ToString(), false));

            Assert.AreEqual(JobStateEnum.Canceled.ToString(), updatedJob.State);

            Mock.Assert(_coreService);
            Mock.Assert(_entityController);
        }
        public async Task<IHttpActionResult> Decline([FromODataUri] String token, ODataActionParameters parameters)
        {
            var declaringType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            var fn = String.Format("{0}:{1}",
                declaringType.Namespace,
                declaringType.Name);

            try
            {
                Debug.WriteLine(fn);
                var identity = CurrentUserDataProvider.GetIdentity(TenantId);

                var permissionId = CreatePermissionId("CanDecline");
                if (!identity.Permissions.Contains(permissionId))
                {
                    return StatusCode(HttpStatusCode.Forbidden);
                }

                var job = _coreService.Jobs.Where(j => token == j.Token && 
                    CALLOUT_JOB_TYPE == j.Type &&
                    j.State == JobStateEnum.Running.ToString())
                    .SingleOrDefault();

                if (null == job)
                {
                    return StatusCode(HttpStatusCode.NotFound);
                }

                var calloutDefinition = JsonConvert.DeserializeObject<CalloutData>(job.Parameters);
                var lifeCycleManager = new LifeCycleManager(new DefaultAuthenticationProvider(), calloutDefinition.EntityType);
                lifeCycleManager.OnDeclineCallback(job);

                return Ok();
            }
            catch (InvalidOperationException e)
            {
                return BadRequest(String.Format("Decline job with token: '{0} not possible", token));
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", e.Source, e.Message, e.StackTrace));
                throw;
            }
        }
        public void RequestStateChangeForLockedEntityThrowsInvalidOperationException()
        {
            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    CreateStateChangeLock(SAMPLE_ENTITY_URI)
                } ))
                .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            ThrowsAssert.Throws<InvalidOperationException>(() => lifeCycleManager.
                RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID));
            Mock.Assert(_coreService);
        }
        public async Task<IHttpActionResult> Patch([FromODataUri] String key, Delta<LifeCycle> delta)
        {
            var declaringType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            var fn = String.Format("{0}:{1}",
                declaringType.Namespace,
                declaringType.Name);

            if (!ModelState.IsValid)
            {
                Debug.WriteLine("Entity to be changed by LifeCycleManager with id '{0}' has invalid ModelState.", key);
                return BadRequest(ModelState);
            }

            try
            {
                Debug.WriteLine(fn);

                var identity = CurrentUserDataProvider.GetIdentity(TenantId);

                var permissionId = CreatePermissionId("CanUpdate");
                if (!identity.Permissions.Contains(permissionId))
                {
                    return StatusCode(HttpStatusCode.Forbidden);
                }

                var entityUri = new Uri(key);
                var entity = LoadEntity(new DefaultAuthenticationProvider(), entityUri);
                var lifeCycleManager = new LifeCycleManager(new DefaultAuthenticationProvider(), ExtractTypeFromUriString(key));
                lifeCycleManager.RequestStateChange(entityUri, entity, delta.GetEntity().Condition, identity.Tid);

                return Ok();
            }
            catch (UriFormatException e)
            {
                return BadRequest("Invalid Id - Id has to be a valid URI");
            }
            catch (HttpRequestException e)
            {
                return BadRequest("Loading entity from passed Uri failed (Either not found or not authorized)");
            }
            catch (InvalidOperationException e)
            {
                return BadRequest(String.Format("Chaning state with provided condition: '{0}' not possible", delta.GetEntity().Condition));
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", e.Source, e.Message, e.StackTrace));
                throw;
            }
        }
        public async Task<IHttpActionResult> Cancel([FromODataUri] String key, ODataActionParameters parameters)
        {
            var declaringType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            var fn = String.Format("{0}:{1}",
                declaringType.Namespace,
                declaringType.Name);

            try
            {
                Debug.WriteLine(fn);

                var identity = CurrentUserDataProvider.GetIdentity(TenantId);

                var permissionId = CreatePermissionId("CanCancel");
                if (!identity.Permissions.Contains(permissionId))
                {
                    return StatusCode(HttpStatusCode.Forbidden);
                }

                var entityUri = new Uri(key);
                var entity = LoadEntity(new DefaultAuthenticationProvider(), entityUri);
                var lifeCycleManager = new LifeCycleManager(new DefaultAuthenticationProvider(), ExtractTypeFromUriString(key));
                lifeCycleManager.Cancel(entityUri, entity, identity.Tid);

                return Ok();
            }
            catch (UriFormatException e)
            {
                return BadRequest("Invalid id (Id should be a valid URI)");
            }
            catch (HttpRequestException e)
            {
                return BadRequest("Loading entity from passed Uri failed (Either not found or not authorized)");
            }
            catch (InvalidOperationException e)
            {
                return BadRequest("Changing state with 'Cancel' condition not possible");
            }
            catch (Exception e)
            {
                Debug.WriteLine(String.Format("{0}: {1}\r\n{2}", e.Source, e.Message, e.StackTrace));
                throw;
            }
        }
        public void LifeCycleManagerConstructorInitializesEntityController()
        {
            Mock.Arrange(() => _stateMachineConfigLoader.LoadConfiguration(ENTITY_TYPE))
                .IgnoreInstance()
                .Returns(CUSTOM_STATE_MACHINE_CONFIG)
                .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            PrivateObject lifeCycleManagerWithPrivateAccess = new PrivateObject(lifeCycleManager);
            var entityController = (EntityController)lifeCycleManagerWithPrivateAccess.GetField(ENTITY_CONTROLLER_FIELD);
            
            Assert.IsNotNull(entityController);
            Mock.Assert(_stateMachineConfigLoader);
        }
        public void LifeCycleManagerConstructorInitializesStateMachineWithLoadedConfigurationIfAvailable()
        {
            Mock.Arrange(() => _stateMachineConfigLoader.LoadConfiguration(ENTITY_TYPE))
                .IgnoreInstance()
                .Returns(CUSTOM_STATE_MACHINE_CONFIG)
                .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            PrivateObject lifecycleManagerWithPrivateAccess = new PrivateObject(lifeCycleManager);
            var stateMachine = (StateMachine.StateMachine)lifecycleManagerWithPrivateAccess.GetField(STATE_MACHINE_FIELD);

            Assert.IsNotNull(stateMachine);
            Assert.AreEqual(CUSTOM_STATE_MACHINE_CONFIG, stateMachine.GetStringRepresentation());
            Mock.Assert(_stateMachineConfigLoader);
        }
        public void LifeCycleManagerConstructorInitializesStateMachineWithDefaultConfigurationIfNoConfigurationDefinedExplicit()
        {
            Mock.Arrange(() => _stateMachineConfigLoader.LoadConfiguration(ENTITY_TYPE))
                .IgnoreInstance()
                .Returns((String)null)
                .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            var lifeCycleManagerWithPrivateAccess = new PrivateObject(lifeCycleManager);
            var stateMachine = (StateMachine.StateMachine)lifeCycleManagerWithPrivateAccess.GetField(STATE_MACHINE_FIELD);

            Assert.IsNotNull(stateMachine);
            Assert.AreEqual(new StateMachine.StateMachine().GetStringRepresentation(), stateMachine.GetStringRepresentation());
            Mock.Assert(_stateMachineConfigLoader);
        }
        public void OnAllowCallbackForPreCalloutRevertsTransactionAndThrowsInvalidOperationExceptionIfChangingStateFails()
        {
            Mock.Arrange(() => _coreService.Jobs)
            .IgnoreInstance()
            .ReturnsCollection(new List <Job>(new List <Job> {
                CreateJob(SAMPLE_ENTITY_URI.ToString())
            }))
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny <Job>()))
            .IgnoreInstance()
            .InSequence()
            .OccursOnce();

            Mock.Arrange(() => _entityController.LoadEntity(SAMPLE_ENTITY_URI))
            .IgnoreInstance()
            .Returns(UPDATED_ENTITY)
            .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
            .IgnoreInstance()
            .ReturnsCollection(new List <CalloutDefinition>(new List <CalloutDefinition>
            {
                CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(),
                                        Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
            }))
            .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
            .IgnoreInstance()
            .Occurs(3);

            Mock.Arrange(() => _entityController.UpdateEntity(SAMPLE_ENTITY_URI, UPDATED_ENTITY))
            .IgnoreInstance()
            .Throws <HttpRequestException>()
            .OccursOnce();

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);

            Mock.Arrange(() => _coreService.StateChangeLocks)
            .IgnoreInstance()
            .ReturnsCollection(new List <StateChangeLock>(new List <StateChangeLock>
            {
                stateChangeLockToBeDeleted
            }))
            .InSequence()
            .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
            .IgnoreInstance()
            .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);

            lifeCycleManager._calloutExecutor = _calloutExecutor;
            ThrowsAssert.Throws <InvalidOperationException>(() => lifeCycleManager.OnAllowCallback(CreateJob(SAMPLE_ENTITY_URI.ToString())));

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(_entityController);
        }
        public void RequestStateChangeForNonLockedEntityLocksEntity()
        {
            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
                .Returns("Administrator")
                .MustBeCalled();

            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    CreateStateChangeLock(SAMPLE_ENTITY_URI_2)
                }))
                .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
                .Returns(_windowsIdentity)
                .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
                .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
                .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
                .IgnoreInstance()
                .ReturnsCollection(new List<CalloutDefinition>(new List<CalloutDefinition>
                {
                    CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(), 
                    Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString())
                }))
                .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToStateChangeLocks(Arg.IsAny<StateChangeLock>()))
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job>{CreateJob(SAMPLE_ENTITY_URI.ToString())}))
                .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny<CalloutData>()))
                .MustBeCalled();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            lifeCycleManager._calloutExecutor = _calloutExecutor;
            lifeCycleManager.RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
            Mock.Assert(() => HttpContext.Current.User.Identity);
            Mock.Assert(CredentialCache.DefaultCredentials);
            Mock.Assert(_windowsIdentity);
        }
        public void RequestStateChangeForNonLockedEntityRevertsTransactionAndThrowsInvalidOperationExceptionIfPreCalloutFails()
        {
            Job updatedJob = null;
            Mock.Arrange(() => CurrentUserDataProvider.GetCurrentUsername())
                .Returns("Administrator")
                .MustBeCalled();

            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    CreateStateChangeLock(SAMPLE_ENTITY_URI_2)
                }))
                .InSequence()
                .MustBeCalled();

            Mock.Arrange(() => HttpContext.Current.User.Identity)
                .Returns(_windowsIdentity)
                .MustBeCalled();

            Mock.Arrange(() => CredentialCache.DefaultCredentials)
                .MustBeCalled();

            Mock.Arrange(() => _windowsIdentity.Impersonate())
                .MustBeCalled();

            Mock.Arrange(() => _coreService.CalloutDefinitions)
                .IgnoreInstance()
                .ReturnsCollection(new List<CalloutDefinition>(new List<CalloutDefinition>
                {
                    CreateCalloutDefinition(SAMPLE_ENTITY_URI.ToString(), 
                    Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString())
                }))
                .MustBeCalled();

            Mock.Arrange(() => _coreService.AddToStateChangeLocks(Arg.IsAny<StateChangeLock>()))
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.SaveChanges())
                .IgnoreInstance()
                .Occurs(4);

            Mock.Arrange(() => _coreService.AddToJobs(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .MustBeCalled();

            Mock.Arrange(() => _calloutExecutor.ExecuteCallout(CALLOUT_DEFINITION, Arg.IsAny<CalloutData>()))
                .Throws<HttpRequestException>()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.Jobs)
                .IgnoreInstance()
                .ReturnsCollection(new List<Job>(new List<Job> { CreateJob(SAMPLE_ENTITY_URI.ToString()) }))
                .MustBeCalled();

            Mock.Arrange(() => _coreService.UpdateObject(Arg.IsAny<Job>()))
                .IgnoreInstance()
                .DoInstead((Job j) => { updatedJob = j; })
                .MustBeCalled();

            var stateChangeLockToBeDeleted = CreateStateChangeLock(SAMPLE_ENTITY_URI);
            Mock.Arrange(() => _coreService.StateChangeLocks)
                .IgnoreInstance()
                .ReturnsCollection(new List<StateChangeLock>(new List<StateChangeLock>
                {
                    stateChangeLockToBeDeleted
                }))
                .InSequence()
                .MustBeCalled();

            Mock.Arrange(() => _coreService.DeleteObject(stateChangeLockToBeDeleted))
                .IgnoreInstance()
                .OccursOnce();

            var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
            lifeCycleManager._calloutExecutor = _calloutExecutor;
            ThrowsAssert.Throws<InvalidOperationException>(() => lifeCycleManager.
                RequestStateChange(SAMPLE_ENTITY_URI, SAMPLE_ENTITY, CONTINUE_CONDITION, TENANT_ID));

            Assert.AreEqual(JobStateEnum.Failed.ToString(), updatedJob.State);

            Mock.Assert(_coreService);
            Mock.Assert(_calloutExecutor);
            Mock.Assert(() => CurrentUserDataProvider.GetCurrentUsername());
            Mock.Assert(() => HttpContext.Current.User.Identity);
            Mock.Assert(CredentialCache.DefaultCredentials);
            Mock.Assert(_windowsIdentity);
        }
        public void LifeCycleMangerConstructorLoadsAndComposesMefPartsOnFirstCall()
        {
            {
                var container = Mock.Create<CompositionContainer>();
                Mock.Arrange(() => container.ComposeParts())
                    .IgnoreInstance()
                    .CallOriginal()
                    .MustBeCalled();

                var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
                var lifeCycleManagerWithPrivatAccess = new PrivateObject(lifeCycleManager);
                var stateMachine =
                    (StateMachine.StateMachine) lifeCycleManagerWithPrivatAccess.GetField(STATE_MACHINE_FIELD);

                Assert.IsNotNull(stateMachine);
                Assert.AreEqual(CUSTOM_STATE_MACHINE_CONFIG, stateMachine.GetStringRepresentation());
                Mock.Assert(container);
            }
            {
                var container = Mock.Create<CompositionContainer>();
                Mock.Arrange(() => container.ComposeParts())
                    .IgnoreInstance()
                    .CallOriginal()
                    .OccursNever();

                var lifeCycleManager = new LifeCycleManager(_authenticationProvider, ENTITY_TYPE);
                var lifeCycleManagerWithPrivatAccess = new PrivateObject(lifeCycleManager);
                var stateMachine = (StateMachine.StateMachine)lifeCycleManagerWithPrivatAccess.GetField(STATE_MACHINE_FIELD);

                Assert.IsNotNull(stateMachine);
                Assert.AreEqual(CUSTOM_STATE_MACHINE_CONFIG, stateMachine.GetStringRepresentation());
                Mock.Assert(container);
            }
        }