public async Task <IActionResult> Edit(int id, [Bind("ID,Subscription,Title,Content")] TopicMessage topicMessage) { if (id != topicMessage.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(topicMessage); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TopicMessageExists(topicMessage.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(topicMessage)); }
public TopicMessage RequestBase(byte type, TopicMessage msg) { lock (_locker) { return(WLPackage.Request(_NStream, type, msg)); } }
/// <summary> /// Create Message /// </summary> /// <param name="uofw">FlowTasksUnitOfWork</param> /// <param name="topic">Topic</param> /// <param name="isTopic">Is Topic</param> /// <param name="message">Message</param> /// <param name="from">From</param> /// <param name="to">To</param> /// <param name="attachments">Attachments</param> /// <param name="usersToCopy">Users To Copy</param> private static void CreateMessage(FlowTasksUnitOfWork uofw, Core.Topic topic, bool isTopic, string message, string from, string to, IEnumerable <TopicAttachmentInfo> attachments, IEnumerable <string> usersToCopy) { var newMessage = new TopicMessage { Message = message, IsTopic = isTopic, From = from, To = to, When = DateTime.Now, Topic = topic }; uofw.TopicMessages.Insert(newMessage); var statusNewStr = TopicStatusType.New.ToString(); var statusReadStr = TopicStatusType.Read.ToString(); var statusNew = uofw.TopicStatuses.First(s => s.Status == statusNewStr); var statusRead = uofw.TopicStatuses.First(s => s.Status == statusReadStr); foreach (var u in usersToCopy) { var status = string.Equals(u, from, StringComparison.OrdinalIgnoreCase) ? statusRead : statusNew; uofw.TopicUsers.Insert(new TopicUser { TopicMessage = newMessage, User = u, TopicStatus = status }); } if (attachments != null) { foreach (var a in attachments) { uofw.TopicAttachments.Insert(new TopicAttachment { FileName = a.FileName, OidDocument = a.DocumentOid, TopicMessage = newMessage }); } } }
/// <summary> /// This method is used by <see cref="IReceiveDataProcessor" /> to dispatch received messages /// </summary> /// <param name="topicMessage">Message received from server</param> public void OnMessageReceived(TopicMessage topicMessage) { try { ThrowIfDisposed(); var subscriptionMessage = new SubscriptionMessage { MessageId = topicMessage.Id, Data = topicMessage.Data, TopicRoute = topicMessage.Route, TopicName = topicMessage.TopicName }; subscriptionMessage.OnMessageProcessedByClient += OnMessageProcessedByClient; MessageReceived?.Invoke(subscriptionMessage); } // if message process failed then mark it as nacked catch { var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)); OnMessageProcessedByClient(topicMessage.Id, false, cancellationTokenSource.Token); } }
public void SendBase(byte type, TopicMessage msg) { lock (_locker) { WLPackage.Send(_NStream, type, msg); } }
static void Main(string[] args) { try { // 循环发送4条消息 for (int i = 0; i < 4; i++) { TopicMessage sendMsg; if (i % 2 == 0) { sendMsg = new TopicMessage("dfadfadfadf"); // 设置属性 sendMsg.PutProperty("a", i.ToString()); // 设置KEY sendMsg.MessageKey = "MessageKey"; } else { sendMsg = new TopicMessage("dfadfadfadf", "tag"); // 设置属性 sendMsg.PutProperty("a", i.ToString()); // 定时消息, 定时时间为10s后 sendMsg.StartDeliverTime = AliyunSDKUtils.GetNowTimeStamp() + 10 * 1000; } TopicMessage result = producer.PublishMessage(sendMsg); Console.WriteLine("publis message success:" + result); } } catch (Exception ex) { Console.Write(ex); } }
/// <summary> /// Adds a new topic message for everyone with a specific topic and type /// </summary> /// <param name="senderId">The Id of the client that sent the message</param> /// <param name="type">The topic type of the message</param> /// <param name="content">The content of the message</param> /// <param name="expirationDate">The date at which the message should expire</param> /// <exception cref="ArgumentNullException">Thrown when the content of the message is null or empty</exception> /// <exception cref="ArgumentException">Thrown when the Id of the sender is invalid or not registered into the server</exception> public async Task AddTopicMessageAsync(Guid senderId, TopicMessageType type, string content, DateTime expirationDate) { if (string.IsNullOrEmpty(content)) { throw new ArgumentNullException(nameof(content), "Cannot add a message with null content to the queue"); } lock (mClients) { if (mClients.All(client => client.Id != senderId)) { throw new ArgumentException($"Cannot send message from an inexistent client. There is no registered client with id: {senderId}", nameof(senderId)); } } try { await Task.Run(() => { var message = new TopicMessage(senderId, type, content, expirationDate); lock (mTopicMessages) { mTopicMessages.Add(message); } }, mCancellationTokenSource.Token).ConfigureAwait(false); } catch (TaskCanceledException) { Debug.WriteLine($"Task {nameof(AddTopicMessageAsync)} cancelled"); } }
public async Task SendMessage(string user, string message, string topicId) { int id = Convert.ToInt16(topicId); var topic = _context.TopicModels.Include(x => x.Messages).Where(a => a.Id == id).First(); if (topic.Messages == null) { topic.Messages = new List <TopicMessage>(); } User AspNetUser = await _userManager.FindByNameAsync(user); DateTime creationTime = DateTime.Now; var commentary = new TopicMessage { CreationTime = creationTime, User = AspNetUser, UserId = AspNetUser.Id, UserName = AspNetUser.UserName, Text = message, Topic = topic, TopicId = topic.Id, }; topic.Messages.Add(commentary); _context.TopicModels.Update(topic); _context.SaveChanges(); var comment = _context.TopicMessages.Where(x => x.CreationTime == creationTime && x.Text == message).First(); await Clients.All.SendAsync("ReceiveMessage", comment.Id.ToString(), user, Markdown.ToHtml(message), creationTime.ToString()); }
public void DataReceived_DataIsMessage_DispatchToSubscription() { var deserializer = new Deserializer(); var subscriptionStore = new Mock <ISubscriptionStore>(); var taskManager = new Mock <ITaskManager>(); var connectionManager = new Mock <IConnectionManager>(); var sendDataProcessor = new Mock <ISendDataProcessor>(); var payloadFactory = new Mock <IPayloadFactory>(); var subscription = new Mock <Subscription>(payloadFactory.Object, connectionManager.Object, sendDataProcessor.Object); var subscriptionObject = subscription.Object as ISubscription; subscriptionStore.Setup(s => s.TryGet(It.IsAny <string>(), out subscriptionObject)).Returns(true); var receiveDataProcessor = new ReceiveDataProcessor(deserializer, subscriptionStore.Object, taskManager.Object); var message = new TopicMessage() { Id = Guid.NewGuid(), Route = RandomGenerator.GenerateString(10), TopicName = RandomGenerator.GenerateString(10), Data = RandomGenerator.GenerateBytes(10) }; var realSerializer = new Serializer(); var serializedPayload = realSerializer.Serialize(message); var clientSessionDataReceivedEventArgs = new ClientSessionDataReceivedEventArgs { Data = serializedPayload.DataWithoutSize, Id = Guid.NewGuid() }; receiveDataProcessor.DataReceived(default, clientSessionDataReceivedEventArgs);
private void CreateTopicRequest(Profile tryProfile) { Message msg = new TopicMessage("Creation", tryProfile, Destination); Net.SendMsg(comm.GetStream(), msg); SendingMessageTopic(tryProfile); }
public void Add(TopicMessage message) { _inMemoryMessageStore.Add(message); var connection = _redisConnectionProvider.Get(); var serializedMessage = Serialize(message); connection.GetDatabase().SetAdd(MessageRedisKey, serializedMessage); }
public static void Enqueue(TopicMessage msg) { QueueBase queue = new QueueBase(); queue = _dic.GetOrAdd(msg.Topic, queue); queue.Enqueue(msg.Content); Interlocked.Increment(ref _in); }
public void CreateTopicMessage([FromBody] TopicMessage request) { request.Author = db.Users.FirstOrDefault(user => user.Username == User.Identity.Name); var NewTopicMessage = request; db.TopicMessages.Add(NewTopicMessage); db.SaveChanges(); Response.StatusCode = 200; }
public async Task SendMessageAsync(TopicMessage message) { try { await _topicClient.SendAsync(new Message(ObjectSerializer.Serialize(message))); } catch (Exception e) { throw new ExceptionWithFeedback("EWF", "Something went wrong while posting to the servicebus: " + e.Message); } }
/// <summary> /// Send a message to specified target topic. /// </summary> /// <param name="isTest">If true, won't send the message to target. It'll just validate it.</param> /// <param name="message"></param> /// <returns>If successful, the response body contains an instance of T(MassageBase).</returns> public async Task <TopicMessage> SendMessage(bool isTest, TopicMessage message) { var result = await _fcmApi.SendHttpRequestToTopicAsync(_projectId, new SendRequestBody <TopicMessage> { ValidateOnly = isTest, Message = message }); message.Name = result.Name; return(message); }
public void Enqueue(string queue, string value) { var msg = new TopicMessage() { Topic = queue, Content = value }; _client.SendBase((byte)Net.Model.MessageType.EnqueueRequest, msg); _actived = DateTimeHelper.Current; }
/// <summary> /// Create Documents /// </summary> /// <param name="m">TopicMessage</param> /// <param name="uofw">FlowTasksUnitOfWork</param> /// <returns>List of TopicAttachmentInfo</returns> private IEnumerable <TopicAttachmentInfo> CreateDocuments(TopicMessage m, FlowTasksUnitOfWork uofw) { var documents = new List <TopicAttachmentInfo>(); foreach (var d in uofw.TopicAttachments.Find(a => a.TopicMessageId == m.TopicMessageId)) { documents.Add(new TopicAttachmentInfo { FileName = d.FileName, DocumentOid = d.OidDocument }); } return(documents); }
public static void SendTopicMessage(TopicMessage topicMessage, WebSocket receiverWebsocket) { var message = new TopicMessageDto { TopicTitle = topicMessage.Topics.Title, Sender = topicMessage.User.Username, Text = topicMessage.Text, CreatedAt = topicMessage.CreatedAt.ToLocalTime().ToString() }; Communication.SendResponse(receiverWebsocket, message); }
public async Task EnqueueMessageAsync(TopicMessage topicMessage) { var reliableQueue = await _stateManager.GetOrAddAsync <IReliableConcurrentQueue <TopicMessage> >(_queueName); using (var tx = _stateManager.CreateTransaction()) { await reliableQueue.EnqueueAsync(tx, topicMessage); await tx.CommitAsync(); } StartProcessingQueue(); }
public async Task SendMessage(TopicMessage topicMessage) { var objToSend = JsonConvert.SerializeObject(topicMessage); var message = new Message(Encoding.UTF8.GetBytes(objToSend)) { Label = topicMessage.Label }; // Send the message to the queue. await _topicClient.SendAsync(message); }
public bool TryGetValue(Guid id, out TopicMessage message) { if (_store.TryGetValue(id, out var topicMessage)) { message = topicMessage; return(true); } message = default; return(false); }
public virtual void TestTopicMessageImplNoReplicatedInfo() { var topicName = "myTopic"; var builder = new MessageMetadata(); var payload = ReadOnlySequence <byte> .Empty; var msg = Message <byte[]> .Create(builder, payload, ISchema <int> .Bytes); msg.SetMessageId(new MessageId(-1, -1, -1)); var topicMessage = new TopicMessage <byte[]>(topicName, topicName, msg); Assert.False(topicMessage.Replicated); Assert.Null(topicMessage.ReplicatedFrom); }
public async Task CanSubscribeToATestTopic() { await using var fx = await TestTopicMessage.CreateAsync(_network); Assert.Equal(ResponseCode.Success, fx.Record.Status); Assert.Equal(1ul, fx.Record.SequenceNumber); Assert.False(fx.Record.RunningHash.IsEmpty); await Task.Delay(7000); // give the beta net time to sync TopicMessage topicMessage = null; using var ctx = new CancellationTokenSource(); await using var mirror = _network.NewMirror(); try { var subscribeTask = mirror.SubscribeTopicAsync(new SubscribeTopicParams { Topic = fx.TestTopic.Record.Topic, Starting = DateTime.UtcNow.AddHours(-1), MessageWriter = new TopicMessageWriterAdapter(m => { topicMessage = m; ctx.Cancel(); }), CancellationToken = ctx.Token }); ctx.CancelAfter(5000); await subscribeTask; if (topicMessage == null) { _network.Output?.WriteLine("INDETERMINATE TEST - MIRROR NODE DID NOT RETURN TOPIC IN ALLOWED TIME"); } else { Assert.Equal(fx.TestTopic.Record.Topic, topicMessage.Topic); Assert.Equal(1ul, topicMessage.SequenceNumber); Assert.Equal(fx.Record.RunningHash.ToArray(), topicMessage.RunningHash.ToArray()); Assert.Equal(fx.Message.ToArray(), topicMessage.Messsage.ToArray()); Assert.Null(topicMessage.SegmentInfo); } } catch (MirrorException mex) when(mex.Code == MirrorExceptionCode.TopicNotFound) { _network.Output?.WriteLine("INDETERMINATE TEST - MIRROR NODE DID NOT RECEIVE TOPIC CREATE IN ALLOWED TIME"); return; } }
private SocketMessage Process(string id, SocketMessage msg) { try { TopicMessage b_msg; switch (msg.Type) { case (byte)Net.Model.MessageType.Leave: UserListHelper.Remove(id); break; case (byte)Net.Model.MessageType.EnqueueRequest: b_msg = SerializeHelper.ProtolBufDeserialize <TopicMessage>(msg.Content); UserListHelper.GetOrAdd(id, b_msg.Topic); TopicQueueHelper.Enqueue(b_msg); return(new SocketMessage((byte)Net.Model.MessageType.EnqueueResponse, null)); case (byte)Net.Model.MessageType.DequeueRequest: b_msg = SerializeHelper.ProtolBufDeserialize <TopicMessage>(msg.Content); UserListHelper.GetOrAdd(id, b_msg.Topic); var data = TopicQueueHelper.Dequque(b_msg.Topic); if (data != null) { return(new SocketMessage((byte)Net.Model.MessageType.DequeueResponse, SerializeHelper.ProtolBufSerialize(data))); } else { var rmsg = new TopicMessage(b_msg.Topic, null); return(new SocketMessage((byte)Net.Model.MessageType.DequeueResponse, SerializeHelper.ProtolBufSerialize(rmsg))); } case (byte)Net.Model.MessageType.Ping: return(new SocketMessage((byte)Net.Model.MessageType.Pong, null)); default: _server.CloseClientSocket(id); break; } } catch (Exception ex) { OnError?.BeginInvoke(id, ex, null, null); } return(null); }
async internal void Unadvertise(string topic, bool remove = true) { await connectionTask; var unadvertiseMessage = new TopicMessage { op = "unadvertise", topic = topic }; Send(JsonUtility.ToJson(unadvertiseMessage)); if (remove) { advertisedTopics.Remove(topic); } }
private static void Write(Stream stream, byte type, TopicMessage msg) { var content = SerializeHelper.ProtolBufSerialize(msg); var len = BitConverter.GetBytes(content.Length + 1); List <byte> dataList = new List <byte>(); dataList.AddRange(len); dataList.Add(type); dataList.AddRange(content); var data = dataList.ToArray(); stream.Write(data, 0, data.Length); }
async internal void Unsubscribe(string topic, bool remove = true) { await connectionTask; var unsubscribeMessage = new TopicMessage { op = "unsubscribe", topic = topic }; Send(JsonUtility.ToJson(unsubscribeMessage)); if (remove) { subscribedTypes.Remove(topic); subscribers.Remove(topic); } }
public virtual void TestTopicMessageImplReplicatedInfo() { var from = "ClusterNameOfReplicatedFromForTopicMessage"; var topicName = "myTopic"; var builder = new MessageMetadata(); builder.ReplicatedFrom = from; var payload = ReadOnlySequence <byte> .Empty; var msg = Message <byte[]> .Create(builder, payload, ISchema <int> .Bytes); msg.SetMessageId(new MessageId(-1, -1, -1)); var topicMessage = new TopicMessage <byte[]>(topicName, topicName, msg); Assert.True(topicMessage.Replicated); Assert.Equal(msg.ReplicatedFrom, from); }
private void HandleTopicMessage(TopicMessageDto topicMessageDto) { if (!AuthService.IsLoggedIn(_user)) { Communication.SendError(_webSocket, "You must be logged in to send direct message"); Log.Warning("Not logged in user tried to send topic message"); return; } var topic = TopicService.GetTopics(topicMessageDto.TopicTitle); if (topic != null) { var newTopicMessage = new TopicMessage { CreatedAt = DateTimeOffset.Now, Text = topicMessageDto.Text, UserId = _user.UserId, TopicsId = topic.TopicsId }; var topicMessage = MessageService.SaveTopicMessage(newTopicMessage); if (topicMessage != null) { var userList = TopicService.GetUserForTopic(topic); foreach (var user in userList.Where(user => _connectedClient.ContainsKey(user))) { MessageService.SendTopicMessage( topicMessage, _connectedClient[user] ); } } else { Communication.SendError(_webSocket, $"Could not save message to topic {topicMessageDto.TopicTitle}"); Log.Error("Error while saving topic message"); } } else { Communication.SendError(_webSocket, $"Could not send message to topic {topicMessageDto.TopicTitle}"); Log.Warning($"Topic {topicMessageDto.TopicTitle} do not exist"); } }
public string CreateTopicJson(int forumId, string author, string email, string title, DateTime? date, string html, string[] tags) { TopicMessage topicMessage = new TopicMessage(new Topic() { forum_id = forumId, title = title, body = html, tags = tags, }); using (StringWriter json = new StringWriter()) using (JsonWriter writer = new JsonTextWriter(json)) { JsonSerializer.Create(new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }).Serialize(writer, topicMessage); return json.ToString(); } }
public string Dequeue(string queue) { var msg = new TopicMessage() { Topic = queue }; var rmsg = _client.RequestBase((byte)Net.Model.MessageType.DequeueRequest, msg); _actived = DateTimeHelper.Current; if (rmsg == null) { return(string.Empty); } return(rmsg.Content); }