예제 #1
0
        /// <summary>
        /// Publishes a message to the specified topic.
        /// &lt;br/&gt;
        /// The topic endpoint is required for this operation.
        /// To get the topic endpoint, use {@link #getTopic(GetTopicRequest) getTopic}
        /// and review the &#x60;apiEndpoint&#x60; value in the response ({@link NotificationTopic}).
        /// &lt;br/&gt;
        /// Limits information follows.
        /// &lt;br/&gt;
        /// Message size limit per request: 64KB.
        /// &lt;br/&gt;
        /// Message delivery rate limit per endpoint: 60 messages per minute for HTTP-based protocols, 10 messages per minute for the &#x60;EMAIL&#x60; protocol.
        /// HTTP-based protocols use URL endpoints that begin with \&quot;http:\&quot; or \&quot;https:\&quot;.
        /// &lt;br/&gt;
        /// Transactions Per Minute (TPM) per-tenancy limit for this operation: 60 per topic.
        /// &lt;br/&gt;
        /// For more information about publishing messages, see [Publishing Messages](https://docs.cloud.oracle.com/iaas/Content/Notification/Tasks/publishingmessages.htm).
        /// For steps to request a limit increase, see [Requesting a Service Limit Increase](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/servicelimits.htm#three).
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/ons/PublishMessage.cs.html">here</a> to see an example of how to use PublishMessage API.</example>
        public async Task <PublishMessageResponse> PublishMessage(PublishMessageRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called publishMessage");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/topics/{topicId}/messages".Trim('/')));
            HttpMethod         method         = new HttpMethod("POST");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false);
                }
                this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage);

                return(Converter.FromHttpResponseMessage <PublishMessageResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"PublishMessage failed with error: {e.Message}");
                throw;
            }
        }
예제 #2
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="message">消息体</param>
        /// <param name="publisher">主题</param>
        private void SendMail(IEventMessage message, Topic publisher)
        {
            try
            {
                var request   = new PublishMessageRequest();
                var mailAttrs = new MailAttributes
                {
                    AccountName    = message.Data["AccountName"], // 接件邮箱
                    Subject        = message.Data["Subject"],     // 邮件主题
                    IsHtml         = false,
                    ReplyToAddress = false,
                    AddressType    = 0
                };
                var messageAttrs = new MessageAttributes();
                messageAttrs.MailAttributes = mailAttrs;
                request.MessageAttributes   = messageAttrs;
                request.MessageTag          = message.Tag;
                request.MessageBody         = message.Body;
                publisher.PublishMessage(request);

                // 检查发送结果
                var queue    = _client.CreateQueue(QueueName);
                var response = queue.ReceiveMessage(30);
                XTrace.WriteLine($"发送邮件:{response.Message.Body} ");
            }
            catch (Exception ex)
            {
                XTrace.WriteLine("发送邮件失败。");
                XTrace.WriteException(ex);
            }
        }
예제 #3
0
        } //通用MD5加密

        public void SendSMS(string telenum)
        {
            string _endpoint        = "https://1076168149508929.mns.cn-shenzhen.aliyuncs.com/"; // eg. http://1234567890123456.mns.cn-shenzhen.aliyuncs.com
            string _accessKeyId     = "LTAI9KVo5A2RNmaQ";
            string _secretAccessKey = "Ok64W1hAs6tPs3FUC6pOWjnqApvPhW";
            string _topicName       = "printer";
            string _freesignname    = "410打印店";
            string _templatecode    = "SMS_67201137";

            Aliyun.MNS.IMNS    client             = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint);
            Aliyun.MNS.Topic   topic              = client.GetNativeTopic(_topicName);
            BatchSmsAttributes batchsmsattributes = new BatchSmsAttributes();
            MessageAttributes  messageattributes  = new MessageAttributes();

            batchsmsattributes.FreeSignName = _freesignname;
            batchsmsattributes.TemplateCode = _templatecode;
            Dictionary <string, string> param = new Dictionary <string, string>();

            batchsmsattributes.AddReceiver(telenum, param);
            messageattributes.BatchSmsAttributes = batchsmsattributes;

            PublishMessageRequest request = new PublishMessageRequest();

            request.MessageAttributes = messageattributes;

            request.MessageBody = "not null";

            try
            {
                PublishMessageResponse resp = topic.PublishMessage(request);
            }
            catch
            {
            }
        }//发送短信通知
예제 #4
0
 /// <inheritdoc/>
 public PublishMessageResponse PublishMessage(PublishMessageRequest request)
 {
     return(AggregateExceptionExtract.Extract(() =>
     {
         return PublishMessageAsync(request).Result;
     }));
 }
예제 #5
0
        /// <inheritdoc/>
        public PublishMessageResponse PublishMessage(string messageBody)
        {
            var request = new PublishMessageRequest {
                MessageBody = messageBody
            };

            return(PublishMessage(request));
        }
예제 #6
0
        public async Task <PublishMessageResponse> PublishMessageAsync(string messageBody)
        {
            var request = new PublishMessageRequest {
                MessageBody = messageBody
            };

            return(await PublishMessageAsync(request).ConfigureAwait(false));
        }
예제 #7
0
        public async Task SendVerificationCode(string phoneNumber, string code)
        {
            await Task.FromResult(0);

            /**
             * Step 1. 初始化Client
             */
            IMNS client = new Aliyun.MNS.MNSClient(
                SettingManager.GetSettingValue(AppSettingNames.SMS.Ali.AccessKeyId),
                SettingManager.GetSettingValue(AppSettingNames.SMS.Ali.SecretAccessKey),
                SettingManager.GetSettingValue(AppSettingNames.SMS.Ali.RegionEndpoint)
                );

            /**
             * Step 2. 获取主题引用
             */
            Topic topic = client.GetNativeTopic(SettingManager.GetSettingValue(AppSettingNames.SMS.Ali.TopicName));

            /**
             * Step 3. 生成SMS消息属性
             */
            MessageAttributes messageAttributes = new MessageAttributes();
            SmsAttributes     smsAttributes     = new SmsAttributes();

            // 3.1 设置发送短信的签名:SMSSignName
            smsAttributes.FreeSignName = SettingManager.GetSettingValue(AppSettingNames.SMS.FreeSignName);
            // 3.2 设置发送短信的模板SMSTemplateCode
            smsAttributes.TemplateCode = SettingManager.GetSettingValue(AppSettingNames.SMS.Ali.TemplateCode);
            Dictionary <string, string> param = new Dictionary <string, string>();

            // 3.3 (如果短信模板中定义了参数)设置短信模板中的参数,发送短信时,会进行替换
            param.Add("name", code);
            // 3.4 设置短信接收者手机号码
            smsAttributes.Receiver          = phoneNumber;
            smsAttributes.SmsParams         = param;
            messageAttributes.SmsAttributes = smsAttributes;
            PublishMessageRequest request = new PublishMessageRequest();

            request.MessageAttributes = messageAttributes;

            /**
             * Step 4. 设置SMS消息体(必须)
             *
             * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
             */
            request.MessageBody = "smsmessage";
            try
            {
                /**
                 * Step 5. 发布SMS消息
                 */
                PublishMessageResponse resp = topic.PublishMessage(request);
            }
            catch (Exception e)
            {
                Logger.Debug("发送短信失败", e);
            }
        }
예제 #8
0
        public async Task <PublishMessageResponse> PublishMessageAsync(PublishMessageRequest request)
        {
            request.TopicName = this.TopicName;

            var marshaller   = new PublishMessageRequestMarshaller();
            var unmarshaller = PublishMessageResponseUnmarshaller.Instance;

            return(await _serviceClient.InvokeAsync <PublishMessageRequest, PublishMessageResponse>(request, marshaller, unmarshaller).ConfigureAwait(false));
        }
예제 #9
0
        /// <inheritdoc/>
        public PublishMessageResponse PublishMessage(PublishMessageRequest request)
        {
            request.TopicName = this.TopicName;

            var marshaller   = new PublishMessageRequestMarshaller();
            var unmarshaller = PublishMessageResponseUnmarshaller.Instance;

            return(_serviceClient.Invoke <PublishMessageRequest, PublishMessageResponse>(request, marshaller, unmarshaller));
        }
예제 #10
0
        /// <inheritdoc/>
        public IAsyncResult BeginPublishMessage(PublishMessageRequest request, AsyncCallback callback, object state)
        {
            request.TopicName = this.TopicName;

            var marshaller   = new PublishMessageRequestMarshaller();
            var unmarshaller = PublishMessageResponseUnmarshaller.Instance;

            return(_serviceClient.BeginInvoke <PublishMessageRequest>(request, marshaller, unmarshaller,
                                                                      callback, state));
        }
예제 #11
0
        /// <summary>
        /// 身份验证验证码
        /// </summary>
        /// <param name="recNum">接收号码</param>
        /// <returns>6位验证码</returns>
        public static string AuthenticationVerifyCode(string recNum)
        {
            Random ran  = new Random();
            string code = ran.RandomNumber(6, true);

            /**
             * Step 1. 初始化Client
             */
            IMNS client = new Aliyun.MNS.MNSClient(Permanent.ACCESS_KEY_ID, Permanent.ACCESS_KEY_SECRET, Permanent.ENDPOINT);

            /**
             * Step 2. 获取主题引用
             */
            Topic topic = client.GetNativeTopic(Permanent.TOPIC_NAME);

            /**
             * Step 3. 生成SMS消息属性
             */
            MessageAttributes  messageAttributes  = new MessageAttributes();
            BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();

            // 3.1 设置发送短信的签名:SMSSignName
            batchSmsAttributes.FreeSignName = "幻幻平台";
            // 3.2 设置发送短信的模板SMSTemplateCode
            batchSmsAttributes.TemplateCode = "SMS_25255320";
            Dictionary <string, string> param = new Dictionary <string, string>();

            // 3.3 (如果短信模板中定义了参数)设置短信模板中的参数,发送短信时,会进行替换
            param.Add("code", code);
            param.Add("product", "幻幻社区");
            // 3.4 设置短信接收者手机号码
            batchSmsAttributes.AddReceiver(recNum, param);

            messageAttributes.BatchSmsAttributes = batchSmsAttributes;
            PublishMessageRequest request = new PublishMessageRequest();

            request.MessageAttributes = messageAttributes;

            /**
             * Step 4. 设置SMS消息体(必须)
             *
             * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
             */
            request.MessageBody = "smsmessage";

            /**
             * Step 5. 发布SMS消息
             */
            PublishMessageResponse resp = topic.PublishMessage(request);

            //return resp.MessageId;
            return(code);
        }
예제 #12
0
        /// <summary>
        /// 本接口(PublishMessage)用于向某个主题发消息。
        /// </summary>
        /// <param name="req">参考<see cref="PublishMessageRequest"/></param>
        /// <returns>参考<see cref="PublishMessageResponse"/>实例</returns>
        public async Task <PublishMessageResponse> PublishMessage(PublishMessageRequest req)
        {
            JsonResponseModel <PublishMessageResponse> rsp = null;

            try
            {
                var strResp = await this.InternalRequest(req, "PublishMessage");

                rsp = JsonConvert.DeserializeObject <JsonResponseModel <PublishMessageResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
예제 #13
0
파일: AliyunSms.cs 프로젝트: orapow/x.yc
        public static bool SendCode(string to, string code, string sign)
        {
            var client = new MNSClient(_accessKeyId, _secretAccessKey, _endpoint);
            var topic  = client.GetNativeTopic("sms.topic-cn-hangzhou");

            /**
             * Step 3. 生成SMS消息属性
             */
            var messageAttributes  = new MessageAttributes();
            var batchSmsAttributes = new BatchSmsAttributes();

            // 3.1 设置发送短信的签名:SMSSignName
            batchSmsAttributes.FreeSignName = sign;
            // 3.2 设置发送短信的模板SMSTemplateCode
            batchSmsAttributes.TemplateCode = "SMS_63315079";
            Dictionary <string, string> param = new Dictionary <string, string>();

            // 3.3 (如果短信模板中定义了参数)设置短信模板中的参数,发送短信时,会进行替换
            param.Add("code", code);
            // 3.4 设置短信接收者手机号码
            batchSmsAttributes.AddReceiver(to, param);
            messageAttributes.BatchSmsAttributes = batchSmsAttributes;
            var req = new PublishMessageRequest();

            req.MessageAttributes = messageAttributes;

            /**
             * Step 4. 设置SMS消息体(必须)
             * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
             */
            req.MessageBody = "smsmessage";
            try
            {
                /**
                 * Step 5. 发布SMS消息
                 */
                PublishMessageResponse resp = topic.PublishMessage(req);
                Console.WriteLine(resp.MessageId);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #14
0
        /// <summary>
        /// 发送短消息
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="publisher">The publisher.</param>
        private static void SendSms(IEventMessage message, Topic publisher)
        {
            try
            {
                var response   = publisher.Subscribe(SubscriptionName + "batchsms", publisher.GenerateBatchSmsEndpoint());
                var request    = new PublishMessageRequest();
                var batchAttrs = new BatchSmsAttributes
                {
                    FreeSignName = message.Data["FreeSignName"], // 短信签名
                    TemplateCode = message.Data["TemplateCode"]  // 短信模板
                };

                // 分解短信发送参数
                Dictionary <String, String> param = new Dictionary <String, String>();
                foreach (var kv in message.Data)
                {
                    if (!kv.Key.EqualIgnoreCase("FreeSignName", "TemplateCode", "PhoneNumbers"))
                    {
                        param.Add(kv.Key, kv.Value);
                    }
                }

                // 添加接收短信的号码
                var phoneNumbers = message.Data["PhoneNumbers"].Split(",", ";", "|");
                foreach (var phone in phoneNumbers)
                {
                    batchAttrs.AddReceiver(phone, param);
                }

                var messageAttrs = new MessageAttributes {
                    BatchSmsAttributes = batchAttrs
                };
                request.MessageAttributes = messageAttrs;
                request.MessageBody       = message.Body;
                request.MessageTag        = message.Tag;
                publisher.PublishMessage(request); // 发送消息
            }
            catch (Exception ex)
            {
                XTrace.WriteLine($"发送短信失败:{message.ToJson()}");
                XTrace.WriteException(ex);
            }
        }
예제 #15
0
        public static Boolean sendSmsViaMnsSDK(String signName, String accessKey, String accessSecret, String smsTemplate, String recNum, String code, String endpoint, String topicName)
        {
            try {
                IMNS client = new Aliyun.MNS.MNSClient(accessKey, accessSecret, endpoint);

                /**
                 * Step 2. 获取主题引用
                 */
                Topic topic = client.GetNativeTopic(topicName);

                /**
                 * Step 3. 生成SMS消息属性
                 */
                MessageAttributes  messageAttributes  = new MessageAttributes();
                BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
                // 3.1 设置发送短信的签名:SMSSignName
                batchSmsAttributes.FreeSignName = signName;
                // 3.2 设置发送短信的模板SMSTemplateCode
                batchSmsAttributes.TemplateCode = smsTemplate;
                Dictionary <string, string> param = new Dictionary <string, string>();
                // 3.3 (如果短信模板中定义了参数)设置短信模板中的参数,发送短信时,会进行替换
                param.Add("code", code);
                // 3.4 设置短信接收者手机号码
                batchSmsAttributes.AddReceiver(recNum, param);
                //batchSmsAttributes.AddReceiver("$YourReceiverPhoneNumber2", param);
                messageAttributes.BatchSmsAttributes = batchSmsAttributes;
                PublishMessageRequest request = new PublishMessageRequest();
                request.MessageAttributes = messageAttributes;

                /**
                 * Step 4. 设置SMS消息体(必须)
                 *
                 * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
                 */
                request.MessageBody = "smsmessage";
                PublishMessageResponse resp = topic.PublishMessage(request);
                return(true);
            }
            catch (Exception e) {
                return(false);
            }
        }
        public async Task ShouldSendRequestAsExpected()
        {
            // given
            var expectedRequest = new PublishMessageRequest
            {
                CorrelationKey = "p-1",
                Name           = "messageName"
            };

            // when
            await ZeebeClient
            .NewPublishMessageCommand()
            .MessageName("messageName")
            .CorrelationKey("p-1")
            .Send();

            // then
            var request = TestService.Requests[typeof(PublishMessageRequest)][0];

            Assert.AreEqual(expectedRequest, request);
        }
예제 #17
0
        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);
        }
예제 #18
0
        public void Register(string code, string telephone)
        {
            IMNS               client             = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _reginEndPoint);
            Topic              topic              = client.GetNativeTopic(_topicName);
            MessageAttributes  messageAttributes  = new MessageAttributes();
            BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();

            // 3.1 设置发送短信的签名:SMSSignName
            batchSmsAttributes.FreeSignName = _freeSignName;
            // 3.2 设置发送短信的模板SMSTemplateCode
            batchSmsAttributes.TemplateCode = "SMS_62610202";
            Dictionary <string, string> param = new Dictionary <string, string>();

            // 3.3 (如果短信模板中定义了参数)设置短信模板中的参数,发送短信时,会进行替换
            param.Add("code", code);
            param.Add("product", _freeSignName);

            // 3.4 设置短信接收者手机号码
            batchSmsAttributes.AddReceiver(telephone, param);

            messageAttributes.BatchSmsAttributes = batchSmsAttributes;
            PublishMessageRequest request = new PublishMessageRequest();

            request.MessageAttributes = messageAttributes;

            /**
             * Step 4. 设置SMS消息体(必须)
             *
             * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
             */
            request.MessageBody = "smsmessage";
            try
            {
                PublishMessageResponse resp = topic.PublishMessage(request);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Publish SMS message failed, exception info: " + ex.Message);
            }
        }
예제 #19
0
        /// <summary>
        /// Publish a message to a given exchange.
        /// </summary>
        /// <param name="virtualHost"></param>
        /// <param name="exchangeName"></param>
        /// <param name="routingKey">binding key</param>
        /// <param name="payload">message data</param>
        /// <param name="payloadEncoding">The payload_encoding key should be either "string" (in which case the payload will be taken to be the UTF-8 encoding of the payload field) or "base64" (in which case the payload field is taken to be base64 encoded).</param>
        /// <param name="properties"></param>
        /// <returns>true if the message was sent to at least one queue.</returns>
        public async Task <bool> PublishMessage(
            string virtualHost, string exchangeName, string routingKey, dynamic payload,
            PayloadEncoding payloadEncoding = PayloadEncoding.String, Properties properties = null)
        {
            if (exchangeName == String.Empty)
            {
                throw new ArgumentException("Cannot send message using default exchange in HTTP API");
            }

            var request = new PublishMessageRequest
            {
                payload          = JsonConvert.SerializeObject(payload),
                routing_key      = routingKey,
                properties       = new Properties(),
                payload_encoding = payloadEncoding.ToString("G").ToLower()
            };

            string path     = $"/api/exchanges/{virtualHost.Encode()}/{exchangeName.Encode()}/publish";
            var    response = await DoCall <PublishMessageResponse>(path, HttpMethod.Post, request);

            return(response.Routed);
        }
        /// <summary>
        /// Publishes a message to the specified topic.
        /// The topic endpoint is required for this operation. To get the topic endpoint, use GetTopic and review the
        /// apiEndpoint value in the response (NotificationTopic).
        /// Limits information follows.
        /// Message size limit per request: 64KB.
        /// Message delivery rate limit per endpoint: 60 messages per minute for HTTP-based protocols, 10 messages per
        /// minute for the EMAIL protocol. HTTP-based protocols use URL endpoints that begin with "http:" or "https:".
        ///
        /// Transactions Per Minute (TPM) per-tenancy limit for this operation: 60 per topic.
        ///
        /// For more information about publishing messages, see Publishing Messages. For steps to request a limit increase,
        /// see Requesting a Service Limit Increase.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <PublishMessageResponse> PublishMessage(PublishMessageRequest request)
        {
            var uri = new Uri($"{GetEndPoint(NotificationServices.Topics, this.Region)}/{request.TopicId}/messages");

            var httpRequestHeaderParam = new HttpRequestHeaderParam()
            {
                MessageType  = request.MessageType.Value,
                OpcRequestId = request.OpcRequestId
            };
            var webResponse = await this.RestClientAsync.Post(uri, request.MessageDetails, httpRequestHeaderParam);

            using (var stream = webResponse.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    var response = reader.ReadToEnd();

                    return(new PublishMessageResponse()
                    {
                        OpcRequestId = webResponse.Headers.Get("opc-request-id"),
                        PublishResult = this.JsonSerializer.Deserialize <PublishResult>(response)
                    });
                }
        }
예제 #21
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            PublishMessageRequest request;

            try
            {
                request = new PublishMessageRequest
                {
                    TopicId        = TopicId,
                    MessageDetails = MessageDetails,
                    OpcRequestId   = OpcRequestId,
                    MessageType    = MessageType
                };

                response = client.PublishMessage(request).GetAwaiter().GetResult();
                WriteOutput(response, response.PublishResult);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
예제 #22
0
 public override Task <PublishMessageResponse> PublishMessage(PublishMessageRequest request, ServerCallContext context)
 {
     return(Task.FromResult((PublishMessageResponse)HandleRequest(request, context)));
 }
예제 #23
0
 public PublishMessageCommand(GatewayClient client, IAsyncRetryStrategy asyncRetryStrategy)
 {
     gatewayClient           = client;
     request                 = new PublishMessageRequest();
     this.asyncRetryStrategy = asyncRetryStrategy;
 }
예제 #24
0
        public async Task PublishMessage(PublishMessageRequest request)
        {
            await _fonotecaService.CheckNotificationsAccess(request.User, request.Password);

            await _fonotecaService.SendMessage(request.Notification, request.Title, request.Message, request.SubscriptionId, request.MaterialId);
        }
예제 #25
0
        /// 管理控制台中配置的短信签名(状态必须是验证通过)
        //private const string SignName = "深圳市利德行";
        //private const string SignName = "一生时光";

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public static bool SendSMS(SendSmsRequest req)
        {
            var flag = true;

            /**
             * Step 1. 初始化Client
             */
            IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint);

            /**
             * Step 2. 获取主题引用
             */
            Topic topic = client.GetNativeTopic(_topicName);

            /**
             * Step 3. 生成SMS消息属性
             */
            MessageAttributes  messageAttributes  = new MessageAttributes();
            BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();

            // 3.1 设置发送短信的签名:SMSSignName
            batchSmsAttributes.FreeSignName = req.SignName;
            // 3.2 设置发送短信的模板SMSTemplateCode
            //batchSmsAttributes.TemplateCode = "SMS_61750032";
            batchSmsAttributes.TemplateCode = req.TemplateCode;
            //Dictionary<string, string> param = new Dictionary<string, string>();
            // 3.3 (如果短信模板中定义了参数)设置短信模板中的参数,发送短信时,会进行替换

            //param.Add("code", "4567");
            // 3.4 设置短信接收者手机号码


            if (!string.IsNullOrWhiteSpace(req.RecNum))
            {
                batchSmsAttributes.AddReceiver(req.RecNum, req.ParamString);
            }
            else
            {
                ///循环电话号码
                foreach (var item in req.LiRecNum)
                {
                    batchSmsAttributes.AddReceiver(item, req.ParamString);
                }
            }



            messageAttributes.BatchSmsAttributes = batchSmsAttributes;
            PublishMessageRequest request = new PublishMessageRequest();

            request.MessageAttributes = messageAttributes;

            /**
             * Step 4. 设置SMS消息体(必须)
             *
             * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
             */
            request.MessageBody = "smsmessage";
            try
            {
                /**
                 * Step 5. 发布SMS消息
                 */
                PublishMessageResponse resp = topic.PublishMessage(request);
                //Console.WriteLine(resp.MessageId);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Publish SMS message failed, exception info: " + ex.Message);
                //Logger.Debug("错误信息:"+ex.Message + "!接收号码:" + req.RecNum + "!短信码:" + req.ParamString["code"] + "!签名:" + req.SignName + "!模板" + req.TemplateCode);
                flag = false;
            }

            return(flag);
        }
예제 #26
0
 public override AsyncUnaryCall <PublishMessageResponse> PublishMessageAsync(PublishMessageRequest request, CallOptions options)
 {
     throw new ObjectDisposedException(ZeebeClientWasAlreadyDisposed);
 }
예제 #27
0
 public override AsyncUnaryCall <PublishMessageResponse> PublishMessageAsync(PublishMessageRequest request, Metadata headers = null, DateTime?deadline = null,
                                                                             CancellationToken cancellationToken             = default(CancellationToken))
 {
     throw new ObjectDisposedException(ZeebeClientWasAlreadyDisposed);
 }
 public async Task <PublishMessageResponse> PublishMessage([FromBody] PublishMessageRequest request)
 {
     return(await _daprClient.InvokeBindingAsync <PublishMessageRequest, PublishMessageResponse>(
                "command", Commands.PublishMessage, request));
 }
 public PublishMessageCommand(GatewayClient client)
 {
     gatewayClient = client;
     request       = new PublishMessageRequest();
 }
예제 #30
0
        static void Main(string[] args)
        {
            #region Topic Releated Test Cases

            IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint);

            /* 1.1. Create queue */
            var createTopicRequest = new CreateTopicRequest
            {
                TopicName = _topicName
            };

            Topic topic = null;
            try
            {
                client.DeleteTopic(_topicName);
                topic = client.CreateTopic(createTopicRequest);
                Console.WriteLine("Create topic successfully, topic name: {0}", topic.TopicName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create topic failed, exception info: " + ex.Message);
                return;
            }

            topic = client.GetNativeTopic(_topicName);
            try
            {
                ListTopicResponse res = client.ListTopic(null, null, 10);
                Console.WriteLine("List topic successfully, topic name: {0}", _topicName);
                foreach (String topicUrl in res.TopicUrls)
                {
                    Console.WriteLine(topicUrl);
                }
                if (res.NextMarker != null)
                {
                    Console.WriteLine("NextMarker: " + res.NextMarker);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete topic failed, exception info: " + ex.Message);
            }

            try
            {
                GetTopicAttributesResponse res = topic.GetAttributes();
                Console.WriteLine("GetTopicAttributes, topic name: {0}", _topicName);
                Console.WriteLine(res.Attributes.CreateTime);
                Console.WriteLine(res.Attributes.LastModifyTime);
                Console.WriteLine(res.Attributes.MaximumMessageSize);
                Console.WriteLine(res.Attributes.MessageRetentionPeriod);
                Console.WriteLine(res.Attributes.LoggingEnabled);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetTopicAttributes failed, exception info: " + ex.Message);
            }

            try
            {
                TopicAttributes attributes = new TopicAttributes()
                {
                    MaximumMessageSize = 2048
                };
                topic.SetAttributes(attributes);
                Console.WriteLine("SetTopicAttributes succeed, topic name: {0}", _topicName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("SetTopicAttributes failed, exception info: " + ex.Message + ex.GetType().Name);
            }

            try
            {
                SubscribeResponse res = topic.Subscribe(_subscriptionName, "http://XXXX");
                Console.WriteLine("Subscribe, subscriptionUrl: {0}", res.SubscriptionUrl);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
            }

            try
            {
                GetSubscriptionAttributeResponse res = topic.GetSubscriptionAttribute(_subscriptionName);
                Console.WriteLine("GetSubscriptionAttributeResponse, subs name: {0}", _subscriptionName);
                Console.WriteLine(res.Attributes.CreateTime);
                Console.WriteLine(res.Attributes.LastModifyTime);
                Console.WriteLine(res.Attributes.TopicName);
                Console.WriteLine(res.Attributes.TopicOwner);
                Console.WriteLine(res.Attributes.EndPoint);
                Console.WriteLine(res.Attributes.Strategy);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetSubscriptionAttribute failed, exception info: " + ex.Message);
            }

            try
            {
                SubscriptionAttributes attributes = new SubscriptionAttributes()
                {
                    Strategy = SubscriptionAttributes.NotifyStrategy.EXPONENTIAL_DECAY_RETRY
                };
                topic.SetSubscriptionAttribute(_subscriptionName, attributes);
                Console.WriteLine("SetSubscriptionAttribute succeed, topic name: {0}", _topicName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("SetSubscriptionAttribute failed, exception info: " + ex.Message + ex.GetType().Name);
            }

            try
            {
                GetSubscriptionAttributeResponse res = topic.GetSubscriptionAttribute(_subscriptionName);
                Console.WriteLine("GetSubscriptionAttributeResponse, subs name: {0}", _subscriptionName);
                Console.WriteLine(res.Attributes.CreateTime);
                Console.WriteLine(res.Attributes.LastModifyTime);
                Console.WriteLine(res.Attributes.TopicName);
                Console.WriteLine(res.Attributes.TopicOwner);
                Console.WriteLine(res.Attributes.EndPoint);
                Console.WriteLine(res.Attributes.Strategy);
                Console.WriteLine(res.Attributes.ContentFormat);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetSubscriptionAttribute failed, exception info: " + ex.Message);
            }

            try
            {
                ListSubscriptionResponse res = topic.ListSubscription("");
                Console.WriteLine("ListSubscription successfully, topic name: {0}", _topicName);
                foreach (String subscriptionUrl in res.SubscriptionUrls)
                {
                    Console.WriteLine(subscriptionUrl);
                }
                if (res.NextMarker != null)
                {
                    Console.WriteLine("NextMarker: " + res.NextMarker);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ListSubscription failed, exception info: " + ex.Message);
            }

            try
            {
                var response = topic.PublishMessage("message here </asdas\">");
                Console.WriteLine("PublishMessage succeed! " + response.MessageId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("PublishMessage failed, exception info: " + ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            try
            {
                topic.Unsubscribe(_subscriptionName);
                Console.WriteLine("Unsubscribe succeed!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            // PUBLISH MESSAGE for SMS
            try
            {
                var res = topic.Subscribe(_subscriptionName + "batchsms", topic.GenerateBatchSmsEndpoint());
                Console.WriteLine(res.SubscriptionUrl);

                PublishMessageRequest request            = new PublishMessageRequest();
                MessageAttributes     messageAttributes  = new MessageAttributes();
                BatchSmsAttributes    batchSmsAttributes = new BatchSmsAttributes();
                batchSmsAttributes.FreeSignName = "陈舟锋";
                batchSmsAttributes.TemplateCode = "SMS_15535414";
                Dictionary <string, string> param = new Dictionary <string, string>();
                param.Add("name", "CSharpBatch");
                batchSmsAttributes.AddReceiver("13735576932", param);

                messageAttributes.BatchSmsAttributes = batchSmsAttributes;
                request.MessageAttributes            = messageAttributes;
                request.MessageBody = "</asdas\">";
                PublishMessageResponse resp = topic.PublishMessage(request);

                Console.WriteLine(resp.MessageId);

                // check sms
                System.Threading.Thread.Sleep(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
            }

            // PUBLISH MESSAGE for SMS
            try
            {
                var res = topic.Subscribe(_subscriptionName + "singlesms", topic.GenerateSmsEndpoint());
                Console.WriteLine(res.SubscriptionUrl);

                PublishMessageRequest request           = new PublishMessageRequest();
                MessageAttributes     messageAttributes = new MessageAttributes();
                SmsAttributes         smsAttributes     = new SmsAttributes();
                smsAttributes.FreeSignName = "陈舟锋";
                smsAttributes.TemplateCode = "SMS_15535414";
                Dictionary <string, string> param = new Dictionary <string, string>();
                param.Add("name", "CSharpSingle");
                smsAttributes.Receiver  = "13735576932";
                smsAttributes.SmsParams = param;

                messageAttributes.SmsAttributes = smsAttributes;
                request.MessageAttributes       = messageAttributes;
                request.MessageBody             = "</asdas\">";
                PublishMessageResponse resp = topic.PublishMessage(request);

                Console.WriteLine(resp.MessageId);

                // check sms
                System.Threading.Thread.Sleep(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
            }

            // PUBLISH MESSAGE TO QUEUE AND MAIL
            string queueName = "TestQueueNameHere";
            try
            {
                var queue = client.CreateQueue(queueName);

                var res = topic.Subscribe(_subscriptionName, topic.GenerateMailEndpoint("*****@*****.**"));
                // res = topic.Subscribe(_subscriptionName + "2", topic.GenerateQueueEndpoint(queueName));
                res = topic.Subscribe(new SubscribeRequest(_subscriptionName + "2", topic.GenerateQueueEndpoint(queueName), "TAG", SubscriptionAttributes.NotifyStrategy.BACKOFF_RETRY, SubscriptionAttributes.NotifyContentFormat.JSON));

                PublishMessageRequest request           = new PublishMessageRequest();
                MessageAttributes     messageAttributes = new MessageAttributes();
                MailAttributes        mailAttributes    = new MailAttributes();
                mailAttributes.AccountName       = "*****@*****.**";
                mailAttributes.Subject           = "TestMail C#";
                mailAttributes.IsHtml            = false;
                mailAttributes.ReplyToAddress    = false;
                mailAttributes.AddressType       = 0;
                messageAttributes.MailAttributes = mailAttributes;
                request.MessageAttributes        = messageAttributes;
                request.MessageTag  = "TAG";
                request.MessageBody = "message here2222 </asdas\">";
                topic.PublishMessage(request);

                var resp = queue.ReceiveMessage(30);
                Console.WriteLine(resp.Message.Body);

                // check mailbox
                System.Threading.Thread.Sleep(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
            }

            try
            {
                client.DeleteQueue(queueName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete queue failed, exception info: " + ex.Message);
            }

            try
            {
                client.DeleteTopic(_topicName);
                Console.WriteLine("Delete topic successfully, topic name: {0}", _topicName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete topic failed, exception info: " + ex.Message);
            }
        }