public void AttachmentsAddAlsoToCommunity( Domain.DTO.DTO_Ticket TkData, Domain.Enums.MailSettings ownerSettings, Domain.Enums.MailSettings creatorSettings, Boolean alwaysLastVersion) { if (!this.SaveTicket(TkData, ownerSettings, creatorSettings, true)) { return; } Domain.Message Msg = service.MessageGetFromTicketDraft(TkData.TicketId, TkData.CreatorId); if (Msg == null || View.DraftMsgId != Msg.Id) { return; } int UserID = (this.UserContext != null) ? UserContext.CurrentUserID : 0; lm.Comol.Core.FileRepository.Domain.ModuleRepository cRepository = service.GetRepositoryPermissions(CurrentCommunityId, UserID); List <lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions> actions = service.UploadAvailableActionsGet(MessageUserType.Partecipant, CurrentCommunityId, UserContext.CurrentUserID, cRepository); if (!actions.Contains(lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions.uploadtomoduleitemandcommunity)) { return; } //service.MessageDraftUpdate(HtmlText, PreviewText, View.CurrentTicketId, View.DraftMsgId); //------------------------------------------------------------------------------------- service.AttachmentsAddFiles(View.DraftMsgId, View.GetUploadedItems(Msg, RepositoryAttachmentUploadActions.uploadtomoduleitemandcommunity)); //------------------------------------------------------------------------------------- this.InitView(); }
// POST /api/messages public HttpResponseMessage Post(MessageModels.SubmitMessageRequest request) { _logger.Log(LogLevel.Info, String.Format("{0} - New Message Posted {1} {2} {3} {4}", request.apiKey, request.senderUri, request.recipientUri, request.recipientFirstName, request.recipientLastName)); Domain.Message message = null; HttpResponseMessage responseMessage; try { message = _messageServices.AddMessage(request.apiKey, request.senderUri, request.recipientUri, request.senderAccountId, request.amount, request.comments, request.messageType, request.securityPin, request.latitude, request.longitude, request.recipientFirstName, request.recipientLastName, request.recipientImageUri); } catch (Exception ex) { _logger.Log(LogLevel.Fatal, String.Format("Exception Adding Message {0} {1} {2}. {3}", request.apiKey, request.senderUri, request.recipientUri, ex.Message)); responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError); responseMessage.ReasonPhrase = ex.Message; return(responseMessage); } if (message != null) { _amazonNotificationService.PushSNSNotification(ConfigurationManager.AppSettings["MessagePostedTopicARN"], "New Message Received", message.Id.ToString()); } responseMessage = new HttpResponseMessage(HttpStatusCode.Created); //responseMessage.Headers.C return(responseMessage); }
public void AttachmentsAddInternal( Domain.DTO.DTO_Ticket TkData, Domain.Enums.MailSettings ownerSettings, Domain.Enums.MailSettings creatorSettings) { if (!this.SaveTicket(TkData, ownerSettings, creatorSettings, true)) { return; } Domain.Message message = service.MessageGetFromTicketDraft(TkData.TicketId, TkData.CreatorId); if (message == null || View.DraftMsgId != message.Id) { return; } List <lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions> FileActions = service.UploadAvailableActionsGet(Domain.Enums.MessageUserType.Partecipant, 0, 0, null); if (!FileActions.Contains(lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions.uploadtomoduleitem)) { return; } service.AttachmentsAddFiles(message.Id, View.GetUploadedItems(message, RepositoryAttachmentUploadActions.uploadtomoduleitem)); this.InitView(); }
public async Task <MessageDto> Handle(Command request, CancellationToken cancellationToken) { var room = await _context.Rooms.SingleOrDefaultAsync(x => x.Id == request.RoomId); if (room == null) { throw new Exception("Room not found"); } var newMessage = new Domain.Message { Room = room, Body = request.Body, CreatedAt = DateTime.Now, Username = request.Username }; room.Messages.Add(newMessage); var success = await _context.SaveChangesAsync() > 0; if (success) { return(_mapper.Map <MessageDto>(newMessage)); } throw new Exception("Problem saving changes"); }
public void AttachmentsAddInternal(Domain.DTO.DTO_Ticket TkData, Boolean alwaysLastVersion) { if (!SaveTicket(TkData, true) || View.CurrentUser.PersonId <= 0) { return; } Domain.Message Msg = service.MessageGetFromTicketDraft(TkData.TicketId, TkData.CreatorId); if (Msg == null) { return; } List <lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions> actions = service.UploadAvailableActionsGet(Domain.Enums.MessageUserType.Partecipant, 0, 0, null); if (!actions.Contains(lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions.uploadtomoduleitem)) { return; } service.AttachmentsAddFiles(View.DraftMsgId, View.CurrentUser.UserId, View.GetUploadedItems(Msg)); this.InitView(); }
public static DetailsModel CreateFromMessage(Domain.Message message) { return(new DetailsModel() { Id = message.MessageId, AuthorId = message.AuthorId, DateTimeCreated = message.CreatedAt, Text = message.Text, Sender = message.Author.Email, // TODO :: fix StartedDateTime = message.CreatedAt, }); }
/// <summary> /// Publishes the specified message. /// </summary> /// <param name="message">The message.</param> public void Publish(Domain.Message message) { EnsureArg.IsNotNull(message, nameof(message)); if (message.CorrelationId.IsNullOrEmpty()) { message.CorrelationId = IdGenerator.Instance.Next; } var loggerState = new Dictionary <string, object> { [LogEventPropertyKeys.CorrelationId] = message.CorrelationId, }; using (this.logger.BeginScope(loggerState)) { if (message.Id.IsNullOrEmpty()) { message.Id = IdGenerator.Instance.Next; this.logger.LogDebug($"{{LogKey:l}} set message (id={message.Id})", LogKeys.Messaging); } if (message.Origin.IsNullOrEmpty()) { message.Origin = this.options.MessageScope; this.logger.LogDebug($"{{LogKey:l}} set message (origin={message.Origin})", LogKeys.Messaging); } // TODO: async publish! if (this.options.Mediator != null) { /*await */ this.options.Mediator.Publish(new MessagePublishedDomainEvent(message)).GetAwaiter().GetResult(); /*.AnyContext();*/ } var messageName = message.GetType().PrettyName(); // TODO: really need non-async Result? var serviceBusMessage = new Microsoft.Azure.ServiceBus.Message { Label = messageName, MessageId = message.Id, CorrelationId = message.CorrelationId.IsNullOrEmpty() ? IdGenerator.Instance.Next : message.CorrelationId, //Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), // TODO: use ISerializer here, compacter messages Body = this.serializer.SerializeToBytes(message), To = this.options.FilterScope }; serviceBusMessage.UserProperties.AddOrUpdate("Origin", this.options.MessageScope); this.logger.LogJournal(LogKeys.Messaging, $"publish (name={{MessageName}}, id={{MessageId}}, origin={{MessageOrigin}}, size={serviceBusMessage.Body.Length.Bytes().ToString("#.##")})", LogEventPropertyKeys.TrackPublishMessage, args: new[] { messageName, message.Id, message.Origin }); this.logger.LogTraceEvent(LogKeys.Messaging, message.Id, messageName, LogTraceEventNames.Message); this.options.Provider.CreateModel().SendAsync(serviceBusMessage).GetAwaiter().GetResult(); } }
public static Message ToServiceModel(Domain.Message message) { return(new Message { Id = message.Id, Body = message.Body, Subject = message.Subject, Sender = message.Sender, Receiver = message.Receiver, DateSent = message.DateSent, Read = message.Read }); }
public async Task SendMessage(long chatId, string recipientId, string text, CancellationToken cancellationToken) { var chat = await _chatRepository.FindById(chatId, cancellationToken); if (chat == null) { throw new ChatNotFoundExceptions($"Чат с id {chatId} не был найден"); } var userId = await _identityService.GetCurrentUserId(cancellationToken); if (chat.BuyerId != userId && chat.Advertisement.OwnerId != userId) { throw new HaveNoRigthToSendMessageChat($"Чат с id {chatId} не пренадлежит вам"); } //Kostil, users is null; var sender = await _userRepository.FindById(userId, cancellationToken); var recipient = await _userRepository.FindById(recipientId, cancellationToken); if (recipient == null) { throw new UserNotFoundException($"Пользователь с id{recipientId}, которому отправляется сообщение не был найден"); } var message = new Domain.Message { Text = text, SenderId = userId, Sender = sender, RecipientId = recipientId, Recipient = recipient, CreatedDate = DateTime.UtcNow, ChatId = chatId }; await _messageRepository.Save(message, cancellationToken); await _signalRService.SendMessage(new SignalR.Contracts.Message { SenderId = message.SenderId, SenderName = message.Sender.Name, CreatedDate = message.CreatedDate, Text = message.Text, RecipientId = message.RecipientId, RecipientName = message.Recipient.Name }, cancellationToken); }
public async Task <ActionResult> Create(CreateBindingModel model) { Domain.Message message = new Domain.Message { User = model.User, Content = model.Content, CreatedOn = DateTime.UtcNow }; await this.context.Messages.AddAsync(message); await this.context.SaveChangesAsync(); return(this.Ok()); }
public FubuContinuation Post(NewMessageInput request) { var to = _session.Query<Domain.User>().First(); var from = _session.Query<Domain.User>().First(x => x.Username == request.ToUser); var message = new Domain.Message { Body = request.Message, ToId = to.Id, FromId = from.Id, Sent = DateTime.Now }; _session.Store(message); return FubuContinuation.RedirectTo(new NewMessageInput()); }
public async Task ShouldSaveMessage() { IMessageRepository repository = Substitute.For <IMessageRepository>(); Guid messageId = Guid.NewGuid(); MessageBuilder messageBuilder = new MessageBuilder().WithData(ApplicationConstants.DefaultData); Domain.Message domain = messageBuilder.Build(); repository.Save(domain).Returns(messageId); MessageController controller = new MessageController(repository); ActionResult result = await controller.Save(new WebApi.Models.Message() { Data = domain.Data }); result.ShouldBeAssignableTo <OkObjectResult>(); ((OkObjectResult)result).Value.ToString().ShouldBe(messageId.ToString()); }
public async Task <IHttpActionResult> PostNewMessage([FromUri] int id, [FromBody] Domain.Message message) { if (User == null || User.Identity == null || !User.Identity.IsAuthenticated) { return(Unauthorized()); } long userId = User.Identity.GetUserId <long>(); if (userId <= 0) { return(Unauthorized()); } if (message == null || string.IsNullOrWhiteSpace(message.MessageText)) { return(BadRequest("The message cannot be empty")); } var newMessage = await _conversationBoundedContext.CreateMessage(userId, message.MessageText, id); Hub.Clients.Group(id.ToString()).addItem(newMessage); return(Ok(newMessage)); }
protected override async Task <MessageViews.FullResult> HandleCore(Command command) { var user = await db.Users.FindAsync(command.UserId); if (user == null) { throw new BadRequestException("Usuário com o Id " + command.UserId + " não existe"); } var message = new Domain.Message() { Title = command.Title, Content = command.Content, User = user }; await db.Messages.AddAsync(message); await db.SaveChangesAsync(); return(new MessageViews.FullResult(message)); }
public void AttachmentsLinkFromCommunity(Domain.DTO.DTO_Ticket TkData, Domain.Enums.MailSettings ownerSettings, Domain.Enums.MailSettings creatorSettings, List <ModuleActionLink> links) { if (!this.SaveTicket(TkData, ownerSettings, creatorSettings, true)) { return; } Domain.Message Msg = service.MessageGetFromTicketDraft(TkData.TicketId, TkData.CreatorId); if (Msg == null || View.DraftMsgId != Msg.Id) { return; } int UserID = (this.UserContext != null) ? UserContext.CurrentUserID : 0; lm.Comol.Core.FileRepository.Domain.ModuleRepository cRepository = service.GetRepositoryPermissions(CurrentCommunityId, UserID); List <lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions> actions = service.UploadAvailableActionsGet(MessageUserType.Partecipant, CurrentCommunityId, UserContext.CurrentUserID, cRepository); if (!actions.Contains(lm.Comol.Core.DomainModel.Repository.RepositoryAttachmentUploadActions.linkfromcommunity)) { return; } IList <Domain.TicketFile> attachments = service.AttachmentsLinkFiles(View.DraftMsgId, links); int addedfiles = 0; if (attachments != null) { addedfiles = attachments.Count(); } this.InitView(); }
public FullResult(Domain.Message message) : base(message) { this.User = new UserViews.SimpleResult(message.User); }
public SimpleResult(Domain.Message message) { this.Id = message.Id; this.Title = message.Title; this.Content = message.Content; }
/// <summary> /// Publishes the specified message. /// </summary> /// <param name="message">The message.</param> public void Publish(Domain.Message message) { EnsureArg.IsNotNull(message, nameof(message)); if (message.CorrelationId.IsNullOrEmpty()) { message.CorrelationId = IdGenerator.Instance.Next; } var messageName = message.GetType().PrettyName(); using (this.logger.BeginScope(new Dictionary <string, object> { [LogPropertyKeys.CorrelationId] = message.CorrelationId })) using (var scope = this.options.Tracer?.BuildSpan(messageName, LogKeys.AppMessaging, SpanKind.Producer).Activate(this.logger)) { if (message.Id.IsNullOrEmpty()) { message.Id = IdGenerator.Instance.Next; this.logger.LogDebug($"{{LogKey:l}} set message (id={message.Id})", LogKeys.AppMessaging); } if (message.Origin.IsNullOrEmpty()) { message.Origin = this.options.MessageScope; this.logger.LogDebug($"{{LogKey:l}} set message (origin={message.Origin})", LogKeys.AppMessaging); } // TODO: really need non-async Result? var serviceBusMessage = new Microsoft.Azure.ServiceBus.Message { Label = messageName, MessageId = message.Id, CorrelationId = message.CorrelationId.IsNullOrEmpty() ? IdGenerator.Instance.Next : message.CorrelationId, //Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), // TODO: use ISerializer here, compacter messages Body = this.serializer.SerializeToBytes(message), To = this.options.FilterScope }; if (this.options.Expiration.HasValue) { serviceBusMessage.TimeToLive = this.options.Expiration.Value; } serviceBusMessage.UserProperties.AddOrUpdate("Origin", message.Origin); if (scope?.Span != null) { // propagate the span infos serviceBusMessage.UserProperties.AddOrUpdate("TraceId", scope.Span.TraceId); serviceBusMessage.UserProperties.AddOrUpdate("SpanId", scope.Span.SpanId); } this.logger.LogJournal(LogKeys.AppMessaging, $"message publish: {messageName} (id={{MessageId}}, origin={{MessageOrigin}}, size={serviceBusMessage.Body.Length.Bytes().ToString("#.##")})", LogPropertyKeys.TrackPublishMessage, args: new[] { message.Id, message.Origin }); this.logger.LogTrace(LogKeys.AppMessaging, message.Id, messageName, LogTraceNames.Message); var policy = Policy.Handle <Exception>() .WaitAndRetry(this.options.Retries, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { this.logger.LogWarning(ex, "{LogKey:l} could not publish message: {MessageId} after {Timeout}s ({ExceptionMessage})", LogKeys.AppMessaging, message.Id, $"{time.TotalSeconds:n1}", ex.Message); }); policy.Execute(() => { this.options.Provider.TopicClientFactory().SendAsync(serviceBusMessage).GetAwaiter().GetResult(); }); // TODO: async publish! if (this.options.Mediator != null) { /*await */ this.options.Mediator.Publish(new MessagePublishedDomainEvent(message)).GetAwaiter().GetResult(); /*.AnyContext();*/ } } }
/// <summary> /// Handles the Click event of the SendButton control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void SendButtonClick(object sender, EventArgs e) { var algo = (CryptoAlgorithm)this.CryptoAlgorithmComboBox.SelectedValue; if (algo == CryptoAlgorithm.None) { var m = new Domain.Message(); m.SetPayload(this.MessageTextBox.Text); this.messagingProxy.Send( m, this.currentSession); } else { var cp = this.GetCryptoProvider(algo); this.messagingProxy.Send( new Domain.Message { Payload = cp.Encrypt(this.MessageTextBox.Text), Algorithm = (CryptoAlgorithm)this.CryptoAlgorithmComboBox.SelectedValue }, this.currentSession); } this.MessageTextBox.Text = string.Empty; }