protected override int FixedHeaderLength(MessageVersion version) { using (var scope = ObjectHost.Host.BeginLifetimeScope()) { return scope.ResolveKeyed<IMessageReader<DuplexMessage>>(version).HeaderLength; } }
protected override object DoDecode(MessageVersion version, IoBuffer input) { using (var scope = ObjectHost.Host.BeginLifetimeScope()) { return scope.ResolveKeyed<IMessageReader<DuplexMessage>>(version).Read(input); } }
public MessageTypeIndicator(MessageVersion messageVersion, MessageClass messageClass, MessageFunction messageFunction, MessageOrigin originMessage) { MessageVersion = messageVersion; MessageClass = messageClass; MessageFunction = messageFunction; OriginMessage = originMessage; Mit = (int)messageVersion + (int)messageClass + (int)messageFunction + (int)originMessage; }
public MessageHeader( string messageID, MessageVersion version, string identifier, byte[] filterCode, MessageFilterType filterType, MessageState state, ErrorCode errorCode, SerializeMode serializeMode, CommandCode commandCode, MessageType messageType) { this.MessageID = messageID; this.Version = version; this.State = state; this.FilterCode = filterCode; this.FilterType = filterType; this.ErrorCode = errorCode; this.SerializeMode = serializeMode; this.CommandCode = commandCode; this.Identifier = identifier; this.MessageType = messageType; }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteRaw(GetToken().OuterXml); writer.WriteStartElement("Timestamp"); writer.WriteXmlnsAttribute("", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); writer.WriteAttributeString("Id", "Timestamp-79"); //Created writer.WriteStartElement("Created"); writer.WriteString(this.token.ValidFrom.ToString("yyyy-MM-ddTHH:mm:ssZ")); writer.WriteEndElement(); //Expires writer.WriteStartElement("Expires"); writer.WriteString(this.token.ValidTo.ToString("yyyy-MM-ddTHH:mm:ssZ")); writer.WriteEndElement(); writer.WriteEndElement(); }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (((this.basicSupportingTokenParameters != null) && (this.basicSupportingTokenParameters.Count > 0)) && (base.RequireMessageProtection && !this.basicTokenEncrypted)) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("BasicTokenCannotBeWrittenWithoutEncryption")), base.Message); } if ((this.elementContainer.Timestamp != null) && (base.Layout != SecurityHeaderLayout.LaxTimestampLast)) { base.StandardsManager.WSUtilitySpecificationVersion.WriteTimestamp(writer, this.elementContainer.Timestamp); } if (this.elementContainer.PrerequisiteToken != null) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, this.elementContainer.PrerequisiteToken); } if ((this.elementContainer.SourceSigningToken != null) && ShouldSerializeToken(this.signingTokenParameters, base.MessageDirection)) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, this.elementContainer.SourceSigningToken); } if (this.elementContainer.DerivedSigningToken != null) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, this.elementContainer.DerivedSigningToken); } if (((this.elementContainer.SourceEncryptionToken != null) && (this.elementContainer.SourceEncryptionToken != this.elementContainer.SourceSigningToken)) && ShouldSerializeToken(this.encryptingTokenParameters, base.MessageDirection)) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, this.elementContainer.SourceEncryptionToken); } if (this.elementContainer.WrappedEncryptionToken != null) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, this.elementContainer.WrappedEncryptionToken); } if (this.elementContainer.DerivedEncryptionToken != null) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, this.elementContainer.DerivedEncryptionToken); } if (this.SignThenEncrypt && (this.elementContainer.ReferenceList != null)) { this.elementContainer.ReferenceList.WriteTo(writer, ServiceModelDictionaryManager.Instance); } SecurityToken[] signedSupportingTokens = this.elementContainer.GetSignedSupportingTokens(); if (signedSupportingTokens != null) { for (int i = 0; i < signedSupportingTokens.Length; i++) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, signedSupportingTokens[i]); } } SendSecurityHeaderElement[] basicSupportingTokens = this.elementContainer.GetBasicSupportingTokens(); if (basicSupportingTokens != null) { for (int j = 0; j < basicSupportingTokens.Length; j++) { basicSupportingTokens[j].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } SecurityToken[] endorsingSupportingTokens = this.elementContainer.GetEndorsingSupportingTokens(); if (endorsingSupportingTokens != null) { for (int k = 0; k < endorsingSupportingTokens.Length; k++) { if (ShouldSerializeToken(this.endorsingTokenParameters[k], base.MessageDirection)) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, endorsingSupportingTokens[k]); } } } SecurityToken[] endorsingDerivedSupportingTokens = this.elementContainer.GetEndorsingDerivedSupportingTokens(); if (endorsingDerivedSupportingTokens != null) { for (int m = 0; m < endorsingDerivedSupportingTokens.Length; m++) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, endorsingDerivedSupportingTokens[m]); } } SecurityToken[] signedEndorsingSupportingTokens = this.elementContainer.GetSignedEndorsingSupportingTokens(); if (signedEndorsingSupportingTokens != null) { for (int n = 0; n < signedEndorsingSupportingTokens.Length; n++) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, signedEndorsingSupportingTokens[n]); } } SecurityToken[] signedEndorsingDerivedSupportingTokens = this.elementContainer.GetSignedEndorsingDerivedSupportingTokens(); if (signedEndorsingDerivedSupportingTokens != null) { for (int num6 = 0; num6 < signedEndorsingDerivedSupportingTokens.Length; num6++) { base.StandardsManager.SecurityTokenSerializer.WriteToken(writer, signedEndorsingDerivedSupportingTokens[num6]); } } SendSecurityHeaderElement[] signatureConfirmations = this.elementContainer.GetSignatureConfirmations(); if (signatureConfirmations != null) { for (int num7 = 0; num7 < signatureConfirmations.Length; num7++) { signatureConfirmations[num7].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } if ((this.elementContainer.PrimarySignature != null) && (this.elementContainer.PrimarySignature.Item != null)) { this.elementContainer.PrimarySignature.Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } SendSecurityHeaderElement[] endorsingSignatures = this.elementContainer.GetEndorsingSignatures(); if (endorsingSignatures != null) { for (int num8 = 0; num8 < endorsingSignatures.Length; num8++) { endorsingSignatures[num8].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } if (!this.SignThenEncrypt && (this.elementContainer.ReferenceList != null)) { this.elementContainer.ReferenceList.WriteTo(writer, ServiceModelDictionaryManager.Instance); } if ((this.elementContainer.Timestamp != null) && (base.Layout == SecurityHeaderLayout.LaxTimestampLast)) { base.StandardsManager.WSUtilitySpecificationVersion.WriteTimestamp(writer, this.elementContainer.Timestamp); } }
protected override object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, string action, MessageDescription messageDescription, object[] parameters, bool isRequest) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parameters")); } MessageInfo messageInfo; if (isRequest) { messageInfo = requestMessageInfo; } else { messageInfo = replyMessageInfo; } if (messageInfo.WrapperName != null) { if (!reader.IsStartElement(messageInfo.WrapperName, messageInfo.WrapperNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.SFxInvalidMessageBody, messageInfo.WrapperName, messageInfo.WrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI))); } bool isEmptyElement = reader.IsEmptyElement; reader.Read(); if (isEmptyElement) { return(null); } } object returnValue = null; if (messageInfo.ReturnPart != null) { while (true) { PartInfo part = messageInfo.ReturnPart; if (part.Serializer.IsStartObject(reader)) { returnValue = DeserializeParameter(reader, part, isRequest); break; } if (!reader.IsStartElement()) { break; } OperationFormatter.TraceAndSkipElement(reader); } } DeserializeParameters(reader, messageInfo.BodyParts, parameters, isRequest); if (messageInfo.WrapperName != null) { reader.ReadEndElement(); } return(returnValue); }
protected virtual Message GetNewFaultMessage(MessageVersion version, Exception error) { Exception ex = error; // if (ex != null && ex.Message == "Access is denied.") { Logger.Warning(LogCategory.WebService, "Please note: The default SecurityException behaviour is not overriden. Any Exception thrown as a SecurityException will end up in a 'text/html' response."); } // NOTE: code below will not be able to handle SecurityException's... as the Threads are aborted before this completes. //Exception spEx = SPThreadContextItemsRecoverException; //if (spEx != null) { ex = spEx; } // bool serviceDebug = (OperationContext.Current.EndpointDispatcher.ChannelDispatcher.IncludeExceptionDetailInFaults == true); // List <Type> knownTypes = new List <Type>(); PropertyInfo piDetail = ((error != null && error is FaultException) ? error.GetType().GetProperty("Detail") : null); object faultDetail = ((piDetail != null) ? piDetail.GetGetMethod().Invoke(error, null) : null); PropertyInfo piStatusCode = ((error != null && error is FaultException) ? error.GetType().GetProperty("StatusCode") : null); HttpStatusCode?faultStatusCode = (((piStatusCode != null) ? piStatusCode.GetGetMethod().Invoke(error, null) : null) as HttpStatusCode?); PropertyInfo piStatusDescription = ((error != null && error is FaultException) ? error.GetType().GetProperty("StatusDescription") : null); string faultStatusDescription = (((piStatusDescription != null) ? piStatusDescription.GetGetMethod().Invoke(error, null) : null) as string); if (faultDetail != null) { knownTypes.Add(faultDetail.GetType()); } else { if (faultDetail is Exception) { ex = (faultDetail as Exception); } // const string defaultMessage = @"Sorry, an unexpected error occurred."; string message = null, fullMessage = null; // override the default reason message //if (ex is ActiveDirectoryUserNotFoundException) { message = @"The user could not be found."; } //else if (ex is ActiveDirectoryUserLockedOutException) { message = @"The user is locked out! Please reset your password."; } //else if (ex is ActiveDirectoryException) { } // ignore any other sensitive messages (with usernames) //else if (ex is UserNotAuthenticatedException) { faultStatusCode = HttpStatusCode.Unauthorized; faultStatusDescription = "Unauthorized"; } if (ex is SecurityException) { message = @"Access is denied. Please make sure you're Signed-in and have correct permissions to access this resource."; faultStatusCode = HttpStatusCode.Unauthorized; faultStatusDescription = "Unauthorized"; } else if (ex is ArgumentNullException) { message = @"Invalid request! One or more properties were not provided."; } else if (ex is NullReferenceException) { message = defaultMessage; } else if (ex is System.Data.Entity.Validation.DbEntityValidationException) { System.Data.Entity.Validation.DbEntityValidationException dbEx = (ex as System.Data.Entity.Validation.DbEntityValidationException); string dbErrorMessages = string.Join($@";{Environment.NewLine}", dbEx.EntityValidationErrors.Select(_ => $@"Entity:{_.Entry.Entity}. Errors:{string.Join(", ", _.ValidationErrors.SelectMany(_2 => $@"[{_2.PropertyName}]: {_2.ErrorMessage}"))}")); message = defaultMessage; faultDetail = $@"There was a Database error ({ex.Message}). The validation errors were: {dbErrorMessages}"; } //else if (ex is Microsoft.Xrm.Sdk.SaveChangesException) //{ // message = defaultMessage; // // // Microsoft.Xrm.Sdk.SaveChangesException ex2 = (ex as Microsoft.Xrm.Sdk.SaveChangesException); // string crmErrorMessage = string.Format(@"CRM Error on SaveChangesResults - {0}", ((ex2.Results != null) ? string.Join(", ", ex2.Results.Select(_ => _.Error)) : "<null>")); // Logger.Error(ex, LogCategory.WebService, crmErrorMessage); // // // if (serviceDebug == true) { fullMessage = string.Join(Environment.NewLine, new string[] { crmErrorMessage, fullMessage, }.Where(_ => string.IsNullOrEmpty(_) == false)); } //} else if (ex is PortalException) { message = ex.Message; } //else if (ex is Exception && string.IsNullOrEmpty(ex.Message) == false) { message = ex.Message; } // if (string.IsNullOrEmpty(message) == true) { message = defaultMessage; } if (string.IsNullOrEmpty(fullMessage) == true && ex != null && serviceDebug == true) { fullMessage = getFullMessage(ex); } // Logger.Error(ex, LogCategory.WebService, string.Format("ProvideFault :: Did an override of the Fault Message with Message '{0}'.", message)); // faultDetail = new FaultInfo() { Message = message, Type = ((ex != null) ? ex.GetType().FullName : null), Details = ((serviceDebug == true) ? fullMessage : null), }; knownTypes.Add(typeof(FaultInfo)); } // Message faultMessage = Message.CreateMessage(version, "", faultDetail, new DataContractJsonSerializer(faultDetail.GetType(), knownTypes)); faultMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json)); HttpResponseMessageProperty rmp = new HttpResponseMessageProperty() { StatusCode = (faultStatusCode ?? HttpStatusCode.BadRequest), StatusDescription = (faultStatusDescription ?? "Bad Request"), }; rmp.Headers[System.Net.HttpResponseHeader.ContentType] = "application/json"; faultMessage.Properties.Add(HttpResponseMessageProperty.Name, rmp); // return(faultMessage); }
void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref System.ServiceModel.Channels.Message fault) { m_ErrorHandler.ProvideFault(error, version, ref fault); }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteValue("f0058694-0969-4cf0-9dcb-62c509e4c025"); }
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (!(value is string)) { return(base.ConvertFrom(context, culture, value)); } string str = (string)value; MessageVersion soap11WSAddressing10 = null; string str1 = str; string str2 = str1; if (str1 != null) { switch (str2) { case "Soap11WSAddressing10": { soap11WSAddressing10 = MessageVersion.Soap11WSAddressing10; break; } case "Soap12WSAddressing10": { soap11WSAddressing10 = MessageVersion.Soap12WSAddressing10; break; } case "Soap11WSAddressingAugust2004": { soap11WSAddressing10 = MessageVersion.Soap11WSAddressingAugust2004; break; } case "Soap12WSAddressingAugust2004": { soap11WSAddressing10 = MessageVersion.Soap12WSAddressingAugust2004; break; } case "Soap11": { soap11WSAddressing10 = MessageVersion.Soap11; break; } case "Soap12": { soap11WSAddressing10 = MessageVersion.Soap12; break; } case "None": { soap11WSAddressing10 = MessageVersion.None; break; } case "Default": { soap11WSAddressing10 = MessageVersion.Default; break; } default: { throw new ArgumentOutOfRangeException("messageVersion"); } } return(soap11WSAddressing10); } throw new ArgumentOutOfRangeException("messageVersion"); }
/// <summary> /// Serialize the reply /// </summary> public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { try { // Outbound control var format = WebContentFormat.Raw; Message request = OperationContext.Current.RequestContext.RequestMessage; HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; string accepts = httpRequest.Headers[HttpRequestHeader.Accept], contentType = httpRequest.Headers[HttpRequestHeader.ContentType], formatParm = httpRequest.QueryString; Message reply = null; // Result is serializable if (result?.GetType().GetCustomAttribute <XmlTypeAttribute>() != null || result?.GetType().GetCustomAttribute <JsonObjectAttribute>() != null) { XmlSerializer xsz = s_serializers[result.GetType()]; MemoryStream ms = new MemoryStream(); xsz.Serialize(ms, result); format = WebContentFormat.Xml; contentType = "application/xml+fhir"; ms.Seek(0, SeekOrigin.Begin); // The request was in JSON or the accept is JSON if (accepts?.StartsWith("application/json+fhir") == true || contentType?.StartsWith("application/json+fhir") == true || formatParm.Contains("_format=json")) { // Parse XML object Object fhirObject = null; using (StreamReader sr = new StreamReader(ms)) { String fhirContent = sr.ReadToEnd(); fhirObject = FhirParser.ParseFromXml(fhirContent); } // Now we serialize to JSON byte[] body = FhirSerializer.SerializeResourceToJsonBytes(fhirObject as Hl7.Fhir.Model.Resource); // Prepare reply for the WCF pipeline format = WebContentFormat.Raw; contentType = "application/json+fhir"; reply = Message.CreateMessage(messageVersion, this.m_operationDescription?.Messages[1]?.Action, new RawBodyWriter(body)); } // The request was in XML and/or the accept is JSON else { reply = Message.CreateMessage(messageVersion, this.m_operationDescription?.Messages[1]?.Action, XmlDictionaryReader.Create(ms)); } } else if (result is XmlSchema) { MemoryStream ms = new MemoryStream(); (result as XmlSchema).Write(ms); ms.Seek(0, SeekOrigin.Begin); format = WebContentFormat.Xml; contentType = "text/xml"; reply = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action, XmlDictionaryReader.Create(ms)); } else if (result is Stream) // TODO: This is messy, clean it up { reply = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action, new RawBodyWriter(result as Stream)); } reply.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(format)); WebOperationContext.Current.OutgoingResponse.ContentType = contentType; WebOperationContext.Current.OutgoingResponse.Headers.Add("X-PoweredBy", String.Format("{0} v{1} ({2})", Assembly.GetEntryAssembly().GetName().Name, Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion)); WebOperationContext.Current.OutgoingResponse.Headers.Add("X-GeneratedOn", DateTime.Now.ToString("o")); return(reply); } catch (Exception e) { this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString()); throw; } }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement(Addressing10Strings.ProblemHeaderQName, Namespace); writer.WriteQualifiedName(invalidHeaderName, Namespace); writer.WriteEndElement(); }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { WebException webException; if (error is WebException) { webException = (WebException)error; } else { var behavior = GetWebErrorHandlerConfiguration(); string unhandledErrorMessage; if (behavior.ReturnRawException) { unhandledErrorMessage = error.ToString(); } else { unhandledErrorMessage = (behavior != null && behavior.UnhandledErrorMessage != null) ? behavior.UnhandledErrorMessage : "An error has occured processing your request."; } webException = new WebException(error, System.Net.HttpStatusCode.InternalServerError, unhandledErrorMessage); } webException.UpdateHeaders(WebOperationContext.Current.OutgoingResponse.Headers); WebOperationContext.Current.OutgoingResponse.StatusCode = webException.Status; WebOperationContext.Current.OutgoingResponse.StatusDescription = webException.Status.ToString(); WebDispatchFormatter webDispatchFormatter = null; if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(WebDispatchFormatter.WebDispatcherFormatterProperty)) { webDispatchFormatter = OperationContext.Current.OutgoingMessageProperties[WebDispatchFormatter.WebDispatcherFormatterProperty] as WebDispatchFormatter; } if (webDispatchFormatter != null) { var behavior = GetWebErrorHandlerConfiguration(); IWebExceptionDataContract exceptionContract = null; if (behavior != null) { exceptionContract = behavior.CreateExceptionDataContract(); } if (exceptionContract == null) { exceptionContract = new WebExceptionContract(); } exceptionContract.Init(webException); fault = webDispatchFormatter.Serialize( exceptionContract, typeof(WebExceptionContract), WebOperationContext.Current.IncomingRequest.GetAcceptTypes()); } else { WebOperationContext.Current.OutgoingResponse.ContentType = MediaTypeNames.Text.Html; fault = Message.CreateMessage( MessageVersion.None, null, new BinaryBodyWriter(GenerateResponseText(webException.Message))); fault.SetWebContentFormatProperty(WebContentFormat.Raw); } fault.UpdateHttpProperty(); if (OperationContainer.Exists()) { DependencyResolver.Current.OperationError(OperationContainer.GetCurrent(), error); } }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement("ns:Address"); writer.WriteString("###"); writer.WriteEndElement(); }
/// <summary> /// Provide fault /// </summary> public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { this.m_traceSource.TraceEvent(TraceEventType.Error, error.HResult, "Error on IMSI WCF Pipeline: {0}", error); ErrorResult retVal = null; // Formulate appropriate response if (error is PolicyViolationException || error is SecurityException || (error as FaultException)?.Code.SubCode?.Name == "FailedAuthentication") { AuditUtil.AuditRestrictedFunction(error, WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri); WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Forbidden; } else if (error is SecurityTokenException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Unauthorized; WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate", "Bearer"); } else if (error is FileNotFoundException || error is KeyNotFoundException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound; } else if (error is WebFaultException) { WebOperationContext.Current.OutgoingResponse.StatusCode = (error as WebFaultException).StatusCode; } else if (error is Newtonsoft.Json.JsonException || error is System.Xml.XmlException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; } else if (error is LimitExceededException) { WebOperationContext.Current.OutgoingResponse.StatusCode = (HttpStatusCode)429; WebOperationContext.Current.OutgoingResponse.StatusDescription = "Too Many Requests"; WebOperationContext.Current.OutgoingResponse.Headers.Add(HttpResponseHeader.RetryAfter, "1200"); } else if (error is UnauthorizedRequestException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Unauthorized; WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate", (error as UnauthorizedRequestException).AuthenticateChallenge); } else if (error is UnauthorizedAccessException) { AuditUtil.AuditRestrictedFunction(error as UnauthorizedAccessException, WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri); WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Forbidden; } else if (error is DomainStateException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.ServiceUnavailable; } else if (error is DetectedIssueException) { WebOperationContext.Current.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode) 422; retVal = new ErrorResult() { Key = Guid.NewGuid(), Type = "BusinessRuleViolation", Details = (error as DetectedIssueException).Issues.Select(o => new ResultDetail(o.Priority == Core.Services.DetectedIssuePriorityType.Error ? DetailType.Error : o.Priority == Core.Services.DetectedIssuePriorityType.Warning ? DetailType.Warning : DetailType.Information, o.Text)).ToList() }; } else if (error is PatchAssertionException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Conflict; } else if (error is PatchException) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotAcceptable; } else { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError; } // Construct an error result if (retVal == null) { retVal = new ErrorResult() { Key = Guid.NewGuid(), Type = error.GetType().Name, Details = new List <ResultDetail>() { new ResultDetail(DetailType.Error, error.Message) } } } ; // Cascade inner exceptions var ie = error.InnerException; while (ie != null) { retVal.Details.Add(new ResultDetail(DetailType.Error, String.Format("Caused By: {0}", ie.Message))); ie = ie.InnerException; } // Return error in XML only at this point fault = new WcfMessageDispatchFormatter <IImsiServiceContract>().SerializeReply(version, null, retVal); } }
internal DuplexListenerBinder(IChannelListener <IDuplexChannel> listener, MessageVersion messageVersion) { correlator = new RequestReplyCorrelator(); this.listener = listener; this.messageVersion = messageVersion; }
protected abstract object DoDecode(MessageVersion version, IoBuffer input);
public CommitMessage(MessageVersion version, ProtocolVersion protocolVersion) : base(AtomicTransactionStrings.Version(protocolVersion).CommitAction, version, protocolVersion) { }
internal ReplySessionListenerBinder(IChannelListener <IReplySessionChannel> listener, MessageVersion messageVersion) { this.listener = listener; this.messageVersion = messageVersion; }
public static void MessageVersion_Verify_AddressingVersions_And_EnvelopeVersions(MessageVersion messageVersion, EnvelopeVersion envelopeVersion, AddressingVersion addressingVersion) { Assert.Equal <EnvelopeVersion>(envelopeVersion, messageVersion.Envelope); Assert.Equal <AddressingVersion>(addressingVersion, messageVersion.Addressing); }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartAttribute("role"); writer.WriteString(this.role); writer.WriteEndAttribute(); }
// Provide a fault. The Message fault parameter can be replaced, or set to // null to suppress reporting a fault. public void ProvideFault(Exception error, MessageVersion version, ref Message msg) { _mSELDao = (ISELDao)ContextHelper.GetContextObject("SELDAO"); ASAException translatedException = new ASAException(); //catch all, in case error comes into EHF without being translated if (error is ASAException) { translatedException = (ASAException)error; } else { ASAExceptionTranslator afterThrowingTranslator = new ASAExceptionTranslator(); translatedException = afterThrowingTranslator.Translate(error); } string tidCorrelationID = ASATIDHelper.GetTIDCorrelationID(); if (error != null && error is NoMatchingObjectException) { msg = BuildErrorMessage <ASAFaultDetail>(version, "Server", tidCorrelationID, translatedException.Error_FaultString, translatedException.Error_DetailMessage); } else if (error != null && error is ServiceRequestValidationException) { msg = BuildErrorMessage <ASAFaultDetail>(version, "Server", tidCorrelationID, translatedException.Error_FaultString + ": " + translatedException.Error_DetailMessage, translatedException.Error_DetailMessage); } else if (error != null && error is ServiceReplyValidationException) { msg = BuildErrorMessage <ASAFaultDetail>(version, "Server", tidCorrelationID, translatedException.Error_FaultString, translatedException.Error_DetailMessage); } else if (error != null && error is ASADemogBusinessException) { //QC 1690-1693 handle new exception types msg = BuildErrorMessage <ASADemogFaultDetail>(version, "Server", tidCorrelationID, translatedException.Error_FaultString + ": " + translatedException.Error_DetailMessage, translatedException.Error_DetailMessage); } else if (error != null && error is ASABusinessException) { //QC 1690-1693 handle new exception types msg = BuildErrorMessage <ASABusinessFaultDetail>(version, "Server", tidCorrelationID, translatedException.Error_FaultString + ": " + translatedException.Error_DetailMessage, translatedException.Error_DetailMessage); } else if (error != null && error is Exception) { switch (translatedException.ExceptionType) { case "ASADataAccessException": case "ASAUnknownException": case "ASA.ExcErrCodeUnavail": { msg = BuildErrorMessage <ASAFaultDetail>(version, "Server", tidCorrelationID, translatedException.BusinessDescription, translatedException.Original_Message); break; } default: { msg = BuildErrorMessage <ASAFaultDetail>(version, "Server", tidCorrelationID, translatedException.Error_FaultString, translatedException.Error_DetailMessage); break; } } } Log.Error(msg); #region add message to the LogException tables string payload = string.Empty; if (Payload.ContainsMessagePayLoad(tidCorrelationID)) { payload = Payload.GetMessagePayLoad(tidCorrelationID); } //LogEvent logEventRec = new LogEvent(); LogException logExceptionRec = new LogException(); logExceptionRec.CreatedBy = (ASATIDHelper.GetTIDUsername() != "") ? ASATIDHelper.GetTIDUsername() : "ASA_USER"; logExceptionRec.CreatedDate = DateTime.Now; logExceptionRec.Payload = payload.ToString(); logExceptionRec.ExceptionStack = error.StackTrace; logExceptionRec.Correlationid = new Guid(tidCorrelationID); logExceptionRec.ExceptionErrorid = translatedException.ExceptionError_id; long eventID; try { //_mSELDao.AddLogExceptionRecord(logExceptionRec, out eventID); Log.Error(payload); Log.Error(logExceptionRec); } catch (Exception ex) { //if there is an error logging the record to the DB, write payload to log file Log.Error(payload); } #endregion }
static void Main(string[] args) { // <Snippet0> MessageVersion msgVersion = MessageVersion.Default; // </Snippet0> // <Snippet1> AddressingVersion addrVersion = msgVersion.Addressing; // </Snippet1> // <Snippet2> EnvelopeVersion envVersion = msgVersion.Envelope; // </Snippet2> // <Snippet3> msgVersion.ToString(); // </Snippet3> // <Snippet4> MessageVersion msgVersion2 = MessageVersion.None; // </Snippet4> // <Snippet5> msgVersion = MessageVersion.Soap11; // </Snippet5> // <Snippet6> msgVersion = MessageVersion.Soap11WSAddressing10; // </Snippet6> // <Snippet7> msgVersion = MessageVersion.Soap11WSAddressingAugust2004; // </Snippet7> // <Snippet8> msgVersion = MessageVersion.Soap12; // </Snippet8> // <Snippet9> msgVersion = MessageVersion.Soap12WSAddressing10; // </Snippet9> // <Snippet10> msgVersion = MessageVersion.Soap12WSAddressingAugust2004; // </Snippet10> // <Snippet11> msgVersion = MessageVersion.CreateVersion(envVersion); // </Snippet11> // <Snippet12> msgVersion = MessageVersion.CreateVersion(envVersion, addrVersion); // </Snippet12> // <Snippet13> msgVersion.Equals(msgVersion2); // </Snippet13> // <Snippet14> msgVersion.GetHashCode(); // </Snippet14> }
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteElementString(_elementName, _attr); }
void AddMessageHeaderForParameter(MessageHeaders headers, PartInfo headerPart, MessageVersion messageVersion, object parameterValue, bool isXmlElement) { string actor; bool mustUnderstand; bool relay; MessageHeaderDescription headerDescription = (MessageHeaderDescription)headerPart.Description; object valueToSerialize = GetContentOfMessageHeaderOfT(headerDescription, parameterValue, out mustUnderstand, out relay, out actor); if (isXmlElement) { if (valueToSerialize == null) { return; } XmlElement xmlElement = (XmlElement)valueToSerialize; headers.Add(new XmlElementMessageHeader(this, messageVersion, xmlElement.LocalName, xmlElement.NamespaceURI, mustUnderstand, actor, relay, xmlElement)); return; } headers.Add(new DataContractSerializerMessageHeader(headerPart, valueToSerialize, mustUnderstand, actor, relay)); }
internal OperationContext(MessageVersion outgoingMessageVersion) { OutgoingMessageVersion = outgoingMessageVersion ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(outgoingMessageVersion))); }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { //we do not handle any errors to wrap them up for the client }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { // TODO: Fault handling }
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement(Name, Namespace); }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { if (!(error is FaultException)) { LoggingExceptionDetails guidException = new LoggingExceptionDetails(); FaultException<LoggingExceptionDetails> faultException = new FaultException<LoggingExceptionDetails>(guidException, new FaultReason(guidException.Message)); fault = Message.CreateMessage(version, faultException.CreateMessageFault(), faultException.Action); this.LogMessage(error, guidException); } }
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { base.StandardsManager.SecurityVersion.WriteStartHeader(writer); base.WriteHeaderAttributes(writer, messageVersion); }
protected override void OnWriteHeaderContents(XmlDictionaryWriter xmlDictionaryWriter, MessageVersion messageVersion) { xmlDictionaryWriter.WriteString(value); }
protected abstract int FixedHeaderLength(MessageVersion version);
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { _logger.Error($"Exception: {0}. MessageVersion: {1}. Message: {2}.", error, version, fault); }
internal InputListenerBinder(IChannelListener <IInputChannel> listener, MessageVersion messageVersion) { this.listener = listener; this.messageVersion = messageVersion; }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { Message errormsg=fault; if (error.Message == "The data contract type 'WCFWebHTTPService.Student' cannot be deserialized because the data member 'FirstName' was found more than once in the input.") { errormsg=Message.CreateMessage(version, "The reply action", error.Message); } fault = errormsg; }
public CreateCoordinationContextResponseMessage(MessageVersion version, ref CreateCoordinationContextResponse response) : base(CoordinationStrings.Version(response.ProtocolVersion).CreateCoordinationContextResponseAction, version) { this.response = response; }