public IHttpActionResult Get(int id)
        {
            try
            {
                Message message;
                var     messageRepository = new MessageRepository();

                if (id > 0)
                {
                    var messages = messageRepository.Retrieve();
                    message = messages.FirstOrDefault(p => p.MessageId == id);
                    if (message == null)
                    {
                        return(NotFound());
                    }
                }
                else
                {
                    message = messageRepository.Create();
                }
                return(Ok(message));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemple #2
0
        public IActionResult CreateMessage([FromBody] Message message)
        {
            var tokenString        = Request.Headers["Authorization"].ToString().Substring("Bearer ".Length).Trim();
            JwtSecurityToken token = new JwtSecurityTokenHandler().ReadJwtToken(tokenString);
            var username           = token.Claims.Where(claim => claim.Type == ClaimTypes.Name).First().Value;
            var account            = _contextA.GetOne(username);

            if (account is null)
            {
                return(Unauthorized());
            }
            if (account.Id != message.OwnerId && account.Id != message.Addressee)
            {
                return(Unauthorized());
            }
            try
            {
                _context.Create(message);
                return(Ok());
            }
            catch (Exception exe)
            {
                return(BadRequest(exe.Message));
            }
        }
        public override async Task Queue()
        {
            await Task.Run(() =>
            {
                var showDebugInfo    = Options.FirstOrDefault(o => o.Name == "show_debug_info").Value;
                var showProgressInfo = Options.FirstOrDefault(o => o.Name == "show_progress_info").Value;
                var limit            = 500;
                var offset           = 0;
                while (true)
                {
                    // Create success message (MessageType = Information)
                    var successItems = queueItemRepository.GetQueuedItemsByStatus(
                        PushState.Success,
                        PushState.Failed | PushState.ByPassed | PushState.Reported, // exclude items that are reported, failed...
                        limit,
                        offset);

                    foreach (var item in successItems)
                    {
                        var messageText = string.Empty;
                        messageText     = item.TargetEntityType == EntityType.Entity
                            ? GetEntityMessage(item, out IIndexModel indexModel, out IndexItemModel itemModel)
                            : GetAttributeMessage(item, out indexModel, out itemModel);

                        if (showDebugInfo == bool.TrueString)
                        {
                            //var message = messageRepository.GetById(item.MessageId.ToString());
                            messageText = $@"{messageText}
* Index Info:
```{JsonConvert.SerializeObject(indexModel, Formatting.Indented)}```
* Index Item Info:
```{JsonConvert.SerializeObject(itemModel, Formatting.Indented)}```";
                        }

                        if (showProgressInfo == bool.TrueString)
                        {
                            var message = messageRepository.GetById(item.MessageId.ToString());
                            messageText = $@"{messageText}
* Progress:
```{message.Message}```";
                        }

                        var messageId = messageRepository.Create(new
                        {
                            CreatedAt   = DateTime.Now.ToUnixTimestamp(),
                            Message     = messageText,
                            MessageType = MessageType.Information,
                            Status      = MessageStatus.None
                        });

                        messageRepository.LinkToReporter(messageId, ReporterModel);
                    }
                    offset += limit;
                }
            });
        }
Exemple #4
0
 /// <summary>
 /// Добавление комментария к лодке
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public int AddComment(MessageViewModel data)
 {
     try
     {
         Message new_message = new Message
         {
             BoatId = data.BoatId,
             FromId = data.ClientId,
             ToId = data.CustomerId,
             Text = data.Text,
             Date = DateTime.Today,
             Type = "comment"
         };
         m_repository.Create(new_message);
         return 0;
     }
     catch
     {
         return 1;
     }
 }
Exemple #5
0
 public IActionResult CreateMessage(MessageViewModel message)
 {
     if (ModelState.IsValid)
     {
         Message newMessage = new Message();
         newMessage.Content         = message.Content;
         newMessage.MessageDateTime = DateTime.Now;
         _mr.Create(newMessage);
         return(RedirectToAction("MessageBoard", "Home"));
     }
     return(RedirectToAction("MessageBoard", "Home"));
 }
Exemple #6
0
 public Guid Create(Model.Message message)
 {
     Domain.Message domainMessage = this.mapper.Map <Domain.Message>(message);
     try
     {
         messageRepository.Create(domainMessage);
         messageRepository.SaveChanges();
     }
     catch (Exception ex)
     {
         logger.Fatal(ex.ToString());
     }
     return(domainMessage.Id);
 }
Exemple #7
0
        public IActionResult Post([FromBody] Message message)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (message.Id == 0)
            {
                long id = messageRepository.Create(message);
                message.Id = id;

                return(Ok(message));
            }
            else
            {
                messageRepository.Update(message);

                return(Ok(message));
            }
        }
Exemple #8
0
 public void CreateItem(Message message)
 {
     _messageRepository.Create(message);
 }
 public async Task <MessageDto> CreateMessage(MessageCreateDto dto) =>
 _mapper.Map <MessageDto>(await _repository.Create(_mapper.Map <Message>(dto)));
        public override async Task Invoke(IStepExecutionContext context = null)
        {
            var executeAt       = DateTime.Now.ToUnixTimestamp();
            var firstQueuedItem = entityRepository.GetCurrentQueuedItems();

            if (firstQueuedItem == null)
            {
                return;
            }
            IIndexModel              indexModel = null;
            IndexItemModel           itemModel  = null;
            IIndexer                 indexer    = null;
            IPusher                  pusher     = null;
            IEnumerable <OptionItem> options    = null;

            if (firstQueuedItem.TargetEntityType == EntityType.Entity)
            {
                indexModel = entityRepository.GetById(firstQueuedItem.TargetEntityId.ToString());
                options    = entityRepository.LoadOptions(indexModel.Id.ToString()).Select(o => new OptionItem {
                    Name = o.Key, Value = o.Value
                });
                var sourceConnection      = connectionRepository.GetById(indexModel.SourceConnectionId.ToString());
                var destinationConnection = connectionRepository.GetById(indexModel.DestinationConnectionId.ToString());
                indexer = entityIndexers.FirstOrDefault(i => i.IsImplemented(indexModel.SourceProcessorId, sourceConnection.ProviderId));
                pusher  = entityPushers.FirstOrDefault(p => p.IsImplemented(indexModel.DestinationProcessorId, destinationConnection.ProviderId));
            }
            else
            {
                var attributeModel = attributeRepository.GetById(firstQueuedItem.TargetEntityId.ToString());
                indexModel = attributeModel;
                var entityModel = entityRepository.GetById(attributeModel.EntityId.ToString());
                options = attributeRepository.LoadOptions(attributeModel.Id.ToString()).Select(o => new OptionItem {
                    Name = o.Key, Value = o.Value
                });
                var sourceConnection      = connectionRepository.GetById(attributeModel.SourceConnectionId.ToString());
                var destinationConnection = connectionRepository.GetById(attributeModel.DestinationConnectionId.ToString());
                indexer = attributeIndexers.FirstOrDefault(i => i.IsImplemented(attributeModel.SourceProcessorId, entityModel.SourceProcessorId, sourceConnection.ProviderId));
                pusher  = attributePushers.FirstOrDefault(p => p.IsImplemented(attributeModel.DestinationProcessorId, entityModel.DestinationProcessorId, destinationConnection.ProviderId));
            }

            indexer.SetIndex(indexModel);
            indexer.SetOptions(options);
            pusher.SetIndex(indexModel);
            pusher.SetOptions(options);
            pusherManager.SetIndex(indexModel);
            pusherManager.OnReport(s => Logger.Information(s));
            pusherManager.SetIndexer(indexer);
            pusherManager.SetPusher(pusher);

            try
            {
                itemModel = entityRepository.GetIndexedItemById(indexModel, firstQueuedItem.TargetItemId.ToString());
                var pushState = await pusherManager.PushItem(itemModel);

                var queueItemStatus = firstQueuedItem.Status == PushState.None ? PushState.Success : firstQueuedItem.Status;
                var messageId       = messageRepository.Create(new
                {
                    Message     = string.Join("\n", pusherManager.GetReportMessages()),
                    CreatedAt   = DateTime.Now.ToUnixTimestamp(),
                    MessageType = MessageType.Information,
                    Status      = MessageStatus.None
                });
                queueItemStatus = queueItemStatus & pushState;
                if ((pushState & PushState.Success) <= 0)
                {
                    queueItemStatus = (queueItemStatus | PushState.Success) ^ (PushState.Success);
                }
                queueItemRepository.Update(firstQueuedItem.Id.ToString(), new
                {
                    UpdatedAt  = DateTime.Now.ToUnixTimestamp(),
                    ExecuteAt  = executeAt,
                    ExecutedAt = DateTime.Now.ToUnixTimestamp(),
                    MessageId  = messageId,
                    Status     = queueItemStatus
                });
            }
            catch (Exception ex)
            {
                var messages  = $@"Queue item (Id: {firstQueuedItem.Id}) failed to run. 
Addtional information:
```{JsonConvert.SerializeObject(indexModel, Formatting.Indented)}```
Progress: 
```{string.Join("\n - ", pusherManager.GetReportMessages())}```
Exception: 
```{ex}```";
                var messageId = messageRepository.Create(new
                {
                    Message     = messages,
                    CreatedAt   = DateTime.Now.ToUnixTimestamp(),
                    MessageType = MessageType.Error,
                    Status      = MessageStatus.None
                });

                queueItemRepository.Update(firstQueuedItem.Id.ToString(), new
                {
                    UpdatedAt  = DateTime.Now.ToUnixTimestamp(),
                    ExecuteAt  = executeAt,
                    ExecutedAt = DateTime.Now.ToUnixTimestamp(),
                    MessageId  = messageId,
                    Status     = (firstQueuedItem.Status | PushState.UnexpectedError | PushState.Failed | PushState.Success) ^ PushState.Success, // remove success
                });
                throw;
            }
        }
 public Message Create(Message entity)
 {
     Validate(entity);
     return(_messageRepository.Create(entity));
 }
        public static void CreateMessage(string text, string receiver, int roomID, int? imageID)
        {
            // Select UserProfile for UserID given
            CurrentUser cUser = CurrentUser.Instance;
            string currentUsername = cUser.Username;
            int currentUserID = cUser.UserID;

            Message msg = new Message
            {
                TimeStamp = DateTime.Now.ToUniversalTime(),
                Text = text,
                Receiver = receiver,
                RoomID = roomID,
                ImageID = imageID.GetValueOrDefault(),
                UserID = currentUserID
            };

            if (text.Length == 0 && imageID == 4)
            {
                // No text or image is attached
                return;
            }

            if (text.Length < 3 && text.Length > 0)
            {
                if (text.Substring(0, 1) != "/")
                {
                    // Message is not a command, must be public
                    msg.Text = currentUsername + ": " + text;
                    msg.Receiver = "Public";
                }
                else
                {
                    // Commands must contain more than 3 characters
                    msg.Text = "Incorrect command format, please use \"/[command]\"";
                    msg.Receiver = currentUsername;
                }
            }
            else
            {
                if (GetMessageCommand(text) != null)
                {
                    // Is a command
                    switch (GetMessageCommand(text))
                    {
                        case "PrivateMessage":
                            string receiverUsername, messageText;
                            int receiverNameIndex, messageTextIndex;
                            messageText = text.Substring(3, text.Length - 3); // Obtain everything except /m
                            receiverNameIndex = messageText.IndexOf(" ");

                            if (receiverNameIndex == -1)
                            {
                                msg.Text = "Incorrect message format, please use \"/m [username] [message]\"";
                                msg.Receiver = currentUsername;
                                goto done;
                            }

                            receiverUsername = messageText.Substring(0, receiverNameIndex);
                            messageTextIndex = receiverUsername.Length + 1;
                            messageText = messageText.Substring(messageTextIndex, messageText.Length - messageTextIndex);

                            // Create new private message
                            if (Membership.GetUser(receiverUsername) == null || !Membership.GetUser(receiverUsername).IsOnline)
                            {
                                msg.Text = "That user is offline.";
                                msg.Receiver = currentUsername;
                                break;
                            }

                            msg.Text = "To " + receiverUsername + ": " + messageText;
                            msg.Receiver = currentUsername;

                            UserProfile receiverProfile = UserProfileController.GetUserProfile((Guid)Membership.GetUser(receiverUsername).ProviderUserKey);

                            var messageRep = new MessageRepository();
                            Message pMsg = new Message
                            {
                                TimeStamp = DateTime.Now.ToUniversalTime(),
                                Receiver = receiverUsername,
                                Text = "From " + currentUsername + ": " + messageText,
                                RoomID = receiverProfile.RoomID,
                                ImageID = imageID.GetValueOrDefault(),
                                UserID = currentUserID
                            };

                            messageRep.Create(pMsg);
                            messageRep.SaveChanges();
                            break;

                        case "AddFriend":
                            string friendUsername = text.Substring(3, text.Length - 3);

                            if (friendUsername.IndexOf(" ") != -1)
                            {
                                msg.Text = "Incorrect friend addition format, please use \"/f [username]\"";
                                msg.Receiver = cUser.Username;
                                break;
                            }

                            if (Membership.GetUser(friendUsername) == null)
                            {
                                // User does not exist
                                msg.Text = "That person is offline.";
                                msg.Receiver = cUser.Username;
                                break;
                            }

                            UserProfile friendProfile = UserProfileController.GetUserProfile((Guid)Membership.GetUser(friendUsername).ProviderUserKey);

                            // Check to see if friend already exists
                            if (!UserFriend.GetByUserID(currentUserID).Select(i => i.FriendUserID).Contains(friendProfile.UserID))
                            {
                                UserFriendController.AddFriend(cUser.UserID, friendProfile.UserID);
                                msg.Text = friendUsername + " was added to friend's list.";
                                msg.Receiver = cUser.Username;
                                break;
                            }
                            else
                            {
                                // Friend already exists
                                msg.Text = "That person has already been added to your friends list.";
                                msg.Receiver = cUser.Username;
                                break;
                            }
                    }
                }
                else
                {
                    // Is not a command
                    if (receiver == "Public")
                    {
                        // Submit message to public
                        msg.Text = cUser.Username + ": " + text;
                        goto done;
                    }
                }
            }done:;

            var mRep = new MessageRepository();
            mRep.Create(msg);
            mRep.SaveChanges();
        }