示例#1
0
        public static void ServiceThrowsExceptionDetailsIncludedInFault()
        {
            string exceptionMessage    = "This is the exception message";
            string stackTraceTopMethod = "   at ErrorHandling.ThrowingService.Echo(String echo)";

            System.ServiceModel.ChannelFactory <ISimpleService> factory = DispatcherHelper.CreateChannelFactory <ThrowingDetailInFaultService, ISimpleService>(
                (services) =>
            {
                services.AddSingleton(new ThrowingDetailInFaultService(new Exception(exceptionMessage)));
            });
            factory.Open();
            ISimpleService channel = factory.CreateChannel();

            ((System.ServiceModel.IClientChannel)channel).Open();
            System.ServiceModel.FaultException <System.ServiceModel.ExceptionDetail> exceptionThrown = Assert.Throws <System.ServiceModel.FaultException <System.ServiceModel.ExceptionDetail> >(() =>
            {
                _ = channel.Echo("hello");
            });
            Assert.NotNull(exceptionThrown);
            Assert.NotNull(exceptionThrown.Detail);
            Assert.True(exceptionThrown.Code.IsReceiverFault);
            System.ServiceModel.ExceptionDetail detail = exceptionThrown.Detail;
            Assert.Equal(exceptionMessage, detail.Message);
            Assert.StartsWith(stackTraceTopMethod, detail.StackTrace);
            Assert.Equal("InternalServiceFault", exceptionThrown.Code.SubCode.Name);
            ((System.ServiceModel.Channels.IChannel)channel).Close();
            factory.Close();
            TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory);
        }
示例#2
0
        public static void ServiceThrowsTimeoutException()
        {
            var factory = DispatcherHelper.CreateChannelFactory <ThrowingService, ISimpleService>(
                (services) =>
            {
                services.AddSingleton(new ThrowingService(new TimeoutException()));
            });

            factory.Open();
            var channel = factory.CreateChannel();

            System.ServiceModel.FaultException exceptionThrown = null;
            try
            {
                var echo = channel.Echo("hello");
            }
            catch (System.ServiceModel.FaultException e)
            {
                exceptionThrown = e;
            }

            Assert.NotNull(exceptionThrown);
            Assert.True(exceptionThrown.Code.IsReceiverFault);
            Assert.Equal("InternalServiceFault", exceptionThrown.Code.SubCode.Name);
            ((System.ServiceModel.Channels.IChannel)channel).Close();
            factory.Close();
            TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory);
        }
示例#3
0
        public static async Task AsyncServiceThrowsTimeoutExceptionAfterAwait()
        {
            System.ServiceModel.ChannelFactory <ISimpleAsyncService> factory = DispatcherHelper.CreateChannelFactory <ThrowingAsyncService, ISimpleAsyncService>(
                (services) =>
            {
                services.AddSingleton(new ThrowingAsyncService(new TimeoutException(), beforeAwait: false));
            });
            factory.Open();
            ISimpleAsyncService channel = factory.CreateChannel();

            ((System.ServiceModel.IClientChannel)channel).Open();
            System.ServiceModel.FaultException exceptionThrown = null;
            try
            {
                string echo = await channel.EchoAsync("hello");
            }
            catch (System.ServiceModel.FaultException e)
            {
                exceptionThrown = e;
            }

            Assert.NotNull(exceptionThrown);
            Assert.True(exceptionThrown.Code.IsReceiverFault);
            Assert.Equal("InternalServiceFault", exceptionThrown.Code.SubCode.Name);
            ((System.ServiceModel.Channels.IChannel)channel).Close();
            factory.Close();
            TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory);
        }
示例#4
0
 private void VerifyFaultThrown(System.ServiceModel.FaultException <ClientContract.SampleServiceFault> faultEx)
 {
     if (faultEx == null)
     {
         throw new ArgumentNullException("faultEx");
     }
     ClientContract.SampleServiceFault detail = faultEx.Detail;
     Assert.True(detail.ID.Equals("101") && detail.Message.Equals("Error has occurred while performing an operation."));
 }
        /// <summary>
        /// Initialize a new instance of UpstreamServerException from a SOAP FaultException.
        /// </summary>
        /// <param name="soapException">The inner SOAP exception.</param>
        public UpstreamServerException(System.ServiceModel.FaultException soapException) : base(soapException.Message, soapException)
        {
            var faultReasonText = soapException.Reason.GetMatchingTranslation().Text;

            ErrorCode = UpstreamServerErrorCode.Unknown;

            if (!string.IsNullOrEmpty(faultReasonText))
            {
                // Match the reason in the inner exception with a known error code
                foreach (var errorCode in (UpstreamServerErrorCode[])Enum.GetValues(typeof(UpstreamServerErrorCode)))
                {
                    if (faultReasonText.Contains(errorCode.ToString()))
                    {
                        ErrorCode = errorCode;
                        break;
                    }
                }
            }
        }
示例#6
0
        /// <summary>
        /// Handles "StepCompleted" event.
        /// </summary>
        /// <param name="result"></param>
        void _td_StepCompleted(StepResult result)
        {
            System.ServiceModel.FaultException fault = result.Exception as System.ServiceModel.FaultException;
            bool bFault = false;

            if (fault != null)
            {
                bFault = true;
            }

            string stepResult = string.Format("STEP {0}", result.Status.ToString().ToUpper());

            if (result.Status == StepStatus.Failed && !bFault)
            {
                WriteLog(result.Message, LogEntryLevel.StepDetails);
            }
            WriteLog(stepResult, LogEntryLevel.Step);
            WriteLog(string.Empty, LogEntryLevel.Test);

            DisplayStepResult(result);
        }
示例#7
0
        public void ServiceOp_ThrowsFaultException(string serviceOpType)
        {
            var host = ServiceHelper.CreateWebHostBuilder <AggregateExceptionStartup>(_output).Build();

            using (host)
            {
                host.Start();
                var sampleServiceClient = ClientHelper.GetProxy <ClientContract.IAggregateExceptionService>();
                try
                {
                    switch (serviceOpType)
                    {
                    case "SimpleOperationThrowingFault":
                        sampleServiceClient.SimpleOperationThrowingFault();
                        break;

                    case "SimpleOperationThrowingFault_WithTask":
                    {
                        Task task = sampleServiceClient.SimpleOperationThrowingFaultAsync();
                        task.Wait();
                        break;
                    }

                    case "ServiceOpWithMultipleTasks":
                        sampleServiceClient.ServiceOpWithMultipleTasks();
                        break;

                    case "ServiceOpWithMultipleTasks_WithTask":
                    {
                        Task task2 = sampleServiceClient.ServiceOpWithMultipleTasksAsync();
                        task2.Wait();
                        break;
                    }

                    case "ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTask":
                        sampleServiceClient.ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTask();
                        break;

                    case "ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTask_WithTask":
                    {
                        Task task3 = sampleServiceClient.ServiceOpWithChainedTasks_ThrowFaultExceptionInOneTaskAsync();
                        task3.Wait();
                        break;
                    }
                    }
                    throw new Exception("Expected fault but got result successfully.");
                }
                catch (System.ServiceModel.FaultException <ClientContract.SampleServiceFault> faultEx)
                {
                    this.VerifyFaultThrown(faultEx);
                }
                catch (AggregateException ex)
                {
                    System.ServiceModel.FaultException <ClientContract.SampleServiceFault> faultEx2 = ex.InnerExceptions[0] as System.ServiceModel.FaultException <ClientContract.SampleServiceFault>;
                    this.VerifyFaultThrown(faultEx2);
                }
                catch (Exception ex2)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine();
                    stringBuilder.AppendLine("Expected a fault exception of type 'SampleServiceFault' but got the following.");
                    stringBuilder.Append("Message: " + ex2.GetType().ToString());
                    stringBuilder.AppendLine(ex2.Message);
                    stringBuilder.Append("StackTrace: ");
                    stringBuilder.AppendLine(ex2.StackTrace);
                    throw new Exception(stringBuilder.ToString());
                }
            }
        }
        private void CreateCheckpoint()
        {
            OperatorShiftCheckpoint checkpoint = new OperatorShiftCheckpoint();

            DateTime stDate;
            DateTime enDate;
            int      ebTN;
            int      pTN;
            decimal  ebTA;
            decimal  pTA;
            decimal  tempBalance;
            string   operatorName;

            if (CheckForEmptyBox())
            {
                ShowError(TranslationProvider.Translate(MultistringTags.TERMINAL_PLEASE_EMPTY_BOX).ToString(), null, false);
                return;
            }

            try
            {
                OperatorShiftData data = WsdlRepository.CreateOperatorShiftCheckpoint(StationRepository.LocationID, Int16.Parse(StationRepository.GetUid(ChangeTracker.CurrentUser).account_id));
                stDate       = data.startDate;
                enDate       = data.endDate;
                ebTA         = data.emptyBoxTotalAmount;
                pTA          = data.payoutTotalAmount;
                ebTN         = data.emptyBoxTotalNumber;
                pTN          = data.payoutTotalNumber;
                tempBalance  = data.balance;
                operatorName = data.operatorName;
            }
            catch (Exception ex)
            {
                if (ex is System.ServiceModel.FaultException <HubServiceException> )
                {
                    System.ServiceModel.FaultException <HubServiceException> exep = (System.ServiceModel.FaultException <HubServiceException>)ex;
                    ShowError(TranslationProvider.Translate(MultistringTags.TERMINAL_NO_EMPTY_BOXES).ToString(), null, false);
                }

                return;
            }

            checkpoint.startDate           = stDate;
            checkpoint.endDate             = enDate;
            checkpoint.emptyBoxTotalAmount = ebTA;
            checkpoint.emptyBoxTotalNumber = ebTN;
            checkpoint.payoutTotalAmount   = pTA;
            checkpoint.payoutTotalNumber   = pTN;
            checkpoint.operatorName        = operatorName;
            checkpoint.operatorId          = (int)ChangeTracker.CurrentUser.AccountId;

            ObservableCollection <OperatorShiftCheckpoint> tempCollection = new ObservableCollection <OperatorShiftCheckpoint>();

            globalCollection.Insert(0, checkpoint);

            if ((currentPosition + pageSize) < globalCollection.Count)
            {
                for (int i = currentPosition; i < pageSize; i++)
                {
                    tempCollection.Add(globalCollection[i]);
                }
            }
            else
            {
                for (int i = currentPosition; i < globalCollection.Count; i++)
                {
                    tempCollection.Add(globalCollection[i]);
                }
            }

            SelectedCheckpoint = tempCollection[0];

            //recalculate balance
            //CalculateBalance();

            _Checkpoints           = new ObservableCollection <OperatorShiftCheckpoint>(tempCollection);
            EnabledPrintCheckpoint = _Checkpoints.Count > 0 && SelectedCheckpoint != null && SelectedCheckpoint.id != -1000;
            OnPropertyChanged("Checkpoints");
            OnPropertyChanged("EnabledPrintCheckpoint");

            Balance = tempBalance;
            OnPropertyChanged("Balance");

            CurrentShiftReport();

            //printout
            bool isPrinted = PrinterHandler.PrintOperatorShiftReport(checkpoint, tempBalance);

            if (!isPrinted)
            {
                ShowPrinterErrorMessage();
            }

            ShowError(TranslationProvider.Translate(MultistringTags.TERMINAL_SHIFT_REPORT_CREATED).ToString() + "\n\n" + SelectedCheckpoint.startDate.ToString() + " - " + SelectedCheckpoint.endDate.ToString(), null, false, 15);
        }
示例#9
0
        private void ProduceSettlement(object sender, EventArgs e)
        {
            if (SelectedOperator == null)
            {
                return;
            }

            //produce settlement and reload page
            PrinterHandler.InitPrinter(true);
            if (StationRepository.PrinterStatus == 0)
            {
                ShowPrinterErrorMessage();
                return;
            }

            int      operatorID   = SelectedOperator.id; //should be selected operator ID
            string   opName       = "";
            string   opLName      = "";
            string   frName       = "";
            string   locName      = "";
            string   locOwnerName = "";
            DateTime stDate;
            DateTime enDate;

            CheckpointSlip[]       cpArray;
            TotalSettlementSection totSection = new TotalSettlementSection();

            ProduceOperatorSettlementResponse opSett = new ProduceOperatorSettlementResponse();

            try
            {
                WsdlRepository.ProduceOperatorSettlement(ref operatorID, (int)ChangeTracker.CurrentUser.AccountId, out opName, out opLName, out frName, out locName, out locOwnerName, out stDate, out enDate, out cpArray, out totSection);
                opSett.checkpoints               = cpArray;
                opSett.currentDate               = DateTime.Now;
                opSett.franchisorName            = frName;
                opSett.locationName              = locName;
                opSett.operatorFirstName         = opName;
                opSett.operatorLastName          = opLName;
                opSett.settlementPeriodEndDate   = enDate;
                opSett.settlementPeriodStartDate = stDate;
                opSett.total             = totSection;
                opSett.operatorId        = operatorID;
                opSett.LocationOwnerName = locOwnerName;
            }
            catch (System.ServiceModel.FaultException <HubServiceException> ex)
            {
                System.ServiceModel.FaultException <HubServiceException> exep = (System.ServiceModel.FaultException <HubServiceException>)ex;
                ShowError(TranslationProvider.Translate(MultistringTags.TERMINAL_SETTLEMENT_NO_SHIFTS).ToString(), onLoadData, false);
                return;
            }
            WaitOverlayProvider.ShowWaitOverlay();

            //print
            if (opSett.checkpoints != null)
            {
                bool isPrinted = PrinterHandler.PrintOperatorSettlementResponce(opSett);
                if (!isPrinted)
                {
                    ShowPrinterErrorMessage();
                }

                isPrinted = PrinterHandler.PrintOperatorSettlementResponce(opSett);
                if (!isPrinted)
                {
                    ShowPrinterErrorMessage();
                }
            }
            onLoadData(null, null);
        }
 public ReturnValue(System.ServiceModel.FaultException Exception)
 {
     this.Exception = Exception;
 }
示例#11
0
        /// <summary>
        /// 终止系统产生的异常,并以消息的形式提示给用户。
        /// </summary>
        /// <param name="ex">异常</param>
        /// <param name="expectMsgOnError">出错时期待提示的消息。</param>
        public void ExceptionTerminate(Exception ex, string expectMsgOnError)
        {
            MB.Util.APPException appEx = getAppException(ex);// as MB.Util.APPException;
            string reason = string.Empty;

            if (appEx == null)
            {
                appEx = ex.InnerException as MB.Util.APPException;
            }

            if (appEx != null)
            {
                if (appEx.MsgLever == MB.Util.APPMessageType.DisplayToUser)
                {
                    MessageBoxEx.Show(appEx.Message);

                    return;
                }
                else
                {
                    expectMsgOnError = MB.Util.TraceEx.GetErrorMessageByType(appEx.MsgLever) + " " + appEx.Message;
                }
            }
            else
            {
                System.ServiceModel.FaultException <MB.Util.Model.WcfFaultMessage> fex = ex as System.ServiceModel.FaultException <MB.Util.Model.WcfFaultMessage>;
                if (fex != null)
                {
                    if (fex.Detail != null)
                    {
                        if (fex.Detail.MessageType == MB.Util.APPMessageType.DisplayToUser)
                        {
                            MessageBoxEx.Show(fex.Detail.Message);
                            return;
                        }
                        else
                        {
                            reason = fex.Detail.Message + " " + MB.Util.TraceEx.GetErrorMessageByType(fex.Detail.MessageType);
                        }
                    }
                    else
                    {
                        reason = fex.Message;
                    }
                }
                string msg = string.Empty;
                if (string.IsNullOrEmpty(reason))
                {
                    getErrMessage(ex, ref msg);
                }

                TraceEx.Write(msg, APPMessageType.SysErrInfo);
                if (!string.IsNullOrEmpty(ex.StackTrace))
                {
                    TraceEx.Write(ex.StackTrace, APPMessageType.SysErrInfo);
                }
            }

            if (string.IsNullOrEmpty(expectMsgOnError))
            {
                if (string.IsNullOrEmpty(reason))
                {
                    reason = "系统出现未知的异常,请重试!";
                }
                MessageBoxEx.Show(reason);
            }
            else
            {
                MessageBoxEx.Show("系统错误:" + expectMsgOnError);
            }
        }
示例#12
0
        object Request(OperationDescription od, bool isAsync, ref object[] parameters, System.ServiceModel.OperationContext context)
        {
            System.ServiceModel.Dispatcher.ClientOperation op = runtime.Operations[od.Name];
            object[] inspections = new object[runtime.MessageInspectors.Count];
            Message  req         = CreateRequest(op, parameters, context);

            for (int i = 0; i < inspections.Length; i++)
            {
                inspections[i] = runtime.MessageInspectors[i].BeforeSendRequest(ref req, this);
            }
            Message res = Request(req, OperationTimeout);

            if (res.IsFault)
            {
                var          resb  = res.CreateBufferedCopy(runtime.MaxFaultSize);
                MessageFault fault = MessageFault.CreateFault(resb.CreateMessage(), runtime.MaxFaultSize);
                var          conv  = OperationChannel.GetProperty <FaultConverter>() ?? FaultConverter.GetDefaultFaultConverter(res.Version);
                Exception    ex;
                if (!conv.TryCreateException(resb.CreateMessage(), fault, out ex))
                {
                    if (fault.HasDetail)
                    {
                        Type detailType = typeof(System.ServiceModel.ExceptionDetail);
                        var  freader    = fault.GetReaderAtDetailContents();
                        System.Runtime.Serialization.DataContractSerializer ds = null;
                        foreach (var fci in op.FaultContractInfos)
                        {
                            if (res.Headers.Action == fci.Action || GetSerializer(fci).IsStartObject(freader))
                            {
                                detailType = fci.Detail;
                                ds         = GetSerializer(fci);
                                break;
                            }
                        }
                        if (ds == null)
                        {
                            ds = new System.Runtime.Serialization.DataContractSerializer(detailType);
                        }
                        var detail = ds.ReadObject(freader);
                        ex = (Exception)Activator.CreateInstance(typeof(System.ServiceModel.FaultException <>).MakeGenericType(detailType), new object[] {
                            detail,
                            fault.Reason,
                            fault.Code,
                            res.Headers.Action
                        });
                    }
                    if (ex == null)
                    {
                        ex = new System.ServiceModel.FaultException(fault);
                    }
                }
                throw ex;
            }
            for (int i = 0; i < inspections.Length; i++)
            {
                runtime.MessageInspectors[i].AfterReceiveReply(ref res, inspections[i]);
            }
            if (!op.DeserializeReply)
            {
                return(res);
            }
            if (isAsync && od.EndMethod != null)
            {
                var endParams = od.EndMethod.GetParameters();
                parameters = new object[endParams.Length - 1];
            }
            return(op.Formatter.DeserializeReply(res, parameters));
        }