示例#1
0
        public void TestPersistenceException()
        {
            var e1 = new PersistenceException();
            Assert.IsTrue(e1.Message.Contains("PersistenceException"));

            var e2 = new PersistenceException("a");
            Assert.AreEqual("a", e2.Message);

            var e3 = new PersistenceException("a", new Exception("x"));
            Assert.AreEqual("a", e3.Message);
            Assert.AreEqual("x", e3.InnerException.Message);

            using (var ms = new MemoryStream())
            {
                var serializer = new BinaryFormatter();
                serializer.Serialize(ms, e3);
                ms.Seek(0, SeekOrigin.Begin);

                var e4 = serializer.Deserialize(ms) as PersistenceException;

                Assert.IsNotNull(e4);
                Assert.AreEqual("a", e4.Message);
                Assert.AreEqual("x", e4.InnerException.Message);
            }
        }
示例#2
0
        public void PersistenceExceptionCtorTest()
        {
            PersistenceException perex = new PersistenceException();

            Assert.IsNotNull(perex, "C1#1");

            string msg = Guid.NewGuid().ToString();

            perex = new PersistenceException(msg);
            Assert.AreEqual(msg, perex.Message, "C1#2");

            perex = null;
            msg   = Guid.NewGuid().ToString();
            try
            {
                DivideBy0();
                Assert.Fail("C1#3");
            }
            catch (Exception ex)
            {
                perex = new PersistenceException(msg, ex);
            }
            Assert.AreEqual(msg, perex.Message, "C1#4");
            Assert.IsTrue(perex.InnerException is DivideByZeroException, "C1#5");
            Assert.IsNull(perex.InnerException.InnerException, "C1#6");
            Assert.IsTrue(perex.GetBaseException() is DivideByZeroException, "C1#7");

            // TODO: deserialization
        }
        public void ShouldHaveMessageAndInnerExceptionInPersistenceException()
        {
            var e = new PersistenceException("testMessage", new Exception("testInner"));

            e.Message.Should().Be("testMessage");
            e.InnerException.Message.Should().Be("testInner");
        }
示例#4
0
 public static void ValidateId <TClassLogger, T>(IApolloLogger <TClassLogger> logger, long id)
 {
     if (id <= 0)
     {
         var persistenceException = new PersistenceException("Insert failed!");
         logger.Error(persistenceException, "Insert {Entity} failed", typeof(T).Name);
         throw persistenceException;
     }
 }
示例#5
0
 public static void ValidateUpdate <TClassLogger, T>(IApolloLogger <TClassLogger> logger, int affected, int expected = 1)
 {
     if (affected != expected)
     {
         var persistenceException = new PersistenceException("Update failed!");
         logger.Error(persistenceException, "Update {entity} failed", typeof(T).Name);
         throw persistenceException;
     }
 }
示例#6
0
        public async Task <RowDto> AddRowAsync(RowDto row)
        {
            ValidateNull(Logger.Here(), row);
            var rows = await GetRowsFromCinemaHallAsync(row.CinemaHallId);

            if (rows.Any(r => r.Number == row.Number))
            {
                var exception = new PersistenceException(nameof(AddRowAsync));
                Logger.Error(exception, "{Row} with {number} already exists", row, row.Number);
                throw exception;
            }

            var id = await _unitOfWork.RepositoryInfrastructure.AddRowAsync(Map(row));

            row.Id = id;
            return(row);
        }
示例#7
0
        /// <summary>
        /// Check to see whether the result of a persistence operation
        /// was successful, raise appropriate exceptions if not.
        /// </summary>
        /// <param name="dbCommand">
        /// <see cref="DbCommand" /> to retrieve result information from.
        /// </param>
        /// <param name="resultParameter">
        /// Name of the parameter storing the result.
        /// </param>
        /// <param name="instanceParameter">
        /// Name of the parameter storing the instance identifier.
        /// </param>
        private void CheckResult(DbCommand dbCommand, String resultParameter, String instanceParameter)
        {
            Int32?result     = _valueReader.GetNullableInt32(dbCommand, resultParameter);
            Guid  instanceId = _valueReader.GetGuid(dbCommand, instanceParameter);

            switch (result)
            {
            case _ownershipError:
                // ownership error
                throw new WorkflowOwnershipException(instanceId);

            case _instanceNotFoundError:
                // workflow could not be found
                PersistenceException e = new PersistenceException(RM.Get_Error_InstanceCouldNotBeLoaded(instanceId));
                e.Data["WorkflowNotFound"] = true;
                throw e;
            }
        }
示例#8
0
        public async Task <SeatDto> AddSeatAsync(SeatDto seat)
        {
            ValidateNull(Logger.Here(), seat);
            var cinemaHall = await _unitOfWork.RepositoryInfrastructure.GetCinemaHallByIdAsync(seat.Row.CinemaHallId);

            ValidateNull(Logger.Here(), cinemaHall);
            ValidateLessOrEquals <InfrastructureService, long>(Logger.Here(), seat.LayoutColumn, cinemaHall.SizeColumn);
            ValidateLessOrEquals <InfrastructureService, long>(Logger.Here(), seat.LayoutRow, cinemaHall.SizeRow);

            var row = await _unitOfWork.RepositoryInfrastructure.GetRowByIdAsync(seat.RowId);

            var seats = await _unitOfWork.RepositoryInfrastructure.GetSeatsWithRowAndCategoryAsync(row.CinemaHallId);

            if (seats.Any(s => s.LayoutColumn == seat.LayoutColumn && s.LayoutRow == seat.LayoutRow))
            {
                var exception = new PersistenceException(nameof(AddSeatAsync));
                Logger.Error(exception, "{Seat} with same layout already exists", seat);
                throw exception;
            }

            await _unitOfWork.RepositoryInfrastructure.AddSeatAsync(Map(seat));

            return(seat);
        }
        /// <summary>
        /// Persist a workflow instance to the persistence store.
        /// </summary>
        /// <param name="rootActivity">
        /// Root activity of the workflow instance.
        /// </param>
        /// <param name="unlock">
        /// Indicates whether to unlock the instance when complete.
        /// </param>
        protected override void SaveWorkflowInstanceState(Activity rootActivity, bool unlock)
        {
            TraceHelper.Trace();

            try
            {
                if (rootActivity == null)
                    throw new ArgumentNullException("rootActivity");

                PendingWorkItem workItem = new PendingWorkItem();
                workItem.Status = GetWorkflowStatus(rootActivity);
                workItem.IsBlocked = GetIsBlocked(rootActivity);
                workItem.Info = GetSuspendOrTerminateInfo(rootActivity);
                workItem.StateId = (Guid) rootActivity.GetValue(Activity.ActivityContextGuidProperty);
                workItem.Type = PendingWorkItem.ItemType.Instance;
                workItem.InstanceId = WorkflowEnvironment.WorkflowInstanceId;
                workItem.Unlock = unlock;
                if (workItem.Status != WorkflowStatus.Completed && workItem.Status != WorkflowStatus.Terminated)
                    workItem.SerialisedActivity = GetDefaultSerializedForm(rootActivity);
                else
                    workItem.SerialisedActivity = new byte[0];

                TimerEventSubscription timerEventSubscription =
                    ((TimerEventSubscriptionCollection) rootActivity.GetValue(
                    TimerEventSubscriptionCollection.TimerCollectionProperty)).Peek();

                if (timerEventSubscription == null)
                    workItem.NextTimer = null;
                else
                    workItem.NextTimer = timerEventSubscription.ExpiresAt;

                WorkflowEnvironment.WorkBatch.Add(this, workItem);
            }
            catch (Exception e)
            {
                Tracer.Debug("�־û�SaveWorkflowInstanceState�����쳣:" + e.ToString());
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException,
                    WorkflowEnvironment.WorkflowInstanceId);

                throw persistenceException;
            }
        }
        ///<summary>
        ///Commits the list of work items by using the specified <see cref="T:System.Transactions.Transaction"></see> object.
        ///</summary>
        ///
        ///<param name="items">The work items to be committed.</param>
        ///<param name="transaction">The <see cref="T:System.Transactions.Transaction"></see> associated with the pending work.</param>
        public void Commit(Transaction transaction, ICollection items)
        {
            TraceHelper.Trace();

            if (transaction == null)
                throw new ArgumentNullException("transaction");

            if (items == null)
                throw new ArgumentNullException("items");

            try
            {
                using (IPersistenceResourceAccessor resourceAccessor = CreateAccessor(this.resourceProvider, transaction))
                {
                    foreach (PendingWorkItem item in items)
                    {
                        switch (item.Type)
                        {
                            case PendingWorkItem.ItemType.Instance:
                                resourceAccessor.InsertInstanceState(item,
                                    serviceId, this.OwnershipTimeout);

                                continue;

                            case PendingWorkItem.ItemType.CompletedScope:
                                resourceAccessor.InsertCompletedScope(
                                    item.InstanceId, item.StateId,
                                    item.SerialisedActivity);

                                continue;

                            case PendingWorkItem.ItemType.ActivationComplete:
                                resourceAccessor.UnlockInstanceState(
                                    item.InstanceId, this.serviceId);

                                continue;
                        }
                    }
                }
                Tracer.Debug("�־û��ύ����Commit���......");
            }
            catch (Exception e)
            {
                Tracer.Debug("�־û��ύ����Commit�����쳣:" + e.ToString());
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException,
                    Guid.Empty);

                throw persistenceException;
            }
        }
        ///<summary>
        ///Called when the transaction has completed.
        ///</summary>
        ///
        ///<param name="items">An <see cref="T:System.Collections.ICollection"></see> of work items.</param>
        ///<param name="succeeded">true if the transaction succeeded; otherwise, false.</param>
        public void Complete(bool succeeded, ICollection items)
        {
            TraceHelper.Trace();

            try
            {
                if (succeeded)
                {
                    foreach (PendingWorkItem item in items)
                    {
                        if (item.Type == PendingWorkItem.ItemType.Instance && item.NextTimer != null)
                            this.smartTimer.Update(item.NextTimer.Value);
                    }
                    Tracer.Debug("�־û��ύ����Complete���......");
                }
            }
            catch (Exception e)
            {
                Tracer.Debug("�־û�Complete�����쳣:" + e.ToString());
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException
                    = new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException, Guid.Empty);

                throw persistenceException;
            }
        }
        /// <summary>
        /// Load a completed scope from the persistence store.
        /// </summary>
        /// <param name="scopeId">
        /// <see cref="Guid" /> representing the unique identifier of the completed scope.
        /// </param>
        /// <param name="outerActivity">
        /// The activity in which to load the completed scope into.
        /// </param>
        protected override Activity LoadCompletedContextActivity(Guid scopeId, Activity outerActivity)
        {
            TraceHelper.Trace();

            Activity contextActivity;
            try
            {
                using (IPersistenceResourceAccessor resourceAccessor = CreateAccessor(this.resourceProvider))
                {
                    byte[] instanceState = resourceAccessor.RetrieveCompletedScope(scopeId);

                    contextActivity = RestoreFromDefaultSerializedForm(instanceState, outerActivity);
                }
            }
            catch (Exception e)
            {
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException,
                    WorkflowEnvironment.WorkflowInstanceId);

                throw persistenceException;
            }

            return contextActivity;
        }
        /// <summary>
        /// Retrieve instance state from the persistence store.
        /// </summary>
        /// <param name="instanceId"></param>
        /// <param name="ownerId"></param>
        /// <param name="ownedUntil"></param>
        /// <returns></returns>
        public byte[] RetrieveInstanceState(Guid instanceId, Guid ownerId, DateTime ownedUntil)
        {
            byte[] instanceState = null;

            using (DbCommand dbCommand = CreateCommand(nameResolver.ResolveCommandName(PersistenceCommandName.RetrieveInstanceState), CommandType.StoredProcedure))
            {
                string instanceParameter = nameResolver.ResolveParameterName(
                    PersistenceCommandName.InsertInstanceState,
                    PersistenceParameterName.InstanceId);

                string resultParameter = nameResolver.ResolveParameterName(
                    PersistenceCommandName.InsertInstanceState,
                    PersistenceParameterName.Result);

                AddParameter(dbCommand, instanceParameter, instanceId, AdoDbType.Guid);

                AddParameter(dbCommand, nameResolver.ResolveParameterName(
                                 PersistenceCommandName.RetrieveInstanceState,
                                 PersistenceParameterName.OwnerId), ownerId, AdoDbType.Guid);

                AddParameter(dbCommand, nameResolver.ResolveParameterName(
                                 PersistenceCommandName.RetrieveInstanceState,
                                 PersistenceParameterName.OwnedUntil), ownedUntil, AdoDbType.DateTime);

                AddParameter(dbCommand, resultParameter,
                             AdoDbType.Int32, ParameterDirection.Output);

                AddParameter(dbCommand, nameResolver.ResolveParameterName(
                                 PersistenceCommandName.RetrieveInstanceState,
                                 PersistenceParameterName.CurrentOwnerId), AdoDbType.Guid,
                             ParameterDirection.Output);

                AddParameter(dbCommand, nameResolver.ResolveParameterName(
                                 PersistenceCommandName.RetrieveInstanceState,
                                 PersistenceParameterName.State), AdoDbType.Cursor,
                             ParameterDirection.Output);

                int?result;
                using (IDataReader dataReader = dbCommand.ExecuteReader())
                {
                    if (dataReader.Read())
                    {
                        instanceState = (byte[])valueReader.GetValue(dataReader, 0);
                    }

                    result = valueReader.GetNullableInt32(dbCommand, resultParameter);
                }

                if (instanceState == null && result > 0)
                {
                    // workflow could not be found
                    PersistenceException e = new PersistenceException(
                        RM.Get_Error_InstanceCouldNotBeLoaded(instanceId));

                    e.Data["WorkflowNotFound"] = true;
                    WfLogHelper.WriteLog("检索实例状态 public byte[] RetrieveInstanceState(" + instanceId + ", " + ownerId + ", " + ownedUntil + ")发生异常:" + e.ToString());
                    throw e;
                }
                else
                {
                    checkResult(dbCommand, resultParameter, instanceParameter);
                }
            }

            return(instanceState);
        }
        /// <summary>
        /// Unlock a workflow instance.
        /// </summary>
        /// <param name="rootActivity">
        /// The root activity of the workflow instance.
        /// </param>
        protected override void UnlockWorkflowInstanceState(Activity rootActivity)
        {
            TraceHelper.Trace();

            try
            {
                PendingWorkItem workItem = new PendingWorkItem();
                workItem.Type = PendingWorkItem.ItemType.ActivationComplete;
                workItem.InstanceId = WorkflowEnvironment.WorkflowInstanceId;

                WorkflowEnvironment.WorkBatch.Add(this, workItem);
            }
            catch (Exception e)
            {
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException,
                    WorkflowEnvironment.WorkflowInstanceId);

                throw persistenceException;
            }
        }
        /// <summary>
        /// Perform shutdown duties associated with this persistence service.
        /// <remarks>
        /// This implementation disposes the internal <see cref="SmartTimer" />
        /// responsible for loading expired workflows into memory.
        /// </remarks>
        /// </summary>
        protected override void Stop()
        {
            TraceHelper.Trace();

            try
            {
                base.Stop();

                lock (this.timerLock)
                {
                    if (this.smartTimer != null)
                    {
                        this.smartTimer.Dispose();
                        this.smartTimer = null;
                    }
                }
            }
            catch (Exception e)
            {
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException, Guid.Empty);

                throw persistenceException;
            }
        }
        /// <summary>
        /// Perform startup duties associated with this persistence service.
        /// <remarks>
        /// This implementation calls a virtual method to create a single 
        /// resource provider for this persistence service.
        /// </remarks>
        /// </summary>
        protected override void Start()
        {
            TraceHelper.Trace();

            try
            {
                // retrieve the active resource provider
                this.resourceProvider = CreateResourceProvider();

                base.Start();
            }
            catch (Exception e)
            {
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException, Guid.Empty);

                throw persistenceException;
            }
        }
        /// <summary>
        /// Persist a completed scope to the persistence store.
        /// </summary>
        /// <param name="activity">
        /// The completed scope to pesist.
        /// </param>
        protected override void SaveCompletedContextActivity(Activity activity)
        {
            TraceHelper.Trace();

            try
            {
                PendingWorkItem workItem = new PendingWorkItem();
                workItem.Type = PendingWorkItem.ItemType.CompletedScope;
                workItem.SerialisedActivity = GetDefaultSerializedForm(activity);
                workItem.InstanceId = WorkflowEnvironment.WorkflowInstanceId;
                workItem.StateId = (Guid)activity.GetValue(
                    Activity.ActivityContextGuidProperty);

                WorkflowEnvironment.WorkBatch.Add(this, workItem);
            }
            catch (Exception e)
            {
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException,
                    WorkflowEnvironment.WorkflowInstanceId);

                throw persistenceException;
            }
        }
        /// <summary>
        /// Kick-off the timer to check for workflows with expired timers, 
        /// and recover running workflow instances.
        /// </summary>
        protected override void OnStarted()
        {
            TraceHelper.Trace();

            try
            {
                base.OnStarted();

                if (this.loadInterval > TimeSpan.Zero)
                {
                    lock (this.timerLock)
                    {
                        this.smartTimer = new SmartTimer(loadWorkflowsWithExpiredTimers,
                            null, this.loadInterval, this.loadInterval);
                    }
                }

                recoverRunningWorkflows();
            }
            catch (Exception e)
            {
                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException, Guid.Empty);

                throw persistenceException;
            }
        }
        ///<summary>
        /// Load the specified workflow instance into memory from the 
        /// persistence store.
        ///</summary>
        ///<param name="instanceId">
        /// The <see cref="T:System.Guid"></see> of the root activity of the workflow instance.
        /// </param>
        protected override Activity LoadWorkflowInstanceState(Guid instanceId)
        {
            TraceHelper.Trace();

            Activity rootActivity;
            try
            {
                using (IPersistenceResourceAccessor resourceAccessor = CreateAccessor(this.resourceProvider))
                {
                    byte[] instanceState = resourceAccessor.RetrieveInstanceState(
                        instanceId, serviceId, OwnershipTimeout);

                    rootActivity = RestoreFromDefaultSerializedForm(instanceState, null);
                }
            }
            catch (Exception e)
            {
                Tracer.Debug("���ع�����״̬ʵ�������쳣:LoadWorkflowInstanceState("+instanceId+");�쳣��Ϣ:"+e.ToString());

                string errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                TraceHelper.Trace(errorMessage);

                PersistenceException persistenceException =
                    new PersistenceException(errorMessage, e);

                base.RaiseServicesExceptionNotHandledEvent(
                    persistenceException, instanceId);

                throw persistenceException;
            }

            return rootActivity;
        }