public static void WaitBeforeRetry(int retries, int maxBackoffInMilliseconds) { int delay = (int)(Math.Pow(4, retries) * 100); delay = Math.Min(delay, maxBackoffInMilliseconds); AliyunSDKUtils.Sleep(delay); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { XmlTextReader reader = new XmlTextReader(context.ResponseStream); ChangeMessageVisibilityResponse response = new ChangeMessageVisibilityResponse(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ELEMENT_RECEIPT_HANDLE: reader.Read(); response.ReceiptHandle = reader.Value; break; case MNSConstants.XML_ELEMENT_NEXT_VISIBLE_TIME: reader.Read(); response.NextVisibleTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value)); break; } break; } } reader.Close(); return(response); }
internal static TResponse EndInvoke <TResponse>(IAsyncResult result) where TResponse : WebServiceResponse { if (result == null) { throw new ArgumentNullException("result", "Parameter result cannot be null."); } var asyncResult = result as RuntimeAsyncResult; if (asyncResult == null) { throw new ArgumentOutOfRangeException("result", "Parameter result is not of type RuntimeAsyncResult."); } using (asyncResult) { if (!asyncResult.IsCompleted) { asyncResult.AsyncWaitHandle.WaitOne(); } if (asyncResult.Exception != null) { AliyunSDKUtils.PreserveStackTrace(asyncResult.Exception); throw asyncResult.Exception; } return((TResponse)asyncResult.Response); } }
static void Main(string[] args) { try { // 循环发送4条消息 for (int i = 0; i < 4; i++) { TopicMessage sendMsg; if (i % 2 == 0) { sendMsg = new TopicMessage("dfadfadfadf"); // 设置属性 sendMsg.PutProperty("a", i.ToString()); // 设置KEY sendMsg.MessageKey = "MessageKey"; } else { sendMsg = new TopicMessage("dfadfadfadf", "tag"); // 设置属性 sendMsg.PutProperty("a", i.ToString()); // 定时消息, 定时时间为10s后 sendMsg.StartDeliverTime = AliyunSDKUtils.GetNowTimeStamp() + 10 * 1000; } TopicMessage result = producer.PublishMessage(sendMsg); Console.WriteLine("publis message success:" + result); } } catch (Exception ex) { Console.Write(ex); } }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { XmlTextReader reader = new XmlTextReader(context.ResponseStream); TopicAttributes attributes = new TopicAttributes(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ELEMENT_TOPIC_NAME: reader.Read(); attributes.TopicName = reader.Value; break; case MNSConstants.XML_ELEMENT_CREATE_TIME: reader.Read(); attributes.CreateTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value) * 1000); break; case MNSConstants.XML_ELEMENT_LAST_MODIFY_TIME: reader.Read(); attributes.LastModifyTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value) * 1000); break; case MNSConstants.XML_ELEMENT_MAXIMUM_MESSAGE_SIZE: reader.Read(); attributes.MaximumMessageSize = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_MESSAGE_RETENTION_PERIOD: reader.Read(); attributes.MessageRetentionPeriod = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_MESSAGE_COUNT: reader.Read(); attributes.MessageCount = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_LOGGING_ENABLED: reader.Read(); attributes.LoggingEnabled = bool.Parse(reader.Value); break; } break; } } reader.Close(); return(new GetTopicAttributesResponse() { Attributes = attributes }); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { XmlTextReader reader = new XmlTextReader(context.ResponseStream); Message message = new Message(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ELEMENT_MESSAGE_ID: reader.Read(); message.Id = reader.Value; break; case MNSConstants.XML_ELEMENT_MESSAGE_BODY_MD5: reader.Read(); message.BodyMD5 = reader.Value; break; case MNSConstants.XML_ELEMENT_MESSAGE_BODY: reader.Read(); message.Body = reader.Value; break; case MNSConstants.XML_ELEMENT_ENQUEUE_TIME: reader.Read(); message.EnqueueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value)); break; case MNSConstants.XML_ELEMENT_FIRST_DEQUEUE_TIME: reader.Read(); message.FirstDequeueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value)); break; case MNSConstants.XML_ELEMENT_DEQUEUE_COUNT: reader.Read(); message.DequeueCount = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_PRIORITY: reader.Read(); message.Priority = uint.Parse(reader.Value); break; } break; } } reader.Close(); return(new PeekMessageResponse() { Message = message }); }
public MQConsumer(string instanceId, string topicName, string consumer, string messageTag, AliyunServiceClient serviceClient) { this._instanceId = instanceId; this._topicName = topicName; this._consumer = consumer; if (messageTag != null) { this._messageTag = AliyunSDKUtils.UrlEncode(messageTag, false); } this._serviceClient = serviceClient; }
/// <summary> /// Handles an exception for the given execution context. /// </summary> /// <param name="executionContext">The execution context, it contains the /// request and response context.</param> /// <param name="exception">The exception to handle.</param> /// <returns> /// Returns a boolean value which indicates if the original exception /// should be rethrown. /// This method can also throw a new exception to replace the original exception. /// </returns> public override bool HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) { var requestContext = executionContext.RequestContext; var httpErrorResponse = exception.Response; // If 404 was suppressed and successfully unmarshalled, // don't rethrow the original exception. if (HandleSuppressed404(executionContext, httpErrorResponse)) { return(false); } AliyunServiceException errorResponseException = null; // Unmarshall the service error response and throw the corresponding service exception string responseContent = null; try { using (httpErrorResponse.ResponseBody) { var unmarshaller = requestContext.Unmarshaller; var errorContext = unmarshaller.CreateContext(httpErrorResponse, httpErrorResponse.ResponseBody.OpenResponse()); using (MemoryStream stream = new MemoryStream()) { AliyunSDKUtils.CopyTo(errorContext.ResponseStream, stream); stream.Seek(0, SeekOrigin.Begin); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); responseContent = Encoding.UTF8.GetString(bytes); stream.Seek(0, SeekOrigin.Begin); errorContext.ResponseStream = stream; errorResponseException = unmarshaller.UnmarshallException(errorContext, exception, httpErrorResponse.StatusCode); Debug.Assert(errorResponseException != null); } } } catch (ResponseUnmarshallException unmarshallException) { if (responseContent != null) { throw new AliyunServiceException(responseContent, unmarshallException, ErrorCode.InternalError, null, null, httpErrorResponse.StatusCode); } throw; } throw errorResponseException; }
public override string ToString() { return(string.Format( "ID:{0}, PublishTime:{1}, NextConsumeTime:{2}, ConsumedTimes:{3}, " + "\nTag:{4}, BodyMD5:{5}, NextConsumeTime:{6}" + "\nBody:{7}" + "\nProperties:{8}" + "\nMessageKey:{9}", Id, PublishTime, NextConsumeTime, ConsumedTimes, MessageTag, BodyMD5, NextConsumeTime, Body, AliyunSDKUtils.DictToString(Properties), MessageKey )); }
internal static Uri ComposeUrl(IRequest iRequest) { Uri url = iRequest.Endpoint; var resourcePath = iRequest.ResourcePath; if (resourcePath == null) { resourcePath = string.Empty; } else { if (resourcePath.StartsWith("//", StringComparison.Ordinal)) { resourcePath = resourcePath.Substring(2); } else if (resourcePath.StartsWith("/", StringComparison.Ordinal)) { resourcePath = resourcePath.Substring(1); } } var delim = "?"; var sb = new StringBuilder(); if (iRequest.SubResources.Count > 0) { foreach (var subResource in iRequest.SubResources) { sb.AppendFormat("{0}{1}", delim, subResource.Key); if (subResource.Value != null) { sb.AppendFormat("={0}", subResource.Value); } delim = "&"; } } if (iRequest.Parameters.Count > 0) { var queryString = AliyunSDKUtils.GetParametersAsString(iRequest.Parameters); sb.AppendFormat("{0}{1}", delim, queryString); } var parameterizedPath = string.Concat(resourcePath, sb); var uri = new Uri(url.AbsoluteUri + parameterizedPath); return(uri); }
public void UnmarshallTest() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Message xmlns = \"http://mns.aliyuncs.com/doc/v1/\">\n<MessageId>5F290C926D472878-2-14D9529A8FA-200000001</MessageId><ReceiptHandle>1-ODU4OTkzNDU5My0xNDMyNzI3ODI3LTItOA==</ReceiptHandle><MessageBodyMD5>C5DD56A39F5F7BB8B3337C6D11B6D8C7</MessageBodyMD5><MessageBody>This is a test message</MessageBody><EnqueueTime>1250700979248</EnqueueTime><NextVisibleTime>1250700799348</NextVisibleTime><FirstDequeueTime>1250700779318</FirstDequeueTime><DequeueCount>1</DequeueCount><Priority>8</Priority></Message>"; MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)); XmlUnmarshallerContext context = new XmlUnmarshallerContext(stream, null); ReceiveMessageResponse response = (ReceiveMessageResponse)ReceiveMessageResponseUnmarshaller.Instance.Unmarshall(context); Message message = response.Message; Assert.IsTrue(message.Id == "5F290C926D472878-2-14D9529A8FA-200000001"); Assert.IsTrue(message.ReceiptHandle == "1-ODU4OTkzNDU5My0xNDMyNzI3ODI3LTItOA=="); Assert.IsTrue(message.BodyMD5 == "C5DD56A39F5F7BB8B3337C6D11B6D8C7"); Assert.IsTrue(message.Body == "This is a test message"); Assert.IsTrue(message.EnqueueTime == AliyunSDKUtils.ConvertFromUnixEpochSeconds(1250700979248)); Assert.IsTrue(message.NextVisibleTime == AliyunSDKUtils.ConvertFromUnixEpochSeconds(1250700799348)); Assert.IsTrue(message.FirstDequeueTime == AliyunSDKUtils.ConvertFromUnixEpochSeconds(1250700779318)); Assert.IsTrue(message.DequeueCount == 1); Assert.IsTrue(message.Priority == 8); }
public TopicMessage PublishMessage(TopicMessage topicMessage) { var request = new PublishMessageRequest(topicMessage.Body, topicMessage.MessageTag); request.TopicName = this._topicName; request.IntanceId = this._instanceId; request.Properties = AliyunSDKUtils.DictToString(topicMessage.Properties); var marshaller = PublishMessageRequestMarshaller.Instance; var unmarshaller = PublishMessageResponseUnmarshaller.Instance; PublishMessageResponse result = _serviceClient.Invoke <PublishMessageRequest, PublishMessageResponse>(request, marshaller, unmarshaller); TopicMessage retMsg = new TopicMessage(null); retMsg.Id = result.MessageId; retMsg.BodyMD5 = result.MessageBodyMD5; retMsg.ReceiptHandle = result.ReeceiptHandle; return(retMsg); }
/// <summary> /// Creates the HttpWebRequest and configures the end point, content, user agent and proxy settings. /// </summary> /// <param name="requestContext">The async request.</param> /// <returns>The web request that actually makes the call.</returns> protected virtual IHttpRequest <TRequestContent> CreateWebRequest(IRequestContext requestContext) { IRequest request = requestContext.Request; Uri url = AliyunServiceClient.ComposeUrl(request); var httpRequest = _requestFactory.CreateHttpRequest(url); httpRequest.ConfigureRequest(requestContext); httpRequest.Method = request.HttpMethod; if (request.MayContainRequestBody()) { if (request.Content == null && (request.ContentStream == null)) { string queryString = AliyunSDKUtils.GetParametersAsString(request.Parameters); request.Content = Encoding.UTF8.GetBytes(queryString); } if (request.Content != null) { request.Headers[HttpHeader.ContentLengthHeader] = request.Content.Length.ToString(CultureInfo.InvariantCulture); } else if (request.ContentStream != null && !request.Headers.ContainsKey(HttpHeader.ContentLengthHeader)) { request.Headers[HttpHeader.ContentLengthHeader] = request.ContentStream.Length.ToString(CultureInfo.InvariantCulture); } } else if (request.UseQueryString && (request.HttpMethod == "POST" || request.HttpMethod == "PUT" || request.HttpMethod == "DELETE")) { request.Content = new Byte[0]; } return(httpRequest); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { XmlTextReader reader = new XmlTextReader(context.ResponseStream); QueueAttributes attributes = new QueueAttributes(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ELEMENT_QUEUE_NAME: reader.Read(); attributes.QueueName = reader.Value; break; case MNSConstants.XML_ELEMENT_CREATE_TIME: reader.Read(); attributes.CreateTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value) * 1000); break; case MNSConstants.XML_ELEMENT_LAST_MODIFY_TIME: reader.Read(); attributes.LastModifyTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value) * 1000); break; case MNSConstants.XML_ELEMENT_VISIBILITY_TIMEOUT: reader.Read(); attributes.VisibilityTimeout = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_MAXIMUM_MESSAGE_SIZE: reader.Read(); attributes.MaximumMessageSize = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_MESSAGE_RETENTION_PERIOD: reader.Read(); attributes.MessageRetentionPeriod = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_DELAY_SECONDS: reader.Read(); attributes.DelaySeconds = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_POLLING_WAIT_SECONDS: reader.Read(); attributes.PollingWaitSeconds = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_INACTIVE_MESSAGES: reader.Read(); attributes.InactiveMessages = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_ACTIVE_MESSAGES: reader.Read(); attributes.ActiveMessages = uint.Parse(reader.Value); break; case MNSConstants.ATTRIBUTE_DELAY_MESSAGES: reader.Read(); attributes.DelayMessages = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_LOGGING_ENABLED: reader.Read(); attributes.LoggingEnabled = bool.Parse(reader.Value); break; } break; } } reader.Close(); return(new GetQueueAttributesResponse() { Attributes = attributes }); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(context.ResponseStream); ConsumeMessageResponse consumeMessageResponse = new ConsumeMessageResponse(); Message message = null; while (reader.Read()) { switch (reader.NodeType) { case System.Xml.XmlNodeType.Element: switch (reader.LocalName) { case Constants.XML_ROOT_MESSAGE: message = new Message(); break; case Constants.XML_ELEMENT_MESSAGE_ID: reader.Read(); message.Id = reader.Value; break; case Constants.XML_ELEMENT_RECEIPT_HANDLE: reader.Read(); message.ReceiptHandle = reader.Value; break; case Constants.XML_ELEMENT_MESSAGE_BODY_MD5: reader.Read(); message.BodyMD5 = reader.Value; break; case Constants.XML_ELEMENT_MESSAGE_BODY: reader.Read(); message.Body = reader.Value; break; case Constants.XML_ELEMENT_PUBLISH_TIME: reader.Read(); message.PublishTime = long.Parse(reader.Value); break; case Constants.XML_ELEMENT_NEXT_CONSUME_TIME: reader.Read(); message.NextConsumeTime = long.Parse(reader.Value); break; case Constants.XML_ELEMENT_FIRST_CONSUME_TIME: reader.Read(); message.FirstConsumeTime = long.Parse(reader.Value); break; case Constants.XML_ELEMENT_CONSUMED_TIMES: reader.Read(); message.ConsumedTimes = uint.Parse(reader.Value); break; case Constants.XML_ELEMENT_MESSAGE_TAG: reader.Read(); message.MessageTag = reader.Value; break; case Constants.XML_ELEMENT_MESSAGE_PROPERTIES: reader.Read(); AliyunSDKUtils.StringToDict(reader.Value, message.Properties); break; } break; case System.Xml.XmlNodeType.EndElement: if (reader.LocalName == Constants.XML_ROOT_MESSAGE) { consumeMessageResponse.Messages.Add(message); } break; } } reader.Close(); return(consumeMessageResponse); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(context.ResponseStream); BatchReceiveMessageResponse batchReceiveMessageResponse = new BatchReceiveMessageResponse(); Message message = null; while (reader.Read()) { switch (reader.NodeType) { case System.Xml.XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ROOT_MESSAGE: message = new Message(); break; case MNSConstants.XML_ELEMENT_MESSAGE_ID: reader.Read(); message.Id = reader.Value; break; case MNSConstants.XML_ELEMENT_RECEIPT_HANDLE: reader.Read(); message.ReceiptHandle = reader.Value; break; case MNSConstants.XML_ELEMENT_MESSAGE_BODY_MD5: reader.Read(); message.BodyMD5 = reader.Value; break; case MNSConstants.XML_ELEMENT_MESSAGE_BODY: reader.Read(); message.Body = reader.Value; break; case MNSConstants.XML_ELEMENT_ENQUEUE_TIME: reader.Read(); message.EnqueueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value)); break; case MNSConstants.XML_ELEMENT_NEXT_VISIBLE_TIME: reader.Read(); message.NextVisibleTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value)); break; case MNSConstants.XML_ELEMENT_FIRST_DEQUEUE_TIME: reader.Read(); message.FirstDequeueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value)); break; case MNSConstants.XML_ELEMENT_DEQUEUE_COUNT: reader.Read(); message.DequeueCount = uint.Parse(reader.Value); break; case MNSConstants.XML_ELEMENT_PRIORITY: reader.Read(); message.Priority = uint.Parse(reader.Value); break; } break; case System.Xml.XmlNodeType.EndElement: if (reader.LocalName == MNSConstants.XML_ROOT_MESSAGE) { batchReceiveMessageResponse.Messages.Add(message); } break; } } reader.Close(); return(batchReceiveMessageResponse); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { XmlTextReader reader = new XmlTextReader(context.ResponseStream); SubscriptionAttributes attributes = new SubscriptionAttributes(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ELEMENT_TOPIC_NAME: reader.Read(); attributes.TopicName = reader.Value; break; case MNSConstants.XML_ELEMENT_CREATE_TIME: reader.Read(); attributes.CreateTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value) * 1000); break; case MNSConstants.XML_ELEMENT_LAST_MODIFY_TIME: reader.Read(); attributes.LastModifyTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(long.Parse(reader.Value) * 1000); break; case MNSConstants.XML_ELEMENT_TOPIC_OWNER: reader.Read(); attributes.TopicOwner = reader.Value; break; case MNSConstants.XML_ELEMENT_SUBSCRIPTION_NAME: reader.Read(); attributes.SubscriptionName = reader.Value; break; case MNSConstants.XML_ELEMENT_ENDPOINT: reader.Read(); attributes.EndPoint = reader.Value; break; case MNSConstants.XML_ELEMENT_NOTIFY_STRATEGY: reader.Read(); string strategyStr = reader.Value; attributes.Strategy = (SubscriptionAttributes.NotifyStrategy) Enum.Parse(typeof(SubscriptionAttributes.NotifyStrategy), strategyStr.ToUpper()); break; case MNSConstants.XML_ELEMENT_NOTIFY_CONTENT_FORMAT: reader.Read(); string contentFormatStr = reader.Value; attributes.ContentFormat = (SubscriptionAttributes.NotifyContentFormat) Enum.Parse(typeof(SubscriptionAttributes.NotifyContentFormat), contentFormatStr.ToUpper()); break; } break; } } reader.Close(); return(new GetSubscriptionAttributeResponse() { Attributes = attributes }); }