/// <summary> /// Gets the data from specified <see cref="Message"/> object. /// </summary> /// <typeparam name="T">Type of returned object with data.</typeparam> /// <param name="data">The <see cref="Message"/> with data.</param> /// <returns>Object with data.</returns> public static T GetData <T>(Message data) { RoboFramework.Tools.RandomLogHelper.GetLog().Debug("SynchronizationHelper::T GetData<T>(Message data)"); using (data) { if (data == null) { return(default(T)); } if (data.IsFault == true) { MessageFault fault = MessageFault.CreateFault(data, 500000); if (fault.HasDetail) { System.ServiceModel.ExceptionDetail excDet = fault.GetDetail <System.ServiceModel.ExceptionDetail>(); Type excType = String.IsNullOrEmpty(excDet.Type) ? null : Type.GetType(excDet.Type); Exception e = (excType == null) ? new Exception() : (Exception)Activator.CreateInstance(excType); FieldInfo innerExceptionField = typeof(Exception).GetField("_innerException", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo messageField = typeof(Exception).GetField("_message", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo stackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.NonPublic | BindingFlags.Instance); innerExceptionField.SetValue(e, excDet.InnerException); messageField.SetValue(e, excDet.Message); stackTraceField.SetValue(e, excDet.StackTrace); throw e; } } return(data.GetBody <T>()); } }
public IEnumerable <string> GetAllWebUrls() { try { XmlNode xn = SPContext.WSSWebs.GetAllSubWebCollection(); //XmlNode xn = SPContext.WSSWebs.GetWebCollection(); var elements = xn.GetChildElements(); var currentWebUrl = SPContext.WSSWebs.Url.Replace("/_vti_bin/Webs.asmx", ""); var webs = elements.Where(e => e.Attribute("Url").Value.StartsWith(currentWebUrl, StringComparison.CurrentCultureIgnoreCase)).Select(e => e.Attribute("Url").Value); return(webs); } catch (FaultException fe) { MessageFault mf = fe.CreateMessageFault(); if (mf.HasDetail) { XmlElement fexe = mf.GetDetail <XmlElement>(); Console.WriteLine("\tError: " + fexe.OuterXml); } throw fe; } catch (Exception ex) { logger.Log(LogLevel.Error, ex, $"Site:{SPContext.WSSWebs.Url}"); throw ex; } }
// TO DO: Add this method to SellBitcoins private async void GetQuote() { try { // Gets a quote for bitcoins - Not a balance. Bad Method Name - TODO FiatAmount = Convert.ToDecimal(txtAmount.Text); // TODO: Refresh Service Reference // BitcoinAmount = await client.GetBitcoinAmountAsync(FiatAmount, "AUD"); Price = BitcoinAmount / FiatAmount; txtBitcoins.Text = BitcoinAmount.ToString(); txtRate.Text = Price.ToString(); } catch (FaultException ex) { string msg = "FaultException: " + ex.Message; MessageFault fault = ex.CreateMessageFault(); if (fault.HasDetail == true) { System.Xml.XmlReader reader = fault.GetReaderAtDetailContents(); if (reader.Name == "ExceptionDetail") { ExceptionDetail detail = fault.GetDetail <ExceptionDetail>(); msg += "\n\nStack Trace: " + detail.StackTrace; } } MessageBox.Show(msg); } }
public Exception CapturarSoapError(Exception ex) { try { FaultException faultException = ex as FaultException; MessageFault msgFault = faultException != null?faultException.CreateMessageFault() : null; XmlElement elm = msgFault != null?msgFault.GetDetail <XmlElement>() : null; if (elm != null) { var errorCodeTag = elm.GetElementsByTagName("ErrorCode"); var errorDescripcionTag = elm.GetElementsByTagName("ErrorDescription"); if (errorCodeTag != null && errorCodeTag.Count > 0 && errorDescripcionTag != null && errorDescripcionTag.Count > 0) { ex = new Exception(errorCodeTag[0].InnerText + " " + errorDescripcionTag[0].InnerText); } } } catch { } return(ex); }
public void Test1EliminarBusesOk() { BusesWS.BusesClient proxy = new BusesWS.BusesClient(); try { string respuesta = proxy.EliminarMovilidad(1); Assert.AreEqual("OK", respuesta); } //catch (FaultException<BusesWS.RepetidoException> errora) //{ // Assert.AreEqual("Error al intentar eliminar", error.Reason.ToString()); // Assert.AreEqual(error.Detail.codigo, "102"); // Assert.AreEqual(error.Detail.descripcion, "La movilidad está ACTIVA, no se puede eliminar"); //} catch (FaultException error) { MessageFault fault = error.CreateMessageFault(); BusesWS.RepetidoException detail = fault.GetDetail <BusesWS.RepetidoException>(); Assert.AreEqual("Error al intentar eliminar", error.Reason.ToString()); Assert.AreEqual(detail.codigo, "102"); Assert.AreEqual(detail.descripcion, "La movilidad está ACTIVA, no se puede eliminar"); } }
private void Button1_Click(object sender, EventArgs e) { // access to web service UrlConverterService.URLConverter oTestWebservice = new UrlConverterService.URLConverterClient(); // return object for web service call UrlConverterService.executeResponse ret; // parameter object for Web service call UrlConverterService.executeRequest request = new UrlConverterService.executeRequest(); // set Web service options request.operation = new UrlConverterService.operation(); // set the billing values request.operation.billing = new UrlConverterService.BillingType(); request.operation.billing.userName = "******"; request.operation.billing.applicationName = "webPDF Sample Application"; request.operation.billing.customerCode = "ABC123"; // set converter options request.operation.urlconverter = new UrlConverterService.UrlConverterType(); request.operation.urlconverter.url = TextBoxFileName.Text; String targetFile = Path.GetFullPath(TextBoxTargetFile.Text); File.Delete(targetFile); try { // call the Web service ret = oTestWebservice.execute(request); } //{ "net.webpdf.ws.soap.exception.WebserviceException"} catch (FaultException ex) { MessageFault messageFault = ex.CreateMessageFault(); if (messageFault.HasDetail) { UrlConverterService.FaultInfo fault = messageFault.GetDetail <UrlConverterService.FaultInfo>(); MessageBox.Show("webPDF Fault: " + fault.errorMessage + " (" + fault.errorCode + ")", "Info"); } else { // catch the exception MessageBox.Show(ex.Message.ToString(), "Info"); } return; } // save the returned file to disk FileStream fs; fs = new FileStream(Path.GetFullPath(TextBoxTargetFile.Text), FileMode.OpenOrCreate); fs.Seek(0, SeekOrigin.End); fs.Write(ret.@return, 0, [email protected]); fs.Close(); Process.Start(targetFile); MessageBox.Show("Output file '" + targetFile + "' created!", "Info"); }
/// <summary> /// Process a general FaultException from Medicare, and rethrow a FaultException<![CDATA[<ServiceMessageType>]]> fault. /// </summary> /// <typeparam name="T">ServiceMessageType type belonging to any of the SMD namespaces.</typeparam> /// <param name="ex">Exception to process</param> internal static void ProcessAndThrowFault <T>(Exception ex) { if (!(ex is FaultException)) { throw ex; } FaultException fex = (FaultException)ex; MessageFault fault = fex.CreateMessageFault(); if (fault != null && fault.HasDetail) { XmlElement errorElement = fault.GetDetail <XmlElement>(); if (errorElement.LocalName == "serviceMessages") { T serviceMessages = errorElement.Deserialize <T>(); throw new FaultException <T>( serviceMessages, fex.Reason, fex.Code, fex.Action); } } throw ex; }
private static void LogFaultException(FaultException ex) { if (ex == null) { return; } try { TraceHelper.WriteError("Fault Exception"); TraceHelper.WriteError("Fault Message: {0}", ex.Message); TraceHelper.WriteError("Fault Action: {0}", ex.Action); TraceHelper.WriteError("Fault Code: {0}-{1}", ex.Code.Name, ex.Code); TraceHelper.WriteError("Fault Reason: {0}", ex.Reason); MessageFault fault = ex.CreateMessageFault(); if (fault.HasDetail) { XmlReader reader = fault.GetReaderAtDetailContents(); if (reader != null && reader.Name == "ExceptionDetail") { var detail = fault.GetDetail <ExceptionDetail>(); if (detail != null) { TraceHelper.WriteError("-Detail Message: {0}", detail.Message); TraceHelper.WriteError("-Detail Stack: {0}", detail.StackTrace); } } } } catch (Exception e) { TraceHelper.WriteError("Error handling Fault Exception: {0}", e.Message); } }
private void IsFaultEqual(MessageFault f1, MessageFault f2) { if (f1.Code.Name != f2.Code.Name) { throw new ApplicationException("Message Fault Names are not equal"); } if (f1.Reason.ToString() != f2.Reason.ToString()) { throw new ApplicationException("Message Fault Reason are not equal"); } if (f1.Node != f2.Node) { throw new ApplicationException("Message Fault Node are not equal"); } if (f1.Actor != f2.Actor) { throw new ApplicationException("Message Fault Actor are not equal"); } if (!(f1.HasDetail ^ f2.HasDetail)) { if (f1.GetDetail <string>() != f2.GetDetail <string>()) { throw new ApplicationException("Message Fault Detail are not equal"); } } }
public IEnumerable <string> GetSiteContentTypes() { try { XmlNode xn = SPContext.WSSWebs.GetContentTypes(); var elements = xn.GetChildElements(); var ctypes = elements .Where(e => e.Attribute("Group") != null && e.Attribute("Group").Value.ToLower() != "_hidden") .Select(e => e.Attribute("Name").Value); return(ctypes); } catch (FaultException fe) { MessageFault mf = fe.CreateMessageFault(); if (mf.HasDetail) { XmlElement fexe = mf.GetDetail <XmlElement>(); Console.WriteLine("\tError: " + fexe.OuterXml); } throw fe; } catch (Exception ex) { logger.Log(LogLevel.Error, ex, $"Site:{SPContext.WSSWebs.Url}"); throw ex; } }
private void ThrowIfFaultMessage(Message wcfMessage) { Exception exception; if (wcfMessage.IsFault) { MessagingClientEtwProvider.TraceClient(() => { }); string action = wcfMessage.Headers.Action; MessageFault messageFault = MessageFault.CreateFault(wcfMessage, 65536); FaultConverter property = this.innerChannel.GetProperty <FaultConverter>(); if (property == null || !property.TryCreateException(wcfMessage, messageFault, out exception)) { if (!messageFault.HasDetail) { throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsWarning(new FaultException(messageFault, action), null); } ExceptionDetail detail = messageFault.GetDetail <ExceptionDetail>(); if (!this.clientMode && string.Equals(detail.Type, typeof(CommunicationException).FullName, StringComparison.Ordinal)) { MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelFaulting(this.innerChannel.GetType().Name, this.innerChannel.LocalAddress.Uri.AbsoluteUri, this.innerChannel.RemoteAddress.Uri.AbsoluteUri, this.innerChannel.Via.AbsoluteUri, this.innerChannel.Session.Id, string.Concat("ThrowIfFaultMessage: Received CommunicationException as fault message. ", detail.ToString()))); base.Fault(); } if (!this.includeExceptionDetails) { throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsInformation(new FaultException <ExceptionDetailNoStackTrace>(new ExceptionDetailNoStackTrace(detail, true), messageFault.Reason, messageFault.Code, action), null); } throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsInformation(new FaultException <ExceptionDetail>(detail, messageFault.Reason, messageFault.Code, action), null); } throw Fx.Exception.AsWarning(exception, null); } }
public static Exception FindXmlErrorDetail(Exception ex) { try { FaultException faultException = ex as FaultException; MessageFault msgFault = faultException != null?faultException.CreateMessageFault() : null; XmlElement elm = msgFault != null?msgFault.GetDetail <XmlElement>() : null; if (elm != null) { var errorCodeTag = elm.GetElementsByTagName("ErrorCode"); var errorDescripcionTag = elm.GetElementsByTagName("ErrorDescription"); if (errorCodeTag != null && errorCodeTag.Count > 0 && errorDescripcionTag != null && errorDescripcionTag.Count > 0) { ex = new Exception(errorCodeTag[0].InnerText + " " + errorDescripcionTag[0].InnerText); } } else { XmlDocument document = new XmlDocument(); document.LoadXml(ex.Message); var xmlNodeList = document.GetElementsByTagName("detail"); if (xmlNodeList != null && xmlNodeList.Count > 0 && xmlNodeList[0].HasChildNodes) { string mensaje = string.Empty; foreach (var element in xmlNodeList[0].ChildNodes) { elm = element as XmlElement; if (elm != null) { var errorCodeTag = elm.GetElementsByTagName("ErrorCode"); var errorDescripcionTag = elm.GetElementsByTagName("ErrorDescription"); if (errorCodeTag != null && errorCodeTag.Count > 0 && errorDescripcionTag != null && errorDescripcionTag.Count > 0) { mensaje += errorCodeTag[0].InnerText + " " + errorDescripcionTag[0].InnerText + Environment.NewLine; } } } if (!string.IsNullOrEmpty(mensaje) && mensaje.Length > 0) { ex = new Exception(mensaje); } } } } catch { ex = null; } return(ex); }
private static void AddPhoneToConstituent(Donor d, ref constituent constt, bool setPrimary = false, bool SendToApi = false) { try { var phone = new phone { number = d.Phone, inactive = false, primary = setPrimary, createDate = DateTime.Now, updateDate = DateTime.Now, customFieldMap = new abstractCustomizableEntityEntry[0], }; //check if is null or already has phone. if (constt.phones == null) { constt.phones = new phone[1]; constt.phones[0] = phone; } else { var newmax = constt.phones.Count() + 1; var newArray = new phone[newmax]; constt.phones.CopyTo(newArray, 0); newArray[newmax - 1] = phone; constt.phones = newArray; } if (SendToApi) { var saveOrUpdateConstituentRequest = new SaveOrUpdateConstituentRequest { constituent = constt }; _client.SaveOrUpdateConstituent(saveOrUpdateConstituentRequest); } } catch (FaultException exception) { Type exType = exception.GetType(); MessageFault mf = exception.CreateMessageFault(); Console.WriteLine("Error when add phone to constituent // " + exception.Message); if (mf.HasDetail) { var detailedMessage = mf.GetDetail <System.Xml.Linq.XElement>(); String message = detailedMessage.FirstNode.ToString(); Console.WriteLine("More details // " + message); } } catch (Exception exc) { var txt = exc; } }
private static void AddEmailToConstituent(Donor d, ref constituent constt, bool setPrimary = false, bool SendToApi = false) { try { var email = new email { emailAddress = d.Email, emailDisplay = d.FullName, primary = setPrimary, createDate = DateTime.Now, updateDate = DateTime.Now, customFieldMap = new abstractCustomizableEntityEntry[0], }; if (constt.emails == null) { constt.emails = new email[1]; constt.emails[0] = email; } else { var newmax = constt.emails.Count() + 1; var newArray = new email[newmax]; constt.emails.CopyTo(newArray, 0); newArray[newmax - 1] = email; constt.emails = newArray; } if (SendToApi) { var saveOrUpdateConstituentRequest = new SaveOrUpdateConstituentRequest { constituent = constt }; _client.SaveOrUpdateConstituent(saveOrUpdateConstituentRequest); } } catch (FaultException exception) { Type exType = exception.GetType(); MessageFault mf = exception.CreateMessageFault(); Console.WriteLine("Error when adding email to constituent // " + exception.Message); if (mf.HasDetail) { var detailedMessage = mf.GetDetail <System.Xml.Linq.XElement>(); String message = detailedMessage.FirstNode.ToString(); Console.WriteLine("More details // " + message); } } catch (Exception exc) { var txt = exc; } }
protected override void OnException(ExceptionContext filterContext) { if (IsAjax(filterContext)) { filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8; filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.StatusCode = 400; var myobj = filterContext.Exception as System.ServiceModel.FaultException; if (myobj != null) { MessageFault mf = myobj.CreateMessageFault(); if (mf.HasDetail) { ExcepcionLDS e = mf.GetDetail <ExcepcionLDS>(); if (e != null) { ViewBag.Path = Request.Url.Host; filterContext.Result = View("../Errores/ErrorJsons", e); } } } else { Exception e = filterContext.Exception; ExcepcionLDS excLDS; excLDS = new ExcepcionLDS() { categoria = Convert.ToInt32(LuzdelSur.Plataforma.Explorador.WCFEntity.TipoErrorControlado.Grave) , mensajeUsuario = "Error en el procesamiento de la solicitud" , mensajeAplicacion = e.Message }; ViewBag.Path = Request.Url.Host; filterContext.Result = View("../Errores/ErrorJsons", excLDS); } } else { filterContext.ExceptionHandled = true; Exception e = filterContext.Exception; string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; HandleErrorInfo model = new HandleErrorInfo(e, controllerName, actionName); ViewBag.Path = Request.Url.Host; filterContext.Result = PartialView("../Errores/ErrorVistas", model); } }
/* * Show Message Box With SOAP Error If We Receive A Fault Code Back From Service * */ private void LogSoapException(FaultException e) { MessageFault message = e.CreateMessageFault(); XmlElement errorDetail = message.GetDetail <XmlElement>(); XmlNodeList errorDetails = errorDetail.ChildNodes; String fullErrorDetails = ""; for (int i = 0; i < errorDetails.Count; i++) { fullErrorDetails += errorDetails.Item(i).Name + ": " + errorDetails.Item(i).InnerText + "\n"; } _log.Error("An Error Occured With Royal Mail Api Service: " + message.Reason.ToString() + "\n\n" + fullErrorDetails); }
private static MethodFault GetVIServerFault(FaultException soapEx) { if (soapEx == null) { throw new ArgumentNullException("soapEx"); } PropertyInfo property = soapEx.GetType().GetTypeInfo().GetProperty("Detail"); VimApi_65.MethodFault methodFault; if (property != (PropertyInfo)null) { methodFault = property.GetValue((object)soapEx) as VimApi_65.MethodFault; } else { MessageFault messageFault = soapEx.CreateMessageFault(); XmlSerializer xmlSerializer = FaultUtility.GetFaultSerializer(); if (xmlSerializer == null) { /* XElement xelement = (XElement)XNode.ReadFrom((XmlReader)messageFault.GetReaderAtDetailContents()); * System.Type type = typeof(VimApi_65.MethodFault).Assembly.GetType(string.Format("{0}.{1}", (object)typeof(VimApi_65.MethodFault).Namespace, (object)xelement.Attribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance")).Value)); * XmlRootAttribute xmlRootAttribute = new XmlRootAttribute(xelement.Name.LocalName); * // ISSUE: variable of the null type * __Null local1 = null; * // ISSUE: variable of the null type * __Null local2 = null; * XmlRootAttribute root = xmlRootAttribute; * string defaultNamespace = "urn:vim25"; * xmlSerializer = new XmlSerializer(type, (XmlAttributeOverrides)local1, (System.Type[])local2, root, defaultNamespace); */ XElement xElement = (XElement)XNode.ReadFrom(messageFault.GetReaderAtDetailContents()); XAttribute xAttribute = xElement.Attribute(XName.Get("type", "http://www.w3.org/2001/XMLSchema-instance")); string name = string.Format("{0}.{1}", typeof(VimApi_65.MethodFault).Namespace, xAttribute.Value); Type arg_D0_0 = typeof(VimApi_65.MethodFault).Assembly.GetType(name); XmlRootAttribute root = new XmlRootAttribute(xElement.Name.LocalName); xmlSerializer = new XmlSerializer(arg_D0_0, null, null, root, "urn:vim25"); } StringReader stringReader = new StringReader(messageFault.GetDetail <XElement>().ToString().Replace("xsd:", "")); using (XmlReader xmlReader = XmlReader.Create((TextReader)stringReader, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true })) { int content = (int)xmlReader.MoveToContent(); methodFault = xmlSerializer.Deserialize(xmlReader) as VimApi_65.MethodFault; } } return(VIConvert.ToVim((object)methodFault) as MethodFault); }
public ActionResult Grabar(int id, string placa, string clase, string marca, string modelo, string color, int motor, int asientos, int puertas, string fecinscripcion, string anio, string estado) { try { Movilidad busAGrabar = new Movilidad() { Id = id, Placa = placa, Clase = clase, Marca = marca, Modelo = modelo, Color = color, Motor = motor, Asientos = asientos, Puertas = puertas, FeInscripcion = DateTime.Parse(fecinscripcion), Año = anio, Estado = estado }; Movilidad bus = null; if (busAGrabar.Id == 0) { bus = new BusesClient().CrearMovilidad(busAGrabar); } else { bus = new BusesClient().ModificarMovilidad(busAGrabar); } if (bus != null) { return(Json("Success", JsonRequestBehavior.AllowGet)); } else { return(Json("Datos incorrectos", JsonRequestBehavior.AllowGet)); } } catch (FaultException error) { MessageFault fault = error.CreateMessageFault(); BusWS.RepetidoException detail = fault.GetDetail <BusWS.RepetidoException>(); return(Json(detail.descripcion, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// Try to parse broker exception from the message /// </summary> /// <param name="messageFault">indicating the message fault</param> /// <param name="action">indicating the action</param> /// <param name="brokerException">output the broker exception</param> /// <returns>returns a value indicating whether successfully parsed out broker exception</returns> private static bool TryParseBrokerException(MessageFault messageFault, string action, out Exception brokerException) { switch (action) { case AuthenticationFailure.Action: AuthenticationFailure af = messageFault.GetDetail <AuthenticationFailure>(); brokerException = new AuthenticationException(String.Format(SR.Broker_AuthenticationFailure, af.UserName)); return(true); case RetryOperationError.Action: RetryOperationError rle = messageFault.GetDetail <RetryOperationError>(); brokerException = new RetryOperationException(String.Format(SR.Broker_RetryLimitExceeded, rle.RetryCount, rle.Reason), rle.Reason); return(true); case SessionFault.Action: SessionFault fault = messageFault.GetDetail <SessionFault>(); brokerException = Utility.TranslateFaultException(new FaultException <SessionFault>(fault, messageFault.Reason)); return(true); default: brokerException = null; return(false); } }
private static void AddAddressToConstituent(Address add, ref constituent constt, bool setPrimary = false, bool sendToApi = false) { try { var address = TranslateAddress(add, setPrimary); address.createDate = DateTime.Now; address.updateDate = DateTime.Now; address.customFieldMap = new abstractCustomizableEntityEntry[0]; if (constt.addresses == null) { constt.addresses = new address[1]; constt.addresses[0] = address; } else { var newmax = constt.addresses.Count() + 1; var newArray = new address[newmax]; constt.addresses.CopyTo(newArray, 0); newArray[newmax - 1] = address; constt.addresses = newArray; } if (sendToApi) { var saveOrUpdateConstituentRequest = new SaveOrUpdateConstituentRequest { constituent = constt }; _client.SaveOrUpdateConstituent(saveOrUpdateConstituentRequest); } } catch (FaultException exception) { Type exType = exception.GetType(); MessageFault mf = exception.CreateMessageFault(); Console.WriteLine("Error when adding address to constituent // " + exception.Message); if (mf.HasDetail) { var detailedMessage = mf.GetDetail <System.Xml.Linq.XElement>(); String message = detailedMessage.FirstNode.ToString(); Console.WriteLine("More details // " + message); } } catch (Exception exc) { var txt = exc; } }
/// <summary> /// Handle retry limit exceeded /// </summary> /// <param name="data"></param> public void HandleRetryLimitExceeded(DispatchData data) { // handle retry limit only when we get exception or fault message Contract.Requires(data.Exception != null || (data.ReplyMessage != null && data.ReplyMessage.IsFault == true), "Retry Limit Exceeded when there is exception or fault message"); int retryLimit = this.sharedData.Config.LoadBalancing.MessageResendLimit; BrokerTracing.EtwTrace.LogBackendResponseReceivedRetryLimitExceed(data.SessionId, data.TaskId, data.MessageId, retryLimit); // Initialize retry error and fault reason RetryOperationError retryError; FaultReason faultReason; if (data.Exception != null) { // generate fault exception from original exception retryError = new RetryOperationError(data.Exception.Message); string exceptionFaultReason = String.Format(SR.RetryLimitExceeded, retryLimit + 1, data.Exception.Message); faultReason = new FaultReason(exceptionFaultReason); } else { #region Debug Failure Test SimulateFailure.FailOperation(1); #endregion // generate fault exception from original reply MessageFault messageFault = MessageFault.CreateFault(data.ReplyMessage, Constant.MaxBufferSize); retryError = messageFault.GetDetail <RetryOperationError>(); faultReason = messageFault.Reason; // close original reply message data.ReplyMessage.Close(); } retryError.RetryCount = retryLimit + 1; retryError.LastFailedServiceId = data.TaskId; // Construct the new exception FaultException <RetryOperationError> faultException = new FaultException <RetryOperationError>(retryError, faultReason, Constant.RetryLimitExceedFaultCode, RetryOperationError.Action); data.Exception = faultException; this.responseQueueAdapter.PutResponseBack(data); }
public void CanProvideFaultOnCustomPolicyName() { ExceptionShieldingErrorHandler shielding = new ExceptionShieldingErrorHandler("CustomPolicy"); Message message = GetDefaultMessage(); shielding.ProvideFault(new ArgumentException("Arg"), MessageVersion.Default, ref message); MessageFault fault = GetFaultFromMessage(message); Assert.IsTrue(fault.HasDetail); Assert.IsTrue(fault.Code.IsSenderFault); //DataContractSerializer serializer = new DataContractSerializer(typeof(MockFaultContract)); MockFaultContract details = fault.GetDetail <MockFaultContract>(); Assert.IsNotNull(details); Assert.AreEqual("Arg", details.Message); }
public void CanProvideFaultWithMockHandler() { ExceptionShieldingErrorHandler shielding = new ExceptionShieldingErrorHandler(); ArithmeticException exception = new ArithmeticException("My Exception"); Message message = GetDefaultMessage(); shielding.ProvideFault(exception, MessageVersion.Default, ref message); MessageFault fault = GetFaultFromMessage(message); Assert.IsTrue(fault.Code.IsSenderFault); //DataContractSerializer serializer = new DataContractSerializer(typeof(MockFaultContract)); MockFaultContract details = fault.GetDetail <MockFaultContract>(); Assert.IsNotNull(details); Assert.AreEqual(exception.Message, details.Message); }
public void CanPopulateFaultContractFromExceptionProperties() { ExceptionShieldingErrorHandler shielding = new ExceptionShieldingErrorHandler(); Message message = GetDefaultMessage(); Exception exception = new ArgumentNullException("MyMessage"); shielding.ProvideFault(exception, MessageVersion.Default, ref message); MessageFault fault = GetFaultFromMessage(message); Assert.IsTrue(fault.HasDetail); Assert.IsTrue(fault.Code.IsSenderFault); MockFaultContract details = fault.GetDetail <MockFaultContract>(); Assert.IsNotNull(details); Assert.AreEqual(exception.Message, details.Message); Assert.IsTrue(details.Id != Guid.Empty); }
public void ShouldReturnSenderFault() { ExceptionShieldingErrorHandler shielding = new ExceptionShieldingErrorHandler(); Message message = GetDefaultMessage(); Exception exception = new ArithmeticException("Message"); shielding.ProvideFault(exception, MessageVersion.Default, ref message); MessageFault fault = GetFaultFromMessage(message); Assert.IsTrue(fault.Code.IsSenderFault); Assert.IsFalse(string.IsNullOrEmpty(fault.Reason.ToString())); Assert.IsTrue(fault.HasDetail); MockFaultContract details = fault.GetDetail <MockFaultContract>(); Assert.IsNotNull(details); Assert.AreEqual(exception.Message, details.Message); }
private static constituent CreateConstituent(Donor d) { var constt = new constituent(); try { var fieldMap = new abstractCustomizableEntityEntry[2]; fieldMap[0] = AddSourceCodeToConstintuent(d); fieldMap[1] = AddCommunicationPreferences(d); constt.firstName = d.FName; constt.lastName = d.LName; constt.constituentType = "individual"; constt.customFieldMap = fieldMap; constt.inactive = false; constt.createDate = DateTime.Now; constt.updateDate = DateTime.Now; var request = new SaveOrUpdateConstituentRequest { constituent = constt }; var response = _client.SaveOrUpdateConstituent(request); return(response.constituent); } catch (FaultException exception) { Type exType = exception.GetType(); MessageFault mf = exception.CreateMessageFault(); Console.WriteLine("Error when creating constituent // " + exception.Message); if (mf.HasDetail) { var detailedMessage = mf.GetDetail <System.Xml.Linq.XElement>(); String message = detailedMessage.FirstNode.ToString(); Console.WriteLine("More details // " + message); } } catch (Exception exc) { var txt = exc; } return(null); }
/// <summary> /// Exceptions thrown during broker proxy and service host communication /// are wrapped into FaultException(ProxyFault) and passed back to /// AzureDispatcher. Here we check if the message is a fault message that /// carries ProxyFault. If so, extract the inner exception from ProxyFault /// and throw it out. Dispatcher will handle the exception as if it is /// talking to service host directly. /// </summary> /// <param name="message">response message</param> protected override void PostProcessMessage(Message message) { if (message.IsFault) { if (message.Headers.Action == ProxyFault.Action) { MessageFault fault = MessageFault.CreateFault(message, int.MaxValue); ProxyFault proxyFault = fault.GetDetail <ProxyFault>(); if (proxyFault != null) { // Create exception according to the FaultCode, and mark it as "indirect" // by setting its source to IndirectExceptionMark. This mark will later // be checked by dispatcher to determine if it need to recreate the // underlying WCF channel. For indirect exception, we don't need to // recreate the channel(between dispatcher and broker proxy). Exception e; if (proxyFault.FaultCode == ProxyFault.ProxyEndpointNotFound) { // will throw EndpointNotFoundException for ProxyFault.ProxyEndpointNotFound e = new EndpointNotFoundException(proxyFault.Message); } else if (proxyFault.FaultCode == ProxyFault.ProxyCommunicationException) { // will throw CommunicationException for ProxyFault.ProxyCommunicationException e = new CommunicationException(proxyFault.Message); } else { // will throw general exception for other FaultCode e = new Exception(proxyFault.Message); } e.Source = IndirectExceptionMark; throw e; } } } }
private static void AddCommunicationHistoryToDonor(string note, ref constituent c) { try { var req = new SaveOrUpdateCommunicationHistoryRequest(); req.constituentId = c.id; var history = new communicationHistory(); history.comments = note; history.communicationHistoryType = "MANUAL"; history.constituentId = c.id; history.createDate = DateTime.Now; history.entryType = "Note"; //pick list during setup, let admin decide. history.updateDate = DateTime.Now; history.customFieldMap = new abstractCustomizableEntityEntry[0]; req.communicationHistory = history; var resp = _client.SaveOrUpdateCommunicationHistory(req); var his = resp.communicationHistory; } catch (FaultException exception) { Type exType = exception.GetType(); MessageFault mf = exception.CreateMessageFault(); Console.WriteLine("Error when add phone to constituent // " + exception.Message); if (mf.HasDetail) { var detailedMessage = mf.GetDetail <System.Xml.Linq.XElement>(); String message = detailedMessage.FirstNode.ToString(); Console.WriteLine("More details // " + message); } } catch (Exception exc) { var txt = exc; } }
public JsonFaultBodyWriter(MessageFault fault, bool includeExceptionDetailInFaults) : base(false) { faultDetail = new JsonFaultDetail(); if (includeExceptionDetailInFaults) { faultDetail.Message = fault.Reason.ToString(); if (fault.HasDetail) { try { ExceptionDetail originalFaultDetail = fault.GetDetail <ExceptionDetail>(); faultDetail.StackTrace = originalFaultDetail.StackTrace; faultDetail.ExceptionType = originalFaultDetail.Type; faultDetail.ExceptionDetail = originalFaultDetail; } catch (SerializationException exception) { System.ServiceModel.DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); // A SerializationException will be thrown if the detail isn't of type ExceptionDetail // In that case, we want to just move on. } catch (SecurityException exception) { System.ServiceModel.DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); // A SecurityException will be thrown if the detail can't be obtained in partial trust // (This is guaranteed to happen unless there's an Assert for MemberAccessPermission, since ExceptionDetail // has DataMembers that have private setters.) // In that case, we want to just move on. } } } else { faultDetail.Message = System.ServiceModel.SR.GetString(System.ServiceModel.SR.SFxInternalServerError); } }
private bool PlaceBuyOrder(string PublicKey, decimal btc) { try { srAtm.Order order = client.CreateOrder(PublicKey, btc); return(true); } catch (FaultException ex) { string msg = "FaultException: " + ex.Message; MessageFault fault = ex.CreateMessageFault(); if (fault.HasDetail == true) { System.Xml.XmlReader reader = fault.GetReaderAtDetailContents(); if (reader.Name == "ExceptionDetail") { ExceptionDetail detail = fault.GetDetail <ExceptionDetail>(); msg += "\n\nStack Trace: " + detail.StackTrace; } } MessageBox.Show(msg); } return(false); }
public JsonFaultBodyWriter(MessageFault fault, bool includeExceptionDetailInFaults) : base(false) { faultDetail = new JsonFaultDetail(); if (includeExceptionDetailInFaults) { faultDetail.Message = fault.Reason.ToString(); if (fault.HasDetail) { try { ExceptionDetail originalFaultDetail = fault.GetDetail<ExceptionDetail>(); faultDetail.StackTrace = originalFaultDetail.StackTrace; faultDetail.ExceptionType = originalFaultDetail.Type; faultDetail.ExceptionDetail = originalFaultDetail; } catch (SerializationException exception) { System.ServiceModel.DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); // A SerializationException will be thrown if the detail isn't of type ExceptionDetail // In that case, we want to just move on. } catch (SecurityException exception) { System.ServiceModel.DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); // A SecurityException will be thrown if the detail can't be obtained in partial trust // (This is guaranteed to happen unless there's an Assert for MemberAccessPermission, since ExceptionDetail // has DataMembers that have private setters.) // In that case, we want to just move on. } } } else { faultDetail.Message = System.ServiceModel.SR.GetString(System.ServiceModel.SR.SFxInternalServerError); } }