internal JsonApiMessage(Message message, string requestUri) { id = SessionController.Context.Messages.IndexOf(message); attributes = new MessageAttributes(message); relationships = new JsonApiRelationship(message.Creator, requestUri); links = new SelfLink(requestUri, id); }
/// <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); } }
public void Listening(TimeSpan timeout, CancellationToken cancellationToken) { Connect(); var request = new ReceiveMessageRequest(_queueUrl) { WaitTimeSeconds = 5, MaxNumberOfMessages = 1 }; while (true) { var response = _sqsClient !.ReceiveMessageAsync(request, cancellationToken).GetAwaiter().GetResult(); if (response.Messages.Count == 1) { var messageObj = JsonSerializer.Deserialize <SQSReceivedMessage>(response.Messages[0].Body); var header = messageObj !.MessageAttributes.ToDictionary(x => x.Key, x => x.Value.Value); var body = messageObj.Message; var message = new TransportMessage(header, body != null ? Encoding.UTF8.GetBytes(body) : null); message.Headers.Add(Headers.Group, _groupId); OnMessageReceived?.Invoke(response.Messages[0].ReceiptHandle, message); } else { cancellationToken.ThrowIfCancellationRequested(); cancellationToken.WaitHandle.WaitOne(timeout); } } }
} //通用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 { } }//发送短信通知
internal MessageArgument(string name, object value, bool readOnly) { this.name = name; this.value = value; this.readOnly = readOnly; children = new MessageArguments(readOnly); attributes = new MessageAttributes(this); }
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); } }
private void ProcessNotificaionFeed(NotificationMessage notificationMsg) { try { FeedMessage feedMsg = new FeedMessage(); feedMsg.SubscriptionCode = notificationMsg.NotificationKey; string messageType = GetMessageType(feedMsg.SubscriptionCode); feedMsg.MessageAction = notificationMsg.MessageAction.ToString(); feedMsg.MessageFields = new Dictionary <string, string>(); SequenceNumber = SequenceNumber + 1; feedMsg.SequenceNumber = SequenceNumber; // string notificaionType = notificationMsg.NotificationKey;// will be replaced with Notificaion type. MessageAttributes msgAttributes = m_FeedProcessorConfigStorage.MessagesAttributesInfo[messageType]; foreach (MessageTag tag in msgAttributes.MessageTagsList) { if (notificationMsg.BodyDictionary.ContainsKey(tag.SourceFeild)) { string fieldName = tag.ColumnName; string value = notificationMsg.BodyDictionary[tag.SourceFeild]; feedMsg.MessageFields.Add(fieldName, value); } } switch (notificationMsg.MessageAction) { case EFG.OPS.NotificationEngineService.Contracts.Enums.MessageAction.Insert: feedMsg.MessageFields.Add("command", "ADD"); feedMsg.MessageFields.Add("key", feedMsg.MessageFields[m_NotificaionKeyField]); break; case EFG.OPS.NotificationEngineService.Contracts.Enums.MessageAction.Update: feedMsg.MessageFields.Add("command", "UPDATE"); feedMsg.MessageFields.Add("key", feedMsg.MessageFields[m_NotificaionKeyField]); break; case EFG.OPS.NotificationEngineService.Contracts.Enums.MessageAction.Delete: feedMsg.MessageFields.Add("command", "DELETE"); feedMsg.MessageFields.Add("key", feedMsg.MessageFields[m_NotificaionKeyField]); break; } m_msgRouter.Route(feedMsg); } catch (Exception ex) { m_NLog.Error("Error in ProcessNotificaionFeed() .Error Details : {0}", ex.ToString()); } }
/// <summary> /// Creates a message converting raw csound message attributes into various /// property enums conveying equivalent information. /// </summary> /// <param name="attrs"></param> /// <param name="msg"></param> public Csound6MessageEventArgs(MessageAttributes attrs, string msg) { Message = msg; uint attr = (uint)attrs; Type = (MessageType)((attr & 0x7000) >> 12); Bold = (attrs & MessageAttributes.Bold) != 0; Foreground = ((attr & 0x0100) != 0) ? (MessageColor)(attr & 0x0007) : MessageColor.Default; Background = ((attr & 0x0200) != 0) ? (MessageColor)((attr >> 4) & 0x0007) : MessageColor.Default; Underline = (attrs.HasFlag(MessageAttributes.Underline)); }
/// <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); }
/// <summary> /// This class encapsulates a messages context as it passes through a middleware pipeline. /// </summary> /// <param name="message">The JustSaying message that was deserialized from SQS.</param> /// <param name="messageType">The type of the JustSaying message contained in <see cref="Message"/>.</param> /// <param name="queueName">The queue from which this message was received.</param> /// <param name="visibilityUpdater">The <see cref="IMessageVisibilityUpdater"/> to use to update message visibilities on failure.</param> /// <param name="messageDeleter">The <see cref="IMessageDeleter"/> to use to remove a message from the queue on success.</param> public HandleMessageContext(string queueName, Amazon.SQS.Model.Message rawMessage, Message message, Type messageType, IMessageVisibilityUpdater visibilityUpdater, IMessageDeleter messageDeleter, Uri queueUri, MessageAttributes messageAttributes) { Message = message; MessageType = messageType; QueueName = queueName; VisibilityUpdater = visibilityUpdater; MessageDeleter = messageDeleter; QueueUri = queueUri; MessageAttributes = messageAttributes; RawMessage = rawMessage; }
public async Task <CompletionResult> HandleMessageAsync(MyMessage message, MessageAttributes attributes, object?userData, CancellationToken cancellationToken) { if (message is null || attributes is null) { return(CompletionResult.Abandon); } Console.WriteLine($"reader {userData}: {JsonConvert.SerializeObject(message)}"); await Task.CompletedTask; return(CompletionResult.Complete); }
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 async Task <CompletionResult> HandleMessageAsync(TMessage message, MessageAttributes attributes, object?userData, CancellationToken cancellationToken) { try { await _destinationQueue.PostMessageAsync(message, attributes, cancellationToken).ConfigureAwait(false); return(CompletionResult.Complete); } catch (Exception ex) { _logger.LogError(ex, $"Failure posting to {nameof(Handler<TMessage>)} destination queue"); return(await _forwarderErrorHandler(ex).ConfigureAwait(false)); } }
public DiskMessage(Guid id, long sequenceNumber, MessageAttributes attributes, JObject body) { if (id == Guid.Empty) { throw new ArgumentException($"Argument may not be empty", nameof(id)); } if (sequenceNumber <= 0L) { throw new ArgumentOutOfRangeException(nameof(sequenceNumber)); } Id = id; SequenceNumber = sequenceNumber; Attributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); Body = body ?? throw new ArgumentNullException(nameof(body)); }
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); } }
/// <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); } }
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 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); } }
static async Task SNSAsync() { var topicArn = ConfigurationManager.AppSettings["DemoTopicArn"]; var snsClient = new AmazonSimpleNotificationServiceClient(ConfigurationManager.AppSettings["AccessId"], ConfigurationManager.AppSettings["SecretKey"], RegionEndpoint.USEast1); var publisher = new SNSPublisher(); PublishResponse response = await publisher.SendMessage(snsClient, topicArn, "MESSAGE"); Console.WriteLine(response.MessageId); MessageAttributes messageAttributes = new MessageAttributes(); messageAttributes.Add("provider_type", "LOA"); response = await publisher.SendMessage(snsClient, topicArn, "MESSAGE WITH MATCHING ATTRIBUTES", messageAttributes); Console.WriteLine(response.MessageId); messageAttributes.Add("provider_type", "MR"); response = await publisher.SendMessage(snsClient, topicArn, "MESSAGE WITH NON-MATCHING ATTRIBUTES", messageAttributes); Console.WriteLine(response.MessageId); }
private static async Task WriteMessages(IMessageQueue <MyMessage> queue, CancellationToken token) { for (var i = 0; i < 10; i++) { Console.WriteLine($"writing message {i}"); var msg = new MyMessage() { Id = Guid.NewGuid(), Test = "TEST" }; var attributes = new MessageAttributes() { Label = "" }; await queue.PostMessageAsync(msg, attributes, token); await Task.Delay(500); } }
public ButtplugMessage[] Deserialize(string aJsonMsg) { _bpLogger?.Trace($"Got JSON Message: {aJsonMsg}"); var res = new List <ButtplugMessage>(); JsonData json = JsonMapper.ToObject(aJsonMsg); for (var i = 0; i < json.Count; ++i) { foreach (var key in json[i].Keys) { if (json[i][key].Keys.Contains("Id")) { _bpLogger?.Trace($"Got BP {key} Message: {json[i][key].ToJson()}"); switch (key) { case "Ok": res.Add(JsonUtility.FromJson <Ok>(json[i][key].ToJson())); break; case "Test": res.Add(JsonUtility.FromJson <Test>(json[i][key].ToJson())); break; case "Error": res.Add(JsonUtility.FromJson <Error>(json[i][key].ToJson())); break; case "DeviceList": var dList = JsonUtility.FromJson <DeviceList>(json[i][key].ToJson()); List <DeviceMessageInfo> devs = new List <DeviceMessageInfo>(); if (json[i][key].ContainsKey("Devices") && json[i][key]["Devices"].IsArray) { foreach (JsonData dev in json[i][key]["Devices"]) { var dInfo = JsonUtility.FromJson <DeviceMessageInfo>(dev.ToJson()); dInfo.DeviceMessages = new Dictionary <string, MessageAttributes>(); if (dev.ContainsKey("DeviceMessages")) { foreach (var key2 in dev["DeviceMessages"].Keys) { var attr = new MessageAttributes(); if (dev["DeviceMessages"][key2].ContainsKey("FeatureCount")) { attr.FeatureCount = Convert.ToUInt32(dev["DeviceMessages"][key2]["FeatureCount"].IsInt); } dInfo.DeviceMessages.Add(key2, attr); } } devs.Add(dInfo); } dList.Devices = devs.ToArray(); } res.Add(dList); _bpLogger.Trace("Converted back: " + JsonMapper.ToJson(res.Last())); break; case "DeviceAdded": var dAdded = JsonUtility.FromJson <DeviceAdded>(json[i][key].ToJson()); dAdded.DeviceMessages = new Dictionary <string, MessageAttributes>(); if (json[i][key].ContainsKey("DeviceMessages")) { foreach (var key2 in json[i][key]["DeviceMessages"].Keys) { var attr = new MessageAttributes(); if (json[i][key]["DeviceMessages"][key2].ContainsKey("FeatureCount")) { attr.FeatureCount = (uint)json[i][key]["DeviceMessages"][key2]["FeatureCount"]; } dAdded.DeviceMessages.Add(key2, attr); } } res.Add(dAdded); _bpLogger.Trace("Converted back: " + JsonMapper.ToJson(res.Last())); break; case "DeviceRemoved": res.Add(JsonUtility.FromJson <DeviceRemoved>(json[i][key].ToJson())); break; case "ScanningFinished": res.Add(JsonUtility.FromJson <ScanningFinished>(json[i][key].ToJson())); break; case "Log": res.Add(JsonUtility.FromJson <Log>(json[i][key].ToJson())); break; case "ServerInfo": res.Add(JsonUtility.FromJson <ServerInfo>(json[i][key].ToJson())); break; default: _bpLogger?.Trace($"Don't know how to handle: {key}"); break; } } } } return(res.ToArray()); }
public MessageWithAttributes(Message message, MessageAttributes messageAttributes) { Message = message; MessageAttributes = messageAttributes; }
internal Message(string name) { this.name = name; arguments = new MessageArguments(false); attributes = new MessageAttributes(this); }
public static async Task Main(string[] _) { //elasticsearch setup example var elasticSearchOptions = new ElasticSearchMessageQueueOptions <MyMessage>() .UseConnectionUri(new Uri("YOUR URI HERE"), (options) => { options.ThrowExceptions(); } ); var elasticSearchQueue = new ElasticSearchMessageQueue <MyMessage>(new Logger <ElasticSearchMessageQueue <MyMessage> >(), Options.Create(elasticSearchOptions)); //sqlite setup example var sqliteOptions = new SqliteMessageQueueOptions <MyMessage>() { ConnectionString = $"Data Source = {Path.Combine(AppContext.BaseDirectory, "Queue.db")}" }; var sqliteQueue = new SqliteMessageQueue <MyMessage>(new Logger <SqliteMessageQueue <MyMessage> >(), Options.Create(sqliteOptions)); //mqtt setup example var mqttOptions = new MqttMessageQueueOptions <MyMessage>() .UseManagedMqttClientOptionsBuilder(builder => { builder.WithClientOptions(options => options .WithTcpServer("HOST HERE") .WithCredentials("USERNAME", "PASSWORD") .Build() ); }); //setup for disk queue forwarding to azure queue var diskOptions = new DiskMessageQueueOptions <MyMessage>() { MessageStore = new DirectoryInfo("/my-messages") }; var diskQueue = new DiskMessageQueue <MyMessage>(new Logger <DiskMessageQueue <MyMessage> >(), Options.Create(diskOptions)); var azureTopicOptions = new AzureTopicMessageQueueOptions <MyMessage>() .UseConnectionStringBuilder( endpoint: "YOUR ENDPOINT HERE", entityPath: "YOUR ENTITYPATH HERE", sharedAccessKeyName: "YOUR SHARED ACCESS KEY NAME HERE", sharedAccessKey: "YOUR SHARED ACCESS KEY HERE" ); var azureTopic = new AzureTopicMessageQueue <MyMessage>(new Logger <AzureTopicMessageQueue <MyMessage> >(), Options.Create(azureTopicOptions)); var forwarderLogger = new Logger <ForwarderMessageQueue <MyMessage> >(); var forwarderOptions = new ForwarderMessageQueueOptions() { SourceSubscriptionName = "YOUR SUBSCRIPTION NAME HERE", ForwardingErrorHandler = (ex) => { forwarderLogger.LogError(ex, string.Empty); return(Task.FromResult(CompletionResult.Abandon)); } }; var forwarder = new ForwarderMessageQueue <MyMessage>(forwarderLogger, Options.Create(forwarderOptions), diskQueue, azureTopic); //create the message var msg = new MyMessage() { GUID = Guid.NewGuid(), TEST = "TEST" }; //with attributes var attributes = new MessageAttributes() { Label = "YOUR LABEL HERE", ContentType = "application/json" }; //and post to whichever queue you'd like. this one posts to the forwarder queue which posts to the disk and then forwards to azure await forwarder.PostMessageAsync(msg, attributes, CancellationToken.None); Console.Write("press any key to exit"); Console.ReadKey(); }
/// <summary> /// Use this method to poll SQS for incoming messages. /// </summary> /// <typeparam name="T">Type of business object.</typeparam> /// <param name="queueName">name of the queue to poll from</param> /// <param name="handler">a handler for business object. Should take a T generic business object as input and returns bool success as output</param> /// <param name="cancellationToken"></param> /// <param name="deleteMsgOnSuccess">SQS can store messages even after successful handling. Generally this should be true</param> /// <param name="maxMessagesAtaTime">Describes how many messages receiver can capture to local processing</param> /// <param name="waitTimeSeconds">Delay between sqs message pollings</param> public void ReceiveMessage <T>(string queueName, Func <T, string, CancellationToken, bool> handler, CancellationToken cancellationToken, bool deleteMsgOnSuccess = true, int maxMessagesAtaTime = 10, int waitTimeSeconds = 20) { _logger.Debug("ReceiveMessage called."); string queueUrl; try { queueUrl = GetQueueUrl <T>(queueName); } catch (Exception ex) { _logger.Error("GetQueueUrl Failed: {0}", ex.Message); throw new Exception($"Error subscribing to Queue [{queueName}]: {ex}", ex); } _logger.Debug("queueUrl: [{0}]", queueUrl); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl) { // Magic const VisibilityTimeout = VisibilityTimeout, //43200, //Max Value MaxNumberOfMessages = maxMessagesAtaTime, WaitTimeSeconds = waitTimeSeconds, }; // TODO: this can be redone to use attributes passed directly to this method. foreach (var key in MessageAttributes.Keys) { receiveMessageRequest.MessageAttributeNames.Add(key); } receiveMessageRequest.MessageAttributeNames.Add(SQSConstants.RESERVED_ATTRIBUTE_NAME); receiveMessageRequest.MessageAttributeNames.Add(SQSConstants.MESSAGE_TYPE_NAME); ReceiveMessageResponse receiveMessageResponse = _sqsClient.ReceiveMessageAsync(receiveMessageRequest, cancellationToken).Result; _logger.Debug("HttpStatusCode: [{0}]", receiveMessageResponse.HttpStatusCode); //check if we're good if (receiveMessageResponse.HttpStatusCode != HttpStatusCode.OK) { _logger.Error("Error Receiving from queue [{0}]: {1}; {2}", queueName, receiveMessageResponse.HttpStatusCode, receiveMessageResponse.ResponseMetadata); return; } //_logger.Debug("Messages.Count: [{0}]", receiveMessageResponse.Messages.Count); TimerCallback timerDelegate = TimerTask; //Parse each message from the queue response foreach (Message message in receiveMessageResponse.Messages) { if (cancellationToken != null && cancellationToken.IsCancellationRequested) { //Console.WriteLine("Message processing has been canceled."); //System.Diagnostics.Debug.WriteLine("Message processing has been canceled."); //cancellationToken.ThrowIfCancellationRequested(); _logger.Trace("Message processing has been canceled."); break; } // Compare Message Type MessageAttributeValue messageTypeAttributeValue; if (message.MessageAttributes.TryGetValue(SQSConstants.MESSAGE_TYPE_NAME, out messageTypeAttributeValue)) { if (messageTypeAttributeValue.StringValue != typeof(T).FullName) { _logger.Trace("Message Type '{0}' does not match to '{1}'", messageTypeAttributeValue.StringValue, typeof(T).FullName); continue; } } // Compare Custom attributes. // Search for at least one custom attribute (if indicated) in the message. if (MessageAttributes.Count > 0) { if (!MessageAttributes.Any(x => message.MessageAttributes.ContainsKey(x.Key))) { _logger.Trace("Message has no matched attribuets."); continue; } } StateObject stateObj = new StateObject { TimerCanceled = false, Attempts = 1, DueTime = Math.Max(0, receiveMessageRequest.VisibilityTimeout * 1000 - 2000), // in milliseconds Request = new ChangeMessageVisibilityRequest(queueUrl, message.ReceiptHandle, receiveMessageRequest.VisibilityTimeout), TokenSource = new CancellationTokenSource() }; try { bool success = false; try { _logger.Debug("Message Body: [{0}]", message.Body); MessageAttributeValue largePayloadAttributeValue; if (message.MessageAttributes.TryGetValue(SQSConstants.RESERVED_ATTRIBUTE_NAME, out largePayloadAttributeValue) && _storageClient != null) { var pointer = (IStorageReference)JsonConvert.DeserializeObject(message.Body, _storageClient.StorageReferenceType); message.Body = _storageClient.GetData(pointer); message.ReceiptHandle = EmbedS3PointerInReceiptHandle(message.ReceiptHandle, pointer.GetStorageKey()); message.MessageAttributes.Remove(SQSConstants.RESERVED_ATTRIBUTE_NAME); } if (message.Body.Length <= 256) { _logger.Debug("Parse serializedObject: [{0}]", message.Body); } // Getting object from body T dataObj; try { dataObj = JsonConvert.DeserializeObject <T>(message.Body); _logger.Debug("Object has been deserialized."); } catch (Exception) { _logger.Error("Could not deserialize message body. Skipping this message."); continue; } if (stateObj.DueTime > 0) { // Save a reference for Dispose. stateObj.TimerReference = new Timer(timerDelegate, stateObj, stateObj.DueTime, Timeout.Infinite); } CancellationToken ct = stateObj.TokenSource.Token; // Each message is being handled here. var task = Task <bool> .Factory.StartNew(() => handler(dataObj, stateObj.Request.ReceiptHandle, ct), ct); task.Wait(ct); stateObj.StopTimer(); success = task.Result; _logger.Info("handler -> success = {0}", success); } catch (OperationCanceledException oce) { success = false; _logger.Warn("SQS.ReceiveMessage <OperationCanceledException>: {0}", oce.Message); Console.WriteLine("Message processing has been canceled."); System.Diagnostics.Debug.WriteLine("Message processing has been canceled."); } catch (SQSManagerException sx) { _logger.Warn("SQS.ReceiveMessage <StoreManagerException>: {0} \nErrorCode: {1}. \nStatusCode: {2}.", sx.Message, sx.ErrorCode, sx.StatusCode); if (sx.StatusCode == HttpStatusCode.NotFound) { _logger.Info("DeleteMessage"); DeleteMessage <T>(queueName, message.ReceiptHandle); } else { throw; } } if (success && deleteMsgOnSuccess) { _logger.Info("Success: DeleteMessage."); DeleteMessage <T>(queueName, message.ReceiptHandle); } } finally { stateObj.StopTimer(); stateObj.TokenSource?.Dispose(); stateObj.TimerReference?.Dispose(); } } }
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); } }
/// <summary> /// Initializes a new instance of the <see cref="ButtplugDeviceWrapper"/> class. /// </summary> /// <param name="aFunction">The method to call for the message</param> /// <param name="aAttrs">The message attributes</param> public ButtplugDeviceWrapper(Func <ButtplugDeviceMessage, Task <ButtplugMessage> > aFunction, MessageAttributes aAttrs = null) { Function = aFunction; Attrs = aAttrs ?? new MessageAttributes(); }
public ElasticSearchMessage(MessageAttributes attributes) { MessageAttributes = attributes ?? throw new ArgumentNullException(nameof(attributes)); }
/// 管理控制台中配置的短信签名(状态必须是验证通过) //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); }
/// <summary> /// Creates an instance of <see cref="MessageContext"/>. /// </summary> /// <param name="message">The <see cref="Amazon.SQS.Model.Message"/> currently being processed.</param> /// <param name="queueUri">The URI of the SQS queue the message is from.</param> /// <param name="messageAttributes">The <see cref="MessageAttributes"/> from the message.</param> public MessageContext(SQSMessage message, Uri queueUri, MessageAttributes messageAttributes) { Message = message ?? throw new ArgumentNullException(nameof(message)); QueueUri = queueUri ?? throw new ArgumentNullException(nameof(queueUri)); MessageAttributes = messageAttributes ?? throw new ArgumentNullException(nameof(messageAttributes)); }