コード例 #1
0
    public bool PosTest2()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest2: Verify createed exception object's InnerException is not null";
        const string c_TEST_ID = "P002";

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            NullReferenceException exception = new NullReferenceException();
            if (exception.InnerException != null)
            {
                string errorDesc = "created exception's InnerException should be null";
                TestLibrary.TestFramework.LogError("003 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
コード例 #2
0
        public async Task ThenItShouldLogAndRethrowExceptions()
        {
            var exception = new NullReferenceException("unit test error");

            _changeProcessorMock.Setup(processor => processor.ProcessProviderAsync(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <CancellationToken>()))
            .ThrowsAsync(exception);

            var actual = Assert.ThrowsAsync <NullReferenceException>(async() =>
                                                                     await _function.RunAsync(
                                                                         new CloudQueueMessage(JsonSerializer.Serialize(new ProviderQueueItem())),
                                                                         CancellationToken.None));

            Assert.AreSame(exception, actual);
        }
コード例 #3
0
        public void NullNamesDictionary_ThrowException()
        {
            NullReferenceException ex = Assert.Throws <NullReferenceException>(() => new NumberTransformerBuilder()
                                                                               .SetNumbersDictionary(new EnglishNumbersDictionary())
                                                                               .Build());

            NullReferenceException ex2 = Assert.Throws <NullReferenceException>(() => new NumberTransformerBuilder()
                                                                                .SetNumbersDictionary(new EnglishNumbersDictionary())
                                                                                .SetLargeNumberNamesDictionary(null)
                                                                                .Build());

            Assert.Equal("ILargeNumberNamesDictionary cannot be null. Use SetLargeNumberNamesDictionary to set it.", ex.Message);
            Assert.Equal("ILargeNumberNamesDictionary cannot be null. Use SetLargeNumberNamesDictionary to set it.", ex2.Message);
        }
コード例 #4
0
        public ResponseGetComandaById GetById(string comandaId)
        {
            ResponseGetComandaById comandaById = _query.GetById(comandaId);

            if (comandaById == null)
            {
                NullReferenceException exception = new NullReferenceException("Comanda con id " + comandaId + " no encontrada");
                throw exception;
            }
            else
            {
                return(comandaById);
            }
        }
コード例 #5
0
        static void Main(string[] args)
        {
            int sum = Utils.Addition(2, 5);

            try
            {
                NullReferenceException test = new NullReferenceException("This is the message in my exception");
                throw test;
            }
            catch (Exception ex)
            {
                string temp = ex.Message;
            }
        }
        public void IncludeExceptionDataInLoggedRow()
        {
            var exception = new NullReferenceException();
            var errorId   = Guid.NewGuid();

            exception.Data["id"]   = errorId;
            exception.Data["name"] = "ahmed";
            _logger.LogException(LogLevel.Error, "execption messege", exception);
            var entities = GetLogEntities();
            var entity   = entities.Single();

            Assert.True(entity.ExceptionData.Contains(errorId.ToString()));
            Assert.True(entity.ExceptionData.Contains("name=ahmed"));
        }
コード例 #7
0
        public async Task ThenItShouldLogAndRethrowExceptions()
        {
            var exception = new NullReferenceException("unit test error");

            _changeProcessorMock.Setup(processor => processor.CheckForUpdatedProvidersAsync(It.IsAny <CancellationToken>()))
            .ThrowsAsync(exception);

            var actual = Assert.ThrowsAsync <NullReferenceException>(async() =>
                                                                     await _function.RunAsync(
                                                                         new TimerInfo(new ConstantSchedule(new TimeSpan(0, 1, 0)), new ScheduleStatus(), false),
                                                                         CancellationToken.None));

            Assert.AreSame(exception, actual);
        }
コード例 #8
0
        public override IPaymentGatewayMethod GetPaymentGatewayMethodByKey(Guid paymentMethodKey)
        {
            var paymentMethod = this.PaymentMethods.FirstOrDefault(x => x.Key == paymentMethodKey);

            if (paymentMethod != null)
            {
                return(GetPaymentGatewayMethodByPaymentCode(paymentMethod.PaymentCode));
            }

            var error = new NullReferenceException("Failed to find BraintreePaymentGatewayMethod with key specified");

            LogHelper.Error <StripePaymentGatewayProvider>("Failed to find BraintreePaymentGatewayMethod with key specified", error);
            throw error;
        }
コード例 #9
0
        private void CheckStartState()
        {
            string message;

            if (string.IsNullOrEmpty(_startState))
            {
                message = "Start state not set";
                var exception = new NullReferenceException(message: message);
                _logger?.LogError(exception, message);
                throw exception;
            }
            _startState   = _StateExists(_startState, out _, true);
            _currentState = _startState;
        }
コード例 #10
0
        public void CheckThatExcludedExceptionsAreIgnored()
        {
            var exception = new NullReferenceException();
            var circuit   = new Circuit(1)
            {
                ExcludedExceptions = new[] { typeof(NullReferenceException) }
            };

            var    circuit1  = circuit;
            Action execution = () => circuit1.Execute(() => throw exception);

            execution.ShouldThrow <NullReferenceException>().Where(e => e == exception);
            circuit.State.Position.Should().Be(CircuitPosition.Closed);
        }
コード例 #11
0
        /// <summary>
        /// Brings up a window with the given error.
        /// </summary>
        /// <param name="error">Error.</param>
        void errorHandle(NullReferenceException error)
        {
            NSAlert oAlert = new NSAlert();

            // Set the buttons
            oAlert.InvokeOnMainThread(delegate
            {
                oAlert.AddButton("Ok");
            });
            // Show the message box and capture
            oAlert.MessageText     = "There's a problem with the website or your internet connection!";
            oAlert.InformativeText = error.ToString();
            oAlert.AlertStyle      = NSAlertStyle.Informational;
        }
コード例 #12
0
        /// <summary>
        /// Ensures the class is decorated with a <see cref="GatewayMethodUiAttribute"/>.
        /// </summary>
        /// <exception cref="NullReferenceException">
        /// Throws a null reference exception if the <see cref="GatewayMethodUiAttribute"/> is not found
        /// </exception>
        private void EnsureAttribute()
        {
            // Ensure GatewayMethodUiAttribute // FYI THIS WAS AN UMBRACO EXTENSION
            var att = GetType().GetCustomAttribute <GatewayMethodUiAttribute>(true);

            if (att == null)
            {
                var logData = MultiLogger.GetBaseLoggingData();
                logData.AddCategory("Controllers");
                var nullRef = new NullReferenceException("Implementation of CheckoutPaymentControllerBase must be decorated with a GatewayMethodUiAttribute");
                MultiLogHelper.Error <CheckoutPaymentControllerBase <TPaymentModel> >("GatewayMethodUiAttribute was not found.", nullRef, logData);
                throw nullRef;
            }
        }
コード例 #13
0
ファイル: MyLogger.cs プロジェクト: VynarN/Workshop
 public void Log(Exception exception)
 {
     if (Writer != null)
     {
         Writer(exception);
     }
     else
     {
         NullReferenceException loggerException = new NullReferenceException("Logger has been turned off! " +
                                                                             "To use it, turn it on by invoking TunrOn() funcntion!");
         WriteMessage(loggerException);
         throw loggerException;
     }
 }
コード例 #14
0
ファイル: MyLogger.cs プロジェクト: VynarN/Workshop
 public string ReadLog()
 {
     if (Reader != null)
     {
         return(Reader());
     }
     else
     {
         NullReferenceException loggerException = new NullReferenceException("Logger has been turned off! " +
                                                                             "To use it, turn it on by invoking TunrOn() funcntion!");
         WriteMessage(loggerException);
         throw loggerException;
     }
 }
コード例 #15
0
        /// <summary>
        /// Gets the <see cref="TreeNode{IProductCollection}"/>.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <returns>
        /// The <see cref="TreeNode{IProductCollection}"/>.
        /// </returns>
        /// <exception cref="NullReferenceException">
        /// Throws a null reference exception if the collection could not be found in the cached collection tree.
        /// </exception>
        private static TreeNode <IProductCollection> AsTreeNode(this IProductCollection value)
        {
            var tree = TreeQuery().GetTreeByValue(value);

            if (tree != null)
            {
                return(tree);
            }

            var nullRef = new NullReferenceException("The product collection was not found in Tree cache");

            MultiLogHelper.Error(typeof(ProductCollectionExtensions), "Tree nod found for collection", nullRef);
            throw nullRef;
        }
コード例 #16
0
        public void NullReferenceReturnsProperlyPopulatedNullReferenceException()
        {
            var culture = CultureInfo.CurrentCulture;

            CultureInfo.CurrentCulture = EnglishUs;
            NullReferenceException target =
                ExceptionHelper.NullReferenceNotAllowedException(
                    nameof(target));

            CultureInfo.CurrentCulture = culture;
            Assert.NotNull(target);
            Assert.Contains("null", target.Message);
            Assert.Contains(nameof(target), target.Message);
        }
コード例 #17
0
        internal void _CheckStartState()
        {
            string message;

            if (string.IsNullOrEmpty(_startState))
            {
                message = "Start state not set";
                var exception = new NullReferenceException(message: message);
                _logger.LogError(exception, message);
                throw exception;
            }
            _startState      = _StateExists(_startState, out _, true, false);
            CurrentStateName = _startState;
        }
コード例 #18
0
        public BatchStaticCachedConfigurationReader(String batchMainSettingsFileName)
        {
            if (string.IsNullOrWhiteSpace(batchMainSettingsFileName))
            {
                //implement system exception
                MessageData messageData = new MessageData("ffce00050", Properties.Resources.ffce00050);
                Exception   nullEx      = new NullReferenceException();
                logger.Error(messageData, nullEx);

                throw new Framework.SystemException(messageData, nullEx);
            }

            base.SetApplicationEnvironmentSettingsFileName(batchMainSettingsFileName);
        }
コード例 #19
0
        public void TypePropertiesAreCorrect()
        {
            Assert.AreEqual("System.NullReferenceException", typeof(NullReferenceException).FullName, "Name");
            Assert.True(typeof(NullReferenceException).IsClass, "IsClass");
            Assert.AreEqual(typeof(Exception), typeof(NullReferenceException).BaseType, "BaseType");
            object d = new NullReferenceException();

            Assert.True(d is NullReferenceException, "is NullReferenceException");
            Assert.True(d is Exception, "is Exception");

            var interfaces = typeof(NullReferenceException).GetInterfaces();

            Assert.AreEqual(0, interfaces.Length, "Interfaces length");
        }
        public void IncludeInnerExceptionDetailsInLoggedRow()
        {
            var message   = "exception message";
            var exception = new NullReferenceException(message, new DivideByZeroException());

            _logger.Log(LogLevel.Error, exception, message);

            var entity = GetLogEntities().Single();

            Assert.NotNull(entity.Exception);
            Assert.Equal(exception.ToString().ExceptBlanks(), entity.Exception.ExceptBlanks());
            Assert.NotNull(entity.InnerException);
            Assert.Equal(exception.InnerException.ToString().ExceptBlanks(), entity.InnerException.ExceptBlanks());
        }
コード例 #21
0
        private void Awake()
        {
            if (@lock == null)
            {
                @lock = CachedTransform.Find("Lock").gameObject;
            }

            // Throw exception if lock is still null
            if (@lock == null)
            {
                Exception exception = new NullReferenceException("Lock is not assigned in the inspector");
                Debug.LogException(exception, this);
            }
        }
コード例 #22
0
        public async Task <IActionResult> UpdateById(int id, [FromBody] Employee employee)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            var validationResult = _validator.Validate(employee);

            if (!validationResult.IsValid)
            {
                var ex = new ArgumentException($"{nameof(employee)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentEmployee = await _employeeRepository.Get(x => x.Id == id);

                if (currentEmployee == null)
                {
                    var ex = new NullReferenceException($"Error while updating employee. Employee with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentEmployee.FirstName     = employee.FirstName;
                currentEmployee.LastName      = employee.LastName;
                currentEmployee.DepartamentId = employee.DepartamentId;
                currentEmployee.PhoneNumber   = employee.PhoneNumber;
                currentEmployee.PositionId    = employee.PositionId;
                currentEmployee.GenderId      = employee.GenderId;
                currentEmployee.BirthDate     = employee.BirthDate;

                _employeeRepository.Update(currentEmployee);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentEmployee));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
        public virtual ActionResult Process(StripePaymentModel model)
        {
            try
            {
                var provider = GatewayContext.Payment.GetProviderByKey(Constants.Stripe.GatewayProviderSettingsKey);
                //var paymentMethod = CheckoutManager.Payment.GetPaymentMethod();
                var paymentMethod = this.CheckoutManager.Payment.GetPaymentGatewayMethods().FirstOrDefault(x => x.PaymentMethod.ProviderKey == provider.Key).PaymentMethod;
                if (paymentMethod == null)
                {
                    var ex = new NullReferenceException("PaymentMethod was null");
                    return(HandlePaymentException(model, ex));
                }

                var args = new ProcessorArgumentCollection();
                args.SetTokenId(model.Token);
                args.SetCustomerName(model.Name);
                args.SetCustomerEmail(model.Email);

                // We can now capture the payment
                // This will actually make a few more API calls back to Stripe to get required transaction
                // data so that we can refund the payment later through the back office if needed.
                var attempt = CheckoutManager.Payment.AuthorizeCapturePayment(paymentMethod.Key, args);

                // Raise the event to process the email
                Processed.RaiseEvent(new PaymentAttemptEventArgs <IPaymentResult>(attempt), this);

                var resultModel = CheckoutPaymentModelFactory.Create(CurrentCustomer, paymentMethod, attempt);
                resultModel.SuccessRedirectUrl = model.SuccessRedirectUrl;
                string invoiceId = attempt.Invoice.Key.ToString().EncryptWithMachineKey();

                if (attempt.Payment.Success)
                {
                    CustomerContext.SetValue("invoiceKey", attempt.Invoice.Key.ToString());
                }

                if (!resultModel.ViewData.Success)
                {
                    var invoiceKey = attempt.Invoice.Key;
                    var paymentKey = attempt.Payment.Result != null ? attempt.Payment.Result.Key : Guid.Empty;
                    EnsureDeleteInvoiceOnCancel(invoiceKey, paymentKey);
                }

                return(HandlePaymentSuccess(resultModel, invoiceId));
            }
            catch (Exception ex)
            {
                return(HandlePaymentException(model, ex));
            }
        }
コード例 #24
0
        public async Task <ShareableLinkModel> GetShareableLink(Guid linkId)
        {
            ShareableLinkModel link = await _context.ShareableLinks.FirstOrDefaultAsync(x => x.Id == linkId);

            if (link != null)
            {
                return(link);
            }
            else
            {
                NullReferenceException ex = new NullReferenceException();
                ex.Data.Add("message", "FILE_NOT_FOUND_OR_DELETED");
                throw ex;
            }
        }
コード例 #25
0
        public async Task <GlobalSettingsModel> GetGlobalSettings()
        {
            GlobalSettingsModel settings = await _context.GlobalSettings.FirstOrDefaultAsync(x => x.Id == 1);

            if (settings != null)
            {
                return(settings);
            }
            else
            {
                NullReferenceException ex = new NullReferenceException();
                ex.Data.Add("message", "NO_GLOBAL_SETTINGS");
                throw ex;
            }
        }
コード例 #26
0
        /// <summary>
        /// The get provider for collection.
        /// </summary>
        /// <param name="collectionKey">
        /// The collection key.
        /// </param>
        /// <returns>
        /// The <see cref="EntityCollectionProviderBase"/>.
        /// </returns>
        public Attempt <EntityCollectionProviderBase> GetProviderForCollection(Guid collectionKey)
        {
            this.EnsureInitialized();

            // check the cache
            if (_entityCollectionProviderCache.ContainsKey(collectionKey))
            {
                var attempt = this.CreateInstance(_entityCollectionProviderCache[collectionKey], collectionKey);
                return(attempt);
            }

            var nullReference = new NullReferenceException("EntityCollectionProvider could not be resolved for the collection.");

            return(Attempt <EntityCollectionProviderBase> .Fail(nullReference));
        }
コード例 #27
0
    private void StringExceptionConstructor()
    {
        // Construct a CryptographicUnexpectedOperationException using a
        // custom error message and an inner exception.
        string errorMessage = ("The current operation is not supported.");
        NullReferenceException nullException = new NullReferenceException();
        CryptographicUnexpectedOperationException cryptographicException =
            new CryptographicUnexpectedOperationException(
                errorMessage, nullException);

        Console.WriteLine("Created a " +
                          "CryptographicUnexpectedOperationException with the following" +
                          "error message: " + errorMessage + " and inner exception: "
                          + nullException.ToString());
    }
コード例 #28
0
        public void TestGoodRequestButStorageConnectionError()
        {
            var principal = AccessTokenResult.Success(new System.Security.Claims.ClaimsPrincipal());

            tokenProvider.Setup(t => t.ValidateToken(It.IsAny <HttpRequest>())).Returns(principal);

            var exception = new NullReferenceException("");

            userRepository.Setup(t => t.Add(It.IsAny <UserEntity>(), It.IsAny <String>())).Throws(exception);

            var request  = TestFactory.CreateHttpRequest("{\"id\": \"TEST\",\"name\": \"Test User\",\"family_name\": \"User\",\"given_name\": \"Test\",\"city\": \"\",\"country\": \"\",\"postalCode\": \"\",\"state\": \"\",\"streetAddress\": \"\",\"email\": \"[email protected]\",\"isNew\": false,}");
            var response = (BadRequestObjectResult)_fixture.Run(request, testLogger);

            Assert.AreEqual(StatusCodes.Status400BadRequest, response.StatusCode);
        }
コード例 #29
0
        /// <summary>
        /// The get customer item cache.
        /// </summary>
        /// <param name="instruction">
        /// The instruction.
        /// </param>
        /// <returns>
        /// The <see cref="CustomerItemCacheBase"/>.
        /// </returns>
        /// <exception cref="NullReferenceException">
        /// Throws a null reference if the customer is not found
        /// </exception>
        private CustomerItemCacheBase GetCustomerItemCache(ItemCacheInstructionBase instruction)
        {
            var customer = GetCustomer(instruction);

            if (customer == null)
            {
                var notFound = new NullReferenceException("Customer was not found");
                MultiLogHelper.Error <BackOfficeCheckoutApiController>("Could not add item to customer ItemCache", notFound);
                return(null);
            }

            return(instruction.ItemCacheType == ItemCacheType.Wishlist
                       ? (CustomerItemCacheBase)customer.WishList()
                       : (CustomerItemCacheBase)customer.Basket());
        }
コード例 #30
0
        /// <summary>
        /// Ensures this is the provider for the <see cref="EntityType"/>.
        /// </summary>
        /// <param name="entityType">
        /// The entity Type.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        /// <exception cref="NullReferenceException">
        /// Throws an exception if the EntityCollectionProviderAttribute was not found
        /// </exception>
        /// <remarks>
        /// Used in classes such as the MerchelloHelper
        /// </remarks>
        internal bool EnsureEntityType(EntityType entityType)
        {
            var att = this.ProviderAttribute();

            if (att == null)
            {
                var nullReference =
                    new NullReferenceException(
                        "EntityCollectionProvider was not decorated with an EntityCollectionProviderAttribute");
                MultiLogHelper.Error <EntityCollectionProviderBase>("Provider must be decorated with an attribute", nullReference);
                throw nullReference;
            }

            return(att.EntityTfKey.Equals(EnumTypeFieldConverter.EntityType.GetTypeField(entityType).TypeKey));
        }
コード例 #31
0
        public ActionResult Delete(Guid id, string r = "/")
        {
            var person = Services.Person.Get(id);

            if (person == null)
            {
                var nullRef = new NullReferenceException("Person record was null in Delete");
                Logger.Error <PersonEditorController>("Person not found", nullRef);
                throw nullRef;
            }

            Services.Person.Delete(person);

            return(Redirect(r));
        }
コード例 #32
0
ファイル: HttpChannelHelpers.cs プロジェクト: mind0n/hive
 public static Exception CreateNullReferenceResponseException(NullReferenceException nullReferenceException)
 {
     return TraceResponseException(
         new ProtocolException(SR.GetString(SR.NullReferenceOnHttpResponse), nullReferenceException));
 }
コード例 #33
0
ファイル: HPScript.cs プロジェクト: symbol24/ProjectJuice
 // Use this for initialization
 protected override void Start()
 {
     var ex = new NullReferenceException("TestException");
     ex.Log("Testing comment");
     MaxHp = Database.instance.PlayerBaseHP;
     base.Start();
     if (_centerOfReferenceForJuice == null) _centerOfReferenceForJuice = transform;
     if (_mainRigidbody == null) _mainRigidbody = GetComponent<Rigidbody2D>();
     if (_inputController == null) _inputController = GetComponent<IPlatformer2DUserControl>();
     if (_character == null) _character = GetComponent<PlatformerCharacter2D>();
     HpChanged += OnHpChanged;
 }
コード例 #34
0
    public bool PosTest3()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest3: Verify create the exception object's Message is localized error message";
        const string c_TEST_ID = "P003";

        string message = "Object reference not set to an instance of an object.";
        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            NullReferenceException exception = new NullReferenceException();
            if ((exception.Message != message) &
                (!exception.Message.Contains("[Arg_NullReferenceException]")))
            {
                string errorDesc = "Message is not \""+message+"\" as expected :Actual(\""+exception.Message+"\")";
                TestLibrary.TestFramework.LogError("005 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }