Example #1
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);
            }
        }
        public IRequest Marshall(PublishMessageRequest publicRequest)
        {
            MemoryStream  stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.WriteStartDocument();
            writer.WriteStartElement(MNSConstants.XML_ROOT_MESSAGE, MNSConstants.MNS_XML_NAMESPACE);
            if (publicRequest.IsSetMessageBody())
            {
                writer.WriteElementString(MNSConstants.XML_ELEMENT_MESSAGE_BODY, publicRequest.MessageBody);
            }
            if (publicRequest.IsSetMessageTag())
            {
                writer.WriteElementString(MNSConstants.XML_ELEMENT_MESSAGE_TAG, publicRequest.MessageTag);
            }
            if (publicRequest.IsSetMessageAttributes())
            {
                MessageAttributes messageAttributes = publicRequest.MessageAttributes;
                writer.WriteStartElement(MNSConstants.XML_ELEMENT_MESSAGE_ATTRIBUTES);
                if (messageAttributes.IsSetMailAttributes())
                {
                    MailAttributes mailAttributes = messageAttributes.MailAttributes;
                    writer.WriteElementString(MNSConstants.XML_ELEMENT_DIRECT_MAIL, mailAttributes.ToJson());
                }
                if (messageAttributes.IsSetSmsAttributes())
                {
                    SmsAttributes smsAttributes = messageAttributes.SmsAttributes;
                    writer.WriteElementString(MNSConstants.XML_ELEMENT_DIRECT_SMS, smsAttributes.ToJson());
                }
                if (messageAttributes.IsSetBatchSmsAttributes())
                {
                    BatchSmsAttributes batchSmsAttributes = messageAttributes.BatchSmsAttributes;
                    writer.WriteElementString(MNSConstants.XML_ELEMENT_DIRECT_SMS, batchSmsAttributes.ToJson());
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();

            stream.Seek(0, SeekOrigin.Begin);

            IRequest request = new DefaultRequest(publicRequest, MNSConstants.MNS_SERVICE_NAME);

            request.HttpMethod    = HttpMethod.POST.ToString();
            request.ContentStream = stream;
            request.ResourcePath  = MNSConstants.MNS_TOPIC_PRE_RESOURCE + publicRequest.TopicName
                                    + MNSConstants.MNS_MESSAGE_SUB_RESOURCE;
            return(request);
        }
        public void ToJsonTest()
        {
            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;

            Assert.AreEqual("{\"FreeSignName\":\"陈舟锋\",\"Receiver\":\"13735576932\",\"SmsParams\":\"{\\\"name\\\": \\\"CSharpSingle\\\"}\",\"TemplateCode\":\"SMS_15535414\"}",
                            smsAttributes.ToJson());
        }
Example #4
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);
            }
        }