Inheritance: System.Exception
        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            _logger.LogError(
                $"Error while processing request {context.Request.Method} {context.Request.Path}: {ex.Message}");
            if (ex is AutoMapperMappingException mappingException && mappingException.InnerException != null)
            {
                ex = mappingException.InnerException;
            }
            var code = ex switch
            {
                ArgumentException _ => HttpStatusCode.BadRequest,
                BadDataException _ => HttpStatusCode.BadRequest,
                DataChangedException _ => HttpStatusCode.BadRequest,
                ForbiddenException _ => HttpStatusCode.Forbidden,
                InfrastructureException _ => HttpStatusCode.InternalServerError,
                InvalidDataException _ => HttpStatusCode.BadRequest,
                NotFoundException _ => HttpStatusCode.NotFound,
                UnauthorizedException _ => HttpStatusCode.Unauthorized,
                _ => HttpStatusCode.InternalServerError
            };

            var result = JsonSerializer.Serialize(new { error = ex.Message });

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(result));
        }
    }
Example #2
0
        protected override IPaymentResult PerformProcessPayment(SalePreparationBase preparation, IPaymentMethod paymentMethod)
        {
            // We have to use the CheckoutConfirmationModel in this implementation.  If this were to be used
            // outside of a demo, you could consider writing your own base controller that inherits directly from
            // Merchello.Web.Mvc.PaymentMethodUiController<TModel> and complete the transaction there in which case the
            // BazaarPaymentMethodFormControllerBase would be a good example.

            var form = UmbracoContext.HttpContext.Request.Form;
            var purchaseOrderNumber = form.Get("purchaseOrderNumber");

            if (string.IsNullOrEmpty(purchaseOrderNumber))
            {
                var invalidData = new InvalidDataException("The Purchase Order Number cannot be an empty string");
                return(new PaymentResult(Attempt <IPayment> .Fail(invalidData), null, false));
            }

            // You need a ProcessorArgumentCollection for this transaction to store the payment method nonce
            // The braintree package includes an extension method off of the ProcessorArgumentCollection - SetPaymentMethodNonce([nonce]);
            var args = new ProcessorArgumentCollection();

            args.SetPurchaseOrderNumber(purchaseOrderNumber);

            // We will want this to be an Authorize(paymentMethod.Key, args);
            // -- Also in a real world situation you would want to validate the PO number somehow.
            return(preparation.AuthorizePayment(paymentMethod.Key, args));
        }
Example #3
0
        /// <summary>
        /// Creates a new view.
        /// </summary>
        /// <param name="fileName">
        /// The file name.
        /// </param>
        /// <param name="viewType">
        /// The view type.
        /// </param>
        /// <param name="modelName">
        /// The model name.
        /// </param>
        /// <param name="viewBody">
        /// The view body.
        /// </param>
        /// <returns>
        /// A value indicating whether or not the create was successful.
        /// </returns>
        public override PluginViewEditorContent CreateNewView(string fileName, PluginViewType viewType, string modelName, string viewBody)
        {
            var virtualPath = GetVirtualPathByPlugViewType(viewType);

            var mapped = EnsureMappedPath(virtualPath);

            fileName = fileName.Replace(" ", string.Empty);

            var fullFileName = string.Format("{0}{1}", mapped, fileName);

            if (!File.Exists(fullFileName))
            {
                using (var sw = File.CreateText(fullFileName))
                {
                    sw.WriteLine("@inherits Merchello.Web.Mvc.MerchelloHelperViewPage<{0}>", modelName);
                    sw.WriteLine("@using Merchello.Core");
                    sw.WriteLine("@using Merchello.Core.Models");
                    sw.WriteLine("@*");
                    sw.WriteLine("     MerchelloHelperViewPage<T> inherits from UmbracoViewPage<t> and exposes the MerchelloHelper as 'Merchello'");
                    sw.WriteLine("     Example usage:  var product = Merchello.TypedProductContent(YOURPRODUCTKEY);");
                    sw.WriteLine("*@");
                    sw.Close();
                }

                return(GetView(virtualPath, fileName, viewType));
            }

            var logData = MultiLogger.GetBaseLoggingData();
            var ex      = new InvalidDataException("File already exists");

            MultiLogHelper.Error <PluginViewEditorProvider>("Cannot create a duplicate file", ex, logData);
            throw ex;
        }
        protected Exception CreateException(InvalidDataException innerException)
        {
            string framingError = Resources.FramingError;

            object[] streamPosition = new object[] { this.StreamPosition, this.CurrentStateAsString };
            return(new ProtocolException(Microsoft.ServiceBus.SR.GetString(framingError, streamPosition), innerException));
        }
Example #5
0
        public void InvalidData()
        {
            var exception        = new InvalidDataException();
            var observedExitCode = ExitCodeUtilities.ShowException(exception);

            Assert.Equal((int)ExitCodes.InvalidData, observedExitCode);
        }
Example #6
0
        private void OnNewDataAvailable(byte[] frame)
        {
            ArrayList data = new ArrayList(frame);

            do
            {
                try
                {
                    SPPMessage msg = SPPMessage.DecodeMessage(data.OfType <byte>().ToArray());

                    MessageReceived?.Invoke(this, msg);

                    if (msg.TotalPacketSize >= data.Count)
                    {
                        break;
                    }
                    data.RemoveRange(0, msg.TotalPacketSize);
                }
                catch (InvalidDataException e)
                {
                    InvalidDataException?.Invoke(this, e);
                }
            } while (data.Count > 0);

            NewDataAvailable?.Invoke(this, frame);
        }
Example #7
0
        protected override Exception OnSizeQuotaExceeded(int size)
        {
            Exception result = new InvalidDataException(SR.Format(SR.FramingViaTooLong, size));

            FramingEncodingString.AddFaultString(result, FramingEncodingString.ViaTooLongFault);
            return(result);
        }
Example #8
0
        public static void MessageConstructor()
        {
            string message           = "MessageConstructor";
            InvalidDataException ide = new InvalidDataException(message);

            Assert.Equal(message, ide.Message);
        }
        public static void MessageConstructor()
        {
            string message = "MessageConstructor";
            InvalidDataException ide = new InvalidDataException(message);

            Assert.Equal(message, ide.Message);
        }
Example #10
0
        public async Task GivenThatABaseUriChangesVerifyValidationFails()
        {
            using (var target = new TestFolder())
                using (var cache = new LocalCache())
                {
                    var log      = new TestLogger();
                    var settings = new LocalSettings();


                    var fileSystem1 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root), UriUtility.CreateUri("https://tempuri.org/"));
                    var fileSystem2 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root), UriUtility.CreateUri("https://tempuri.org/b/"));

                    await InitCommand.RunAsync(settings, fileSystem1, log);

                    await SourceUtility.EnsureBaseUriMatchesFeed(fileSystem1, log, CancellationToken.None);

                    InvalidDataException foundEx = null;

                    try
                    {
                        await SourceUtility.EnsureBaseUriMatchesFeed(fileSystem2, log, CancellationToken.None);
                    }
                    catch (InvalidDataException ex)
                    {
                        foundEx = ex;
                    }

                    foundEx.Message.Should().Contain("https://tempuri.org/");
                }
        }
Example #11
0
        /// <summary>
        /// Throws an invalid data exception
        /// </summary>
        /// <param name="reason">The reason for the exception</param>
        public static void ThrowInvalidDataException(string reason)
        {
            var e = new InvalidDataException(reason);

            ExceptionUtility.TraceException(e);
            throw e;
        }
Example #12
0
        public static T FromJson <T>(string json)
        {
            if (typeof(T).IsPrimitive || typeof(T) == typeof(string))
            {
                return((T)Convert.ChangeType(json, typeof(T)));
            }

            T instance;

            try
            {
                instance = JsonConvert.DeserializeObject <T>(json);
            }
            catch (JsonReaderException)
            {
                json     = EscapeDoubleQuotesInJsonPropertyValues(json);
                instance = JsonConvert.DeserializeObject <T>(json);

                Device.BeginInvokeOnMainThread(() =>
                {
                    var ex = new InvalidDataException("Double quotes in json property value detected");
                    ex.Data.Add("Json", json);
                    MessagingCenter.Send(Application.Current, MessageTypes.ExceptionOccurred, ex);
                });
            }
            return(instance);
        }
Example #13
0
        public async Task ReadCsvFile(BufferBlock <string> queue, string filename)
        {
            // Use HashSet to avoid duplicated data which can produce errors in further work.
            var result = new HashSet <string>();

            using (var reader = new StreamReader(filename))
            {
                var csv = new CsvReader(
                    reader, new CsvHelper.Configuration.Configuration {
                    HasHeaderRecord = true
                }
                    );

                if (!csv.Read() || !csv.ReadHeader())
                {
                    var ex = new InvalidDataException("CSV file doesn't contain header!");
                    _logger.Error(ex, "Got CSV file without header.");
                    throw ex;
                }
                while (csv.Read())
                {
                    string thingName = csv[_thingNameHeader];
                    if (result.Add(thingName))
                    {
                        await queue.SendAsync(thingName);
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Verifies that the file can be written safely.
        /// </summary>
        public override bool Validate(out Exception ex)
        {
            if (!(Version == 101 || Version == 102 || Version == 103 || Version == 104 || Version == 201))
            {
                ex = new InvalidDataException($"Unknown version: {Version}");
                return(false);
            }

            if (!ValidateNull(ParamType, $"{nameof(ParamType)} may not be null.", out ex) ||
                !ValidateNull(Fields, $"{nameof(Fields)} may not be null.", out ex))
            {
                return(false);
            }

            for (int i = 0; i < Fields.Count; i++)
            {
                Field  field = Fields[i];
                string which = $"{nameof(Fields)}[{i}]";
                if (!ValidateNull(field, $"{which}: {nameof(Field)} may not be null.", out ex) ||
                    !ValidateNull(field.DisplayName, $"{which}: {nameof(Field.DisplayName)} may not be null.", out ex) ||
                    !ValidateNull(field.DisplayFormat, $"{which}: {nameof(Field.DisplayFormat)} may not be null.", out ex) ||
                    !ValidateNull(field.InternalType, $"{which}: {nameof(Field.InternalType)} may not be null.", out ex) ||
                    Version >= 102 && !ValidateNull(field.InternalName, $"{which}: {nameof(Field.InternalName)} may not be null on version {Version}.", out ex))
                {
                    return(false);
                }
            }

            ex = null;
            return(true);
        }
Example #15
0
        public static async Task <TObject> Deserialize <TObject>(this HttpResponseMessage response, JsonSerializer jsonSerializer = null) where TObject : class
        {
            jsonSerializer ??= _serializer;

            await ThrowIfNotSuccess(response).ConfigureAwait(false);

            using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                using (var sr = new StreamReader(stream))
                    using (var jsonTextReader = new JsonTextReader(sr))
                    {
                        try
                        {
                            return(jsonSerializer.Deserialize <TObject>(jsonTextReader));
                        }
                        catch (Exception ex)
                        {
                            var exception = new InvalidDataException("failed to deserialize response", ex);

                            string rawResponse = null;
                            try
                            {
                                stream.Position = 0;
                                rawResponse     = await sr.ReadLineAsync().ConfigureAwait(false);

                                exception.Data.Add("rawResponse", rawResponse);
                            }
                            catch { }

                            throw exception;
                        }
                    }
        }
        private void InstanceOnInvalidDataException(object sender, InvalidDataException e)
        {
            Dispatcher.Invoke(() =>
            {
                _popupShownCurrentSession = false;

                if (_mainPage == null)
                {
                    Task.Delay(500).ContinueWith(delegate
                    {
                        BluetoothService.Instance.Connect(GetRegisteredDevice(), GetRegisteredDeviceModel());
                    });
                    return;
                }

                GenerateTrayContext(-1, -1, -1);
                BluetoothService.Instance.Disconnect();
                _mainPage.SetWarning(true, $"{Loc.GetString("mainpage_corrupt_data")} ({e.Message})");
                Task.Delay(500).ContinueWith(delegate
                {
                    BluetoothService.Instance.Connect(GetRegisteredDevice(), GetRegisteredDeviceModel());
                    _mainPage.SetWarning(false);
                });
            });
        }
Example #17
0
        protected override Exception OnSizeQuotaExceeded(int size)
        {
            Exception result = new InvalidDataException(string.Format(SRServiceModel.FramingContentTypeTooLong, size));

            FramingEncodingString.AddFaultString(result, FramingEncodingString.ContentTypeTooLongFault);
            return(result);
        }
Example #18
0
        protected override void ProcessRecord()
        {
            const string particular = @"Software\ParticularSoftware";

            ProviderInfo provider;
            PSDriveInfo  drive;
            var          psPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LicenseFile, out provider, out drive);


            if (provider.ImplementingType != typeof(FileSystemProvider))
            {
                var ex    = new ArgumentException(string.Format("{0} does not resolve to a path on the FileSystem provider.", psPath));
                var error = new ErrorRecord(ex, "InvalidProvider", ErrorCategory.InvalidArgument, psPath);
                WriteError(error);
                return;
            }

            var content = File.ReadAllText(psPath);

            if (!CheckFileContentIsALicenseFile(content))
            {
                var ex    = new InvalidDataException(string.Format("{0} is not not a valid license file", psPath));
                var error = new ErrorRecord(ex, "InvalidLicense", ErrorCategory.InvalidData, psPath);
                WriteError(error);
                return;
            }

            if (EnvironmentHelper.Is64BitOperatingSystem)
            {
                RegistryHelper.LocalMachine(RegistryView.Registry64).WriteValue(particular, "License", content, RegistryValueKind.String);
            }
            RegistryHelper.LocalMachine(RegistryView.Registry32).WriteValue(particular, "License", content, RegistryValueKind.String);
        }
        public void InvalidDataExceptionTest()
        {
            var exception = new InvalidDataException("error");
            var result    = ExceptionTest(exception);

            Assert.AreEqual(exception, result.InnerException);
        }
        protected override Exception OnSizeQuotaExceeded(int size)
        {
            Exception exception = new InvalidDataException(System.ServiceModel.SR.GetString("FramingContentTypeTooLong", new object[] { size }));

            FramingEncodingString.AddFaultString(exception, "http://schemas.microsoft.com/ws/2006/05/framing/faults/ContentTypeTooLong");
            return(exception);
        }
Example #21
0
        /// <inheritdoc />
        /// <remarks>File must contain "Status" and "Thing Name" columns.</remarks>
        /// <exception cref="InvalidDataException">CSV file doesn't contain header.</exception>
        public List <string> ReadCsvFile(string filename)
        {
            // Use HashSet to avoid duplicated data which can produce errors in further work.
            var result = new HashSet <string>();

            using (var reader = new StreamReader(filename))
            {
                var csv = new CsvReader(
                    reader, new CsvHelper.Configuration.Configuration {
                    HasHeaderRecord = true
                }
                    );

                if (!csv.Read() || !csv.ReadHeader())
                {
                    var ex = new InvalidDataException("CSV file doesn't contain header!");
                    _logger.Error(ex, "Got CSV file without header.");
                    throw ex;
                }
                while (csv.Read())
                {
                    string status = csv[_statusHeader];
                    if (!string.IsNullOrEmpty(status))
                    {
                        continue;
                    }

                    string field = csv[_thingNameHeader];
                    result.Add(field);
                }
            }
            return(result.ToList());
        }
Example #22
0
        public static async Task <bool> WriteFrameAsync(ArraySegment <byte> frame, Stream stream, string traceType)
        {
            bool complete;

            var marker = BitConverter.ToInt32(frame.Array, frame.Offset);

            if (marker == BeginFrameMarker)
            {
                complete = false;
            }
            else if (marker == EndFramesMarker)
            {
                complete = true;
            }
            else
            {
                var exc = new InvalidDataException(string.Format("CheckpointFileHelper.WriteFrameAsync : marker = {0}", marker));
                FabricEvents.Events.ReliableConcurrentQueue_ExceptionError(traceType, exc.ToString());
                throw exc;
            }

            await stream.WriteAsync(frame.Array, frame.Offset, frame.Count).ConfigureAwait(false);

            return(complete);
        }
Example #23
0
            public void WhenDisposalOfAnItemFails_StillDisposesOthers_ThrowsAggregateException()
            {
                var firstDisposable  = A.Fake <IDisposable>();
                var secondDisposable = A.Fake <IDisposable>();
                var thirdDisposable  = A.Fake <IDisposable>();

                _sut.Add("D1", firstDisposable, true);
                _sut.Add("D2", secondDisposable, true);
                _sut.Add("D3", thirdDisposable, true);

                var failureReason1 = new InvalidOperationException("I am the cause of the failure of the first disposable");

                A.CallTo(() => firstDisposable.Dispose()).Throws(failureReason1);

                var failureReason2 = new InvalidDataException("I am the cause of the failure of the second disposable");

                A.CallTo(() => secondDisposable.Dispose()).Throws(failureReason2);

                Action act = () => _sut.Dispose();

                act.Should().Throw <AggregateException>()
                .Where(_ => _.InnerExceptions.SequenceEqual(new Exception[] { failureReason1, failureReason2 }));

                A.CallTo(() => firstDisposable.Dispose()).MustHaveHappened();
                A.CallTo(() => secondDisposable.Dispose()).MustHaveHappened();
                A.CallTo(() => thirdDisposable.Dispose()).MustHaveHappened();
            }
        public async Task <AppUserDto> AddUserToChat(int chatId, string userId)
        {
            var defaultError = new InvalidDataException("Invalid credentials were provided.");

            var FoundConversation = await conversationRepository.GetByIdAsync(chatId);

            if (FoundConversation == null)
            {
                throw defaultError;
            }

            var FoundUser = await usersRepository.GetByIdAsync(userId);

            if (FoundUser == null)
            {
                throw defaultError;
            }

            if (await usersConversationsRepository.Exists(FoundUser.Id, FoundConversation.Id))
            {
                throw new InvalidDataException("User already exists in converation.");
            }

            var addedUser = (await usersConversationsRepository.AddAsync(UsersConversationDataModel.Create(userId, chatId))).User;

            await rolesRepository.AddAsync(ChatRoleDataModel.Create(chatId, userId, ChatRole.NoRole));

            await unitOfWork.Commit();

            return(addedUser.ToAppUserDto());
        }
Example #25
0
        public void TestDown()
        {
            InvalidDataException repoDBException = null;

            try {
                this.repo.RunDbObjectValidationCheck();
            } catch (InvalidDataException e) {
                repoDBException = e;
            }

            this.repo.Dispose();
            if (this.localRootDir.Exists)
            {
                this.localRootDir.Delete(true);
            }

            this.remoteRootDir.Refresh();
            this.remoteRootDir.DeleteTree(true, null, true);
            this.repo.Dispose();

            if (repoDBException != null)
            {
                throw new Exception(repoDBException.Message, repoDBException);
            }
        }
        protected Exception CreateException(InvalidDataException innerException, string framingFault)
        {
            Exception exception = this.CreateException(innerException);

            FramingEncodingString.AddFaultString(exception, framingFault);
            return(exception);
        }
        public void LoadJsonManifestFrom_ReturnsNullIfStreamIsEmpty()
        {
            var mockLogger = new Mock <Logger>();

            Log.Default = mockLogger.Object;
            var mockException = new InvalidDataException("Manifest is empty or failed to load and is null.");

            Assert.IsNull(
                ManifestLoader.LoadJsonManifestFrom(
                    new MockAssembly
            {
                MockManifestResourceInfo = new Dictionary <string, ManifestResourceInfo>
                {
                    {
                        @"manifest.json",
                        typeof(ManifestLoaderTest).Assembly.GetManifestResourceInfo(
                            $@"{VirtualTestManifest.Namespace}.manifest.lowercase.json"
                            )
                    }
                },
                MockManifestResourceStream = new Dictionary <string, Stream>
                {
                    { @"manifest.json", new MemoryStream() }
                }
            }
                    )
                );

            mockLogger.Verify(
                l => l.Warn(
                    It.Is <InvalidDataException>(e => e.Message == mockException.Message),
                    "Failed to load manifest.json from MockAssembly."
                    )
                );
        }
Example #28
0
        protected Exception CreateException(InvalidDataException innerException, string framingFault)
        {
            Exception result = CreateException(innerException);

            FramingEncodingString.AddFaultString(result, framingFault);
            return(result);
        }
        public void ParseWindowsLiveResponseNoFragment()
        {
            string invalidUrlFragment = "https://login.live.com/oauth20_desktop.srf?lc=1337";

            InvalidDataException ex = Assert.Throws <InvalidDataException>(
                delegate { AuthenticationService.ParseWindowsLiveResponse(invalidUrlFragment); });

            Assert.IsTrue(ex.Message.StartsWith("Invalid URL fragment"));
        }
Example #30
0
        public static void MessageInnerExceptionConstructor()
        {
            string               message        = "MessageConstructor";
            Exception            innerException = new Exception();
            InvalidDataException ide            = new InvalidDataException(message, innerException);

            Assert.Equal(message, ide.Message);
            Assert.Same(innerException, ide.InnerException);
        }
        public void ThrowsIfBadJson(string path)
        {
            InvalidDataException exception = Assert.Throws <InvalidDataException>(() =>
            {
                SslConfigLoader.LoadCertJson(Path.Combine(TestDir, path));
            });

            Assert.That(exception.Message, Does.StartWith("Cert Json didnt not contain \"path\""));
        }
        public static void MessageInnerExceptionConstructor()
        {
            string message = "MessageConstructor";
            Exception innerException = new Exception();
            InvalidDataException ide = new InvalidDataException(message, innerException);

            Assert.Equal(message, ide.Message);
            Assert.Same(innerException, ide.InnerException);
        }
		/// <summary>
		/// Creates FFmpegException from XmlDocument
		/// </summary>
		/// <param name="xmlDoc">XmlDocument containing data for creating FFmpegException object.</param>
		/// <returns>FFmpegException object</returns>
		public static FFmpegException CreateFromXml(XmlDocument xmlDoc) {
			FFmpegException exception = null;

			if (xmlDoc.DocumentElement != null) {
				XmlNode formatNode = xmlDoc.DocumentElement.SelectSingleNode(FORMAT_NODE);

				if (formatNode != null && formatNode.Attributes != null) {
					var code = formatNode.Attributes[CODE] != null
					           	? Int32.Parse(formatNode.Attributes[CODE].InnerText)
					           	: 0;

					var message = formatNode.Attributes[MESSAGE] != null ? formatNode.Attributes[MESSAGE].InnerText : null;

					switch (code) {
						case -1:
							exception = new OperationNotPermittedException();
							break;
						case -5:
							exception = new IOException();
							break;
						case -10060:
							exception = new UnknownException();
							break;
						case -1094995529:
							exception = new InvalidDataException();
							break;
						default:
							exception = new FFmpegException(message, code);
							break;
					}

				}
			}

			return exception;
		}
        public static void DefaultConstructor()
        {
            InvalidDataException ide = new InvalidDataException();

            Assert.NotNull(ide.Message);
        }