public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { var context = WebOperationContext.Current; if (HttpContext.Current != null && context != null && context.IncomingRequest.UriTemplateMatch != null) { var curatedFeedName = HttpContext.Current.Request.QueryString["name"]; // Grab the base and request URIs UriBuilder baseUriBuilder = new UriBuilder(context.IncomingRequest.UriTemplateMatch.BaseUri); UriBuilder requestUriBuilder = new UriBuilder(context.IncomingRequest.UriTemplateMatch.RequestUri); // Replace Host Name baseUriBuilder.Host = HttpContext.Current.Request.Url.Host; requestUriBuilder.Host = baseUriBuilder.Host; // Replace "/api/v2/curated-feed" with "/api/v2/curated-feeds/[feedname]" baseUriBuilder.Path = RewriteUrlPath(baseUriBuilder.Path, curatedFeedName); requestUriBuilder.Path = RewriteUrlPath(requestUriBuilder.Path, curatedFeedName); // Set the matching properties on the incoming request OperationContext.Current.IncomingMessageProperties["MicrosoftDataServicesRootUri"] = baseUriBuilder.Uri; OperationContext.Current.IncomingMessageProperties["MicrosoftDataServicesRequestUri"] = requestUriBuilder.Uri; } return null; }
public Message Get(Message message) { HttpRequestMessageProperty requestMessageProperty = (HttpRequestMessageProperty) message.Properties[HttpRequestMessageProperty.Name]; HttpResponseMessageProperty responseMessageProperty = new HttpResponseMessageProperty(); if ((requestMessageProperty != null) && IsServiceUnchanged(requestMessageProperty.Headers[JsonGlobals.IfModifiedSinceString])) { Message responseMessage = Message.CreateMessage(MessageVersion.None, string.Empty); responseMessageProperty.StatusCode = HttpStatusCode.NotModified; responseMessage.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty); return responseMessage; } string proxyContent = this.GetProxyContent(UriTemplate.RewriteUri(this.endpoint.Address.Uri, requestMessageProperty.Headers[HttpRequestHeader.Host])); Message response = new WebScriptMetadataMessage(string.Empty, proxyContent); responseMessageProperty.Headers.Add(JsonGlobals.LastModifiedString, ServiceLastModifiedRfc1123String); responseMessageProperty.Headers.Add(JsonGlobals.ExpiresString, ServiceLastModifiedRfc1123String); if (AspNetEnvironment.Current.AspNetCompatibilityEnabled) { HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public); } else { responseMessageProperty.Headers.Add(JsonGlobals.CacheControlString, JsonGlobals.publicString); } response.Properties.Add(HttpResponseMessageProperty.Name, responseMessageProperty); return response; }
/// <summary> /// Associates a local operation with the incoming method. /// </summary> /// <param name="message">The incoming <see cref="Message"/> to be associated with an operation.</param> /// <returns>The name of the operation to be associated with the message.</returns> string IDispatchOperationSelector.SelectOperation(ref Message message) { if (message == null) { throw new ArgumentNullException("message"); } HttpRequestMessage requestMessage = message.ToHttpRequestMessage(); if (requestMessage == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.HttpOperationSelectorNullRequest, this.GetType().Name)); } string operation = this.SelectOperation(requestMessage); if (operation == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.HttpOperationSelectorNullOperation, this.GetType().Name)); } return operation; }
public override void HandleMessage(Message message) { if (message.Name == "ASR.MainForm:updateSection") { var ctl = message.Sender as Sitecore.Web.UI.HtmlControls.Control; if (ctl != null) { Sitecore.Context.ClientPage.ClientResponse.Refresh(ctl); } return; } if (message.Name.StartsWith("ASRMainFormCommand:")) { string commandname = message.Name.Substring(message.Name.IndexOf(':') + 1); var parameters = new NameValueCollection { { "name", commandname } }; Sitecore.Context.ClientPage.Start(this, "RunCommand", parameters); return; } if (message.Name == "event:click") { var nvc = message.Sender as NameValueCollection; if (nvc != null) { string eventname = nvc["__PARAMETERS"]; if (!string.IsNullOrEmpty(eventname)) { HandleClickEvent(message, eventname); return; } } } base.HandleMessage(message); }
public bool TryCreateException(Message message, MessageFault fault, out Exception exception) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } if (fault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("fault"); } bool created = this.OnTryCreateException(message, fault, out exception); if (created) { if (exception == null) { string text = SR.Format(SR.FaultConverterDidNotCreateException, this.GetType().Name); Exception error = new InvalidOperationException(text); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } else { if (exception != null) { string text = SR.Format(SR.FaultConverterCreatedException, this.GetType().Name); Exception error = new InvalidOperationException(text, exception); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } return created; }
public SecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection transferDirection) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } if (actor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("actor"); } if (standardsManager == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("standardsManager"); } if (algorithmSuite == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("algorithmSuite"); } _message = message; _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; _standardsManager = standardsManager; _algorithmSuite = algorithmSuite; _transferDirection = transferDirection; }
private void ApplyChannelBinding(Message message) { if (this.enableChannelBinding) { ChannelBindingUtility.TryAddToMessage(this.ChannelBinding, message, true); } }
public void should_change_message_label() { var processor = new ContentBasedRouter(m => string.Format("l-{0}", ((string)m.Payload).Length).ToMessageLabel()); var message = new Message( "boo".ToMessageLabel(), new Dictionary<string, object> { { "This", "That" } }, "Body"); var result = processor.Apply(message).ToList(); result.Should().HaveCount(1); result.Single().Label.Name.Should().Be("l-4"); result.Single().Payload.Should().Be("Body"); message = new Message( "boo".ToMessageLabel(), new Dictionary<string, object> { { "This", "That" } }, "Another"); result = processor.Apply(message).ToList(); result.Should().HaveCount(1); result.Single().Label.Name.Should().Be("l-7"); }
/// <summary> /// Publishes the message. /// </summary> /// <param name="message">The message.</param> /// <param name="delayMilliseconds">The delay in ms.</param> public void PublishMessage(Message message, int delayMilliseconds) { var messageId = message.Id; var deliveryTag = message.Header.Bag.ContainsKey(HeaderNames.DELIVERY_TAG) ? message.GetDeliveryTag().ToString() : null; var headers = new Dictionary<string, object> { { HeaderNames.MESSAGE_TYPE, message.Header.MessageType.ToString() }, { HeaderNames.TOPIC, message.Header.Topic }, { HeaderNames.HANDLED_COUNT, message.Header.HandledCount.ToString(CultureInfo.InvariantCulture) } }; if (message.Header.CorrelationId != Guid.Empty) headers.Add(HeaderNames.CORRELATION_ID, message.Header.CorrelationId.ToString()); message.Header.Bag.Each(header => { if (!_headersToReset.Any(htr => htr.Equals(header.Key))) headers.Add(header.Key, header.Value); }); if (!string.IsNullOrEmpty(deliveryTag)) headers.Add(HeaderNames.DELIVERY_TAG, deliveryTag); if (delayMilliseconds > 0) headers.Add(HeaderNames.DELAY_MILLISECONDS, delayMilliseconds); _channel.BasicPublish( _exchangeName, message.Header.Topic, false, CreateBasicProperties(messageId, message.Header.TimeStamp, message.Body.BodyType, message.Header.ContentType, headers), message.Body.Bytes); }
private void IntroduceErrorToMessage(ref Message message) { XmlDocument doc = new XmlDocument(); doc.Load(message.GetReaderAtBodyContents()); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("tempuri", "http://tempuri.org/"); XmlElement xNode = doc.SelectSingleNode("//tempuri:x", nsManager) as XmlElement; XmlText xValue = xNode.FirstChild as XmlText; xValue.Value = (double.Parse(xValue.Value, CultureInfo.InvariantCulture) + 1).ToString(CultureInfo.InvariantCulture); MemoryStream ms = new MemoryStream(); XmlWriterSettings writerSettings = new XmlWriterSettings { CloseOutput = false, OmitXmlDeclaration = true, Encoding = Encoding.UTF8, }; XmlWriter writer = XmlWriter.Create(ms, writerSettings); doc.WriteTo(writer); writer.Close(); ms.Position = 0; XmlReader reader = XmlReader.Create(ms); Message newMessage = Message.CreateMessage(message.Version, null, reader); newMessage.Headers.CopyHeadersFrom(message); newMessage.Properties.CopyProperties(message.Properties); message.Close(); message = newMessage; }
private void AppendTypeToBody(Message message, StringBuilder bodyBuilder) { Type type = message.GetType(); string typeRef = this._typeResolver.CreateTypeRef(type); bodyBuilder.Append(IntegerToString(typeRef.Length)); bodyBuilder.Append(typeRef); }
/// <summary> /// Determines whether the requested message is JSONP. When detected /// changes the message to be treated by the WCF Data services Runtime /// as a common JSON request and correlates the output with the requested /// callback. /// </summary> /// <param name="request">Requested message.</param> /// <param name="channel">Current client channel.</param> /// <param name="instanceContext">Context where the service is running.</param> /// <returns>Returns a correlation value indicating the requested callback (when applies).</returns> public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { if (request.Properties.ContainsKey("UriTemplateMatchResults")) { var match = (UriTemplateMatch)request.Properties["UriTemplateMatchResults"]; var format = match.QueryParameters["$format"]; if ("json".Equals(format, StringComparison.InvariantCultureIgnoreCase)) { // strip out $format from the query options to avoid an error // due to use of a reserved option (starts with "$") match.QueryParameters.Remove("$format"); // replace the Accept header so that the Data Services runtime // assumes the client asked for a JSON representation var httpmsg = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; httpmsg.Headers["Accept"] = "application/json"; var callback = match.QueryParameters["$callback"]; if (!string.IsNullOrEmpty(callback)) { match.QueryParameters.Remove("$callback"); return callback; } } } return null; }
/// <summary> /// Wraps the resulting content into a JSONP callback function /// extracted on the AfterReceiveReply message. /// </summary> /// <param name="reply">Outgoing response message.</param> /// <param name="correlationState">Correlation state returned by the AfterReceiveReply method.</param> public void BeforeSendReply(ref Message reply, object correlationState) { if (correlationState == null || !(correlationState is string)) return; // If we have a JSONP callback then buffer the response, wrap it with the // callback call and then re-create the response message var callback = (string)correlationState; var reader = reply.GetReaderAtBodyContents(); reader.ReadStartElement(); var content = Encoding.UTF8.GetString(reader.ReadContentAsBase64()); content = string.Format(CultureInfo.InvariantCulture, "{0}({1});", callback, content); var newReply = Message.CreateMessage(MessageVersion.None, string.Empty, new JsonBodyWriter(content)); newReply.Properties.CopyProperties(reply.Properties); reply = newReply; // change response content type to text/javascript if the JSON (only done when wrapped in a callback) var replyProperties = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name]; replyProperties.Headers["Content-Type"] = replyProperties.Headers["Content-Type"].Replace("application/json", "text/javascript"); }
public InitiatorSecureMessageDecryptor ( Message source, SecurityMessageProperty secprop, InitiatorMessageSecurityBindingSupport security) : base (source, security) { this.security = security; request_security = secprop; }
public void DeserializeRequest(Message message, object[] parameters) { if (message == null) { return; } WebContentFormat format; IDispatchMessageFormatter selectedFormatter; if (TryGetEncodingFormat(message, out format)) { this.formatters.TryGetValue(format, out selectedFormatter); if (selectedFormatter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.UnrecognizedHttpMessageFormat, format, GetSupportedFormats()))); } } else { selectedFormatter = this.defaultFormatter; if (selectedFormatter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.MessageFormatPropertyNotFound3))); } } selectedFormatter.DeserializeRequest(message, parameters); }
private Message TransformAndHandleFault(Message message) { if (message.Headers.Action.EndsWith("/fault")) { var buffer = message.CreateBufferedCopy(int.MaxValue); var clonedMessage = buffer.CreateMessage(); var reader = clonedMessage.GetReaderAtBodyContents(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); var val = reader.Value; if (string.IsNullOrWhiteSpace(val)) { return buffer.CreateMessage(); } if (val == Constants.SerializationFaultCode.ToString(CultureInfo.InvariantCulture)) { var store = ObjectBuilder.GetModelStore(); store.RemoveAll(); } return buffer.CreateMessage(); } return message; }
public bool TryCreateFaultMessage(Exception exception, out Message message) { bool created = this.OnTryCreateFaultMessage(exception, out message); if (created) { if (message == null) { string text = SR.Format(SR.FaultConverterDidNotCreateFaultMessage, this.GetType().Name); Exception error = new InvalidOperationException(text); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } else { if (message != null) { string text = SR.Format(SR.FaultConverterCreatedFaultMessage, this.GetType().Name); Exception error = new InvalidOperationException(text); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } } return created; }
public bool TryCreateException(Message message, MessageFault fault, out Exception exception) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } if (fault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("fault"); } bool flag = this.OnTryCreateException(message, fault, out exception); if (flag) { if (exception == null) { Exception exception2 = new InvalidOperationException(System.ServiceModel.SR.GetString("FaultConverterDidNotCreateException", new object[] { base.GetType().Name })); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception2); } return flag; } if (exception != null) { Exception exception3 = new InvalidOperationException(System.ServiceModel.SR.GetString("FaultConverterCreatedException", new object[] { base.GetType().Name }), exception); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception3); } return flag; }
public Task Send(Message[] messages) { if (messages == null || messages.Length == 0) { return TaskAsyncHelper.Empty; } SqlConnection connection = null; try { connection = new SqlConnection(_connectionString); connection.Open(); using (var cmd = new SqlCommand(_insertSql, connection)) { cmd.Parameters.AddWithValue("Payload", JsonConvert.SerializeObject(messages)); return cmd.ExecuteNonQueryAsync() .Then(() => connection.Close()) // close the connection if successful .Catch(ex => connection.Close()); // close the connection if it explodes } } catch (SqlException) { if (connection != null && connection.State != ConnectionState.Closed) { connection.Close(); } throw; } }
static internal void CopyActivity(Message source, Message destination) { if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source)); } }
protected override void ProcessReply (Message msg, TimeSpan timeout) { ctx.Response.ContentType = Channel.Encoder.ContentType; MemoryStream ms = new MemoryStream (); Channel.Encoder.WriteMessage (msg, ms); string pname = HttpResponseMessageProperty.Name; bool suppressEntityBody = false; if (msg.Properties.ContainsKey (pname)) { HttpResponseMessageProperty hp = (HttpResponseMessageProperty) msg.Properties [pname]; string contentType = hp.Headers ["Content-Type"]; if (contentType != null) ctx.Response.ContentType = contentType; ctx.Response.Headers.Add (hp.Headers); if (hp.StatusCode != default (HttpStatusCode)) ctx.Response.StatusCode = (int) hp.StatusCode; ctx.Response.StatusDescription = hp.StatusDescription; if (hp.SuppressEntityBody) suppressEntityBody = true; } if (msg.IsFault) ctx.Response.StatusCode = 500; if (!suppressEntityBody) { ctx.Response.AddHeader ("Content-Length", ms.Length.ToString (CultureInfo.InvariantCulture)); ctx.Response.OutputStream.Write (ms.GetBuffer (), 0, (int) ms.Length); ctx.Response.OutputStream.Flush (); } else ctx.Response.SuppressContent = true; }
public override bool Match(Message message) { if (message == null) { throw FxTrace.Exception.ArgumentNull("message"); } return this.GetInnerFilter().Match(message); }
public AspNetRequestContext ( AspNetReplyChannel channel, Message msg, HttpContext ctx) : base (channel, msg) { this.channel = channel; this.ctx = ctx; }
protected override HttpOutput GetHttpOutput(Message message) { if (((base.HttpInput.ContentLength == -1L) && !OSEnvironmentHelper.IsVistaOrGreater) || !base.KeepAliveEnabled) { this.result.SetConnectionClose(); } return new HostedRequestHttpOutput(this.result, base.Listener, message, this); }
public Message Request(Message message, TimeSpan timeout) { CheckAndMakeMetaDataRequest(message, timeout); var response = _innerChannel.Request(message, timeout); return TransformAndHandleFault(response); }
public override Task<Filter> CreateFilter(Message request) { var part = new PartInfo(request); log.Info("Create filter for service {0} with partition key {1}", request.Headers.To, part.ToString()); return createFilter(part, null); }
public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state) { var timeout = ((IDefaultCommunicationTimeouts)this.Manager).ReceiveTimeout; CheckAndMakeMetaDataRequest(message, timeout); return _innerChannel.BeginRequest(message, callback, state); }
public MessageContent(Message message, MessageEncoder messageEncoder) { _message = message; _messageEncoder = messageEncoder; SetContentType(_messageEncoder.ContentType); PrepareContentHeaders(); }
protected MakeConnectionMessageFault(Message message, FaultCode code, string subcode, FaultReason reason) { this.code = code; this.subcode = subcode; this.reason = reason; this.isRemote = true; this.originalMessageId = message.Headers.MessageId; }
public MessageContent(Message message, MessageEncoder messageEncoder) { _message = message; _messageEncoder = messageEncoder; _writeCompletedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); SetContentType(_messageEncoder.ContentType); PrepareContentHeaders(); }