示例#1
0
        private static int Run(CommandLineOptions opts)
        {
            CommandContext.SetVerbose(opts.Verbose);

            var files = FileGlobExpander.Expand(opts.Inputs, Reporter);

            if (files == null)
            {
                return(2);
            }

            foreach (var file in files)
            {
                Reporter.VerboseLine($"Loading file: [{file.FullName}]");

                var context = new ParseContext
                {
                    DisplayedPath   = file.Name,
                    FullPath        = file.FullName,
                    GeneratedFrames = new List <IcoFrame>(),
                    Reporter        = Reporter,
                    PngEncoder      = new SixLabors.ImageSharp.Formats.Png.PngEncoder
                    {
                        CompressionLevel = 9,
                        ColorType        = SixLabors.ImageSharp.Formats.Png.PngColorType.RgbWithAlpha,
                    },
                };

                ExceptionWrapper.Try(() => DoExtractFile(context, opts), context, Reporter);
            }

            return(0);
        }
示例#2
0
        private static void DoFile(ParseContext context, CommandLineOptions opts)
        {
            byte[] data = null;

            try
            {
                if (!opts.AllowGiantFiles)
                {
                    var length = new FileInfo(context.FullPath).Length;
                    if (length > FileFormatConstants.MaxIcoFileSize)
                    {
                        Reporter.WarnLine(IcoErrorCode.FileTooLarge, $"Skipping file because it is unusually large ({length} bytes).  Re-run with --allow-giant-inputs to bypass this safety.", context.FullPath);
                        return;
                    }
                }

                data = File.ReadAllBytes(context.FullPath);
            }
            catch (Exception e)
            {
                System.Console.WriteLine($"Exception {e} while reading file \"{context.DisplayedPath}\"");
                return;
            }

            ExceptionWrapper.Try(() => DoFile(data, context, opts), context, Reporter);
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var            ex = httpContext.Features.Get <IExceptionHandlerFeature>()?.Error;
            HttpStatusCode statusCode;

            if (ex is NotFoundException)
            {
                statusCode = HttpStatusCode.NotFound;
            }
            else if (ex is BadRequestException)
            {
                statusCode = HttpStatusCode.BadRequest;
            }
            else
            {
                statusCode = HttpStatusCode.InternalServerError;
            }
            var wrappedException = new ExceptionWrapper(ex);

            wrappedException.StatusCode      = (int)statusCode;
            httpContext.Response.StatusCode  = (int)statusCode;
            httpContext.Response.ContentType = "application/json";
            await using var writer           = new StreamWriter(httpContext.Response.Body);
            new JsonSerializer().Serialize(writer, wrappedException);
            await writer.FlushAsync().ConfigureAwait(false);
        }
        private static Result <CreditNote> CreateCreditNote(
            WineMsCreditNoteTransactionDocument creditNoteTransactionDocument) =>
        ExceptionWrapper
        .Wrap(
            () =>
        {
            var customer = new Customer(creditNoteTransactionDocument.CustomerAccountCode);

            var creditNote = (CreditNote)
                             new CreditNote {
                Customer        = customer,
                DeliveryDate    = creditNoteTransactionDocument.TransactionDate,
                Description     = "Credit Note",
                DiscountPercent = (double)creditNoteTransactionDocument.DocumentDiscountPercentage,
                DueDate         = creditNoteTransactionDocument.TransactionDate,
                InvoiceDate     = creditNoteTransactionDocument.TransactionDate,
                OrderDate       = creditNoteTransactionDocument.TransactionDate,
                OrderNo         = creditNoteTransactionDocument.DocumentNumber
            }
            .SetDeliveryAddress(customer)
            .SetPostalAddress(customer)
            .SetMessageLines(creditNoteTransactionDocument)
            .SetTaxMode(customer)
            .SetExchangeRate(customer, creditNoteTransactionDocument.ExchangeRate)
            ;

            return(Result.Ok(creditNote));
        });
        private static Result <SalesOrder> CreateSalesOrder(
            WineMsSalesOrderTransactionDocument salesOrderTransactionDocument) =>
        ExceptionWrapper
        .Wrap(
            () =>
        {
            var customer = new Customer(salesOrderTransactionDocument.CustomerAccountCode);

            var salesOrder = (SalesOrder)
                             new SalesOrder {
                Customer        = customer,
                DeliveryDate    = salesOrderTransactionDocument.TransactionDate,
                Description     = "Tax Invoice",
                DiscountPercent = (double)salesOrderTransactionDocument.DocumentDiscountPercentage,
                DueDate         = salesOrderTransactionDocument.TransactionDate,
                InvoiceDate     = salesOrderTransactionDocument.TransactionDate,
                OrderDate       = salesOrderTransactionDocument.TransactionDate,
                OrderNo         = salesOrderTransactionDocument.DocumentNumber
            }
            .SetDeliveryAddress(customer)
            .SetPostalAddress(customer)
            .SetMessageLines(salesOrderTransactionDocument)
            .SetTaxMode(customer)
            .SetExchangeRate(customer, salesOrderTransactionDocument.ExchangeRate)
            ;

            return(Result.Ok(salesOrder));
        });
示例#6
0
        private static int Run(CommandLineOptions opts)
        {
            var files = FileGlobExpander.Expand(opts.Inputs, Reporter);

            if (files == null)
            {
                return(2);
            }

            foreach (var file in files)
            {
                Reporter.VerboseLine($"Loading file: [{file.FullName}]");

                var context = new ParseContext
                {
                    DisplayedPath   = file.Name,
                    FullPath        = file.FullName,
                    GeneratedFrames = new List <IcoFrame>(),
                    Reporter        = Reporter,
                };

                ExceptionWrapper.Try(() => DoPrintFileInfo(context, opts), context, Reporter);
            }

            Reporter.PrintHelpUrls();

            return(0);
        }
        public static AdvancedInformationForm ShowDetailsDialog(ExceptionWrapper ex, IWin32Window owner = null)
        {
            AdvancedInformationForm form = new AdvancedInformationForm(ex);

            form.ShowDialog(owner);
            return(form);
        }
示例#8
0
 private void exceptionTree_AfterSelect(object sender, TreeViewEventArgs e)
 {
     if (e.Node.Tag != null && e.Node.Tag is ExceptionWrapper)
     {
         ExceptionWrapper exceptionWrapper = (ExceptionWrapper)e.Node.Tag;
         exceptionType.Text    = exceptionWrapper.ExceptionType;
         exceptionMessage.Text = exceptionWrapper.ExceptionMessage;
         nativeErrorCode.Text  = exceptionWrapper.NativeErrorCode;
         stackTraceList.Items.Clear();
         foreach (string stackTrace in exceptionWrapper.StackTraceList)
         {
             string text = stackTrace.Trim();
             if (!string.IsNullOrEmpty(text))
             {
                 ListViewItem listViewItem = new ListViewItem(text);
                 if (!text.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("System.", StringComparison.OrdinalIgnoreCase))
                 {
                     ListViewItem listViewItem2 = listViewItem;
                     listViewItem2.Font = new Font(listViewItem2.Font, FontStyle.Bold);
                 }
                 stackTraceList.Items.Add(listViewItem);
             }
         }
     }
 }
        private TreeNode GetTreeNode(ExceptionWrapper exWrap)
        {
            TreeNode tn = new TreeNode("Error");

            tn.Nodes.Add(new TreeNode(nameof(exWrap.Message))
            {
                Tag = exWrap.Message
            });
            tn.Nodes.Add(new TreeNode(nameof(exWrap.Source))
            {
                Tag = exWrap.Source
            });
            tn.Nodes.Add(new TreeNode(nameof(exWrap.Helplink))
            {
                Tag = exWrap.Helplink
            });
            tn.Nodes.Add(new TreeNode(nameof(exWrap.StackTrace))
            {
                Tag = exWrap.StackTrace
            });

            if (exWrap.InnerException != null)
            {
                TreeNode tnInner = GetTreeNode(exWrap.InnerException);
                tn.Nodes.Add(tnInner);
            }
            return(tn);
        }
 public void ShouldDoNothingIfDifferentExceptionType()
 {
     ExceptionWrapper<InvalidOperationException> wrapper = new ExceptionWrapper<InvalidOperationException>((e, m) => e);
     IInvocation invocation = Substitute.For<IInvocation>();
     invocation.Request.Target.Returns(typeof(WithAttribute));
     invocation.Request.Method.Returns(typeof(WithAttribute).GetMethod("DoSomething"));
     invocation.When(i => i.Proceed()).Do(x => { throw new OutOfMemoryException(); });
     wrapper.Intercept(invocation);
 }
        public void ShouldDoNothingIfNoExceptionIsThrown()
        {
            ExceptionWrapper<Exception> wrapper = new ExceptionWrapper<Exception>((e, m) => e);

            IInvocation invocation = Substitute.For<IInvocation>();
            invocation.Request.Target.Returns(typeof(WithAttribute));
            invocation.Request.Method.Returns(typeof(WithAttribute).GetMethod("DoSomething"));
            wrapper.Intercept(invocation);
        }
示例#12
0
        public void ShouldDoNothingIfDifferentExceptionType()
        {
            ExceptionWrapper <InvalidOperationException> wrapper = new ExceptionWrapper <InvalidOperationException>((e, m) => e);
            IInvocation invocation = Substitute.For <IInvocation>();

            invocation.Request.Target.Returns(typeof(WithAttribute));
            invocation.Request.Method.Returns(typeof(WithAttribute).GetMethod("DoSomething"));
            invocation.When(i => i.Proceed()).Do(x => { throw new OutOfMemoryException(); });
            wrapper.Intercept(invocation);
        }
示例#13
0
        public void ShouldDoNothingIfNoExceptionIsThrown()
        {
            ExceptionWrapper <Exception> wrapper = new ExceptionWrapper <Exception>((e, m) => e);

            IInvocation invocation = Substitute.For <IInvocation>();

            invocation.Request.Target.Returns(typeof(WithAttribute));
            invocation.Request.Method.Returns(typeof(WithAttribute).GetMethod("DoSomething"));
            wrapper.Intercept(invocation);
        }
        public ObjectWrapperFactory(SerializationContext context)
        {
            this.context = context;

            defaultWrapper = new BasicObjectWrapper(context);

            wrappers[typeof(AsObject)]        = new AsObjectWrapper(context);
            wrappers[typeof(IExternalizable)] = new ExternalizableWrapper(context);
            wrappers[typeof(Exception)]       = new ExceptionWrapper(context);
        }
示例#15
0
        private static int Run(CommandLineOptions opts)
        {
            CommandContext.SetVerbose(opts.Verbose);

            foreach (var warning in opts.DisabledWarnings)
            {
                var munged = warning;
                if (munged.StartsWith("ico", StringComparison.InvariantCultureIgnoreCase))
                {
                    munged = warning.Substring(3);
                }

                int code;
                if (!int.TryParse(munged, out code) ||
                    null == Enum.GetName(typeof(IcoErrorCode), code))
                {
                    Reporter.ErrorLine(IcoErrorCode.NoError, $"Unknown warning number \"{warning}\"");
                    return(1);
                }

                Reporter.WarningsToIgnore.Add((IcoErrorCode)code);
            }

            var files = FileGlobExpander.Expand(opts.Inputs, Reporter);

            if (files == null)
            {
                return(2);
            }

            foreach (var file in files)
            {
                Reporter.VerboseLine($"Loading file: [{file.FullName}]");

                var context = new ParseContext
                {
                    DisplayedPath   = file.Name,
                    FullPath        = file.FullName,
                    GeneratedFrames = new List <IcoFrame>(),
                    Reporter        = Reporter,
                };

                ExceptionWrapper.Try(() => DoLintFile(context, opts), context, Reporter);
            }

            Reporter.PrintHelpUrls();

            if (Reporter.NumberOfWarningsOrErrors > 0)
            {
                return(3);
            }

            return(0);
        }
        public void TryGetValueOrExceptionString_Can_ReturnValues()
        {
            string someString = "Some string...";

            ExceptionWrapper.Returner <string>           stringReturner     = () => someString;
            ExceptionWrapper.ExceptionConverter <string> exceptionConverter = ExceptionInfoProvider.GetExceptionInfo;

            string gottenString = ExceptionWrapper.TryGetValueOrExceptionString(stringReturner, exceptionConverter);

            Assert.AreEqual <string>(someString, gottenString);
        }
示例#17
0
        private static bool ValidateAndSave(PropertyInfo property, object propertyValue)
        {
            var propertyToSave = typeof(Configuration).GetProperty(property.Name, BindingFlags.Public | BindingFlags.Static);

            if (propertyToSave != null)
            {
                var oldValue = propertyToSave.GetValue(null);
                ExceptionWrapper.TrySafe <Exception>(() => propertyToSave.SetValue(null, propertyValue));
                return(!propertyToSave.GetValue(null).Equals(oldValue));
            }
            return(false);
        }
示例#18
0
        public ClipboardDataItem GetClipboardDataItem()
        {
            string text    = String.Empty;
            bool   isError = false;

            if (Clipboard.ContainsText())
            {
                isError        = !ExceptionWrapper.TrySafe <Exception>(
                    () => text = Clipboard.GetText(),
                    ex => text = String.Format(Resources.ClipboardException, ex.Message));
            }
            return(new ClipboardDataItem(text, isError));
        }
示例#19
0
 private static Result <PurchaseOrder> CreatePurchaseOrder(
     WineMsPurchaseOrderTransactionDocument salesOrderTransactionDocument) =>
 ExceptionWrapper
 .Wrap(
     () => Result.Ok(
         new PurchaseOrder {
     Supplier     = new Supplier(salesOrderTransactionDocument.SupplierAccountCode),
     DeliveryDate = salesOrderTransactionDocument.TransactionDate,
     DueDate      = salesOrderTransactionDocument.TransactionDate,
     OrderDate    = salesOrderTransactionDocument.TransactionDate,
     OrderNo      = salesOrderTransactionDocument.DocumentNumber,
     TaxMode      = TaxMode.Exclusive
 }));
示例#20
0
        private static Result <OrderBase> AddOrderLines(
            this OrderBase order,
            WineMsOrderTransactionDocument salesOrderTransactionDocument,
            OrderTransactionType orderTransactionType) =>
        WineMsTransactionDocumentFunctions
        .ForEachTransactionDocumentLine(
            transactionLine =>
            ExceptionWrapper
            .Wrap(
                () =>
        {
            var isGeneralLedgerLine = IsGeneralLedgerLine(transactionLine);
            var orderLine           = NewOrderDetail(order);

            if (isGeneralLedgerLine)
            {
                SetGeneralLedgerAccount(orderLine, transactionLine);
            }
            else
            {
                SetInventoryItem(orderLine, transactionLine);
            }

            orderLine.Quantity  = (double)transactionLine.Quantity;
            orderLine.ToProcess = orderLine.Quantity;
            SetUnitSellingPrice(orderLine, transactionLine);

            if (transactionLine.TaxTypeId > 0)
            {
                var result = GetOrderLineTaxType(transactionLine);
                if (result.IsFailure)
                {
                    return(Result.Fail(result.Error));
                }
                orderLine.TaxType = result.Value;
            }

            orderLine.DiscountPercent = (double)transactionLine.LineDiscountPercentage;
            orderLine.Description     = transactionLine.Description1;

            if (!transactionLine.ItemNote.IsNullOrWhiteSpace())
            {
                orderLine.Note = transactionLine.ItemNote;
            }

            SetUserDefinedFields(orderTransactionType, orderLine, transactionLine);

            return(Result.Ok());
        }),
            salesOrderTransactionDocument.TransactionLines)
        .OnSuccess(() => order);
 public static Result <WineMsCreditNoteTransactionDocument> ProcessTransaction(
     WineMsCreditNoteTransactionDocument wineMsCreditNoteTransactionDocument) =>
 CreateCreditNote(wineMsCreditNoteTransactionDocument)
 .OnSuccess(
     creditNote => creditNote.AddSalesOrderLines(wineMsCreditNoteTransactionDocument))
 .OnSuccess(
     creditNote => ExceptionWrapper
     .Wrap(
         () =>
 {
     creditNote.Save();
     wineMsCreditNoteTransactionDocument.IntegrationDocumentNumber = creditNote.OrderNo;
     return(Result.Ok(wineMsCreditNoteTransactionDocument));
 }));
示例#22
0
 public static Result <WineMsPurchaseOrderTransactionDocument> ProcessTransaction(
     WineMsPurchaseOrderTransactionDocument wineMsSalesOrderTransactionDocument) =>
 CreatePurchaseOrder(wineMsSalesOrderTransactionDocument)
 .OnSuccess(
     order => order.AddPurchaseOrderLines(wineMsSalesOrderTransactionDocument))
 .OnSuccess(
     order => ExceptionWrapper
     .Wrap(
         () =>
 {
     order.Save();
     wineMsSalesOrderTransactionDocument.IntegrationDocumentNumber = order.OrderNo;
     return(Result.Ok(wineMsSalesOrderTransactionDocument));
 }));
示例#23
0
        private ExceptionWrapper ExtractException(XmlElement node, out bool hasInnerException)
        {
            ExceptionWrapper exceptionWrapper = null;

            hasInnerException = false;
            if (node != null)
            {
                exceptionWrapper = new ExceptionWrapper();
                if (node["ExceptionType"] != null)
                {
                    exceptionWrapper.ExceptionType = node["ExceptionType"].InnerText;
                }
                if (node["Message"] != null)
                {
                    exceptionWrapper.ExceptionMessage = node["Message"].InnerText;
                }
                if (node["NativeErrorCode"] != null)
                {
                    exceptionWrapper.NativeErrorCode = node["NativeErrorCode"].InnerText;
                }
                if (node["InnerException"] != null)
                {
                    hasInnerException = true;
                }
                if (node["StackTrace"] != null)
                {
                    string innerText = node["StackTrace"].InnerText;
                    innerText = innerText.Trim();
                    if (innerText.StartsWith("at ", StringComparison.OrdinalIgnoreCase))
                    {
                        innerText = innerText.Substring("at ".Length);
                    }
                    string[] array = innerText.Split(new string[1]
                    {
                        " at "
                    }, StringSplitOptions.RemoveEmptyEntries);
                    if (array != null)
                    {
                        string[] array2 = array;
                        foreach (string text in array2)
                        {
                            exceptionWrapper.StackTraceList.Add(text.Trim());
                        }
                    }
                }
            }
            return(exceptionWrapper);
        }
        public void TryGetValueOrExceptionString_Can_ReturnExceptionInfo()
        {
            ApplicationException exceptionToThrow = new ApplicationException("Threwn exception");

            ExceptionWrapper.Returner <string> stringReturner = () =>
            {
                throw exceptionToThrow;
            };
            ExceptionWrapper.ExceptionConverter <string> exceptionConverter = ExceptionInfoProvider.GetExceptionInfo;

            string gottenString = ExceptionWrapper.TryGetValueOrExceptionString(stringReturner, exceptionConverter);

            string expected = ExceptionInfoProvider.GetExceptionInfo(exceptionToThrow);

            Assert.AreEqual <string>(expected, gottenString);
        }
示例#25
0
        private void _client_WebSocketFailed(object sender, WebSocketFailedEventArgs e)
        {
            if (e.Error != null)
            {
                var ex = new ExceptionWrapper(e.Error);
                OnError(ex);
            }
            else
            {
                OnError(new Exception("Unknown WebSocket Error!"));
            }

            if (IsOpen)
            {
                OnClosed();
            }
        }
        public async Task <RepositoryActionResult <EventInvite> > AddInviteEmailAsync(int eventId, string senderId, string email)
        {
            var sender = await _context.Users.FirstOrDefaultAsync(u => u.Id == senderId);

            var invited = await _context.Users.FirstOrDefaultAsync(u => u.Email == email);

            var @event = await _context.Events.FirstOrDefaultAsync(e => e.EventId == eventId);

            if (sender == null || invited == null || @event == null)
            {
                return(new RepositoryActionResult <EventInvite>(null, RepositoryStatus.NotFound));
            }

            var existingInvite = await _context.EventInvites.FirstOrDefaultAsync(
                i => i.EventId == eventId && i.Invited.Email == email);

            if (existingInvite != null)
            {
                return(new RepositoryActionResult <EventInvite>(existingInvite, RepositoryStatus.BadRequest));
            }

            try
            {
                var invite = new EventInvite {
                    EventId = eventId, SenderId = senderId, InvitedId = invited.Id
                };
                var result = _context.EventInvites.Add(invite);
                await _context.SaveChangesAsync();

                //new InviteSender().SendEventInvite(invite);
                return(new RepositoryActionResult <EventInvite>(result, RepositoryStatus.Created));
            }
            catch (Exception e)
            {
                var ex = new ExceptionWrapper
                {
                    ExceptionMessage    = e.Message,
                    ExceptionStackTrace = e.StackTrace,
                    LogTime             = DateTime.Now
                };
                _context.Exception.Add(ex);
                await _context.SaveChangesAsync();

                return(new RepositoryActionResult <EventInvite>(null, RepositoryStatus.Error));
            }
        }
        /// <summary>
        /// Загрузка терриконов в главный грид окна.
        /// Если указан ID склада - в выборку попадут терриконы склада,
        /// если ID не указан - ХП вернёт все терриконы цеха.
        /// </summary>
        private void RefreshSimilarHeaps()
        {
            try
            {
                // 1) вызов ХП осуществляющей выборку терриконов,
                // 2) сохранение рекордсета в переменную "dts".
                dts = ExceptionWrapper.ProcessResult(
                    () => spc.FillTable("GetHeap",
                                        "nUnitIdIn", UnitId, SqlDbType.Int,    //если null - ХП вернёт все терриконы цеха.
                                        "nOwnerIdIn", OwnerId, SqlDbType.Int,
                                        "nMaterialIdIn", null, SqlDbType.Int,
                                        "nFractionIdIn", null, SqlDbType.Int,
                                        "nIsDel", 0, SqlDbType.Int
                                        ),
                    "Ошибка получения списка терриконов",
                    this
                    );

                // Загрузка полученного рекордсета в грид.
                igMain.DataSource = dts;

                // Запомним DataRow требуемого террикона.
                if (dts != null && dts.Rows.Count > 0)
                {
                    requiredRow = dts.AsEnumerable()
                                  .Where(row => row.Field <int>("nHeapId").Equals(HeapId))
                                  .FirstOrDefault();

                    // Сортировка терриконов по складам.
                    igMain.Sort(igMain.Columns["colSHPlace"], ListSortDirection.Descending);
                    // Сброс выделения строки по умолчанию
                    igMain.ClearSelection();
                    // Check записи в гриде с входным терриконом.
                    igMain.CheckRow(requiredRow, true);
                }
                // Получаем cуммарную ширину столбцов главного грида.
                WidthVisibleColumnsGrid(igMain);
            }
            catch (Exception ex)
            {
                // public class MessageBoxes from Itm.WClient.Com;
                MessageBoxes.Error(this, ex, "Ошибка наполнения главной таблицы!");
                return;
            }
        }
示例#28
0
 private void DisplayExceptionTree(string exceptionXml)
 {
     if (!string.IsNullOrEmpty(exceptionXml))
     {
         CleanUp();
         try
         {
             XmlDocument xmlDocument = new XmlDocument();
             xmlDocument.LoadXml(exceptionXml);
             XmlElement documentElement = xmlDocument.DocumentElement;
             if (documentElement != null && string.Compare(documentElement.Name, "Exception", true, CultureInfo.CurrentUICulture) == 0)
             {
                 bool             hasInnerException = false;
                 ExceptionWrapper exceptionWrapper  = ExtractException(documentElement, out hasInnerException);
                 if (exceptionWrapper != null)
                 {
                     TreeNode treeNode = new TreeNode(exceptionWrapper.ExceptionType);
                     exceptionTree.Nodes.Add(treeNode);
                     treeNode.Tag         = exceptionWrapper;
                     treeNode.ToolTipText = exceptionWrapper.ExceptionMessage;
                     TreeNode   treeNode2  = exceptionTree.Nodes[0];
                     XmlElement xmlElement = documentElement["InnerException"];
                     while (hasInnerException && xmlElement != null)
                     {
                         exceptionWrapper = ExtractException(xmlElement, out hasInnerException);
                         if (exceptionWrapper == null)
                         {
                             break;
                         }
                         treeNode2.Nodes.Add(exceptionWrapper.ExceptionType);
                         treeNode2.Nodes[0].Tag         = exceptionWrapper;
                         treeNode2.Nodes[0].ToolTipText = exceptionWrapper.ExceptionMessage;
                         treeNode2  = treeNode2.Nodes[0];
                         xmlElement = xmlElement["InnerException"];
                     }
                 }
             }
         }
         catch (XmlException e)
         {
             throw new TraceViewerException(SR.GetString("FV_ERROR"), e);
         }
     }
 }
        public void ShouldUseDifferentErrorMessageWithAttribute()
        {
            ExceptionWrapper<Exception> wrapper = new ExceptionWrapper<Exception>((e, m) => new InvalidOperationException(m, e));

            IInvocation invocation = Substitute.For<IInvocation>();
            invocation.Request.Target.Returns(typeof(WithAttribute));
            invocation.Request.Method.Returns(typeof(WithAttribute).GetMethod("DoSomething"));
            const string message = "Error message";
            invocation.When(i => i.Proceed()).Do(x => { throw new Exception(message); });
            try
            {
                wrapper.Intercept(invocation);
                Assert.Fail("The exception was swallowed.");
            }
            catch (InvalidOperationException exception)
            {
                Assert.AreEqual(WithAttribute.ErrorMessage, exception.Message);
            }
        }
        public void ShouldUseClosestMatchWhenMultipleMessagesProvided()
        {
            ExceptionWrapper<Exception> wrapper = new ExceptionWrapper<Exception>((e, m) => new InvalidOperationException(m, e));

            IInvocation invocation = Substitute.For<IInvocation>();
            invocation.Request.Target.Returns(typeof(WithMultipleAttributes));
            invocation.Request.Method.Returns(typeof(WithMultipleAttributes).GetMethod("DoSomething"));
            const string parameterName = "x";
            invocation.When(i => i.Proceed()).Do(x => { throw new ArgumentNullException(parameterName); });
            try
            {
                wrapper.Intercept(invocation);
                Assert.Fail("The exception was swallowed.");
            }
            catch (InvalidOperationException exception)
            {
                Assert.AreEqual(WithMultipleAttributes.DerivedErrorMessage, exception.Message);
            }
        }
示例#31
0
        /// <summary>
        /// Отмена операции объединения терриконов.
        /// Метод осуществляет вызов соответствующей хранимой процедуры в SQL сервере.
        /// </summary>
        /// <remarks>
        /// Автор: Пантелеев М.Ю.
        /// Дата: 28.05.2015г.
        /// </remarks>
        private void UndoUnionHeap()
        {
            try
            {
                // Формируем сообщение.
                var message = string.Format("Вы действительно желаете отменить объединение терриконов?");

                // Выводим предупреждение и ожидаем решения пользователя.
                var res = MessageBox.Show(message, "Отмена объединения терриконов", MessageBoxButtons.YesNo,
                                          MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                // Если был получен положительный ответ
                if (res == DialogResult.Yes)
                {
                    var row = igMain.SelectedDataRow;

                    // и террикон выбран
                    if (row != null)
                    {
                        // Вызываем хранимую процедуру отката операции объединения.
                        ExceptionWrapper.ProcessNoResult
                        (
                            () =>
                        {
                            spc.ExecuteNonQuery("UndoUnionHeap",
                                                "nHeapGUIDIn", row["nGUID"], SqlDbType.UniqueIdentifier);
                        },
                            "Ошибка отмены объединения терриконов.",
                            this
                        );
                        // Обновление списка терриконов в главном гриде.
                        RefreshGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                // public class MessageBoxes from Itm.WClient.Com;
                MessageBoxes.Error(this, ex, "Ошибка отмены операции объединения терриконов!");
                return;
            }
        }
示例#32
0
        public static void ThrowsSameExceptionAsMsoft(string input, string pattern, AlgorithmType algorithmType, RegexOptions options)
        {
            Exception expected = catchException(() => { Msoft.Regex.Matches(input, pattern, ToMsoftRegexOptions(options)); },
                                                ".NET Regex", input, pattern, options),
            actual = catchException(() => { new Regex2(pattern, algorithmType, options).Matches(input); },
                                    "Regex2", input, pattern, options);

            DisplayExpectedException(input, pattern, algorithmType, options, actual);

            try
            {
                CollectionAssert.AreEqual(exceptionChain(expected).Select(ex => ExceptionWrapper.Create(ex)).ToArray(),
                                          exceptionChain(actual).Select(ex => ExceptionWrapper.Create(ex)).ToArray(),
                                          "Comparing exceptions thrown.");
            }
            catch (Exception ex)
            {
                throw new AssertionException(formatException(input, pattern, options, ex));
            }
        }
示例#33
0
        public void ShouldUseDifferentErrorMessageWithAttribute()
        {
            ExceptionWrapper <Exception> wrapper = new ExceptionWrapper <Exception>((e, m) => new InvalidOperationException(m, e));

            IInvocation invocation = Substitute.For <IInvocation>();

            invocation.Request.Target.Returns(typeof(WithAttribute));
            invocation.Request.Method.Returns(typeof(WithAttribute).GetMethod("DoSomething"));
            const string message = "Error message";

            invocation.When(i => i.Proceed()).Do(x => { throw new Exception(message); });
            try
            {
                wrapper.Intercept(invocation);
                Assert.Fail("The exception was swallowed.");
            }
            catch (InvalidOperationException exception)
            {
                Assert.AreEqual(WithAttribute.ErrorMessage, exception.Message);
            }
        }
示例#34
0
        public void ShouldUseClosestMatchWhenMultipleMessagesProvided()
        {
            ExceptionWrapper <Exception> wrapper = new ExceptionWrapper <Exception>((e, m) => new InvalidOperationException(m, e));

            IInvocation invocation = Substitute.For <IInvocation>();

            invocation.Request.Target.Returns(typeof(WithMultipleAttributes));
            invocation.Request.Method.Returns(typeof(WithMultipleAttributes).GetMethod("DoSomething"));
            const string parameterName = "x";

            invocation.When(i => i.Proceed()).Do(x => { throw new ArgumentNullException(parameterName); });
            try
            {
                wrapper.Intercept(invocation);
                Assert.Fail("The exception was swallowed.");
            }
            catch (InvalidOperationException exception)
            {
                Assert.AreEqual(WithMultipleAttributes.DerivedErrorMessage, exception.Message);
            }
        }