Example #1
0
        public void ExceptionParameterTest_Success()
        {
            var exception = new CoreException("S00001", Guid.Empty.ToString(), ExceptionType.Expected, () => "ABC");

            Assert.AreEqual(exception.Parameter.Count, 1);
            Assert.AreEqual(exception.Parameter[0], "ABC");
        }
Example #2
0
        public void ExceptionParameterTest_Error()
        {
            var exception = new CoreException("S00001", Guid.Empty.ToString(), ExceptionType.Expected, () => int.Parse("abc").ToString());

            Assert.AreEqual(exception.Parameter.Count, 1);
            Assert.IsTrue(exception.Parameter[0].Contains("Invalid parameter"));
        }
Example #3
0
        public static Result NewErrorResult(Exception t, string statement)
        {
            Result        result    = NewResult(2);
            CoreException exception = t as CoreException;

            if (exception != null)
            {
                result._exception  = exception;
                result._mainString = result._exception.GetMessage();
                result._subString  = result._exception.GetSqlState();
                if (statement != null)
                {
                    result._mainString = result._mainString + " in statement [" + statement + "]";
                }
                result._errorCode = result._exception.GetErrorCode();
                return(result);
            }
            if (t is OutOfMemoryException)
            {
                result._exception  = Error.GetError(460, t);
                result._mainString = result._exception.GetMessage();
                result._subString  = result._exception.GetSqlState();
                result._errorCode  = result._exception.GetErrorCode();
                return(result);
            }
            result._exception  = Error.GetError(0x1ca, t);
            result._mainString = result._exception.GetMessage() + " " + t.Message;
            result._subString  = result._exception.GetSqlState();
            result._errorCode  = result._exception.GetErrorCode();
            if (statement != null)
            {
                result._mainString = result._mainString + " in statement [" + statement + "]";
            }
            return(result);
        }
Example #4
0
        public static void SetNotification(this Controller controller, string title, CoreException exception, NotificationStatus status = NotificationStatus.Error)
        {
            var errorCode = new ErrorModel(exception.Code, null);

            var message = errorCode.Message;

            controller.SetNotification(title, message, status);
        }
Example #5
0
        public void CoreExceptionErrorMessageShownAssemblyNameStartsWithDollarButHasNoForwardSlashCharacter()
        {
            IAddInTree     addInTree = MockRepository.GenerateStrictMock <IAddInTree>();
            DerivedRuntime runtime   = new DerivedRuntime(addInTree, "$ICSharpCode.FormsDesigner.dll", String.Empty);
            CoreException  ex        = Assert.Throws <CoreException>(delegate { runtime.Load(); });

            Assert.AreEqual("Expected '/' in path beginning with '$'!", ex.Message);
        }
        public void CoreExceptionErrorMessageShownAssemblyNameStartsWithDollarButHasNoForwardSlashCharacter()
        {
            List <AddIn>   addIns  = GetAddInsList();
            DerivedRuntime runtime = new DerivedRuntime("$ICSharpCode.FormsDesigner.dll", String.Empty, addIns);
            CoreException  ex      = Assert.Throws <CoreException>(delegate { runtime.Load(); });

            Assert.AreEqual("Expected '/' in path beginning with '$'!", ex.Message);
        }
 private Product(ProductId productId, string code) : base(productId)
 {
     if (string.IsNullOrWhiteSpace(code))
     {
         throw CoreException.NullOrEmptyArgument(nameof(code));
     }
     this.Code = code;
 }
Example #8
0
        public void ExceptionParameterTest()
        {
            var exception = new CoreException("S00001", Guid.Empty.ToString(), ExceptionType.Expected);

            Assert.AreEqual(exception.Code, "S00001");
            Assert.AreEqual(exception.Id, Guid.Empty.ToString());
            Assert.AreEqual(exception.Type, ExceptionType.Expected);
        }
Example #9
0
 /// <summary>
 /// Handles the CMS exception.
 /// </summary>
 /// <param name="ex">The exception.</param>
 /// <param name="command">The command.</param>
 /// <param name="request">The request.</param>
 private static void HandleCoreException(CoreException ex, ICommandBase command, object request = null)
 {
     Log.Error(FormatCommandExceptionMessage(command, request), ex);
     if (command.Context != null)
     {
         command.Context.Messages.AddError(RootGlobalization.Message_InternalServerErrorPleaseRetry);
     }
 }
Example #10
0
 public GetProductsByPriceAndNameHandler(
     IProductRepository productRepository,
     IUnitOfWork unitOfWork,
     IMediator mediator)
 {
     ProductRepository = productRepository ?? throw CoreException.NullArgument(nameof(productRepository));
     UnitOfWork        = unitOfWork ?? throw CoreException.NullArgument(nameof(unitOfWork));
     Mediator          = mediator ?? throw CoreException.NullArgument(nameof(mediator));
 }
Example #11
0
        public static Result NewWarningResult(CoreException w)
        {
            Result result1 = NewResult(0x13);

            result1._mainString = w.GetMessage();
            result1._subString  = w.GetSqlState();
            result1._errorCode  = w.GetErrorCode();
            return(result1);
        }
        public Inventory ChangeLocation(string location)
        {
            if (string.IsNullOrWhiteSpace(location))
            {
                throw CoreException.NullOrEmptyArgument(nameof(location));
            }

            this.Location = location;
            return(this);
        }
        public Product ChangeName(string productName)
        {
            if (string.IsNullOrWhiteSpace(productName))
            {
                throw CoreException.NullOrEmptyArgument(nameof(productName));
            }

            this.Name = productName;
            return(this);
        }
Example #14
0
 public NetResult(CoreException e)
 {
     if (e == null)
     {
     }
     if (e.Id != 0)
     {
         ById(e.Id);
     }
 }
        public Inventory ChangeName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw CoreException.NullOrEmptyArgument(nameof(name));
            }

            this.Name = name;
            return(this);
        }
Example #16
0
        /// <summary>
        /// A bad request response.
        /// </summary>
        /// <typeparam name="T">The type</typeparam>
        /// <param name="ex">The ex.</param>
        /// <param name="message">The message.</param>
        /// <returns>the action</returns>
        protected IActionResult BadRequest <T>(CoreException <T> ex, string message = null)
        {
            var error = new ApiErrorModel();

            error.Code    = ex.Code.ToString();
            error.Message = message ?? ex.Message;
            error.Target  = ex.Target;
            return(this.StatusCode(400, new BaseApiErrorModel()
            {
                Error = error
            }));
        }
Example #17
0
        /// <summary>
        /// A bad request response.
        /// </summary>
        /// <typeparam name="T">Exception type</typeparam>
        /// <param name="code">The code.</param>
        /// <param name="errors">The errors.</param>
        /// <param name="target">The target.</param>
        /// <returns>the action</returns>
        protected IActionResult BadRequest <T>(CoreException <T> code, IList <ApiErrorModel> errors, string target = null)
        {
            var error = new ApiErrorModel()
            {
                Code    = code.ToString(),
                Message = this.messageExceptionFinder.GetErrorMessage(code),
                Target  = target,
                Details = errors == null || errors.Count == 0 ? null : errors
            };

            return(this.StatusCode(400, new BaseApiErrorModel()
            {
                Error = error
            }));
        }
        private Inventory(InventoryId inventoryId, string name, string location) : base(inventoryId)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw CoreException.NullOrEmptyArgument(nameof(name));
            }

            if (string.IsNullOrWhiteSpace(location))
            {
                throw CoreException.NullOrEmptyArgument(nameof(location));
            }

            this.Name     = name;
            this.Location = location;
        }
        public async Task <ProductDto> Handle(UpdateProductRequest request, CancellationToken cancellationToken)
        {
            var productDbSet = this._dbContext.Set <Product>();
            var product      = await productDbSet.SingleOrDefaultAsync(x => x.Id == request.ProductId, cancellationToken : cancellationToken);

            if (product == null)
            {
                throw CoreException.NotFound(request.ProductId.ToString());
            }

            product.ChangeName(request.NewProductName);

            var entity = productDbSet.Update(product);

            return(this._mapper.Map <ProductDto>(entity.Entity));
        }
Example #20
0
        internal static CheckMethodResult GetEntityMethodName(Type type, string methodName, BeeDataAdapter dataAdapter)
        {
            ThrowExceptionUtil.ArgumentNotNull(type, "type");
            ThrowExceptionUtil.ArgumentNotNullOrEmpty(methodName, "methodName");

            if (dataAdapter == null)
            {
                dataAdapter = new BeeDataAdapter();
            }

            CheckMethodResult result = new CheckMethodResult();

            MethodSchema        methodSchema = null;
            List <MethodSchema> list         = null;

            //lock (lockobject)
            {
                // 保证参数长的先被匹配
                // 该方法本身就排过序了
                list = EntityProxyManager.Instance.GetEntityMethods(type);

                foreach (MethodSchema item in list)
                {
                    // Check the name of the method.
                    if (string.Compare(item.Name, methodName, true) == 0)
                    {
                        if (CheckMethod(item, methodName, dataAdapter, out result.DataAdapter))
                        {
                            methodSchema = item;
                            break;
                        }
                    }
                }
            }

            if (methodSchema != null)
            {
                result.MethodName = methodSchema.MemberInfo.ToString();
            }
            else
            {
                CoreException exception = new CoreException("Can not match a method for {0}.{1}\r\n".FormatWith(type.Name, methodName));
                exception.ErrorCode = ErrorCode.MVCNoAction;
                throw exception;
            }
            return(result);
        }
Example #21
0
        private ProductInventory(ProductInventoryId productInventoryId, Product product, Inventory inventory, int quantity, bool canPurchase = true)
            : base(productInventoryId)
        {
            if (product == null)
            {
                throw CoreException.NullOrEmptyArgument(nameof(product));
            }
            if (inventory == null)
            {
                throw CoreException.NullOrEmptyArgument(nameof(inventory));
            }

            this.Product     = product;
            this.Inventory   = inventory;
            this.Quantity    = quantity;
            this.CanPurchase = canPurchase;
        }
Example #22
0
        public ExceptionDialogViewModel(CoreException exception, IAppService appService)
        {
            CloseCommand   = Make.UICommand.Do(() => Close());
            CopyCommand    = Make.UICommand.Do(() => appService.CopyToClipBoard(Detail));
            RestartCommand = Make.UICommand.Do(() => appService.Restart());
            ExitCommand    = Make.UICommand.Do(() => appService.Exit());
            ReportCommand  = Make.UICommand.Do(() => appService.SendMail(exception.Description, Detail));

            RightButtons.Add(new UICore.Buttons.ButtonViewModel(CloseCommand, "Continue"));
            RightButtons.Add(new UICore.Buttons.ButtonViewModel(RestartCommand, "Restart"));
            RightButtons.Add(new UICore.Buttons.ButtonViewModel(ExitCommand, "Exit"));

            LeftButtons.Add(new UICore.Buttons.ButtonViewModel(CopyCommand, "Copy"));
            LeftButtons.Add(new UICore.Buttons.ButtonViewModel(ReportCommand, "Report"));

            Detail = exception.Exception.Message + "\n" + exception.Exception.GetBaseException().StackTrace;
        }
        public ProductInventory WithInventory(Inventory inventory, int quantity, bool canPurchase = true)
        {
            if (inventory == null)
            {
                throw CoreException.NullOrEmptyArgument(nameof(inventory));
            }

            if (this._inventories.Any(x => x.Inventory == inventory))
            {
                throw new CoreException($"{this} is existing in {inventory}");
            }

            var productInventory = ProductInventory.Create(this, inventory, quantity, canPurchase);

            this._inventories.Add(productInventory);
            return(productInventory);
        }
Example #24
0
        public void Close(int closemode)
        {
            CoreException error = null;

            this.SetState(8);
            this.sessionManager.CloseAllSessions();
            this.sessionManager.ClearAll();
            if (this._filesReadOnly)
            {
                closemode = -1;
            }
            this.logger.ClosePersistence(closemode);
            this.lobManager.Close();
            try
            {
                if (closemode == 1)
                {
                    this.ClearStructures();
                    this.Reopen();
                    this.SetState(8);
                    this.logger.ClosePersistence(0);
                }
            }
            catch (Exception exception2)
            {
                CoreException exception3 = exception2 as CoreException;
                if (exception3 != null)
                {
                    error = exception3;
                }
                else
                {
                    error = Error.GetError(0x1ca, exception2.Message);
                }
            }
            this.logger.ReleaseLock();
            this.SetState(0x10);
            this.ClearStructures();
            DatabaseManager.RemoveDatabase(this);
            if (error != null)
            {
                throw error;
            }
            this.Dispose();
        }
Example #25
0
        public BadRequestError(CoreException coreException)
        {
            Key     = coreException.Key;
            Message = coreException.Message;

            if (coreException.GetType().BaseType.IsGenericType)
            {
                Items = new List <BadRequestErrorItem>();
                var items = coreException.GetType().GetProperties().Single(p => p.Name == nameof(CoreException <CoreExceptionItem> .Items));
                foreach (var item in (IEnumerable)items.GetValue(coreException))
                {
                    Items.Add(new BadRequestErrorItem()
                    {
                        Key     = (item as CoreExceptionItem)?.Key,
                        Message = (item as CoreExceptionItem)?.Message
                    });
                }
            }
        }
Example #26
0
        private static void printException(CoreException ex)
        {
            var       indentation    = 0;
            var       sb             = new StringBuilder();
            Exception innerException = ex;

            while (innerException != null)
            {
                sb.Clear();
                for (var i = 0; i < indentation; i++)
                {
                    sb.Append('\t');
                }
                sb.Append(innerException.Message);
                Console.WriteLine(sb);

                innerException = innerException?.InnerException;
            }
        }
Example #27
0
        public Object CreateObject(string dllName, string className)
        {
            object result = null;

            try
            {
                ObjectHandle handle =
                    Activator.CreateInstance(dllName, className);
                result = handle.Unwrap();
            }
            catch (Exception e)
            {
                string errorString = string.Format("Reflect class failed. dllName={0}, className={1}", dllName, className);
                logger.Error(errorString, e);
                CoreException ex = new CoreException(errorString, e);
                throw ex;
            }
            return(result);
        }
Example #28
0
        public long Create(Books_DTO obj)
        {
            using (var sqlConnection = CoreConnection.GetConnection())
            {
                long toReturn = 0;

                try
                {
                    toReturn = sqlConnection.Execute("Insert into books (name, pages, create_date, update_date,author, quantity) values (@name, @pages, (select getdate()),(select getdate()),@author,@quantity  )", obj);
                }
                catch (Exception ex)
                {
                    message = CoreException.GetMessage(ex.Message);
                }


                if (toReturn > 0)
                {
                    message = "Cadastro realizado com sucesso";
                }

                return(toReturn);
            }
        }
Example #29
0
        public long Update(Books_DTO obj)
        {
            long toReturn = 0;

            using (var sqlConnection = CoreConnection.GetConnection())
            {
                try
                {
                    toReturn = sqlConnection.Execute("update books set name = @name, pages = @pages, quantity = @quantity, update_date = (select getdate()) where id = @id", obj);
                }
                catch (Exception ex)
                {
                    message = CoreException.GetMessage(ex.Message);
                }


                if (toReturn > 0)
                {
                    message = "Cadastro realizado com sucesso";
                }

                return(toReturn);
            }
        }
        public void CoreExceptionConstructorMessageInnerExceptionTest()
        {
            string expectedMessage = "Exception Message";
            Exception expectedInnerException = new NotImplementedException();
            CoreException target = new CoreException(expectedMessage, expectedInnerException);
            Assert.IsNotNull(target);

            string actualMessage = target.Message;
            Assert.AreEqual(expectedMessage, actualMessage);

            Exception actualInnerException = target.InnerException;
            Assert.AreEqual(expectedInnerException, actualInnerException);
        }
 public void CoreExceptionConstructorEmptyTest()
 {
     CoreException target = new CoreException();
     Assert.IsNotNull(target);
 }
        public void CoreExceptionGetObjectDataTest()
        {
            CoreException source, target;
            source = new CoreException();

            //FUTUREDEV: Set any custom data properties and verify values after deserialization

            using (Stream formatStream = new MemoryStream()) {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(formatStream, source);
                formatStream.Position = 0; //NOTE:  Reset stream

                target = (CoreException)formatter.Deserialize(formatStream); //NOTE:  This will cause a call to GetObjectData
            }

            Assert.IsNotNull(target);
        }
        public void CoreExceptionConstructorMessageTest()
        {
            string expected = "Exception Message";
            CoreException target = new CoreException(expected);
            Assert.IsNotNull(target);

            string actual = target.Message;
            Assert.AreEqual(expected, actual);
        }
Example #34
0
        private Result HandleCondition(Session session, Result result)
        {
            string subString;
            int    errorCode;
            Result r = result;

            if (result.IsError())
            {
                subString = result.GetSubString();
                errorCode = result.GetErrorCode();
            }
            else
            {
                if (session.GetLastWarning() == null)
                {
                    return(result);
                }
                CoreException lastWarning = session.GetLastWarning();
                subString = lastWarning.GetSqlState();
                errorCode = lastWarning.GetErrorCode();
            }
            if ((subString != null) || (errorCode != 0))
            {
                for (int i = 0; i < this.Handlers.Length; i++)
                {
                    StatementHandler handler = this.Handlers[i];
                    session.ClearWarnings();
                    if (handler.HandlesCondition(subString, errorCode))
                    {
                        Result result3;
                        session.ResetSchema();
                        switch (handler.HandlerType)
                        {
                        case 5:
                            result = Result.UpdateZeroResult;
                            break;

                        case 6:
                            result = Result.NewPsmResult(0x59, null, null);
                            break;

                        case 7:
                            session.RollbackToSavepoint();
                            result = Result.NewPsmResult(0x59, this.label.Name, null);
                            break;
                        }
                        session.sessionContext.PushHandlerContext(r);
                        try
                        {
                            result3 = handler.Execute(session);
                        }
                        finally
                        {
                            session.sessionContext.PopHandlerContext();
                        }
                        if (result3.IsError())
                        {
                            result = result3;
                            break;
                        }
                        return(result);
                    }
                }
                if (base.Parent != null)
                {
                    return(base.Parent.HandleCondition(session, result));
                }
            }
            return(result);
        }
 public void Context()
 {
     _coreException = Should.Throw<CoreException>(() => Guard.Hope(false, ExceptionMessage));
 }